repo
stringclasses
358 values
pull_number
int64
6
67.9k
instance_id
stringlengths
12
49
issue_numbers
sequencelengths
1
7
base_commit
stringlengths
40
40
patch
stringlengths
87
101M
test_patch
stringlengths
72
22.3M
problem_statement
stringlengths
3
256k
hints_text
stringlengths
0
545k
created_at
stringlengths
20
20
PASS_TO_PASS
sequencelengths
0
0
FAIL_TO_PASS
sequencelengths
0
0
freedomofpress/securedrop
5,351
freedomofpress__securedrop-5351
[ "5349" ]
141d405ff1dc73739724e7011b489d61e45bfc1f
diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -307,7 +307,7 @@ def get_all_submissions(): def get_all_replies(): replies = Reply.query.all() return jsonify( - {'replies': [reply.to_json() for reply in replies]}), 200 + {'replies': [reply.to_json() for reply in replies if reply.source]}), 200 @api.route('/user', methods=['GET']) @token_required diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -285,10 +285,10 @@ def to_json(self) -> 'Dict[str, Union[str, int, bool]]': uuid = self.journalist.uuid json_submission = { 'source_url': url_for('api.single_source', - source_uuid=self.source.uuid), + source_uuid=self.source.uuid) if self.source else None, 'reply_url': url_for('api.single_reply', source_uuid=self.source.uuid, - reply_uuid=self.uuid), + reply_uuid=self.uuid) if self.source else None, 'filename': self.filename, 'size': self.size, 'journalist_username': username,
diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -415,6 +415,20 @@ def test_authorized_user_can_get_single_submission(journalist_app, test_submissions['source'].submissions[0].size +def test_authorized_user_can_get_all_replies_with_disconnected_replies(journalist_app, + test_files, + journalist_api_token): + with journalist_app.test_client() as app: + db.session.execute( + "DELETE FROM sources WHERE id = :id", + {"id": test_files["source"].id} + ) + response = app.get(url_for('api.get_all_replies'), + headers=get_api_headers(journalist_api_token)) + + assert response.status_code == 200 + + def test_authorized_user_can_get_all_replies(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app:
Journalist API get_all_replies endpoint should omit disconnected replies ## Description Similar to #5315, if there are replies whose sources do not exist in the database, the API should omit them from the response of `get_all_replies`. In most of the API's single-object or source-derived endpoints, we explicitly `get_or_404` to avoid nonexistent sources, so this will make this endpoint consistent. ## Steps to Reproduce 1. `make dev` 1. docker exec into the container, e.g. `docker exec -it securedrop-dev-0 bash` 1. `cd /var/lib/securedrop/` 1. `sqlite3 db.sqlite` 1. `delete from sources where id=1;` 1. While authenticated to the journalist API, `GET /api/v1/replies` ## Expected Behavior That you'd get a JSON document containing only complete and valid replies. ## Actual Behavior <details> <summary>A 500 internal server error as in #5315</summary> ``` Traceback (most recent call last): File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise raise value File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise raise value File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/user/src/fpf/securedrop/securedrop/journalist_app/api.py", line 48, in decorated_function return f(*args, **kwargs) File "/home/user/src/fpf/securedrop/securedrop/journalist_app/api.py", line 310, in get_all_replies {'replies': [reply.to_json() for reply in replies]}), 200 File "/home/user/src/fpf/securedrop/securedrop/journalist_app/api.py", line 310, in <listcomp> {'replies': [reply.to_json() for reply in replies]}), 200 File "/home/user/src/fpf/securedrop/securedrop/models.py", line 288, in to_json source_uuid=self.source.uuid), AttributeError: 'NoneType' object has no attribute 'uuid' ``` </details> ## Comments It's good but not sufficient to make the JSON rendition of the reply robust by making `source_url` `null` (as done in the [fix for #5315](https://github.com/freedomofpress/securedrop/pull/5345), as the SDK currently derives the source UUID from that value without checking, so throws an exception when it's `None`. The simplest fix would be to change line 309 of `journalist_app/api.py` to: ```python return jsonify( {'replies': [reply.to_json() for reply in replies if reply.source]}), 200 ```
@rmol Will take this one up as well. You're awesome. Thanks!
2020-06-30T18:23:17Z
[]
[]
freedomofpress/securedrop
5,370
freedomofpress__securedrop-5370
[ "5361" ]
0ad9e6344b3cff3247c16f453620f4eba95fc142
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -410,7 +410,9 @@ def __init__(self, args): str.split, lambda config: True], ['v2_onion_services', self.check_for_v2_onion(), bool, - 'Do you want to enable v2 onion services (recommended only for SecureDrop instances installed before 1.0.0)?', # noqa: E501 + 'WARNING: For security reasons, support for v2 onion services ' + + 'will be removed in February 2021. ' + + 'Do you want to enable v2 onion services?', SiteConfig.ValidateYesNo(), lambda x: x.lower() == 'yes', lambda config: True],
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -340,7 +340,7 @@ def verify_locales_prompt(child): def verify_v2_onion_for_first_time(child): - child.expect(rb' installed before 1.0.0\)\?\:', timeout=2) # noqa: E501 + child.expect(rb'Do you want to enable v2 onion services\?\:', timeout=2) # noqa: E501 assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'no' # noqa: E501
Add v2 deprecation warning to securedrop-admin As we're implementing an official deprecation timeline for v2 Onion Services (see #5302), as a standard practice for deprecation warnings, we should display appropriate warnings in CLI tooling as well. This includes `securedrop-admin sdconfig`, and possibly `securedrop-admin install`. We don't need to go overboard, but we should make the removal date clear in the CLI output for any command run that includes the enabling or provisioning of v2 Onion Services.
2020-07-13T23:21:47Z
[]
[]
freedomofpress/securedrop
5,380
freedomofpress__securedrop-5380
[ "5378" ]
6fb5a94903e11fced744677caac7895917a39ffe
diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -484,6 +484,10 @@ def check_username_acceptable(cls, username: str) -> None: raise InvalidUsernameException( 'Username "{}" must be at least {} characters long.' .format(username, cls.MIN_USERNAME_LEN)) + if username in cls.INVALID_USERNAMES: + raise InvalidUsernameException( + "This username is invalid because it is reserved " + "for internal use by the software.") @classmethod def check_name_acceptable(cls, name):
diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -529,6 +529,49 @@ def edit_user_page_loaded(): hotp_reset_uid = hotp_reset_button.find_element_by_name("uid") assert hotp_reset_uid.is_displayed() is False + def _admin_editing_invalid_username(self): + # Log the new user out + self._logout() + + self.wait_for(lambda: self.driver.find_element_by_css_selector(".login-form")) + + self._login_user(self.admin, self.admin_pw, self.admin_user["totp"]) + + # Go to the admin interface + self.safe_click_by_id("link-admin-index") + + self.wait_for(lambda: self.driver.find_element_by_css_selector("button#add-user")) + + # Click the "edit user" link for the new user + # self._edit_user(self.new_user['username']) + new_user_edit_links = [ + el + for el in self.driver.find_elements_by_tag_name("a") + if (el.get_attribute("data-username") == self.new_user["username"]) + ] + assert len(new_user_edit_links) == 1 + new_user_edit_links[0].click() + + def can_edit_user(): + h = self.driver.find_elements_by_tag_name("h1")[0] + assert 'Edit user "{}"'.format(self.new_user["username"]) == h.text + + self.wait_for(can_edit_user) + + new_username = "deleted" + + self.safe_send_keys_by_css_selector('input[name="username"]', Keys.CONTROL + "a") + self.safe_send_keys_by_css_selector('input[name="username"]', Keys.DELETE) + self.safe_send_keys_by_css_selector('input[name="username"]', new_username) + self.safe_click_by_css_selector("button[type=submit]") + + def user_edited(): + if not hasattr(self, "accept_languages"): + flash_msg = self.driver.find_element_by_css_selector(".flash") + assert "Invalid username" in flash_msg.text + + self.wait_for(user_edited) + def _admin_can_edit_new_user(self): # Log the new user out self._logout() diff --git a/securedrop/tests/functional/test_admin_interface.py b/securedrop/tests/functional/test_admin_interface.py --- a/securedrop/tests/functional/test_admin_interface.py +++ b/securedrop/tests/functional/test_admin_interface.py @@ -15,6 +15,13 @@ def test_admin_interface(self): self._new_user_can_log_in() self._admin_can_edit_new_user() + def test_admin_edit_invalid_username(self): + self._admin_logs_in() + self._admin_visits_admin_interface() + self._admin_adds_a_user() + self._new_user_can_log_in() + self._admin_editing_invalid_username() + def test_admin_edits_hotp_secret(self): # Toggle security slider to force prefs change self.set_tbb_securitylevel(ft.TBB_SECURITY_HIGH) diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -820,6 +820,29 @@ def test_admin_edits_user_invalid_username( 'error') +def test_admin_edits_user_invalid_username_deleted( + journalist_app, test_admin, test_journo): + """Test expected error message when admin attempts to change a user's + username to deleted""" + new_username = "deleted" + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + + with InstrumentedApp(journalist_app) as ins: + app.post( + url_for('admin.edit_user', user_id=test_admin['id']), + data=dict(username=new_username, + first_name='', + last_name='', + is_admin=None)) + + ins.assert_message_flashed( + 'Invalid username: This username is invalid because it ' + 'is reserved for internal use by the software.', + 'error') + + def test_admin_resets_user_hotp_format_non_hexa( journalist_app, test_admin, test_journo):
A couple of ideas for better handling of deleted journalists ## Description After #5284, you can no longer create a journalist account with a username of "deleted" in the journalist interface admin section, but in review we missed the fact that you can change an existing account's username to that. It's also still possible to use `manage.py` to create an account with a username of "deleted".
2020-07-16T10:17:57Z
[]
[]
freedomofpress/securedrop
5,381
freedomofpress__securedrop-5381
[ "2043" ]
39904269ca2644d586579d69442c70792e545003
diff --git a/securedrop/crypto_util.py b/securedrop/crypto_util.py --- a/securedrop/crypto_util.py +++ b/securedrop/crypto_util.py @@ -16,6 +16,8 @@ import rm +from models import Source + import typing # https://www.python.org/dev/peps/pep-0484/#runtime-or-type-checking if typing.TYPE_CHECKING: @@ -172,8 +174,21 @@ def genrandomid(self, for x in range(words_in_random_id)) def display_id(self): - return ' '.join([random.choice(self.adjectives), - random.choice(self.nouns)]) + """Generate random journalist_designation until we get an unused one""" + + tries = 0 + + while tries < 50: + new_designation = ' '.join([random.choice(self.adjectives), + random.choice(self.nouns)]) + + collisions = Source.query.filter(Source.journalist_designation == new_designation) + if collisions.count() == 0: + return new_designation + + tries += 1 + + raise ValueError("Could not generate unique journalist designation for new source") def hash_codename(self, codename, salt=None): """Salts and hashes a codename using scrypt. diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -72,8 +72,18 @@ def create(): del session['codenames'] filesystem_id = current_app.crypto_util.hash_codename(codename) + try: + source = Source(filesystem_id, current_app.crypto_util.display_id()) + except ValueError as e: + current_app.logger.error(e) + flash( + gettext("There was a temporary problem creating your account. " + "Please try again." + ), + 'error' + ) + return redirect(url_for('.index')) - source = Source(filesystem_id, current_app.crypto_util.display_id()) db.session.add(source) try: db.session.commit()
diff --git a/securedrop/tests/functional/functional_test.py b/securedrop/tests/functional/functional_test.py --- a/securedrop/tests/functional/functional_test.py +++ b/securedrop/tests/functional/functional_test.py @@ -185,6 +185,11 @@ def disable_js_torbrowser_driver(self): if hasattr(self, 'torbrowser_driver'): disable_js(self.torbrowser_driver) + def start_source_server(self, source_port): + config.SESSION_EXPIRATION_MINUTES = self.session_expiration / 60.0 + + self.source_app.run(port=source_port, debug=True, use_reloader=False, threaded=True) + @pytest.fixture(autouse=True) def set_default_driver(self): logging.info("Creating default web driver: %s", self.default_driver_name) @@ -261,16 +266,11 @@ def sd_servers(self): self.admin_user["totp"] = pyotp.TOTP(self.admin_user["secret"]) - def start_source_server(app): - config.SESSION_EXPIRATION_MINUTES = self.session_expiration / 60.0 - - app.run(port=source_port, debug=True, use_reloader=False, threaded=True) - def start_journalist_server(app): app.run(port=journalist_port, debug=True, use_reloader=False, threaded=True) self.source_process = Process( - target=lambda: start_source_server(self.source_app) + target=lambda: self.start_source_server(source_port) ) self.journalist_process = Process( diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -123,6 +123,14 @@ def submit_page_loaded(): self.wait_for(submit_page_loaded) + def _source_continues_to_submit_page_with_colliding_journalist_designation(self): + self.safe_click_by_id("continue-button") + + self.wait_for(lambda: self.driver.find_element_by_css_selector(".error")) + flash_error = self.driver.find_element_by_css_selector(".error") + assert "There was a temporary problem creating your account. Please try again." \ + == flash_error.text + def _source_submits_a_file(self): with tempfile.NamedTemporaryFile() as file: file.write(self.secret_message.encode("utf-8")) diff --git a/securedrop/tests/functional/test_source.py b/securedrop/tests/functional/test_source.py --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -1,5 +1,28 @@ from . import source_navigation_steps, journalist_navigation_steps from . import functional_test +from sdconfig import config + + +class TestSourceInterfaceDesignationCollision( + functional_test.FunctionalTest, + source_navigation_steps.SourceNavigationStepsMixin): + + def start_source_server(self, source_port): + self.source_app.crypto_util.adjectives = \ + self.source_app.crypto_util.adjectives[:1] + self.source_app.crypto_util.nouns = self.source_app.crypto_util.nouns[:1] + config.SESSION_EXPIRATION_MINUTES = self.session_expiration / 60.0 + + self.source_app.run(port=source_port, debug=True, use_reloader=False, threaded=True) + + def test_display_id_designation_collisions(self): + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_logs_out() + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page_with_colliding_journalist_designation() class TestSourceInterface( diff --git a/securedrop/tests/test_crypto_util.py b/securedrop/tests/test_crypto_util.py --- a/securedrop/tests/test_crypto_util.py +++ b/securedrop/tests/test_crypto_util.py @@ -7,6 +7,8 @@ import pytest import re +from flask import url_for, session + os.environ['SECUREDROP_ENV'] = 'test' # noqa import crypto_util import models @@ -198,6 +200,20 @@ def test_display_id(source_app): assert id_words[1] in source_app.crypto_util.nouns +def test_display_id_designation_collisions(source_app): + with source_app.test_client() as app: + app.get(url_for('main.generate')) + source_app.crypto_util.adjectives = source_app.crypto_util.adjectives[:1] + source_app.crypto_util.nouns = source_app.crypto_util.nouns[:1] + tab_id = next(iter(session['codenames'].keys())) + app.post(url_for('main.create'), data={'tab_id': tab_id}, follow_redirects=True) + + with pytest.raises(ValueError) as err: + source_app.crypto_util.display_id() + + assert 'Could not generate unique journalist designation for new source' in str(err) + + def test_genkeypair(source_app): with source_app.app_context(): codename = source_app.crypto_util.genrandomid()
db.Source.journalist_designation is not a unique field # Bug ## Description `db.Source.journalist_designation` provides a 2-word designation which is used in the JI by journalists as the primary mechanism to identify and distinguish between sources (whose real identity and codename remain secret). Since the uniqueness of the field is not being enforced, it's possible that two Sources might end up with the same journalist designation, causing confusion. ## Comments The fix is pretty straightforward. We should set the column/ attribute with `unique=True` and changes to this attribute/ field should be done with something like this pseudo-Python: ```py while True: try: journo.journalist_designation = gen_display_id() db_session.add(journo) db_session.commit() except UniquenessConstraintException: pass else: break ````
Note: adding a [unique constraint](http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.unique) to the `journalist_designation` is blocked on #1419 Well, we could add a `while` loop in `crypto_util.display_id()` similar to [the loop in `source_app.utils.generate_unique_codename()`](https://github.com/freedomofpress/securedrop/blob/develop/securedrop/source_app/utils.py#L38) to make sure that we cycle the `journalist_designation` if a duplicate is generated, that _would_ work going forward. But - the right place to solve this is the database. Specifically we should add the unique constraint, and if a source with a duplicate `journalist_designation` is added to the database, we handle the `IntegrityError` thrown by rolling back the transaction and cycle the `journalist_designation`. Let's tackle after #1419. @redshiftzero I would like to work on this. Hi @prateekj117 ! Thanks for reaching out, your help would be appreciated here. After some discussion with @rmol, we would recommend you adopt the strategy described in the strategy described in https://github.com/freedomofpress/securedrop/issues/2043#issuecomment-332990259 (mirroring `generate_unique_codename` function as opposed to adding a database constraint and creating a database migration) The proposed fix for setting `unique` attribute for `journalist_designation` column may be somewhat risky due to the auto-updating of the web application: Database migrations are automatically performed when the application is updated. To make sure we cover all cases, the Alembic migration, we would need to handle the (unlikely) event a duplicate journalist designation already exists in the database by: - renaming journalist designation in the database (to ensure database integrity) - Also rename files (submissions and messages) on disk. @emkll Sounds right. Will make a PR by EOD.
2020-07-16T13:53:57Z
[]
[]
freedomofpress/securedrop
5,382
freedomofpress__securedrop-5382
[ "5378" ]
867a143c18cfb9b178653627c999f572b87f8c64
diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -484,6 +484,10 @@ def check_username_acceptable(cls, username: str) -> None: raise InvalidUsernameException( 'Username "{}" must be at least {} characters long.' .format(username, cls.MIN_USERNAME_LEN)) + if username in cls.INVALID_USERNAMES: + raise InvalidUsernameException( + "This username is invalid because it is reserved " + "for internal use by the software.") @classmethod def check_name_acceptable(cls, name):
diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -529,6 +529,49 @@ def edit_user_page_loaded(): hotp_reset_uid = hotp_reset_button.find_element_by_name("uid") assert hotp_reset_uid.is_displayed() is False + def _admin_editing_invalid_username(self): + # Log the new user out + self._logout() + + self.wait_for(lambda: self.driver.find_element_by_css_selector(".login-form")) + + self._login_user(self.admin, self.admin_pw, self.admin_user["totp"]) + + # Go to the admin interface + self.safe_click_by_id("link-admin-index") + + self.wait_for(lambda: self.driver.find_element_by_css_selector("button#add-user")) + + # Click the "edit user" link for the new user + # self._edit_user(self.new_user['username']) + new_user_edit_links = [ + el + for el in self.driver.find_elements_by_tag_name("a") + if (el.get_attribute("data-username") == self.new_user["username"]) + ] + assert len(new_user_edit_links) == 1 + new_user_edit_links[0].click() + + def can_edit_user(): + h = self.driver.find_elements_by_tag_name("h1")[0] + assert 'Edit user "{}"'.format(self.new_user["username"]) == h.text + + self.wait_for(can_edit_user) + + new_username = "deleted" + + self.safe_send_keys_by_css_selector('input[name="username"]', Keys.CONTROL + "a") + self.safe_send_keys_by_css_selector('input[name="username"]', Keys.DELETE) + self.safe_send_keys_by_css_selector('input[name="username"]', new_username) + self.safe_click_by_css_selector("button[type=submit]") + + def user_edited(): + if not hasattr(self, "accept_languages"): + flash_msg = self.driver.find_element_by_css_selector(".flash") + assert "Invalid username" in flash_msg.text + + self.wait_for(user_edited) + def _admin_can_edit_new_user(self): # Log the new user out self._logout() diff --git a/securedrop/tests/functional/test_admin_interface.py b/securedrop/tests/functional/test_admin_interface.py --- a/securedrop/tests/functional/test_admin_interface.py +++ b/securedrop/tests/functional/test_admin_interface.py @@ -15,6 +15,13 @@ def test_admin_interface(self): self._new_user_can_log_in() self._admin_can_edit_new_user() + def test_admin_edit_invalid_username(self): + self._admin_logs_in() + self._admin_visits_admin_interface() + self._admin_adds_a_user() + self._new_user_can_log_in() + self._admin_editing_invalid_username() + def test_admin_edits_hotp_secret(self): # Toggle security slider to force prefs change self.set_tbb_securitylevel(ft.TBB_SECURITY_HIGH) diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -820,6 +820,29 @@ def test_admin_edits_user_invalid_username( 'error') +def test_admin_edits_user_invalid_username_deleted( + journalist_app, test_admin, test_journo): + """Test expected error message when admin attempts to change a user's + username to deleted""" + new_username = "deleted" + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + + with InstrumentedApp(journalist_app) as ins: + app.post( + url_for('admin.edit_user', user_id=test_admin['id']), + data=dict(username=new_username, + first_name='', + last_name='', + is_admin=None)) + + ins.assert_message_flashed( + 'Invalid username: This username is invalid because it ' + 'is reserved for internal use by the software.', + 'error') + + def test_admin_resets_user_hotp_format_non_hexa( journalist_app, test_admin, test_journo):
A couple of ideas for better handling of deleted journalists ## Description After #5284, you can no longer create a journalist account with a username of "deleted" in the journalist interface admin section, but in review we missed the fact that you can change an existing account's username to that. It's also still possible to use `manage.py` to create an account with a username of "deleted".
2020-07-16T15:06:47Z
[]
[]
freedomofpress/securedrop
5,497
freedomofpress__securedrop-5497
[ "5402" ]
f41c2f773f760b0ba2564d40e77c02a9c38bce09
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -129,6 +129,9 @@ def lookup(): except UnicodeDecodeError: current_app.logger.error("Could not decode reply %s" % reply.filename) + except FileNotFoundError: + current_app.logger.error("Reply file missing: %s" % + reply.filename) else: reply.date = datetime.utcfromtimestamp( os.stat(reply_path).st_mtime)
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -269,7 +269,8 @@ def test_user_must_log_in_for_protected_views(source_app): def test_login_with_whitespace(source_app): """ - Test that codenames with leading or trailing whitespace still work""" + Test that codenames with leading or trailing whitespace still work + """ def login_test(app, codename): resp = app.get(url_for('main.login')) @@ -299,6 +300,32 @@ def login_test(app, codename): login_test(app, codename_) +def test_login_with_missing_reply_files(source_app): + """ + Test that source can log in when replies are present in database but missing + from storage. + """ + source, codename = utils.db_helper.init_source() + journalist, _ = utils.db_helper.init_journalist() + replies = utils.db_helper.reply(journalist, source, 1) + assert len(replies) > 0 + with source_app.test_client() as app: + with patch("io.open") as ioMock: + ioMock.side_effect = FileNotFoundError + resp = app.get(url_for('main.login')) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Enter Codename" in text + + resp = app.post(url_for('main.login'), + data=dict(codename=codename), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Submit Files" in text + assert session['logged_in'] is True + + def _dummy_submission(app): """ Helper to make a submission (content unimportant), mostly useful in
Source cannot log in with codename if reply files are missing ## Description If a source has received a reply, and the reply file is removed from (or never written to) `/var/lib/securedrop/store`, then the source cannot successfully log in and reach the `/lookup` page. Instead a 500 error is generated, and the only option available is to log in via another codename or log out. On the JI, the source page is listed as normal, but the reply file cannot be downloaded. ## Steps to Reproduce - create a new source on the SI, submit a message, and note their codename - reply to the new source in the JI - verify that the reply is visible on the SI for the new source - on the app server, identify and delete the corresponding `reply.gpg` - log out from the SI and attempt to log in using the new source's codename ## Expected Behavior Source can log in and submit documents or read other replies ## Actual Behavior Source cannot log in, and a stack trace similar to the following is recorded in the source error logs (if enabled): ``` [Wed Jul 22 22:10:08.442888 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] [2020-07-22 22:10:08,442] ERROR in app: Exception on /lookup [GET] [Wed Jul 22 22:10:08.442937 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] Traceback (most recent call last): [Wed Jul 22 22:10:08.442946 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 2292, in wsgi_app [Wed Jul 22 22:10:08.442953 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] response = self.full_dispatch_request() [Wed Jul 22 22:10:08.442959 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1815, in full_dispatch_request [Wed Jul 22 22:10:08.442966 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] rv = self.handle_user_exception(e) [Wed Jul 22 22:10:08.442972 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1718, in handle_user_exception [Wed Jul 22 22:10:08.442979 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] reraise(exc_type, exc_value, tb) [Wed Jul 22 22:10:08.442985 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise [Wed Jul 22 22:10:08.442992 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] raise value [Wed Jul 22 22:10:08.442998 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1813, in full_dispatch_request [Wed Jul 22 22:10:08.443005 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] rv = self.dispatch_request() [Wed Jul 22 22:10:08.443011 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages/flask/app.py", line 1799, in dispatch_request [Wed Jul 22 22:10:08.443017 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] return self.view_functions[rule.endpoint](**req.view_args) [Wed Jul 22 22:10:08.443023 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/var/www/securedrop/source_app/decorators.py", line 12, in decorated_function [Wed Jul 22 22:10:08.443029 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] return f(*args, **kwargs) [Wed Jul 22 22:10:08.443060 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] File "/var/www/securedrop/source_app/main.py", line 115, in lookup [Wed Jul 22 22:10:08.443067 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] with io.open(reply_path, "rb") as f: [Wed Jul 22 22:10:08.443076 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] FileNotFoundError: [Errno 2] No such file or directory: '/var/lib/securedrop/store/YJSI6RQBP5JTHYYMZ4L4MUTQWAI7MNTK5ZUU4K2OXSD34PALIFT7DK6LTAYT43VLGAEOPWBBNV6JWDTHQPFITD6UFPLNYN25RHMJJOY=/2-damp_burner-reply.gpg' [Wed Jul 22 22:10:08.443111 2020] [wsgi:error] [pid 11154:tid 115647289255680] [remote 127.0.0.1:40108] ``` ## Comments This is a pernicious bug, as it prevents a source from logging in with an existing codename but doesn't present any obvious problems on the JI side (unless the journalist tries to download one of their old replies). It's offset by the recent changes to add nightly checks for orphaned db entries and submission/reply files. However, if an admin isn't paying attention to OSSEC alerts, it may seem to a journalist that a source just stopped responding, while the source may want to keep the conversation going but is blocked from doing so. Fix is probably simple enough, if the try/catch loop in source_app/main.py caught ` FileNotFoundError`s that might be enough for a basic effort. A more complex fix could also flag the fact that the file was missing in the JI more obviously, possibly prompting journalists to get their admin to run the cleanup scripts.
Thanks for the detailed report! > on the app server, identify and delete the corresponding reply.gpg > log out from the SI and attempt to log in using the new source's codename I can reproduce this also by simply reloading the Source Interface after deleting the reply file on disk (tested in the Docker dev env). However, I cannot reproduce by deleting the reply through the JI. If this only arises in cases of DB entries with references to files that no longer exist, it seems like a bit of an edge case that's worth fixing, but not urgent enough to try to rush it into 1.5.0 or a point release. Does that seem reasonable? It definitely doesn't need to be a point release, as I'm not aware of any affected instances - the problem is tho, that we wouldn't really have any way of knowing. I'm going to give a little time now to a potential fix and if it's straightforward we can maybe talk about adding it in to 1.5.0 at daily standup. Per discussion at sprint planning, targeting 1.6.0 milestone for now, if we're in good shape on all other release commitments and logistics (e.g., docs protocol), we may still be able to pull it into 1.5.0, but that's very much a stretch goal at this point. > [...] I'm not aware of any affected instances - the problem is tho, that we wouldn't really have any way of knowing. Could this [forum thread](https://forum.securedrop.org/t/codename-not-accepted/1344) be related? I get that there isn't any way of knowing, but I thought it could be useful to put it on your radar @zenmonkeykstop?
2020-09-15T18:09:08Z
[]
[]
freedomofpress/securedrop
5,506
freedomofpress__securedrop-5506
[ "5490" ]
98153cfb977195c9e3ecda035c3a451ac6990cd1
diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -66,6 +66,7 @@ def make_blueprint(config: SDConfig) -> Blueprint: def get_endpoints() -> Tuple[flask.Response, int]: endpoints = {'sources_url': '/api/v1/sources', 'current_user_url': '/api/v1/user', + 'all_users_url': '/api/v1/users', 'submissions_url': '/api/v1/submissions', 'replies_url': '/api/v1/replies', 'auth_token_url': '/api/v1/token'} @@ -323,6 +324,13 @@ def get_current_user() -> Tuple[flask.Response, int]: user = _authenticate_user_from_auth_header(request) return jsonify(user.to_json()), 200 + @api.route('/users', methods=['GET']) + @token_required + def get_all_users() -> Tuple[flask.Response, int]: + users = Journalist.query.all() + return jsonify( + {'users': [user.to_json(all_info=False) for user in users]}), 200 + @api.route('/logout', methods=['POST']) @token_required def logout() -> Tuple[flask.Response, int]: diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -710,15 +710,25 @@ def validate_api_token_and_get_user(token: str) -> 'Optional[Journalist]': return Journalist.query.get(data['id']) - def to_json(self) -> 'Dict[str, Union[str, bool, str]]': + def to_json(self, all_info: bool = True) -> 'Dict[str, Union[str, bool, str]]': + """Returns a JSON representation of the journalist user. If all_info is + False, potentially sensitive or extraneous fields are excluded. Note + that both representations do NOT include credentials.""" + json_user = { 'username': self.username, - 'last_login': self.last_access.isoformat() + 'Z', - 'is_admin': self.is_admin, 'uuid': self.uuid, 'first_name': self.first_name, 'last_name': self.last_name } + + if all_info is True: + json_user['is_admin'] = self.is_admin + try: + json_user['last_login'] = self.last_access.isoformat() + 'Z' + except AttributeError: + json_user['last_login'] = None + return json_user
diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -22,9 +22,9 @@ def test_unauthenticated_user_gets_all_endpoints(journalist_app): with journalist_app.test_client() as app: response = app.get(url_for('api.get_endpoints')) - expected_endpoints = ['current_user_url', 'submissions_url', - 'sources_url', 'auth_token_url', - 'replies_url'] + expected_endpoints = ['current_user_url', 'all_users_url', + 'submissions_url', 'sources_url', + 'auth_token_url', 'replies_url'] expected_endpoints.sort() sorted_observed_endpoints = list(response.json.keys()) sorted_observed_endpoints.sort() @@ -153,7 +153,8 @@ def test_user_without_token_cannot_get_protected_endpoints(journalist_app, url_for('api.single_reply', source_uuid=uuid, reply_uuid=test_files['replies'][0].uuid), url_for('api.all_source_replies', source_uuid=uuid), - url_for('api.get_current_user') + url_for('api.get_current_user'), + url_for('api.get_all_users'), ] with journalist_app.test_client() as app: @@ -639,6 +640,25 @@ def test_authorized_user_can_get_current_user_endpoint(journalist_app, assert response.json['last_name'] == test_journo['journalist'].last_name +def test_authorized_user_can_get_all_users(journalist_app, test_journo, test_admin, + journalist_api_token): + with journalist_app.test_client() as app: + response = app.get(url_for('api.get_all_users'), + headers=get_api_headers(journalist_api_token)) + + assert response.status_code == 200 + + # Ensure that all the users in the database are returned + observed_users = [user['uuid'] for user in response.json['users']] + expected_users = [user.uuid for user in Journalist.query.all()] + assert observed_users == expected_users + + # Ensure that no fields other than the expected ones are returned + expected_fields = ['first_name', 'last_name', 'username', 'uuid'] + for user in response.json['users']: + assert sorted(user.keys()) == expected_fields + + def test_request_with_missing_auth_header_triggers_403(journalist_app): with journalist_app.test_client() as app: response = app.get(url_for('api.get_current_user'),
Add `/users` endpoint to API In order to reliably update local user databases (see, for example, https://github.com/freedomofpress/securedrop-client/issues/1143), it would be useful for the API to expose a `/users` endpoint. Currently, non-admin users do not have the ability to see a list of all users via the *Journalist Interface* , so we may only want to return the UUID for each user (and potentially a property like `is_deleted` or `is_locked` if/when such functionality is implemented, cf. #5467).
Just want to make a note of what bug this would currently solve. Right now, we learn whether or not a user has been deleted through the `replies` endpoint. If a user does not have any successful replies on the server and they are deleted, we will not learn whether or not that user has been deleted. From the client, even though the user would not be able to log in, it would look like that user has an active account. Also if that user has any draft replies that never made it to the server, those replies will continue to exist locally and will continue to be attributed to the user, which others will be able to see in the GUI. A few updates on this issue: 1. We've provisionally agreed that this would be a useful endpoint to add, either in 1.6.0, or after. 2. We would likely want to return user name, first name, and last name, in addition to the UUID, but _not_ the `is_admin` flag. 3. After some back and forth, we agreed it should be called `/users`, to be consistent with the existing `/user` endpoint, and because it's more inclusive of users in different roles in an org. 4. In terms of additional disclosure of user information to non-admins, while non-admins can't currently enumerate all users, they can enumerate _many_ users, since the `/replies` endpoint discloses the same user data which would be provided by this endpoint, for users who have sent replies. 5. Once this lands, in a future release, we could consider removing the full user data from the `/replies` endpoint (returning only the UUID of reply authors). This should only be done once the production release of the SecureDrop Client no longer relies on it. I've raised my hand for putting together a PR for this issue, and then we can reason a bit more about 1) any additional impact in the context of our threat model, 2) whether or not this should land in 1.6.0.
2020-09-17T00:52:13Z
[]
[]
freedomofpress/securedrop
5,513
freedomofpress__securedrop-5513
[ "5475" ]
a1c9cbd6667a4aef7ab9c0d329317e6aed0b33da
diff --git a/securedrop/create-dev-data.py b/securedrop/create-dev-data.py --- a/securedrop/create-dev-data.py +++ b/securedrop/create-dev-data.py @@ -15,7 +15,7 @@ from sdconfig import config from db import db -from models import Journalist, Reply, Source, Submission +from models import Journalist, Reply, SeenReply, Source, Submission from specialstrings import strings @@ -138,6 +138,9 @@ def create_source_and_submissions( journalist = journalist_who_replied reply = Reply(journalist, source, fname) db.session.add(reply) + db.session.flush() + seen_reply = SeenReply(reply_id=reply.id, journalist_id=journalist.id) + db.session.add(seen_reply) db.session.commit() diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -1,7 +1,8 @@ +import collections.abc import json from datetime import datetime, timedelta -from typing import Tuple, Callable, Any +from typing import Tuple, Callable, Any, Set, Union import flask import werkzeug @@ -15,7 +16,7 @@ from db import db from journalist_app import utils -from models import (Journalist, Reply, Source, Submission, +from models import (Journalist, Reply, SeenReply, Source, Submission, LoginThrottledException, InvalidUsernameException, BadTokenException, WrongPasswordException) from sdconfig import SDConfig @@ -69,6 +70,7 @@ def get_endpoints() -> Tuple[flask.Response, int]: 'all_users_url': '/api/v1/users', 'submissions_url': '/api/v1/submissions', 'replies_url': '/api/v1/replies', + 'seen_url': '/api/v1/seen', 'auth_token_url': '/api/v1/token'} return jsonify(endpoints), 200 @@ -268,6 +270,9 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: try: db.session.add(reply) + db.session.flush() + seen_reply = SeenReply(reply_id=reply.id, journalist_id=user.id) + db.session.add(seen_reply) db.session.add(source) db.session.commit() except IntegrityError as e: @@ -311,6 +316,49 @@ def get_all_replies() -> Tuple[flask.Response, int]: return jsonify( {'replies': [reply.to_json() for reply in replies if reply.source]}), 200 + @api.route("/seen", methods=["POST"]) + @token_required + def seen() -> Tuple[flask.Response, int]: + """ + Lists or marks the source conversation items that the journalist has seen. + """ + user = _authenticate_user_from_auth_header(request) + + if request.method == "POST": + if request.json is None or not isinstance(request.json, collections.abc.Mapping): + abort(400, "Please send requests in valid JSON.") + + if not any(map(request.json.get, ["files", "messages", "replies"])): + abort(400, "Please specify the resources to mark seen.") + + # gather everything to be marked seen. if any don't exist, + # reject the request. + targets = set() # type: Set[Union[Submission, Reply]] + for file_uuid in request.json.get("files", []): + f = Submission.query.filter(Submission.uuid == file_uuid).one_or_none() + if f is None or not f.is_file: + abort(404, "file not found: {}".format(file_uuid)) + targets.add(f) + + for message_uuid in request.json.get("messages", []): + m = Submission.query.filter(Submission.uuid == message_uuid).one_or_none() + if m is None or not m.is_message: + abort(404, "message not found: {}".format(message_uuid)) + targets.add(m) + + for reply_uuid in request.json.get("replies", []): + r = Reply.query.filter(Reply.uuid == reply_uuid).one_or_none() + if r is None: + abort(404, "reply not found: {}".format(reply_uuid)) + targets.add(r) + + # now mark everything seen. + utils.mark_seen(list(targets), user) + + return jsonify({"message": "resources marked seen"}), 200 + + abort(405) + @api.route('/user', methods=['GET']) @token_required def get_current_user() -> Tuple[flask.Response, int]: diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -13,16 +13,15 @@ url_for, ) from flask_babel import gettext -from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound from db import db -from models import Reply, SeenFile, SeenMessage, SeenReply, Submission +from models import Reply, Submission from journalist_app.forms import ReplyForm from journalist_app.utils import (make_star_true, make_star_false, get_source, delete_collection, col_download_unread, col_download_all, col_star, col_un_star, - col_delete) + col_delete, mark_seen) def make_blueprint(config): @@ -94,25 +93,18 @@ def download_single_file(filesystem_id, fn): # mark as seen by the current user try: - journalist_id = g.get("user").id + journalist = g.get("user") if fn.endswith("reply.gpg"): reply = Reply.query.filter(Reply.filename == fn).one() - seen_reply = SeenReply(reply_id=reply.id, journalist_id=journalist_id) - db.session.add(seen_reply) + mark_seen([reply], journalist) elif fn.endswith("-doc.gz.gpg") or fn.endswith("doc.zip.gpg"): file = Submission.query.filter(Submission.filename == fn).one() - seen_file = SeenFile(file_id=file.id, journalist_id=journalist_id) - db.session.add(seen_file) + mark_seen([file], journalist) else: message = Submission.query.filter(Submission.filename == fn).one() - seen_message = SeenMessage(message_id=message.id, journalist_id=journalist_id) - db.session.add(seen_message) - - db.session.commit() + mark_seen([message], journalist) except NoResultFound as e: current_app.logger.error("Could not mark {} as seen: {}".format(fn, e)) - except IntegrityError: - pass # expected not to store that a file was seen by the same user multiple times return send_file(current_app.storage.path(filesystem_id, fn), mimetype="application/pgp-encrypted") diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -9,6 +9,7 @@ from flask import (g, flash, current_app, abort, send_file, redirect, url_for, render_template, Markup, sessions, request) from flask_babel import gettext, ngettext +from sqlalchemy.exc import IntegrityError import i18n @@ -163,6 +164,32 @@ def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: return True +def mark_seen(targets: List[Union[Submission, Reply]], user: Journalist) -> None: + """ + Marks a list of submissions or replies seen by the given journalist. + """ + for t in targets: + try: + if isinstance(t, Submission): + t.downloaded = True + if t.is_file: + sf = SeenFile(file_id=t.id, journalist_id=user.id) + db.session.add(sf) + elif t.is_message: + sm = SeenMessage(message_id=t.id, journalist_id=user.id) + db.session.add(sm) + db.session.commit() + elif isinstance(t, Reply): + sr = SeenReply(reply_id=t.id, journalist_id=user.id) + db.session.add(sr) + db.session.commit() + except IntegrityError as e: + db.session.rollback() + if 'UNIQUE constraint failed' in str(e): + continue + raise + + def download(zip_basename: str, submissions: List[Union[Submission, Reply]]) -> werkzeug.Response: """Send client contents of ZIP-file *zip_basename*-<timestamp>.zip containing *submissions*. The ZIP-file, being a @@ -179,31 +206,7 @@ def download(zip_basename: str, submissions: List[Union[Submission, Reply]]) -> zip_basename, datetime.datetime.utcnow().strftime("%Y-%m-%d--%H-%M-%S") ) - # mark as seen by the current user - journalist_id = g.get("user").id - for item in submissions: - if item.filename.endswith("reply.gpg"): - already_seen = SeenReply.query.filter_by( - reply_id=item.id, journalist_id=journalist_id - ).one_or_none() - if not already_seen: - seen_reply = SeenReply(reply_id=item.id, journalist_id=journalist_id) - db.session.add(seen_reply) - elif item.filename.endswith("-doc.gz.gpg"): - already_seen = SeenFile.query.filter_by( - file_id=item.id, journalist_id=journalist_id - ).one_or_none() - if not already_seen: - seen_file = SeenFile(file_id=item.id, journalist_id=journalist_id) - db.session.add(seen_file) - else: - already_seen = SeenMessage.query.filter_by( - message_id=item.id, journalist_id=journalist_id - ).one_or_none() - if not already_seen: - seen_message = SeenMessage(message_id=item.id, journalist_id=journalist_id) - db.session.add(seen_message) - db.session.commit() + mark_seen(submissions, g.user) return send_file( zf.name, diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -100,11 +100,10 @@ def journalist_filename(self) -> str: def documents_messages_count(self) -> 'Dict[str, int]': self.docs_msgs_count = {'messages': 0, 'documents': 0} for submission in self.submissions: - if submission.filename.endswith('msg.gpg'): - self.docs_msgs_count['messages'] += 1 - elif (submission.filename.endswith('doc.gz.gpg') or - submission.filename.endswith('doc.zip.gpg')): - self.docs_msgs_count['documents'] += 1 + if submission.is_message: + self.docs_msgs_count["messages"] += 1 + elif submission.is_file: + self.docs_msgs_count["documents"] += 1 return self.docs_msgs_count @property @@ -212,7 +211,23 @@ def __init__(self, source: Source, filename: str) -> None: def __repr__(self) -> str: return '<Submission %r>' % (self.filename) - def to_json(self) -> 'Dict[str, Union[str, int, bool]]': + @property + def is_file(self) -> bool: + return self.filename.endswith("doc.gz.gpg") or self.filename.endswith("doc.zip.gpg") + + @property + def is_message(self) -> bool: + return self.filename.endswith("msg.gpg") + + def to_json(self) -> "Dict[str, Union[str, int, bool]]": + seen_by = { + f.journalist.uuid for f in SeenFile.query.filter(SeenFile.file_id == self.id) + if f.journalist + } + seen_by.update({ + m.journalist.uuid for m in SeenMessage.query.filter(SeenMessage.message_id == self.id) + if m.journalist + }) json_submission = { 'source_url': url_for('api.single_source', source_uuid=self.source.uuid) if self.source else None, @@ -221,11 +236,14 @@ def to_json(self) -> 'Dict[str, Union[str, int, bool]]': submission_uuid=self.uuid) if self.source else None, 'filename': self.filename, 'size': self.size, - 'is_read': self.downloaded, + "is_file": self.is_file, + "is_message": self.is_message, + "is_read": self.seen, 'uuid': self.uuid, 'download_url': url_for('api.download_submission', source_uuid=self.source.uuid, submission_uuid=self.uuid) if self.source else None, + 'seen_by': list(seen_by) } return json_submission @@ -284,17 +302,21 @@ def __init__(self, def __repr__(self) -> str: return '<Reply %r>' % (self.filename) - def to_json(self) -> 'Dict[str, Union[str, int, bool]]': - username = "deleted" - first_name = "" - last_name = "" - uuid = "deleted" + def to_json(self) -> "Dict[str, Union[str, int, bool]]": + journalist_username = "deleted" + journalist_first_name = "" + journalist_last_name = "" + journalist_uuid = "deleted" if self.journalist: - username = self.journalist.username - first_name = self.journalist.first_name - last_name = self.journalist.last_name - uuid = self.journalist.uuid - json_submission = { + journalist_username = self.journalist.username + journalist_first_name = self.journalist.first_name + journalist_last_name = self.journalist.last_name + journalist_uuid = self.journalist.uuid + seen_by = [ + r.journalist.uuid for r in SeenReply.query.filter(SeenReply.reply_id == self.id) + if r.journalist + ] + json_reply = { 'source_url': url_for('api.single_source', source_uuid=self.source.uuid) if self.source else None, 'reply_url': url_for('api.single_reply', @@ -302,14 +324,15 @@ def to_json(self) -> 'Dict[str, Union[str, int, bool]]': reply_uuid=self.uuid) if self.source else None, 'filename': self.filename, 'size': self.size, - 'journalist_username': username, - 'journalist_first_name': first_name, - 'journalist_last_name': last_name, - 'journalist_uuid': uuid, + 'journalist_username': journalist_username, + 'journalist_first_name': journalist_first_name, + 'journalist_last_name': journalist_last_name, + 'journalist_uuid': journalist_uuid, 'uuid': self.uuid, 'is_deleted_by_source': self.deleted_by_source, + 'seen_by': seen_by } - return json_submission + return json_reply class SourceStar(db.Model):
diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -208,7 +208,7 @@ def test_submissions(journalist_app): def test_files(journalist_app, test_journo): with journalist_app.app_context(): source, codename = utils.db_helper.init_source() - utils.db_helper.submit(source, 2) + utils.db_helper.submit(source, 2, submission_type="file") utils.db_helper.reply(test_journo['journalist'], source, 1) return {'source': source, 'codename': codename, diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -18,6 +18,7 @@ import crypto_util import journalist_app as journalist_app_module +from journalist_app.utils import mark_seen import models from db import db from models import ( @@ -1847,11 +1848,11 @@ def test_delete_collection_updates_db(journalist_app, test_journo, test_source): source = Source.query.get(test_source["id"]) journo = Journalist.query.get(test_journo["id"]) files = utils.db_helper.submit(source, 2) - utils.db_helper.mark_files_seen(journo.id, files) + mark_seen(files, journo) messages = utils.db_helper.submit(source, 2) - utils.db_helper.mark_messages_seen(journo.id, messages) + mark_seen(messages, journo) replies = utils.db_helper.reply(journo, source, 2) - utils.db_helper.mark_replies_seen(journo.id, replies) + mark_seen(replies, journo) journalist_app_module.utils.delete_collection(test_source["filesystem_id"]) @@ -2074,9 +2075,7 @@ def test_download_selected_submissions_and_replies_previously_seen( db.session.add(seen_file) seen_message = SeenMessage(message_id=selected_submissions[1].id, journalist_id=journo.id) db.session.add(seen_message) - for reply in selected_replies: - seen_reply = SeenReply(reply_id=reply.id, journalist_id=journo.id) - db.session.add(seen_reply) + mark_seen(selected_replies, journo) db.session.commit() with journalist_app.test_client() as app: diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -31,7 +31,7 @@ def test_unauthenticated_user_gets_all_endpoints(journalist_app): expected_endpoints = ['current_user_url', 'all_users_url', 'submissions_url', 'sources_url', - 'auth_token_url', 'replies_url'] + 'auth_token_url', 'replies_url', 'seen_url'] expected_endpoints.sort() sorted_observed_endpoints = list(response.json.keys()) sorted_observed_endpoints.sort() @@ -1039,3 +1039,127 @@ def test_revoke_token(journalist_app, test_journo, journalist_api_token): resp = app.get(url_for('api.get_all_sources'), headers=get_api_headers(journalist_api_token)) assert resp.status_code == 403 + + +def test_seen(journalist_app, journalist_api_token, test_files, test_journo, test_submissions): + """ + Happy path for seen: marking things seen works. + """ + with journalist_app.test_client() as app: + replies_url = url_for('api.get_all_replies') + seen_url = url_for('api.seen') + submissions_url = url_for('api.get_all_submissions') + headers = get_api_headers(journalist_api_token) + + # check that /submissions contains no seen items + response = app.get(submissions_url, headers=headers) + assert response.status_code == 200 + assert not any([s["seen_by"] for s in response.json["submissions"]]) + + # check that /replies only contains seen items + response = app.get(replies_url, headers=headers) + assert response.status_code == 200 + assert all([r["seen_by"] for r in response.json["replies"]]) + + # now mark one of each type of conversation item seen + file_uuid = test_files['submissions'][0].uuid + msg_uuid = test_submissions['submissions'][0].uuid + reply_uuid = test_files['replies'][0].uuid + data = { + "files": [file_uuid], + "messages": [msg_uuid], + "replies": [reply_uuid], + } + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 200 + assert response.json["message"] == "resources marked seen" + + # check that /submissions now contains the seen items + response = app.get(submissions_url, headers=headers) + assert response.status_code == 200 + assert [ + s for s in response.json["submissions"] + if s["is_file"] and s["uuid"] == file_uuid + and test_journo["uuid"] in s["seen_by"] + ] + assert [ + s for s in response.json["submissions"] + if s["is_message"] and s["uuid"] == msg_uuid + and test_journo["uuid"] in s["seen_by"] + ] + + # check that /replies still only contains one seen reply + response = app.get(replies_url, headers=headers) + assert response.status_code == 200 + assert len(response.json["replies"]) == 1 + assert all([r["seen_by"] for r in response.json["replies"]]) + + # now mark the same things seen. this should be fine. + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 200 + assert response.json["message"] == "resources marked seen" + + # check that /submissions still only has the test journalist + # once in the seen_by list of the submissions we marked + response = app.get(submissions_url, headers=headers) + assert response.status_code == 200 + assert [ + s for s in response.json["submissions"] + if s["uuid"] in [file_uuid, msg_uuid] + and s["seen_by"] == [test_journo["uuid"]] + ] + + # check that /replies still only contains one seen reply + response = app.get(replies_url, headers=headers) + assert response.status_code == 200 + assert len(response.json["replies"]) == 1 + assert all([r["seen_by"] for r in response.json["replies"]]) + + +def test_seen_bad_requests(journalist_app, journalist_api_token): + """ + Check that /seen rejects invalid requests. + """ + with journalist_app.test_client() as app: + seen_url = url_for('api.seen') + headers = get_api_headers(journalist_api_token) + + # invalid JSON + data = "not a mapping" + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 400 + assert response.json["message"] == "Please send requests in valid JSON." + + # valid JSON, but with invalid content + data = {"valid mapping": False} + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 400 + assert response.json["message"] == "Please specify the resources to mark seen." + + # unsupported HTTP method + response = app.head(seen_url, headers=headers) + assert response.status_code == 405 + + # nonexistent file + data = { + "files": ["not-a-file"], + } + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 404 + assert response.json["message"] == "file not found: not-a-file" + + # nonexistent message + data = { + "messages": ["not-a-message"], + } + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 404 + assert response.json["message"] == "message not found: not-a-message" + + # nonexistent reply + data = { + "replies": ["not-a-reply"], + } + response = app.post(seen_url, data=json.dumps(data), headers=headers) + assert response.status_code == 404 + assert response.json["message"] == "reply not found: not-a-reply" diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -4,6 +4,7 @@ """ import datetime import math +import io import os import random from typing import Dict, List @@ -12,7 +13,8 @@ from flask import current_app from db import db -from models import Journalist, Reply, SeenFile, SeenMessage, SeenReply, Source, Submission +from journalist_app.utils import mark_seen +from models import Journalist, Reply, SeenReply, Source, Submission from sdconfig import config os.environ['SECUREDROP_ENV'] = 'test' # noqa @@ -81,6 +83,9 @@ def reply(journalist, source, num_replies): reply = Reply(journalist, source, fname) replies.append(reply) db.session.add(reply) + db.session.flush() + seen_reply = SeenReply(reply_id=reply.id, journalist_id=journalist.id) + db.session.add(seen_reply) db.session.commit() return replies @@ -148,7 +153,7 @@ def init_source(): return source, codename -def submit(source, num_submissions): +def submit(source, num_submissions, submission_type="message"): """Generates and submits *num_submissions* :class:`Submission`s on behalf of a :class:`Source` *source*. @@ -168,12 +173,21 @@ def submit(source, num_submissions): for _ in range(num_submissions): source.interaction_count += 1 source.pending = False - fpath = current_app.storage.save_message_submission( - source.filesystem_id, - source.interaction_count, - source.journalist_filename, - str(os.urandom(1)) - ) + if submission_type == "file": + fpath = current_app.storage.save_file_submission( + source.filesystem_id, + source.interaction_count, + source.journalist_filename, + "pipe.txt", + io.BytesIO(b"Ceci n'est pas une pipe.") + ) + else: + fpath = current_app.storage.save_message_submission( + source.filesystem_id, + source.interaction_count, + source.journalist_filename, + str(os.urandom(1)) + ) submission = Submission(source, fpath) submissions.append(submission) db.session.add(source) @@ -192,38 +206,6 @@ def new_codename(client, session): return codename -def mark_replies_seen(journalist_id: int, replies: List[Reply]): - """ - Mark replies as seen. - """ - for reply in replies: - seen_reply = SeenReply(journalist_id=journalist_id, reply_id=reply.id) - db.session.add(seen_reply) - db.session.commit() - - -def mark_messages_seen(journalist_id: int, messages: List[Submission]): - """ - Mark messages as seen. - """ - for message in messages: - message.downloaded = True - seen_message = SeenMessage(journalist_id=journalist_id, message_id=message.id) - db.session.add(seen_message) - db.session.commit() - - -def mark_files_seen(journalist_id: int, files: List[Submission]): - """ - Mark files as seen. - """ - for file in files: - file.downloaded = True - seen_file = SeenFile(journalist_id=journalist_id, file_id=file.id) - db.session.add(seen_file) - db.session.commit() - - def bulk_setup_for_seen_only(journo) -> List[Dict]: """ Create some sources with some seen submissions that are not marked as 'downloaded' in the @@ -247,9 +229,9 @@ def bulk_setup_for_seen_only(journo) -> List[Dict]: seen_messages = random.sample(messages, math.ceil(len(messages) / 2)) seen_replies = random.sample(replies, math.ceil(len(replies) / 2)) - mark_files_seen(journo.id, seen_files) - mark_messages_seen(journo.id, seen_messages) - mark_replies_seen(journo.id, seen_replies) + mark_seen(seen_files, journo) + mark_seen(seen_messages, journo) + mark_seen(seen_replies, journo) unseen_files = list(set(files).difference(set(seen_files))) unseen_messages = list(set(messages).difference(set(seen_messages)))
Add API endpoints for `seen_by` As part of adding SecureDrop Client support for highlighting sources with unseen submissions (https://github.com/freedomofpress/securedrop-client/issues/187), we need to make server-side changes to record which journalist has seen a message, file, or reply. This breaks down into two main tasks: - issue #5474: migrating the existing `downloaded` status and business logic to `seen_by` (for messages, files, and replies); - this issue: adding API endpoints for updating and retrieving `seen_by` status ## Technical specification A working draft specification can be found here: https://docs.google.com/document/d/1szPEKI1gTpRiM_YI87plKgiW39T7zT4Y4HG0uFnsJD4/edit# ## Functional requirements **Setting status via API:** As an API user, I should be able to set the `seen_by` status for a file, message, or reply to the authenticated user. **Retrieving status via API:** As an API user, I should be able to retrieve the `seen_by` status for any message, file or reply. ## Performance requirements We want to keep API consumers like the SecureDrop Client responsive with a large number of sources and submissions per source: https://github.com/freedomofpress/securedrop-client/wiki/Scalability-&-Performance#scalability-requirements Our performance goals may impact decisions such as how many API roundtrips are required to update or retrieve information, how much data is returned, and what operations can be grouped together. As part of this issue, we should aim to obtain before/after benchmarks e.g. of metadata sync operations for a server with a large number of submissions, so we can quantify the performance impact.
2020-09-17T19:53:08Z
[]
[]
freedomofpress/securedrop
5,549
freedomofpress__securedrop-5549
[ "5543" ]
eb8d03e66b4b2628b78eb4d8a532e2932728d137
diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -218,22 +218,34 @@ def download(zip_basename: str, submissions: List[Union[Submission, Reply]]) -> def delete_file_object(file_object: Union[Submission, Reply]) -> None: path = current_app.storage.path(file_object.source.filesystem_id, file_object.filename) - current_app.storage.move_to_shredder(path) - db.session.delete(file_object) - db.session.commit() + try: + current_app.storage.move_to_shredder(path) + except ValueError as e: + current_app.logger.error("could not queue file for deletion: %s", e) + raise + finally: + db.session.delete(file_object) + db.session.commit() def bulk_delete( filesystem_id: str, items_selected: List[Union[Submission, Reply]] ) -> werkzeug.Response: + deletion_errors = 0 for item in items_selected: - delete_file_object(item) + try: + delete_file_object(item) + except ValueError: + deletion_errors += 1 flash(ngettext("Submission deleted.", "{num} submissions deleted.".format( num=len(items_selected)), len(items_selected)), "notification") + if deletion_errors > 0: + current_app.logger.error("Disconnected submission entries (%d) were detected", + deletion_errors) return redirect(url_for('col.col', filesystem_id=filesystem_id))
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -1940,6 +1940,94 @@ def assertion(): utils.asynchronous.wait_for_assertion(assertion) +def test_bulk_delete_deletes_db_entries(journalist_app, + test_source, + test_journo, + config): + """ + Verify that when files are deleted, the corresponding db entries are + also deleted. + """ + + with journalist_app.app_context(): + source = Source.query.get(test_source['id']) + journo = Journalist.query.get(test_journo['id']) + + utils.db_helper.submit(source, 2) + utils.db_helper.reply(journo, source, 2) + + dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) + assert os.path.exists(dir_source_docs) + + subs = Submission.query.filter_by(source_id=source.id).all() + assert subs + + replies = Reply.query.filter_by(source_id=source.id).all() + assert replies + + file_list = [] + file_list.extend(subs) + file_list.extend(replies) + + with journalist_app.test_request_context('/'): + journalist_app_module.utils.bulk_delete(test_source['filesystem_id'], + file_list) + + def db_assertion(): + subs = Submission.query.filter_by(source_id=source.id).all() + assert not subs + + replies = Reply.query.filter_by(source_id=source.id).all() + assert not replies + + utils.asynchronous.wait_for_assertion(db_assertion) + + +def test_bulk_delete_works_when_files_absent(journalist_app, + test_source, + test_journo, + config): + """ + Verify that when files are deleted but are already missing, + the corresponding db entries are still + """ + + with journalist_app.app_context(): + source = Source.query.get(test_source['id']) + journo = Journalist.query.get(test_journo['id']) + + utils.db_helper.submit(source, 2) + utils.db_helper.reply(journo, source, 2) + + dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) + assert os.path.exists(dir_source_docs) + + subs = Submission.query.filter_by(source_id=source.id).all() + assert subs + + replies = Reply.query.filter_by(source_id=source.id).all() + assert replies + + file_list = [] + file_list.extend(subs) + file_list.extend(replies) + + with journalist_app.test_request_context('/'): + with patch("store.Storage.move_to_shredder") as delMock: + delMock.side_effect = ValueError + journalist_app_module.utils.bulk_delete(test_source['filesystem_id'], + file_list) + + def db_assertion(): + subs = Submission.query.filter_by(source_id=source.id).all() + assert not subs + + replies = Reply.query.filter_by(source_id=source.id).all() + assert not replies + + utils.asynchronous.wait_for_assertion(db_assertion) + + def test_login_with_invalid_password_doesnt_call_argon2(mocker, test_journo): mock_argon2 = mocker.patch('models.argon2.verify') invalid_pw = 'a'*(Journalist.MAX_PASSWORD_LEN + 1)
Attempting to delete a reply whose corresponding GPG file is missing generates a 500 in the JI ## Description Attempting to delete a reply whose corresponding GPG file is missing generates a 500 in the JI ## Steps to Reproduce In the JI: - reply to a source On the app server: - delete the corresponding reply file in `/var/lib/securedrop/store` In the JI: - delete the reply ## Expected Behavior Good question! I would err on the side of deleting the db entry and calling it done. But it could flag the issue to the user in more detail than that provided by the 500 error page text. This also has issues for deleting multiple files - if multiples are selected, deletion stops at the missing reply file. Expected behaviour in that case would be to continue with the operation. ## Actual Behavior 500 error thrown. If multiple files selected for deletion, all files listed after the buster reply file remain in place.
possibly related to https://github.com/freedomofpress/securedrop/issues/4787 I was going to agree that the file being gone is the desired state, so we could just purge the `Reply` record and continue, but a missing file for a reply probably indicates a problem which should be brought to the attention of the admin. Either there's a hardware or filesystem problem, or someone's been mucking about in the store. This situation is going to cause the same problem as #4787 but right now the cleanup tool we'd tell the admin to run does not address replies, just submissions. Just adding my standard caveat, let's try for a simple fix for 1.6.0 as discussed, but if scope expands significantly we may have to defer. :) I think the recco in #4787 for the related case is the best option overall - delete the entry and flash a message like "the database and file store are in an inconsistent state - this can be manually resolved by an administrator, so go get one." @rmol are you sure the cleanup tool doesn't sort out replies? ISTR you adding that later in. @zenmonkeykstop Pretty sure it [only checks submissions](https://github.com/freedomofpress/securedrop/blob/f81e41539bc5e5ae8b9a443ead719513622553c8/securedrop/management/submissions.py#L14). I think you're remembering that the inverse operation, looking for files without database records, [needed improving](https://github.com/freedomofpress/securedrop/commit/0644b954576fad2fa7c9636422137506cf5943e9) so that reply files wouldn't be counted as disconnected because they didn't have submission records.
2020-10-01T15:24:28Z
[]
[]
freedomofpress/securedrop
5,559
freedomofpress__securedrop-5559
[ "5433" ]
8b50a9e3c438a79be0440d74ba6367092feb55ab
diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -1,5 +1,4 @@ import json -import platform from flask import Blueprint, current_app, make_response @@ -8,6 +7,10 @@ import version +with open("/etc/lsb-release", "r") as f: + server_os = f.readlines()[1].split("=")[1].strip("\n") + + def make_blueprint(config): view = Blueprint('api', __name__) @@ -17,7 +20,7 @@ def metadata(): 'allow_document_uploads': current_app.instance_config.allow_document_uploads, 'gpg_fpr': config.JOURNALIST_KEY, 'sd_version': version.__version__, - 'server_os': platform.linux_distribution()[1], + 'server_os': server_os, 'supported_languages': config.SUPPORTED_LOCALES, 'v2_source_url': get_sourcev2_url(), 'v3_source_url': get_sourcev3_url()
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -583,8 +583,7 @@ def test_why_journalist_key(source_app): def test_metadata_route(config, source_app): - with patch.object(source_app_api.platform, "linux_distribution") as mocked_platform: - mocked_platform.return_value = ("Ubuntu", "16.04", "xenial") + with patch.object(source_app_api, "server_os", new="16.04"): with source_app.test_client() as app: resp = app.get(url_for('api.metadata')) assert resp.status_code == 200
Update removed `platform.linux_distribution` funtion call in Python 3.8 ## Description We are using [platform.linux_distribution](https://github.com/freedomofpress/securedrop/blob/4c73102ca9151a86a08396de40163b48a5a21768/securedrop/source_app/api.py#L20) function in our metadata endpoint. But, this function was deprecated from Python3.5 and totally removed from Python 3.8. ## Solution We can directly read the `/etc/lsb-release` and `/etc/os-release` file as required.
#4768 is dependent on this. @kushaldas and @eloquence, I can take care of this if it's OK with you.
2020-10-07T02:36:53Z
[]
[]
freedomofpress/securedrop
5,573
freedomofpress__securedrop-5573
[ "4787" ]
d3b76c218f730948f04395648fc0cb9abda6b7e7
diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +from pathlib import Path + from flask import ( Blueprint, abort, @@ -93,6 +95,18 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: if '..' in fn or fn.startswith('/'): abort(404) + file = current_app.storage.path(filesystem_id, fn) + if not Path(file).is_file(): + flash( + gettext( + "Your download failed because a file could not be found. An admin can find " + + "more information in the system and monitoring logs." + ), + "error" + ) + current_app.logger.error("File {} not found".format(file)) + return redirect(url_for("col.col", filesystem_id=filesystem_id)) + # mark as seen by the current user try: journalist = g.get("user") diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -3,6 +3,7 @@ import datetime import os from typing import Optional, List, Union, Any +from urllib.parse import urlparse import flask import werkzeug @@ -190,7 +191,7 @@ def mark_seen(targets: List[Union[Submission, Reply]], user: Journalist) -> None raise -def download(zip_basename: str, submissions: List[Union[Submission, Reply]]) -> flask.Response: +def download(zip_basename: str, submissions: List[Union[Submission, Reply]]) -> werkzeug.Response: """Send client contents of ZIP-file *zip_basename*-<timestamp>.zip containing *submissions*. The ZIP-file, being a :class:`tempfile.NamedTemporaryFile`, is stored on disk only @@ -201,7 +202,19 @@ def download(zip_basename: str, submissions: List[Union[Submission, Reply]]) -> :param list submissions: A list of :class:`models.Submission`s to include in the ZIP-file. """ - zf = current_app.storage.get_bulk_archive(submissions, zip_directory=zip_basename) + try: + zf = current_app.storage.get_bulk_archive(submissions, zip_directory=zip_basename) + except FileNotFoundError: + flash( + gettext( + "Your download failed because a file could not be found. An admin can find " + + "more information in the system and monitoring logs." + ), + "error" + ) + referrer = urlparse(str(request.referrer)).path + return redirect(referrer) + attachment_filename = "{}--{}.zip".format( zip_basename, datetime.datetime.utcnow().strftime("%Y-%m-%d--%H-%M-%S") ) diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -201,6 +201,8 @@ def get_bulk_archive(self, for i in selected_submissions]) # The below nested for-loops are there to create a more usable # folder structure per #383 + missing_files = False + with zipfile.ZipFile(zip_file, 'w') as zip: for source in sources: fname = "" @@ -208,18 +210,27 @@ def get_bulk_archive(self, if s.source.journalist_designation == source] for submission in submissions: filename = self.path(submission.source.filesystem_id, submission.filename) - document_number = submission.filename.split('-')[0] - if zip_directory == submission.source.journalist_filename: - fname = zip_directory + + if os.path.exists(filename): + document_number = submission.filename.split('-')[0] + if zip_directory == submission.source.journalist_filename: + fname = zip_directory + else: + fname = os.path.join(zip_directory, source) + zip.write(filename, arcname=os.path.join( + fname, + "%s_%s" % (document_number, + submission.source.last_updated.date()), + os.path.basename(filename) + )) else: - fname = os.path.join(zip_directory, source) - zip.write(filename, arcname=os.path.join( - fname, - "%s_%s" % (document_number, - submission.source.last_updated.date()), - os.path.basename(filename) - )) - return zip_file + missing_files = True + current_app.logger.error("File {} not found".format(filename)) + + if missing_files: + raise FileNotFoundError + else: + return zip_file def move_to_shredder(self, path: str) -> None: """
diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -753,6 +753,17 @@ def cookie_string_from_selenium_cookies(cookies): assert self.secret_message == submission + def _journalist_downloads_message_missing_file(self): + self._journalist_selects_the_first_source() + + self.wait_for(lambda: self.driver.find_element_by_css_selector("ul#submissions")) + + submissions = self.driver.find_elements_by_css_selector("#submissions a") + assert 1 == len(submissions) + + file_link = submissions[0] + file_link.click() + def _journalist_composes_reply(self): reply_text = ( "Thanks for the documents. Can you submit more " "information about the main program?" @@ -1097,3 +1108,42 @@ def _journalist_uses_js_buttons_to_download_unread(self): for checkbox in checkboxes: classes = checkbox.get_attribute("class") assert "unread-cb" in classes + + def _journalist_sees_missing_file_error_message(self): + notification = self.driver.find_element_by_css_selector(".error") + + if self.accept_languages is None: + expected_text = ( + "Your download failed because a file could not be found. An admin can find " + + "more information in the system and monitoring logs." + ) + assert expected_text == notification.text + + def _journalist_is_on_collection_page(self): + return self.wait_for( + lambda: self.driver.find_element_by_css_selector("div.journalist-view-single") + ) + + def _journalist_clicks_source_unread(self): + self.driver.find_element_by_css_selector("span.unread a").click() + + def _journalist_selects_first_source_then_download_all(self): + checkboxes = self.driver.find_elements_by_name("cols_selected") + assert len(checkboxes) == 1 + checkboxes[0].click() + + self.driver.find_element_by_xpath("//button[@value='download-all']").click() + + def _journalist_selects_first_source_then_download_unread(self): + checkboxes = self.driver.find_elements_by_name("cols_selected") + assert len(checkboxes) == 1 + checkboxes[0].click() + + self.driver.find_element_by_xpath("//button[@value='download-unread']").click() + + def _journalist_selects_message_then_download_selected(self): + checkboxes = self.driver.find_elements_by_name("doc_names_selected") + assert len(checkboxes) == 1 + checkboxes[0].click() + + self.driver.find_element_by_xpath("//button[@value='download']").click() diff --git a/securedrop/tests/functional/test_journalist.py b/securedrop/tests/functional/test_journalist.py --- a/securedrop/tests/functional/test_journalist.py +++ b/securedrop/tests/functional/test_journalist.py @@ -15,6 +15,9 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # +from pathlib import Path + +import pytest from . import functional_test as ft from . import journalist_navigation_steps @@ -76,3 +79,76 @@ def test_journalist_interface_ui_with_modal(self): self._journalist_selects_the_first_source() self._journalist_uses_js_buttons_to_download_unread() self._journalist_delete_all_confirmation() + + +class TestJournalistMissingFile( + ft.FunctionalTest, + source_navigation_steps.SourceNavigationStepsMixin, + journalist_navigation_steps.JournalistNavigationStepsMixin +): + """Test error handling when a message file has been deleted from disk but remains in the + database. Ref #4787.""" + + @pytest.fixture(scope="function") + def missing_msg_file(self): + """Fixture to setup the message with missing file used in the following tests.""" + # Submit a message + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_submits_a_message() + self._source_logs_out() + + # Remove the message file from the store + storage_path = Path(self.journalist_app.storage.storage_path) + msg_files = [p for p in storage_path.rglob("*") if p.is_file()] + assert len(msg_files) == 1 + msg_files[0].unlink() + + self.switch_to_firefox_driver() + + yield + + self.switch_to_torbrowser_driver() + + def test_download_source_unread(self, missing_msg_file): + """Test behavior when the journalist clicks on the source's "n unread" button from the + journalist home page.""" + self._journalist_logs_in() + self._journalist_clicks_source_unread() + self._journalist_sees_missing_file_error_message() + self._is_on_journalist_homepage() + + def test_select_source_and_download_all(self, missing_msg_file): + """Test behavior when the journalist selects the source then clicks the "Download" button + from the journalist home page.""" + self._journalist_logs_in() + self._journalist_selects_first_source_then_download_all() + self._journalist_sees_missing_file_error_message() + self._is_on_journalist_homepage() + + def test_select_source_and_download_unread(self, missing_msg_file): + """Test behavior when the journalist selects the source then clicks the "Download Unread" + button from the journalist home page.""" + self._journalist_logs_in() + self._journalist_selects_first_source_then_download_unread() + self._journalist_sees_missing_file_error_message() + self._is_on_journalist_homepage() + + def test_download_message(self, missing_msg_file): + """Test behavior when the journalist clicks on the individual message from the source page. + """ + self._journalist_logs_in() + self._journalist_checks_messages() + self._journalist_downloads_message_missing_file() + self._journalist_sees_missing_file_error_message() + self._journalist_is_on_collection_page() + + def test_select_message_and_download_selected(self, missing_msg_file): + """Test behavior when the journalist selects the individual message from the source page + then clicks "Download Selected".""" + self._journalist_logs_in() + self._journalist_selects_the_first_source() + self._journalist_selects_message_then_download_selected() + self._journalist_sees_missing_file_error_message() + self._journalist_is_on_collection_page() diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -2,7 +2,9 @@ import base64 import binascii import io +from mock import call import os +from pathlib import Path import pytest import random import zipfile @@ -2286,6 +2288,97 @@ def test_download_selected_submissions_previously_downloaded( ) [email protected](scope="function") +def selected_missing_files(journalist_app, test_source): + """Fixture for the download tests with missing files in storage.""" + source = Source.query.get(test_source["id"]) + submissions = utils.db_helper.submit(source, 2) + selected = sorted([s.filename for s in submissions]) + + storage_path = Path(journalist_app.storage.storage_path) + msg_files = sorted([p for p in storage_path.rglob("*") if p.is_file()]) + assert len(msg_files) == 2 + for file in msg_files: + file.unlink() + + yield selected + + +def test_download_selected_submissions_missing_files( + journalist_app, test_journo, test_source, mocker, selected_missing_files +): + """Tests download of selected submissions with missing files in storage.""" + mocked_error_logger = mocker.patch('journalist.app.logger.error') + journo = Journalist.query.get(test_journo["id"]) + + with journalist_app.test_client() as app: + _login_user( + app, + journo.username, + test_journo["password"], + test_journo["otp_secret"] + ) + resp = app.post( + url_for("main.bulk"), + data=dict( + action="download", + filesystem_id=test_source["filesystem_id"], + doc_names_selected=selected_missing_files, + ) + ) + + assert resp.status_code == 302 + + expected_calls = [] + for file in selected_missing_files: + missing_file = ( + Path(journalist_app.storage.storage_path) + .joinpath(test_source["filesystem_id"]) + .joinpath(file) + .as_posix() + ) + expected_calls.append(call("File {} not found".format(missing_file))) + + mocked_error_logger.assert_has_calls(expected_calls) + + +def test_download_single_submission_missing_file( + journalist_app, test_journo, test_source, mocker, selected_missing_files +): + """Tests download of single submissions with missing files in storage.""" + mocked_error_logger = mocker.patch('journalist.app.logger.error') + journo = Journalist.query.get(test_journo["id"]) + missing_file = selected_missing_files[0] + + with journalist_app.test_client() as app: + _login_user( + app, + journo.username, + test_journo["password"], + test_journo["otp_secret"] + ) + resp = app.get( + url_for( + "col.download_single_file", + filesystem_id=test_source["filesystem_id"], + fn=missing_file, + ) + ) + + assert resp.status_code == 302 + + missing_file = ( + Path(journalist_app.storage.storage_path) + .joinpath(test_source["filesystem_id"]) + .joinpath(missing_file) + .as_posix() + ) + + mocked_error_logger.assert_called_once_with( + "File {} not found".format(missing_file) + ) + + def test_download_unread_all_sources(journalist_app, test_journo): """ Test that downloading all unread creates a zip that contains all unread submissions from the
unhandled FileNotFoundError when files have been manually deleted from disk ## Description In 1.0.0, we introduced logic for an admin to check if there are files that have been deleted on disk but not had their corresponding db rows deleted. Right now in the JI, an unhandled exception will occur in the JI if a user tries to download all submissions and there are any missing files on disk. ## Steps to Reproduce 1. Submit a file as a source 2. Delete that file on the server at the filesystem level 3. Now download the file from the journalist interface (e.g. Select All -> Download) ## Expected Behavior All files on the server are downloaded. ## Actual Behavior 500 occurs and `FileNotFoundError` is unhandled ## Comments I don't think this the highest priority since this is an edge case but it might be nice to add exception handling to flash a message instructing the user to get their admin to run the cleanup tool (it's easy for an admin to miss a notification in an OSSEC alert).
There was a case with this on the SI as well (fix in for 1.6.0) - would be cool to look for other potential cases as well. Looks like this issue is not completely addressed: While #5549 addresses the issue for deletions, it does not address this issue for downloads. Steps to reproduce are as follows: 1. Go to source interface, submit two messages 2. SSH into app server, go to `/var/lib/securedrop/store` and delete one of the messages 3. Go to Journalist Interface and try to download the deleted message 4. Observe error 500 We may need to wrap the `send_file` call with try/except in https://github.com/freedomofpress/securedrop/blob/bee63b1b44a0d27f9fdf7aad14f9ef32207502c3/securedrop/journalist_app/utils.py#L211 This issue is flagged with "Help Wanted". I'd be interested in working on it if no one else is. From a UX perspective, when the journalist deletes a message, they don't have to know that the corresponding file was missing. However if the file is missing when they try to download it, they will expect some sort of feedback to tell them the message cannot be downloaded. I see different possible scenarios: #### Missing files cases: A. One of multiple message files is missing B. All of the message files from a source are missing (individual files or the whole source folder) #### Journalist actions: 1. From `/`, clicks "Download" unread against the source or selects the source only and clicks Download or Download Unread (zip) 1. From `/` selects more than one source and clicks Download or Download Unread (zip) 1. From `/col/<filesystem_id>`, clicks on the message with missing file (gpg) 1. From `/col/<filesystem_id>`, selects the message with missing file and clicks Download Selected (zip) 1. From `/col/<filesystem_id>`, selects multiple/all messages and clicks Download Selected (zip) In cases A1, A2, B2 and A5, the zip file can be produced with the remaining available message files. In cases A3 and B3 the gpg file cannot be downloaded. In cases A4, B1, B4 and B5, the zip file cannot be produced/downloaded. Opinions on the way to handle these scenarios from a UX prespective would be helpful. Thx. Hey @DrGFreeman thanks for the analysis and offer of help! Would be very happy to have your involvement on this. For the deletion case addressed in 1.6.0, it originally summarized any non-fatal errors in an additional flash message, after deletions were complete. That flash message was dropped to avoid reopening translations late in the release cycle, but will probably be added again for next release. A similar mechanism would probably work OK for submissions IMO but it would be cool to get @ninavizz' or others' opinions. (In A3 and B3, there would just be the error flash message.) One other thing to bear in mind is that these errors would occur in the context of an inconsistent file store on the server, so there should be: - logging on the JI to reflect this, which will trigger OSSEC alerts for the admins - error messaging that directs journalists to get their admins involved (in case they miss the OSSEC alerts) Thanks from my end as well @DrGFreeman for the awesome breakdown :) It's important to note that this issue is not expected to arise on production systems, and we have no report of journalists or admins seeing these 500 errors. If it does arise, it indicates a serious issue with the file store, and possible tampering. It really does require admin involvement. We discussed this a bit at today's tech meeting and agreed that we can start with the simple possible improvement for now upon any cases where users currently see a 500 error, and that would be a catch-all error message. It would be great to get Nina's input on the wording here. @ninavizz, let's discuss a bit, I can get you up to speed. For now, DrG, you can just put in a placeholder error. What is the current behavior in collections where only some files in a collection are available? Do some of those cases you listed currently work, or do they all throw a 500? > What is the current behavior in collections where only some files in a collection are available? Do some of those cases you listed currently work, or do they all throw a 500? All cases above throw a 500. I will start working on a solution with a generic flash message for now + logging of the errors. That sounds great, thank you @DrGFreeman! :)
2020-10-10T15:06:53Z
[]
[]
freedomofpress/securedrop
5,582
freedomofpress__securedrop-5582
[ "5197" ]
6807447f7451f2aa192bffa5654377ec4302687a
diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -23,7 +23,7 @@ from sdconfig import SDConfig from source_app import main, info, api from source_app.decorators import ignore_static -from source_app.utils import logged_in +from source_app.utils import logged_in, was_in_generate_flow from store import Storage @@ -109,7 +109,7 @@ def check_tor2web() -> None: 'provide anonymity. ' '<a href="{url}">Why is this dangerous?</a>') .format(url=url_for('info.tor2web_warning'))), - "banner-warning") + "banner-warning") @app.before_request @ignore_static @@ -124,11 +124,24 @@ def setup_g() -> Optional[werkzeug.Response]: if 'expires' in session and datetime.utcnow() >= session['expires']: msg = render_template('session_timeout.html') + # Show expiration message only if the user was + # either in the codename generation flow or logged in + show_expiration_message = any([ + session.get('show_expiration_message'), + logged_in(), + was_in_generate_flow(), + ]) + # clear the session after we render the message so it's localized session.clear() + # Persist this properety across sessions to distinguish users whose sessions expired + # from users who never logged in or generated a codename + session['show_expiration_message'] = show_expiration_message + # Redirect to index with flashed message - flash(Markup(msg), "important") + if session['show_expiration_message']: + flash(Markup(msg), "important") return redirect(url_for('main.index')) session['expires'] = datetime.utcnow() + \ diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -257,7 +257,7 @@ def submit() -> werkzeug.Response: current_app.logger.info("generating key, entropy: {}".format( entropy_avail)) else: - current_app.logger.warn( + current_app.logger.warning( "skipping key generation. entropy: {}".format( entropy_avail)) diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -21,6 +21,10 @@ from typing import Optional # noqa: F401 +def was_in_generate_flow() -> bool: + return 'codenames' in session + + def logged_in() -> bool: return 'logged_in' in session
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -727,6 +727,7 @@ def test_source_session_expiration(config, source_app): # which is always present and 'csrf_token' which leaks no info) session.pop('expires', None) session.pop('csrf_token', None) + session.pop('show_expiration_message', None) assert not session text = resp.data.decode('utf-8') @@ -752,12 +753,31 @@ def test_source_session_expiration_create(config, source_app): # which is always present and 'csrf_token' which leaks no info) session.pop('expires', None) session.pop('csrf_token', None) + session.pop('show_expiration_message', None) assert not session text = resp.data.decode('utf-8') assert 'You were logged out due to inactivity' in text +def test_source_no_session_expiration_message_when_not_logged_in(config, source_app): + """If sources never logged in, no message should be displayed + after SESSION_EXPIRATION_MINUTES.""" + + with source_app.test_client() as app: + seconds_session_expire = 1 + config.SESSION_EXPIRATION_MINUTES = seconds_session_expire / 60. + + resp = app.get(url_for('main.index')) + assert resp.status_code == 200 + + time.sleep(seconds_session_expire + 1) + + refreshed_resp = app.get(url_for('main.index'), follow_redirects=True) + text = refreshed_resp.data.decode('utf-8') + assert 'You were logged out due to inactivity' not in text + + def test_csrf_error_page(config, source_app): source_app.config['WTF_CSRF_ENABLED'] = True with source_app.test_client() as app:
session expiry message shows up when not logged in ## Description This is a low-priority issue but filing for awareness: right now our session expiration applies to all routes on the application, including when users aren't logged in. [Here](https://github.com/freedomofpress/securedrop/blob/develop/securedrop/source_app/__init__.py#L143-L151) is the relevant code. ### Steps to Reproduce 1. Go to SecureDrop source interface homepage. Do not log in. 2. Wait for 120 minutes (this is `SESSION_EXPIRATION_MINUTES`). 3. Refresh the page. ### Expected Behavior Nothing happens, page reloads. ### Actual Behavior You'll get a flashed message indicating you have been logged out. This is odd for the user since they're not logged in. ### Comments A proposal is to only use the session expiration logic when `logged_in` is in the session object.
Hi @redshiftzero, I'd love to take this on as my first contribution to SecureDrop. I'll follow your proposal under the Comments heading as a guideline. Other than that, is there anything else I need to know before jumping in? @sheonhan feel free to submit a PR (with tests), we can discuss if anything else is required at that. Thank you for showing interest.
2020-10-15T00:44:28Z
[]
[]
freedomofpress/securedrop
5,585
freedomofpress__securedrop-5585
[ "5584" ]
bb80bfc1171304fb67c1d8ff6a8f3002fd742e66
diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -9,6 +9,7 @@ import io import os import yaml +import testutils # The config tests target staging by default. It's possible to override # for e.g. prod, but the associated vars files are not yet ported. @@ -52,5 +53,13 @@ def lookup_molecule_info(): return molecule_instance_config -def pytest_namespace(): - return securedrop_import_testinfra_vars(target_host, with_header=True) +class Myvalues: + def __init__(self): + pass + + +value = securedrop_import_testinfra_vars(target_host) +res = Myvalues() +for key, value in value.items(): + setattr(res, key, value) +testutils.securedrop_test_vars = res diff --git a/molecule/testinfra/testutils.py b/molecule/testinfra/testutils.py new file mode 100644 --- /dev/null +++ b/molecule/testinfra/testutils.py @@ -0,0 +1 @@ +securedrop_test_vars = {}
diff --git a/molecule/builder-xenial/tests/conftest.py b/molecule/builder-xenial/tests/conftest.py --- a/molecule/builder-xenial/tests/conftest.py +++ b/molecule/builder-xenial/tests/conftest.py @@ -1,22 +1,19 @@ """ -Import variables from vars.yml and inject into pytest namespace +Import variables from vars.yml and inject into testutils namespace """ import os import io import yaml +import testutils -def pytest_namespace(): - """ Return dict of vars imported as 'securedrop_test_vars' into pytest - global namespace - """ - filepath = os.path.join(os.path.dirname(__file__), "vars.yml") - with io.open(filepath, 'r') as f: - securedrop_test_vars = yaml.safe_load(f) +filepath = os.path.join(os.path.dirname(__file__), "vars.yml") +with io.open(filepath, 'r') as f: + securedrop_test_vars = yaml.safe_load(f) - # Tack on target OS for use in tests - securedrop_target_platform = os.environ.get("SECUREDROP_TARGET_PLATFORM") - securedrop_test_vars["securedrop_target_platform"] = securedrop_target_platform - # Wrapping the return value to accommodate for pytest namespacing - return dict(securedrop_test_vars=securedrop_test_vars) +# Tack on target OS for use in tests +securedrop_target_platform = os.environ.get("SECUREDROP_TARGET_PLATFORM") +securedrop_test_vars["securedrop_target_platform"] = securedrop_target_platform + +testutils.securedrop_test_vars = testutils.inject_vars(securedrop_test_vars) diff --git a/molecule/builder-xenial/tests/test_securedrop_deb_package.py b/molecule/builder-xenial/tests/test_securedrop_deb_package.py --- a/molecule/builder-xenial/tests/test_securedrop_deb_package.py +++ b/molecule/builder-xenial/tests/test_securedrop_deb_package.py @@ -2,13 +2,14 @@ import os import re import tempfile +import testutils SECUREDROP_TARGET_PLATFORM = os.environ.get("SECUREDROP_TARGET_PLATFORM") testinfra_hosts = [ "docker://{}-sd-dpkg-verification".format(SECUREDROP_TARGET_PLATFORM) ] -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars def extract_package_name_from_filepath(filepath): diff --git a/molecule/builder-xenial/tests/testutils.py b/molecule/builder-xenial/tests/testutils.py new file mode 100644 --- /dev/null +++ b/molecule/builder-xenial/tests/testutils.py @@ -0,0 +1,13 @@ +class Myvalues: + def __init__(self): + pass + + +securedrop_test_vars = Myvalues() + + +def inject_vars(value): + res = Myvalues() + for key, value in value.items(): + setattr(res, key, value) + return res diff --git a/molecule/testinfra/app-code/test_haveged.py b/molecule/testinfra/app-code/test_haveged.py --- a/molecule/testinfra/app-code/test_haveged.py +++ b/molecule/testinfra/app-code/test_haveged.py @@ -1,6 +1,6 @@ -import pytest +import testutils -sdvars = pytest.securedrop_test_vars +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] diff --git a/molecule/testinfra/app-code/test_securedrop_app_code.py b/molecule/testinfra/app-code/test_securedrop_app_code.py --- a/molecule/testinfra/app-code/test_securedrop_app_code.py +++ b/molecule/testinfra/app-code/test_securedrop_app_code.py @@ -1,7 +1,9 @@ import pytest -securedrop_test_vars = pytest.securedrop_test_vars +import testutils + +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] python_version = securedrop_test_vars.python_version diff --git a/molecule/testinfra/app-code/test_securedrop_rqrequeue.py b/molecule/testinfra/app-code/test_securedrop_rqrequeue.py --- a/molecule/testinfra/app-code/test_securedrop_rqrequeue.py +++ b/molecule/testinfra/app-code/test_securedrop_rqrequeue.py @@ -1,14 +1,13 @@ -import pytest +import testutils -sdvars = pytest.securedrop_test_vars -testinfra_hosts = [sdvars.app_hostname] +securedrop_test_vars = testutils.securedrop_test_vars +testinfra_hosts = [securedrop_test_vars.app_hostname] def test_securedrop_rqrequeue_service(host): """ Verify configuration of securedrop_rqrequeue systemd service. """ - securedrop_test_vars = pytest.securedrop_test_vars service_file = "/lib/systemd/system/securedrop_rqrequeue.service" expected_content = "\n".join([ "[Unit]", diff --git a/molecule/testinfra/app-code/test_securedrop_rqworker.py b/molecule/testinfra/app-code/test_securedrop_rqworker.py --- a/molecule/testinfra/app-code/test_securedrop_rqworker.py +++ b/molecule/testinfra/app-code/test_securedrop_rqworker.py @@ -1,6 +1,6 @@ -import pytest +import testutils -sdvars = pytest.securedrop_test_vars +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] @@ -8,7 +8,7 @@ def test_securedrop_rqworker_service(host): """ Verify configuration of securedrop_rqworker systemd service. """ - securedrop_test_vars = pytest.securedrop_test_vars + securedrop_test_vars = sdvars service_file = "/lib/systemd/system/securedrop_rqworker.service" expected_content = "\n".join([ diff --git a/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py b/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py --- a/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py +++ b/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py @@ -1,6 +1,6 @@ -import pytest +import testutils -sdvars = pytest.securedrop_test_vars +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] @@ -8,7 +8,7 @@ def test_securedrop_shredder_service(host): """ Verify configuration of securedrop_shredder systemd service. """ - securedrop_test_vars = pytest.securedrop_test_vars + securedrop_test_vars = sdvars service_file = "/lib/systemd/system/securedrop_shredder.service" expected_content = "\n".join([ "[Unit]", diff --git a/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py b/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py --- a/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py +++ b/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py @@ -1,14 +1,13 @@ -import pytest +import testutils -sdvars = pytest.securedrop_test_vars -testinfra_hosts = [sdvars.app_hostname] +securedrop_test_vars = testutils.securedrop_test_vars +testinfra_hosts = [securedrop_test_vars.app_hostname] def test_securedrop_source_deleter_service(host): """ Verify configuration of securedrop_source_deleter systemd service. """ - securedrop_test_vars = pytest.securedrop_test_vars service_file = "/lib/systemd/system/securedrop_source_deleter.service" expected_content = "\n".join([ "[Unit]", diff --git a/molecule/testinfra/app/apache/test_apache_journalist_interface.py b/molecule/testinfra/app/apache/test_apache_journalist_interface.py --- a/molecule/testinfra/app/apache/test_apache_journalist_interface.py +++ b/molecule/testinfra/app/apache/test_apache_journalist_interface.py @@ -1,8 +1,9 @@ import pytest import re +import testutils -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] # Setting once so it can be reused in multiple tests. diff --git a/molecule/testinfra/app/apache/test_apache_service.py b/molecule/testinfra/app/apache/test_apache_service.py --- a/molecule/testinfra/app/apache/test_apache_service.py +++ b/molecule/testinfra/app/apache/test_apache_service.py @@ -1,7 +1,8 @@ import pytest +import testutils -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] diff --git a/molecule/testinfra/app/apache/test_apache_source_interface.py b/molecule/testinfra/app/apache/test_apache_source_interface.py --- a/molecule/testinfra/app/apache/test_apache_source_interface.py +++ b/molecule/testinfra/app/apache/test_apache_source_interface.py @@ -1,7 +1,9 @@ import pytest import re -securedrop_test_vars = pytest.securedrop_test_vars +import testutils + +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] diff --git a/molecule/testinfra/app/apache/test_apache_system_config.py b/molecule/testinfra/app/apache/test_apache_system_config.py --- a/molecule/testinfra/app/apache/test_apache_system_config.py +++ b/molecule/testinfra/app/apache/test_apache_system_config.py @@ -1,7 +1,9 @@ import pytest import re -securedrop_test_vars = pytest.securedrop_test_vars +import testutils + +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] diff --git a/molecule/testinfra/app/test_app_network.py b/molecule/testinfra/app/test_app_network.py --- a/molecule/testinfra/app/test_app_network.py +++ b/molecule/testinfra/app/test_app_network.py @@ -5,7 +5,9 @@ from jinja2 import Template -securedrop_test_vars = pytest.securedrop_test_vars +import testutils + +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] diff --git a/molecule/testinfra/app/test_apparmor.py b/molecule/testinfra/app/test_apparmor.py --- a/molecule/testinfra/app/test_apparmor.py +++ b/molecule/testinfra/app/test_apparmor.py @@ -1,7 +1,9 @@ import pytest -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] diff --git a/molecule/testinfra/app/test_appenv.py b/molecule/testinfra/app/test_appenv.py --- a/molecule/testinfra/app/test_appenv.py +++ b/molecule/testinfra/app/test_appenv.py @@ -1,7 +1,9 @@ import os.path import pytest -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] diff --git a/molecule/testinfra/app/test_ossec_agent.py b/molecule/testinfra/app/test_ossec_agent.py --- a/molecule/testinfra/app/test_ossec_agent.py +++ b/molecule/testinfra/app/test_ossec_agent.py @@ -2,7 +2,9 @@ import re import pytest -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] diff --git a/molecule/testinfra/app/test_paxctld.py b/molecule/testinfra/app/test_paxctld.py --- a/molecule/testinfra/app/test_paxctld.py +++ b/molecule/testinfra/app/test_paxctld.py @@ -1,8 +1,7 @@ -import pytest import re +import testutils - -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] diff --git a/molecule/testinfra/app/test_tor_config.py b/molecule/testinfra/app/test_tor_config.py --- a/molecule/testinfra/app/test_tor_config.py +++ b/molecule/testinfra/app/test_tor_config.py @@ -1,7 +1,9 @@ import pytest import re -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] diff --git a/molecule/testinfra/app/test_tor_hidden_services.py b/molecule/testinfra/app/test_tor_hidden_services.py --- a/molecule/testinfra/app/test_tor_hidden_services.py +++ b/molecule/testinfra/app/test_tor_hidden_services.py @@ -1,8 +1,9 @@ import pytest import re +import testutils -sdvars = pytest.securedrop_test_vars +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] # Prod Tor services may have unexpected configs diff --git a/molecule/testinfra/common/test_cron_apt.py b/molecule/testinfra/common/test_cron_apt.py --- a/molecule/testinfra/common/test_cron_apt.py +++ b/molecule/testinfra/common/test_cron_apt.py @@ -1,8 +1,9 @@ import pytest import re +import testutils -test_vars = pytest.securedrop_test_vars +test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] diff --git a/molecule/testinfra/common/test_fpf_apt_repo.py b/molecule/testinfra/common/test_fpf_apt_repo.py --- a/molecule/testinfra/common/test_fpf_apt_repo.py +++ b/molecule/testinfra/common/test_fpf_apt_repo.py @@ -2,7 +2,9 @@ import re -test_vars = pytest.securedrop_test_vars +import testutils + +test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] diff --git a/molecule/testinfra/common/test_grsecurity.py b/molecule/testinfra/common/test_grsecurity.py --- a/molecule/testinfra/common/test_grsecurity.py +++ b/molecule/testinfra/common/test_grsecurity.py @@ -1,8 +1,9 @@ import pytest import re +import testutils -sdvars = pytest.securedrop_test_vars +sdvars = testutils.securedrop_test_vars KERNEL_VERSION = sdvars.grsec_version testinfra_hosts = [sdvars.app_hostname, sdvars.monitor_hostname] diff --git a/molecule/testinfra/common/test_ip6tables.py b/molecule/testinfra/common/test_ip6tables.py --- a/molecule/testinfra/common/test_ip6tables.py +++ b/molecule/testinfra/common/test_ip6tables.py @@ -1,6 +1,6 @@ -import pytest +import testutils -test_vars = pytest.securedrop_test_vars +test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] diff --git a/molecule/testinfra/common/test_platform.py b/molecule/testinfra/common/test_platform.py --- a/molecule/testinfra/common/test_platform.py +++ b/molecule/testinfra/common/test_platform.py @@ -1,6 +1,6 @@ -import pytest +import testutils -test_vars = pytest.securedrop_test_vars +test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] # We expect Ubuntu Xenial diff --git a/molecule/testinfra/common/test_release_upgrades.py b/molecule/testinfra/common/test_release_upgrades.py --- a/molecule/testinfra/common/test_release_upgrades.py +++ b/molecule/testinfra/common/test_release_upgrades.py @@ -1,7 +1,6 @@ -import pytest +import testutils - -test_vars = pytest.securedrop_test_vars +test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] diff --git a/molecule/testinfra/common/test_system_hardening.py b/molecule/testinfra/common/test_system_hardening.py --- a/molecule/testinfra/common/test_system_hardening.py +++ b/molecule/testinfra/common/test_system_hardening.py @@ -1,7 +1,9 @@ import pytest import re -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname, sdvars.monitor_hostname] diff --git a/molecule/testinfra/common/test_tor_mirror.py b/molecule/testinfra/common/test_tor_mirror.py --- a/molecule/testinfra/common/test_tor_mirror.py +++ b/molecule/testinfra/common/test_tor_mirror.py @@ -1,6 +1,8 @@ import pytest -test_vars = pytest.securedrop_test_vars +import testutils + +test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] diff --git a/molecule/testinfra/common/test_user_config.py b/molecule/testinfra/common/test_user_config.py --- a/molecule/testinfra/common/test_user_config.py +++ b/molecule/testinfra/common/test_user_config.py @@ -3,7 +3,9 @@ import pytest -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname, sdvars.monitor_hostname] diff --git a/molecule/testinfra/mon/test_mon_network.py b/molecule/testinfra/mon/test_mon_network.py --- a/molecule/testinfra/mon/test_mon_network.py +++ b/molecule/testinfra/mon/test_mon_network.py @@ -4,8 +4,9 @@ import pytest from jinja2 import Template +import testutils -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] diff --git a/molecule/testinfra/mon/test_ossec_ruleset.py b/molecule/testinfra/mon/test_ossec_ruleset.py --- a/molecule/testinfra/mon/test_ossec_ruleset.py +++ b/molecule/testinfra/mon/test_ossec_ruleset.py @@ -1,7 +1,9 @@ import pytest import re -sdvars = pytest.securedrop_test_vars +import testutils + +sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.monitor_hostname] alert_level_regex = re.compile(r"Level: '(\d+)'") rule_id_regex = re.compile(r"Rule id: '(\d+)'") diff --git a/molecule/testinfra/mon/test_ossec_server.py b/molecule/testinfra/mon/test_ossec_server.py --- a/molecule/testinfra/mon/test_ossec_server.py +++ b/molecule/testinfra/mon/test_ossec_server.py @@ -1,8 +1,9 @@ import os import pytest +import testutils -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] diff --git a/molecule/testinfra/mon/test_postfix.py b/molecule/testinfra/mon/test_postfix.py --- a/molecule/testinfra/mon/test_postfix.py +++ b/molecule/testinfra/mon/test_postfix.py @@ -1,8 +1,9 @@ import re import pytest +import testutils -securedrop_test_vars = pytest.securedrop_test_vars +securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname]
Update pytest-*, molecule, testinfra dependencies ## Description Currently we are using 3 years old versions of `pytest`, `pytest-xdist`, `pluggy`, `testinfra`, `molecule`. We have to update these dependencies up to the latest version where they support both Python3.5 and 3.8 (for `xenial` and `focal`).
2020-10-15T14:48:14Z
[]
[]
freedomofpress/securedrop
5,629
freedomofpress__securedrop-5629
[ "1575" ]
2e513b1bd3541ba4e26a43586ffea3ae69ecc68f
diff --git a/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py b/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py @@ -0,0 +1,32 @@ +"""Added organization_name field in instance_config table + +Revision ID: 92fba0be98e9 +Revises: 48a75abc0121 +Create Date: 2020-11-15 19:36:20.351993 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '92fba0be98e9' +down_revision = '48a75abc0121' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.add_column(sa.Column('organization_name', sa.String(length=255), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.drop_column('organization_name') + + # ### end Alembic commands ### diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -156,6 +156,11 @@ def setup_g() -> 'Optional[Response]': g.html_lang = i18n.locale_to_rfc_5646(g.locale) g.locales = i18n.get_locale2name() + if app.instance_config.organization_name: + g.organization_name = app.instance_config.organization_name + else: + g.organization_name = gettext('SecureDrop') + if not app.config['V3_ONION_ENABLED'] or app.config['V2_ONION_ENABLED']: g.show_v2_onion_eol_warning = True diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -13,12 +13,13 @@ import i18n from db import db +from html import escape from models import (InstanceConfig, Journalist, InvalidUsernameException, FirstOrLastNameError, PasswordError) from journalist_app.decorators import admin_required from journalist_app.utils import (commit_account_changes, set_diceware_password, validate_hotp_secret, revoke_token) -from journalist_app.forms import LogoForm, NewUserForm, SubmissionPreferencesForm +from journalist_app.forms import LogoForm, NewUserForm, SubmissionPreferencesForm, OrgNameForm from sdconfig import SDConfig from passphrases import PassphraseGenerator @@ -38,6 +39,8 @@ def manage_config() -> Union[str, werkzeug.Response]: # The UI prompt ("prevent") is the opposite of the setting ("allow"): submission_preferences_form = SubmissionPreferencesForm( prevent_document_uploads=not current_app.instance_config.allow_document_uploads) + organization_name_form = OrgNameForm( + organization_name=current_app.instance_config.organization_name) logo_form = LogoForm() if logo_form.validate_on_submit(): f = logo_form.logo.data @@ -53,13 +56,14 @@ def manage_config() -> Union[str, werkzeug.Response]: flash("Unable to process the image file." " Try another one.", "logo-error") finally: - return redirect(url_for("admin.manage_config")) + return redirect(url_for("admin.manage_config") + "#config-logoimage") else: for field, errors in list(logo_form.errors.items()): for error in errors: flash(error, "logo-error") return render_template("config.html", submission_preferences_form=submission_preferences_form, + organization_name_form=organization_name_form, logo_form=logo_form) @view.route('/update-submission-preferences', methods=['POST']) @@ -71,9 +75,31 @@ def update_submission_preferences() -> Optional[werkzeug.Response]: flash(gettext("Preferences saved."), "submission-preferences-success") value = not bool(request.form.get('prevent_document_uploads')) InstanceConfig.set_allow_document_uploads(value) - return redirect(url_for('admin.manage_config')) + return redirect(url_for('admin.manage_config') + "#config-preventuploads") else: - return None + for field, errors in list(form.errors.items()): + for error in errors: + flash(gettext("Preferences not updated.") + " " + error, + "submission-preferences-error") + return redirect(url_for('admin.manage_config') + "#config-preventuploads") + + @view.route('/update-org-name', methods=['POST']) + @admin_required + def update_org_name() -> Union[str, werkzeug.Response]: + form = OrgNameForm() + if form.validate_on_submit(): + try: + value = request.form['organization_name'] + InstanceConfig.set_organization_name(escape(value, quote=True)) + flash(gettext("Preferences saved."), "org-name-success") + except Exception: + flash(gettext('Failed to update organization name.'), 'org-name-error') + return redirect(url_for('admin.manage_config') + "#config-orgname") + else: + for field, errors in list(form.errors.items()): + for error in errors: + flash(error, "org-name-error") + return redirect(url_for('admin.manage_config') + "#config-orgname") @view.route('/add', methods=('GET', 'POST')) @admin_required @@ -276,7 +302,7 @@ def new_password(user_id: int) -> werkzeug.Response: def ossec_test() -> werkzeug.Response: current_app.logger.error('This is a test OSSEC alert') flash(gettext('Test alert sent. Please check your email.'), - 'notification') - return redirect(url_for('admin.manage_config')) + 'testalert-notification') + return redirect(url_for('admin.manage_config') + "#config-testalert") return view diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -8,7 +8,7 @@ ValidationError) from wtforms.validators import InputRequired, Optional -from models import Journalist +from models import Journalist, InstanceConfig def otp_secret_validation(form: FlaskForm, field: Field) -> None: @@ -46,6 +46,17 @@ def name_length_validation(form: FlaskForm, field: Field) -> None: ) +def check_orgname(form: FlaskForm, field: Field) -> None: + if len(field.data) > InstanceConfig.MAX_ORG_NAME_LEN: + raise ValidationError( + ngettext( + 'Cannot be longer than {num} characters.', + 'Cannot be longer than {num} characters.', + InstanceConfig.MAX_ORG_NAME_LEN + ).format(num=InstanceConfig.MAX_ORG_NAME_LEN) + ) + + def check_invalid_usernames(form: FlaskForm, field: Field) -> None: if field.data in Journalist.INVALID_USERNAMES: raise ValidationError(gettext( @@ -83,6 +94,13 @@ class SubmissionPreferencesForm(FlaskForm): prevent_document_uploads = BooleanField('prevent_document_uploads') +class OrgNameForm(FlaskForm): + organization_name = StringField('organization_name', validators=[ + InputRequired(message=gettext('This field is required.')), + check_orgname + ]) + + class LogoForm(FlaskForm): logo = FileField(validators=[ FileRequired(message=gettext('File required.')), diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -825,11 +825,15 @@ class InstanceConfig(db.Model): interface. The current version has valid_until=None. ''' + # Limits length of org name used in SI and JI titles, image alt texts etc. + MAX_ORG_NAME_LEN = 64 + __tablename__ = 'instance_config' version = Column(Integer, primary_key=True) valid_until = Column(DateTime, default=None, unique=True) allow_document_uploads = Column(Boolean, default=True) + organization_name = Column(String(255), nullable=True, default="SecureDrop") # Columns not listed here will be included by InstanceConfig.copy() when # updating the configuration. @@ -868,6 +872,31 @@ def get_current(cls) -> "InstanceConfig": db.session.commit() return current + @classmethod + def check_name_acceptable(cls, name: str) -> None: + # Enforce a reasonable maximum length for names + if name is None or len(name) == 0: + raise InvalidNameLength(name) + if len(name) > cls.MAX_ORG_NAME_LEN: + raise InvalidNameLength(name) + + @classmethod + def set_organization_name(cls, name: str) -> None: + '''Invalidate the current configuration and append a new one with the + new organization name. + ''' + + old = cls.get_current() + old.valid_until = datetime.datetime.utcnow() + db.session.add(old) + + new = old.copy() + cls.check_name_acceptable(name) + new.organization_name = name + db.session.add(new) + + db.session.commit() + @classmethod def set_allow_document_uploads(cls, value: bool) -> None: '''Invalidate the current configuration and append a new one with the diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -168,6 +168,12 @@ def setup_g() -> Optional[werkzeug.Response]: del session['codename'] return redirect(url_for('main.index')) g.loc = app.storage.path(g.filesystem_id) + + if app.instance_config.organization_name: + g.organization_name = app.instance_config.organization_name + else: + g.organization_name = gettext('SecureDrop') + return None @app.errorhandler(404) diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -19,6 +19,7 @@ def make_blueprint(config: SDConfig) -> Blueprint: @view.route('/metadata') def metadata() -> flask.Response: meta = { + 'organization_name': current_app.instance_config.organization_name, 'allow_document_uploads': current_app.instance_config.allow_document_uploads, 'gpg_fpr': config.JOURNALIST_KEY, 'sd_version': version.__version__,
diff --git a/securedrop/tests/functional/functional_test.py b/securedrop/tests/functional/functional_test.py --- a/securedrop/tests/functional/functional_test.py +++ b/securedrop/tests/functional/functional_test.py @@ -62,6 +62,9 @@ class FunctionalTest(object): timeout = 10 poll_frequency = 0.1 + orgname_default = "SecureDrop" + orgname_new = "Walden Inquirer" + accept_languages = None default_driver_name = TORBROWSER driver = None diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -302,6 +302,19 @@ def preferences_saved(): assert "Preferences saved." in flash_msg.text self.wait_for(preferences_saved, timeout=self.timeout * 6) + def _admin_sets_organization_name(self): + assert self.orgname_default == self.driver.title + self.driver.find_element_by_id('organization_name').clear() + self.safe_send_keys_by_id("organization_name", self.orgname_new) + self.safe_click_by_id("submit-update-org-name") + + def preferences_saved(): + flash_msg = self.driver.find_element_by_css_selector(".flash") + assert "Preferences saved." in flash_msg.text + + self.wait_for(preferences_saved, timeout=self.timeout * 6) + assert self.orgname_new == self.driver.title + def _add_user(self, username, first_name="", last_name="", is_admin=False, hotp=None): self.safe_send_keys_by_css_selector('input[name="username"]', username) diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -22,6 +22,9 @@ def _is_on_generate_page(self): def _is_on_logout_page(self): return self.wait_for(lambda: self.driver.find_element_by_id("click-new-identity-tor")) + def _source_sees_orgname(self, name="SecureDrop"): + assert name in self.driver.title + def _source_visits_source_homepage(self): self.driver.get(self.source_location) assert self._is_on_source_homepage() diff --git a/securedrop/tests/functional/test_admin_interface.py b/securedrop/tests/functional/test_admin_interface.py --- a/securedrop/tests/functional/test_admin_interface.py +++ b/securedrop/tests/functional/test_admin_interface.py @@ -97,3 +97,15 @@ def test_allow_file_submission(self): self._source_chooses_to_submit_documents() self._source_continues_to_submit_page() self._source_sees_document_attachment_item() + + def test_orgname_is_changed(self): + self._admin_logs_in() + self._admin_visits_admin_interface() + self._admin_visits_system_config_page() + self._admin_sets_organization_name() + + self._source_visits_source_homepage() + self._source_sees_orgname(name=self.orgname_new) + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_sees_orgname(name=self.orgname_new) diff --git a/securedrop/tests/migrations/migration_92fba0be98e9.py b/securedrop/tests/migrations/migration_92fba0be98e9.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_92fba0be98e9.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- + +from db import db +from journalist_app import create_app +import sqlalchemy +import pytest + +from .helpers import random_bool, random_datetime + + +class UpgradeTester: + def __init__(self, config): + self.config = config + self.app = create_app(config) + + def load_data(self): + with self.app.app_context(): + self.update_config() + + db.session.commit() + + @staticmethod + def update_config(): + params = { + "valid_until": random_datetime(nullable=True), + "allow_document_uploads": random_bool(), + } + sql = """ + INSERT INTO instance_config ( + valid_until, allow_document_uploads + ) VALUES ( + :valid_until, :allow_document_uploads + ) + """ + + db.engine.execute(sqlalchemy.text(sql), **params) + + def check_upgrade(self): + """ + Check the new `organization_name` column + + Querying `organization_name` shouldn't cause an error, but it should not yet be set. + """ + with self.app.app_context(): + configs = db.engine.execute( + sqlalchemy.text("SELECT * FROM instance_config WHERE organization_name IS NOT NULL") + ).fetchall() + assert len(configs) == 0 + + +class DowngradeTester: + def __init__(self, config): + self.config = config + self.app = create_app(config) + + def load_data(self): + pass + + def check_downgrade(self): + """ + After downgrade, using `organization_name` in a query should raise an exception + """ + with self.app.app_context(): + with pytest.raises(sqlalchemy.exc.OperationalError): + configs = db.engine.execute( + sqlalchemy.text( + "SELECT * FROM instance_config WHERE organization_name IS NOT NULL" + ) + ).fetchall() + assert len(configs) == 0 diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -17,6 +17,7 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import StaleDataError from sqlalchemy.sql.expression import func +from html import escape as htmlescape import journalist_app as journalist_app_module from journalist_app.utils import mark_seen @@ -1495,6 +1496,119 @@ def test_no_prevent_document_uploads(journalist_app, test_admin): app.post(url_for('admin.update_submission_preferences'), follow_redirects=True) ins.assert_message_flashed('Preferences saved.', 'submission-preferences-success') + assert InstanceConfig.get_current().allow_document_uploads is True + + +def test_prevent_document_uploads_invalid(journalist_app, test_admin): + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + form_true = journalist_app_module.forms.SubmissionPreferencesForm( + prevent_document_uploads=True) + app.post(url_for('admin.update_submission_preferences'), + data=form_true.data, + follow_redirects=True) + assert InstanceConfig.get_current().allow_document_uploads is False + + with patch('flask_wtf.FlaskForm.validate_on_submit') as fMock: + fMock.return_value = False + form_false = journalist_app_module.forms.SubmissionPreferencesForm( + prevent_document_uploads=False) + app.post(url_for('admin.update_submission_preferences'), + data=form_false.data, + follow_redirects=True) + assert InstanceConfig.get_current().allow_document_uploads is False + + +def test_orgname_default_set(journalist_app, test_admin): + + class dummy_current(): + organization_name = None + + with patch.object(InstanceConfig, 'get_current') as iMock: + with journalist_app.test_client() as app: + iMock.return_value = dummy_current() + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + assert g.organization_name == "SecureDrop" + + +def test_orgname_valid_succeeds(journalist_app, test_admin): + test_name = "Walden Inquirer" + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + form = journalist_app_module.forms.OrgNameForm( + organization_name=test_name) + assert InstanceConfig.get_current().organization_name == "SecureDrop" + with InstrumentedApp(journalist_app) as ins: + app.post(url_for('admin.update_org_name'), + data=form.data, + follow_redirects=True) + ins.assert_message_flashed('Preferences saved.', 'org-name-success') + assert InstanceConfig.get_current().organization_name == test_name + + +def test_orgname_null_fails(journalist_app, test_admin): + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + form = journalist_app_module.forms.OrgNameForm( + organization_name=None) + assert InstanceConfig.get_current().organization_name == "SecureDrop" + with InstrumentedApp(journalist_app) as ins: + app.post(url_for('admin.update_org_name'), + data=form.data, + follow_redirects=True) + ins.assert_message_flashed('This field is required.', 'org-name-error') + assert InstanceConfig.get_current().organization_name == "SecureDrop" + + +def test_orgname_oversized_fails(journalist_app, test_admin): + test_name = "1234567812345678123456781234567812345678123456781234567812345678a" + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + form = journalist_app_module.forms.OrgNameForm( + organization_name=test_name) + assert InstanceConfig.get_current().organization_name == "SecureDrop" + with InstrumentedApp(journalist_app) as ins: + app.post(url_for('admin.update_org_name'), + data=form.data, + follow_redirects=True) + ins.assert_message_flashed('Cannot be longer than 64 characters.', 'org-name-error') + assert InstanceConfig.get_current().organization_name == "SecureDrop" + + +def test_orgname_html_escaped(journalist_app, test_admin): + t_name = '"> <a href=foo>' + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + form = journalist_app_module.forms.OrgNameForm( + organization_name=t_name) + assert InstanceConfig.get_current().organization_name == "SecureDrop" + with InstrumentedApp(journalist_app) as ins: + app.post(url_for('admin.update_org_name'), + data=form.data, + follow_redirects=True) + ins.assert_message_flashed('Preferences saved.', 'org-name-success') + assert InstanceConfig.get_current().organization_name == htmlescape(t_name, quote=True) + + +def test_logo_default_available(journalist_app): + # if the custom image is available, this test will fail + custom_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png") + if os.path.exists(custom_image_location): + os.remove(custom_image_location) + + with journalist_app.test_client() as app: + response = app.get(url_for('main.select_logo'), follow_redirects=False) + + assert response.status_code == 302 + observed_headers = response.headers + assert 'Location' in list(observed_headers.keys()) + assert url_for('static', filename='i/logo.png') in observed_headers['Location'] def test_logo_upload_with_valid_image_succeeds(journalist_app, test_admin): @@ -1520,6 +1634,13 @@ def test_logo_upload_with_valid_image_succeeds(journalist_app, test_admin): follow_redirects=True) ins.assert_message_flashed("Image updated.", "logo-success") + with journalist_app.test_client() as app: + response = app.get(url_for('main.select_logo'), follow_redirects=False) + + assert response.status_code == 302 + observed_headers = response.headers + assert 'Location' in list(observed_headers.keys()) + assert url_for('static', filename='i/custom_logo.png') in observed_headers['Location'] finally: # Restore original image to logo location for subsequent tests with io.open(logo_image_location, 'wb') as logo_file: @@ -1544,6 +1665,38 @@ def test_logo_upload_with_invalid_filetype_fails(journalist_app, test_admin): assert "You can only upload PNG image files." in text +def test_logo_upload_save_fails(journalist_app, test_admin): + # Save original logo to restore after test run + logo_image_location = os.path.join(config.SECUREDROP_ROOT, + "static/i/logo.png") + with io.open(logo_image_location, 'rb') as logo_file: + original_image = logo_file.read() + + try: + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + # Create 1px * 1px 'white' PNG file from its base64 string + form = journalist_app_module.forms.LogoForm( + logo=(BytesIO(base64.decodebytes + (b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQ" + b"VR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=")), 'test.png') + ) + with InstrumentedApp(journalist_app) as ins: + with patch('werkzeug.datastructures.FileStorage.save') as sMock: + sMock.side_effect = Exception + app.post(url_for('admin.manage_config'), + data=form.data, + follow_redirects=True) + + ins.assert_message_flashed("Unable to process the image file." + " Try another one.", "logo-error") + finally: + # Restore original image to logo location for subsequent tests + with io.open(logo_image_location, 'wb') as logo_file: + logo_file.write(original_image) + + def test_creation_of_ossec_test_log_event(journalist_app, test_admin, mocker): mocked_error_logger = mocker.patch('journalist.app.logger.error') with journalist_app.test_client() as app: diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -3,6 +3,8 @@ import re import subprocess import time +import os +import shutil from io import BytesIO, StringIO from flask import session, escape, url_for, g, request @@ -21,10 +23,42 @@ from source_app import api as source_app_api from .utils.db_helper import new_codename from .utils.instrument import InstrumentedApp +from sdconfig import config overly_long_codename = 'a' * (PassphraseGenerator.MAX_PASSPHRASE_LENGTH + 1) +def test_logo_default_available(source_app): + # if the custom image is available, this test will fail + custom_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png") + if os.path.exists(custom_image_location): + os.remove(custom_image_location) + + with source_app.test_client() as app: + response = app.get(url_for('main.select_logo'), follow_redirects=False) + + assert response.status_code == 302 + observed_headers = response.headers + assert 'Location' in list(observed_headers.keys()) + assert url_for('static', filename='i/logo.png') in observed_headers['Location'] + + +def test_logo_custom_available(source_app): + # if the custom image is available, this test will fail + custom_image = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png") + default_image = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") + if os.path.exists(default_image) and not os.path.exists(custom_image): + shutil.copyfile(default_image, custom_image) + + with source_app.test_client() as app: + response = app.get(url_for('main.select_logo'), follow_redirects=False) + + assert response.status_code == 302 + observed_headers = response.headers + assert 'Location' in list(observed_headers.keys()) + assert url_for('static', filename='i/custom_logo.png') in observed_headers['Location'] + + def test_page_not_found(source_app): """Verify the page not found condition returns the intended template""" with InstrumentedApp(source_app) as ins: @@ -34,6 +68,19 @@ def test_page_not_found(source_app): ins.assert_template_used('notfound.html') +def test_orgname_default_set(source_app): + + class dummy_current(): + organization_name = None + + with patch.object(InstanceConfig, 'get_current') as iMock: + with source_app.test_client() as app: + iMock.return_value = dummy_current() + resp = app.get(url_for('main.index')) + assert resp.status_code == 200 + assert g.organization_name == "SecureDrop" + + def test_index(source_app): """Test that the landing page loads and looks how we expect""" with source_app.test_client() as app:
Add injectable organization name to source/journalist interface As suggested by @ninavizz here https://github.com/freedomofpress/securedrop/issues/1524, source templates could be improved by including the organization name as string in various copy and flashed messages.
I'm not sure where she actually suggested including the org names in the messaging. Could you clarify @ninavizz @heartsucker? It's very problematic right now, that the name of the newsroom for each SD instance is absent in the Source UI. That's why B2B2C apps co-brand: to cognitively anchor the user with where they're creating/uploading things on/to, not so much to show off logos & attribution. Right now "SecureDrop" appears to users as a service, that newsroom landing pages send them to. That's just a common pattern in the world that today's UI reflects. That matters. My longer-term UI sketch shows a cobranding schema, which wd obvs be much more involved. Short-term, the most obvious/easy area to present the org name to a user in, is the confirmation message—which is also confusing (tho less-urgently) bcuz it follows the "info bubble" UI pattern for color/icon use. All of this is in the latest version of the Source UI stuff that you guys have from me. The GDoc links all point to the most recent versions of everything. "Thank you for submitting your documents" is an incomplete message. "Thank you for submitting your documents to The New York Times" more clearly states that the user's stuff just went to servers owned by the NYT, and reminds users where to follow-up, on the chance they submitted to multiple orgs. As a side note, this is going to be a **massive** pain in the ass if we decide to do internationalization because English basically ignores "cases." We use the same "the" or adjective for naming an object directly, indirectly, etc. If this gets added in extensively, simply injecting "The Local Newspaper" into the templates will lead to significant grammatical incorrectness. [Click here](http://german.about.com/od/grammar/fl/The-Four-German-Noun-Cases.htm) and search for the tables under the phrase "Definite Articles". Also, this [wiki page](https://en.wikipedia.org/wiki/German_adjectives) on adjectives. Yeah. Sadness. I kinda tried to address that concern, with how I asked newsrooms input their names on the admin-pane I sketched-out—and by wording the confirmation bubble *exactly* as I did. I worked on the localization team at Yahoo!, and this issue was an epic PITA. Within my admin pane sketch, it gives newsrooms the oppty to input whatever they want for their name (eg: "The Intercept" or simply "Intercept"), and as they type the character inputs are automatically plugged-in to the confirmation message's sentence, shown below. Should the app get localized, then hopefully that'd take care of it? True, but even in this case, if we had, for exampe, Der Speigel setting up SecureDrop, there' is no way to write that sentence because when you say "to" something, Der Speigel would become "Dem Speigel," and in this case you'd smash the "to" and "the" together and get "zum Spiegel". And if even if you wanted to say "the SecureDrop of Der Speigel," it would have to "der SecureDrop Des Speigels." And possessive like "Der Speigel's SecureDrop" would be "Der Speigels SecureDrop" (no apostrophe). I mean. It seems like translation isn't going to happen any time soon, but again, just making note of what an absolute nightmare this would be. Which is also a bummer because I still think having things in English only is going to hurt adoption outside the US. Also, @fowlslegs the original note about org name is here: https://github.com/freedomofpress/securedrop/issues/1526 @heartsucker Agreed—but that's a bridge yet to cross, that can be elegantly crossed for those users, once the time comes. In the interim, the feature should still be included, for US users. Especially as more and more ppl in big places, are using SD, more often (thank heaven). Localization isn't always pretty, and some times does require complete text-string rewrites. That's just the nature of different languages having different structures... but most localization peeps will all agree, that English does in fact meet the Gold WTF Standard for linguistics. We can only do so much. :)
2020-11-15T23:01:58Z
[]
[]
freedomofpress/securedrop
5,645
freedomofpress__securedrop-5645
[ "5514" ]
405d0cfe04d1bb7a5fb7c6d165354f3792692426
diff --git a/securedrop/create-dev-data.py b/securedrop/create-dev-data.py deleted file mode 100755 --- a/securedrop/create-dev-data.py +++ /dev/null @@ -1,223 +0,0 @@ -#!/opt/venvs/securedrop-app-code/bin/python -# -*- coding: utf-8 -*- - -import datetime -import io -import os -import argparse -import math -from itertools import cycle - -from flask import current_app - -from passphrases import PassphraseGenerator - -os.environ["SECUREDROP_ENV"] = "dev" # noqa -import journalist_app - -from sdconfig import config -from db import db -from models import Journalist, Reply, SeenFile, SeenMessage, SeenReply, Source, Submission -from specialstrings import strings - - -messages = cycle(strings) -replies = cycle(strings) - - -def main(staging: bool = False) -> None: - app = journalist_app.create_app(config) - with app.app_context(): - # Add two test users - test_password = "correct horse battery staple profanity oil chewy" - test_otp_secret = "JHCOGO7VCER3EJ4L" - - journalist_who_saw = add_test_user( - "journalist", - test_password, - test_otp_secret, - is_admin=True - ) - - if staging: - return - - dellsberg = add_test_user( - "dellsberg", - test_password, - test_otp_secret, - is_admin=False - ) - - journalist_tobe_deleted = add_test_user("clarkkent", - test_password, - test_otp_secret, - is_admin=False, - first_name="Clark", - last_name="Kent") - - NUM_SOURCES = os.getenv('NUM_SOURCES', 3) - if NUM_SOURCES == "ALL": - # We ingest two strings per source, so this will create the required - # number of sources to include all special strings - NUM_SOURCES = math.ceil(len(strings) / 2) - - # Create source data - num_sources = int(NUM_SOURCES) - for i in range(num_sources): - # For the first source, the journalist who replied will be deleted, otherwise dellsberg - journalist_who_replied = journalist_tobe_deleted if i == 0 else dellsberg - - create_source_data( - i, - num_sources, - journalist_who_replied, - journalist_who_saw - ) - - # Now let us delete one journalist - db.session.delete(journalist_tobe_deleted) - db.session.commit() - - -def add_test_user(username: str, password: str, otp_secret: str, is_admin: bool = False, - first_name: str = "", last_name: str = "") -> Journalist: - user = Journalist(username=username, - password=password, - is_admin=is_admin, - first_name=first_name, - last_name=last_name) - user.otp_secret = otp_secret - db.session.add(user) - db.session.commit() - print('Test user successfully added: ' - 'username={}, password={}, otp_secret={}, is_admin={}' - ''.format(username, password, otp_secret, is_admin)) - return user - - -def create_source_data( - source_index: int, - source_count: int, - journalist_who_replied: Journalist, - journalist_who_saw: Journalist, - num_files: int = 2, - num_messages: int = 2, - num_replies: int = 2, -) -> None: - # Store source in database - codename = PassphraseGenerator.get_default().generate_passphrase() - filesystem_id = current_app.crypto_util.hash_codename(codename) - journalist_designation = current_app.crypto_util.display_id() - source = Source(filesystem_id, journalist_designation) - source.pending = False - db.session.add(source) - db.session.commit() - - # Generate submissions directory and generate source key - os.mkdir(current_app.storage.path(source.filesystem_id)) - current_app.crypto_util.genkeypair(source.filesystem_id, codename) - - # Mark a third of sources as seen, a third as partially-seen, and a third as unseen - seen_files = 0 if source_index % 3 == 0 else math.floor(num_files / (source_index % 3)) - seen_messages = 0 if source_index % 3 == 0 else math.floor(num_messages / (source_index % 3)) - seen_replies = 0 if source_index % 3 == 0 else math.floor(num_replies / (source_index % 3)) - - # Generate some test messages - seen_messages_count = 0 - for _ in range(num_messages): - source.interaction_count += 1 - submission_text = next(messages) - fpath = current_app.storage.save_message_submission( - source.filesystem_id, - source.interaction_count, - source.journalist_filename, - submission_text - ) - source.last_updated = datetime.datetime.utcnow() - submission = Submission(source, fpath) - db.session.add(submission) - if seen_messages_count < seen_messages: - seen_messages_count = seen_messages_count + 1 - db.session.flush() - seen_message = SeenMessage( - message_id=submission.id, - journalist_id=journalist_who_saw.id - ) - db.session.add(seen_message) - - # Generate some test files - seen_files_count = 0 - for _ in range(num_files): - source.interaction_count += 1 - fpath = current_app.storage.save_file_submission( - source.filesystem_id, - source.interaction_count, - source.journalist_filename, - "memo.txt", - io.BytesIO(b"This is an example of a plain text file upload.") - ) - source.last_updated = datetime.datetime.utcnow() - submission = Submission(source, fpath) - db.session.add(submission) - if seen_files_count < seen_files: - seen_files_count = seen_files_count + 1 - db.session.flush() - seen_file = SeenFile( - file_id=submission.id, - journalist_id=journalist_who_saw.id - ) - db.session.add(seen_file) - - # Generate some test replies - seen_replies_count = 0 - for _ in range(num_replies): - source.interaction_count += 1 - fname = "{}-{}-reply.gpg".format(source.interaction_count, - source.journalist_filename) - current_app.crypto_util.encrypt( - next(replies), - [current_app.crypto_util.get_fingerprint(source.filesystem_id), - config.JOURNALIST_KEY], - current_app.storage.path(source.filesystem_id, fname)) - - reply = Reply(journalist_who_replied, source, fname) - db.session.add(reply) - db.session.flush() - # Journalist who replied has seen the reply - seen_reply = SeenReply( - reply_id=reply.id, - journalist_id=journalist_who_replied.id - ) - db.session.add(seen_reply) - if seen_replies_count < seen_replies: - seen_replies_count = seen_replies_count + 1 - seen_reply = SeenReply( - reply_id=reply.id, - journalist_id=journalist_who_saw.id - ) - db.session.add(seen_reply) - - db.session.commit() - - print( - "Test source {}/{} (codename: '{}', journalist designation '{}') " - "added with {} files, {} messages, and {} replies".format( - source_index + 1, - source_count, - codename, - journalist_designation, - num_files, - num_messages, - num_replies - ) - ) - - -if __name__ == "__main__": # pragma: no cover - parser = argparse.ArgumentParser() - parser.add_argument("--staging", help="Adding user for staging tests.", - action="store_true") - args = parser.parse_args() - - main(args.staging) diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py new file mode 100755 --- /dev/null +++ b/securedrop/loaddata.py @@ -0,0 +1,471 @@ +#!/opt/venvs/securedrop-app-code/bin/python +# -*- coding: utf-8 -*- + +""" +Loads test data into the SecureDrop database. +""" + +import argparse +import datetime +import io +import math +import os +import random +import string +from itertools import cycle +from typing import Optional, Tuple + +from flask import current_app +from sqlalchemy.exc import IntegrityError + +import journalist_app +from db import db +from models import ( + Journalist, + JournalistLoginAttempt, + Reply, + SeenFile, + SeenMessage, + SeenReply, + Source, + SourceStar, + Submission, +) +from passphrases import PassphraseGenerator +from sdconfig import config +from specialstrings import strings + +messages = cycle(strings) +replies = cycle(strings) + + +def fraction(s: str) -> float: + """ + Ensures the string is a float between 0 and 1. + """ + f = float(s) + if 0 <= f <= 1: + return f + raise ValueError("{} should be a float between 0 and 1".format(s)) + + +def non_negative_int(s: str) -> int: + """ + Ensures the string is a non-negative integer. + """ + f = float(s) + if f.is_integer() and f >= 0: + return int(f) + raise ValueError("{} is not a non-negative integer".format(s)) + + +def random_bool() -> bool: + """ + Flips a coin. + """ + return random.choice((True, False)) + + +def random_chars(count: int, chars: str = string.ascii_letters) -> str: + """ + Returns a random string of len characters from the supplied list. + """ + return "".join([random.choice(chars) for _ in range(count)]) + + +def random_datetime(nullable: bool) -> Optional[datetime.datetime]: + """ + Returns a random datetime or possibly None if nullable. + """ + if nullable and random_bool(): + return None + + now = datetime.datetime.now() + return datetime.datetime( + year=random.randint(2013, now.year), + month=random.randint(1, now.month), + day=random.randint(1, now.day), + hour=random.randint(0, 23), + minute=random.randint(0, 59), + second=random.randint(0, 59), + microsecond=random.randint(0, 1000), + ) + + +def default_journalist_count() -> str: + return os.environ.get("NUM_JOURNALISTS", "0") + + +def default_source_count() -> str: + return os.environ.get("NUM_SOURCES", "3") + + +def set_source_count(s: str) -> int: + """ + Sets the source count from command line arguments. + + The --source-count argument can be either a positive integer or + the special string "ALL", which will result in a number of sources + that can demonstrate all of the special strings we want to test, + if each source uses two of the strings. + """ + if s == "ALL": + return math.ceil(len(strings) / 2) + return non_negative_int(s) + + +def add_journalist( + username: str = "", + is_admin: bool = False, + first_name: str = "", + last_name: str = "", + progress: Optional[Tuple[int, int]] = None, +) -> Journalist: + """ + Adds a single journalist account. + """ + test_password = "correct horse battery staple profanity oil chewy" + test_otp_secret = "JHCOGO7VCER3EJ4L" + + if not username: + username = current_app.crypto_util.display_id() + + journalist = Journalist( + username=username, + password=test_password, + first_name=first_name, + last_name=last_name, + is_admin=is_admin, + ) + journalist.otp_secret = test_otp_secret + if random_bool(): + # to add legacy passwords back in + journalist.passphrase_hash = None + salt = random_chars(32).encode("utf-8") + journalist.pw_salt = salt + journalist.pw_hash = journalist._scrypt_hash(test_password, salt) + + db.session.add(journalist) + attempt = JournalistLoginAttempt(journalist) + attempt.timestamp = random_datetime(nullable=True) + db.session.add(attempt) + db.session.commit() + + print( + "Created {}journalist{} (username={}, password={}, otp_secret={}, is_admin={})".format( + "additional " if progress else "", + " {}/{}".format(*progress) if progress else "", + username, + test_password, + test_otp_secret, + is_admin, + ) + ) + return journalist + + +def record_source_interaction(source: Source) -> None: + """ + Updates the source's interaction count, pending status, and timestamp. + """ + source.interaction_count += 1 + source.pending = False + source.last_updated = datetime.datetime.utcnow() + db.session.flush() + + +def submit_message(source: Source, journalist_who_saw: Optional[Journalist]) -> None: + """ + Adds a single message submitted by a source. + """ + record_source_interaction(source) + fpath = current_app.storage.save_message_submission( + source.filesystem_id, + source.interaction_count, + source.journalist_filename, + next(messages), + ) + submission = Submission(source, fpath) + db.session.add(submission) + db.session.flush() + + if journalist_who_saw: + seen_message = SeenMessage(message_id=submission.id, journalist_id=journalist_who_saw.id) + db.session.add(seen_message) + db.session.flush() + + +def submit_file(source: Source, journalist_who_saw: Optional[Journalist]) -> None: + """ + Adds a single file submitted by a source. + """ + record_source_interaction(source) + fpath = current_app.storage.save_file_submission( + source.filesystem_id, + source.interaction_count, + source.journalist_filename, + "memo.txt", + io.BytesIO(b"This is an example of a plain text file upload."), + ) + submission = Submission(source, fpath) + db.session.add(submission) + db.session.flush() + + if journalist_who_saw: + seen_file = SeenFile(file_id=submission.id, journalist_id=journalist_who_saw.id) + db.session.add(seen_file) + db.session.flush() + + +def add_reply( + source: Source, journalist: Journalist, journalist_who_saw: Optional[Journalist] +) -> None: + """ + Adds a single reply to a source. + """ + record_source_interaction(source) + fname = "{}-{}-reply.gpg".format(source.interaction_count, source.journalist_filename) + current_app.crypto_util.encrypt( + next(replies), + [ + current_app.crypto_util.get_fingerprint(source.filesystem_id), + config.JOURNALIST_KEY, + ], + current_app.storage.path(source.filesystem_id, fname), + ) + + reply = Reply(journalist, source, fname) + db.session.add(reply) + db.session.flush() + + # Journalist who replied has seen the reply + author_seen_reply = SeenReply(reply_id=reply.id, journalist_id=journalist.id) + db.session.add(author_seen_reply) + + if journalist_who_saw: + other_seen_reply = SeenReply(reply_id=reply.id, journalist_id=journalist_who_saw.id) + db.session.add(other_seen_reply) + + db.session.commit() + + +def add_source() -> Tuple[Source, str]: + """ + Adds a single source. + """ + codename = PassphraseGenerator.get_default().generate_passphrase() + filesystem_id = current_app.crypto_util.hash_codename(codename) + journalist_designation = current_app.crypto_util.display_id() + source = Source(filesystem_id, journalist_designation) + source.pending = False + db.session.add(source) + db.session.commit() + + # Create source directory in store + os.mkdir(current_app.storage.path(source.filesystem_id)) + + # Generate source key + current_app.crypto_util.genkeypair(source.filesystem_id, codename) + + return source, codename + + +def star_source(source: Source) -> None: + """ + Adds a SourceStar record for the source. + """ + star = SourceStar(source, True) + db.session.add(star) + db.session.commit() + + +def create_default_journalists() -> Tuple[Journalist, ...]: + """ + Adds a set of journalists that should always be created. + """ + try: + default_journalist = add_journalist("journalist", is_admin=True) + except IntegrityError as e: + db.session.rollback() + if "UNIQUE constraint failed: journalists." in str(e): + default_journalist = Journalist.query.filter_by(username="journalist").one() + else: + raise e + + try: + dellsberg = add_journalist("dellsberg") + except IntegrityError as e: + db.session.rollback() + if "UNIQUE constraint failed: journalists." in str(e): + dellsberg = Journalist.query.filter_by(username="dellsberg").one() + else: + raise e + + try: + journalist_to_be_deleted = add_journalist( + username="clarkkent", first_name="Clark", last_name="Kent" + ) + except IntegrityError as e: + db.session.rollback() + if "UNIQUE constraint failed: journalists." in str(e): + journalist_to_be_deleted = Journalist.query.filter_by(username="clarkkent").one() + else: + raise e + + return default_journalist, dellsberg, journalist_to_be_deleted + + +def add_journalists(args: argparse.Namespace) -> None: + total = args.journalist_count + for i in range(1, total + 1): + add_journalist(progress=(i, total)) + + +def add_sources(args: argparse.Namespace, journalists: Tuple[Journalist, ...]) -> None: + """ + Add sources with submissions and replies. + """ + default_journalist, dellsberg, journalist_to_be_deleted = journalists + + starred_sources_count = int(args.source_count * args.source_star_fraction) + replied_sources_count = int(args.source_count * args.source_reply_fraction) + seen_message_count = max( + int(args.source_count * args.messages_per_source * args.seen_message_fraction), + 1, + ) + seen_file_count = max( + int(args.source_count * args.files_per_source * args.seen_file_fraction), 1 + ) + + for i in range(1, args.source_count + 1): + source, codename = add_source() + + for _ in range(args.messages_per_source): + submit_message(source, random.choice(journalists) if seen_message_count > 0 else None) + seen_message_count -= 1 + + for _ in range(args.files_per_source): + submit_file(source, random.choice(journalists) if seen_file_count > 0 else None) + seen_file_count -= 1 + + if i <= starred_sources_count: + star_source(source) + + if i <= replied_sources_count: + for _ in range(args.replies_per_source): + journalist_who_replied = random.choice([dellsberg, journalist_to_be_deleted]) + journalist_who_saw = random.choice([default_journalist, None]) + add_reply(source, journalist_who_replied, journalist_who_saw) + + print( + "Created source {}/{} (codename: '{}', journalist designation '{}', " + "files: {}, messages: {}, replies: {})".format( + i, + args.source_count, + codename, + source.journalist_designation, + args.files_per_source, + args.messages_per_source, + args.replies_per_source if i <= replied_sources_count else 0, + ) + ) + + +def load(args: argparse.Namespace) -> None: + """ + Populate the database. + """ + if args.seed: + random.seed(args.seed) + + if not os.environ.get("SECUREDROP_ENV"): + os.environ["SECUREDROP_ENV"] = "dev" + + app = journalist_app.create_app(config) + with app.app_context(): + journalists = create_default_journalists() + + add_journalists(args) + + add_sources(args, journalists) + + # delete one journalist + _, _, journalist_to_be_deleted = journalists + db.session.delete(journalist_to_be_deleted) + db.session.commit() + + +def parse_arguments() -> argparse.Namespace: + """ + Parses the command line arguments. + """ + parser = argparse.ArgumentParser( + os.path.basename(__file__), + description="Loads test data into the database", + ) + parser.add_argument( + "--journalist-count", + type=non_negative_int, + default=default_journalist_count(), + help=("Number of journalists to create in addition to the default accounts"), + ) + parser.add_argument( + "--source-count", + type=set_source_count, + default=default_source_count(), + help=( + 'Number of sources to create, or "ALL" to create a number sufficient to ' + "demonstrate all of our test strings." + ), + ) + parser.add_argument( + "--messages-per-source", + type=non_negative_int, + default=2, + help=("Number of submitted messages to create for each source"), + ) + parser.add_argument( + "--files-per-source", + type=non_negative_int, + default=2, + help=("Number of submitted files to create for each source"), + ) + parser.add_argument( + "--replies-per-source", + type=non_negative_int, + default=2, + help=("Number of replies to create for any source that receives replies"), + ) + parser.add_argument( + "--source-star-fraction", + type=fraction, + default=0.1, + help=("Fraction of sources with stars"), + ) + parser.add_argument( + "--source-reply-fraction", + type=fraction, + default=1, + help=("Fraction of sources with replies"), + ) + parser.add_argument( + "--seen-message-fraction", + type=fraction, + default=0.75, + help=("Fraction of messages seen by a journalist"), + ) + parser.add_argument( + "--seen-file-fraction", + type=fraction, + default=0.75, + help=("Fraction of files seen by a journalist"), + ) + parser.add_argument( + "--seed", + help=("Random number seed (for reproducible datasets)"), + ) + return parser.parse_args() + + +if __name__ == "__main__": # pragma: no cover + load(parse_arguments()) diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -457,7 +457,7 @@ def __repr__(self) -> str: _LEGACY_SCRYPT_PARAMS = dict(N=2**14, r=8, p=1) - def _scrypt_hash(self, password: str, salt: bytes) -> str: + def _scrypt_hash(self, password: str, salt: bytes) -> bytes: return scrypt.hash(str(password), salt, **self._LEGACY_SCRYPT_PARAMS) MAX_PASSWORD_LEN = 128 diff --git a/securedrop/qa_loader.py b/securedrop/qa_loader.py deleted file mode 100755 --- a/securedrop/qa_loader.py +++ /dev/null @@ -1,318 +0,0 @@ -#!/opt/venvs/securedrop-app-code/bin/python -# -*- coding: utf-8 -*- - -import os -import random -import string -import sys -from argparse import ArgumentParser -from datetime import datetime -from itertools import cycle -from os import path -from typing import Optional - -from flask import current_app -from typing import List - -from crypto_util import DICEWARE_SAFE_CHARS -from db import db -from journalist_app import create_app -from models import Journalist, JournalistLoginAttempt, Reply, Source, SourceStar, Submission -from sdconfig import SDConfig -from passphrases import PassphraseGenerator -from sdconfig import config as sdconfig - - -def random_bool() -> bool: - return bool(random.getrandbits(1)) - - -def random_chars(len: int, chars: str = string.ascii_letters) -> str: - return "".join([random.choice(chars) for _ in range(len)]) - - -def bool_or_none() -> Optional[bool]: - return random.choice([True, False, None]) - - -def random_datetime(nullable: bool) -> Optional[datetime]: - if nullable and random_bool(): - return None - else: - now = datetime.now() - return datetime( - year=random.randint(2013, now.year), - month=random.randint(1, now.month), - day=random.randint(1, now.day), - hour=random.randint(0, 23), - minute=random.randint(0, 59), - second=random.randint(0, 59), - microsecond=random.randint(0, 1000), - ) - - -def positive_int(s: str) -> int: - i = int(s) - if i < 1: - raise ValueError("{} is not >= 1".format(s)) - return i - - -def fraction(s: str) -> float: - f = float(s) - if 0 <= f <= 1: - return f - raise ValueError("{} should be a float between 0 and 1".format(s)) - - -submissions = cycle( - [ - "This is a test submission without markup!", - 'This is a test submission with markup and characters such as \, \\, \', " and ". ' - + "<strong>This text should not be bold</strong>!", # noqa: W605, E501 - ] -) - - -replies = cycle( - [ - "This is a test reply without markup!", - 'This is a test reply with markup and characters such as \, \\, \', " and ". ' - + "<strong>This text should not be bold</strong>!", # noqa: W605, E501 - ] -) - - -class QaLoader: - def __init__( - self, - config: SDConfig, - journalist_count: int = 10, - source_count: int = 50, - submissions_per_source: int = 1, - replies_per_source: int = 1, - source_star_fraction: float = 0.1, - source_reply_fraction: float = 0.5, - ) -> None: - """ - source_star_fraction and source_reply_fraction are simply the - fraction of sources starred or replied to. - """ - self.config = config - self.app = create_app(config) - - self.journalist_count = journalist_count - self.source_count = source_count - self.submissions_per_source = submissions_per_source - self.replies_per_source = replies_per_source - self.source_star_fraction = source_star_fraction - self.source_reply_fraction = source_reply_fraction - - self.journalists = [] # type: List[int] - self.sources = [] # type: List[int] - - def new_journalist(self) -> None: - # Make a diceware-like password - pw = " ".join( - [random_chars(3, chars=DICEWARE_SAFE_CHARS) for _ in range(7)] - ) - journalist = Journalist( - username=random_chars(random.randint(3, 32)), - password=pw, - is_admin=random_bool(), - ) - if random_bool(): - # to add legacy passwords back in - journalist.passphrase_hash = None - journalist.pw_salt = random_chars(32).encode("utf-8") - journalist.pw_hash = random_chars(64).encode("utf-8") - - journalist.is_admin = bool_or_none() - - journalist.is_totp = bool_or_none() - journalist.hotp_counter = random.randint(-1000, 1000) if random_bool() else None - journalist.created_on = random_datetime(nullable=True) - journalist.last_access = random_datetime(nullable=True) - - db.session.add(journalist) - db.session.flush() - self.journalists.append(journalist.id) - - def new_source(self) -> None: - codename = PassphraseGenerator.get_default().generate_passphrase() - filesystem_id = current_app.crypto_util.hash_codename(codename) - journalist_designation = current_app.crypto_util.display_id() - source = Source(filesystem_id, journalist_designation) - db.session.add(source) - db.session.flush() - - # Generate submissions directory and generate source key - os.mkdir(current_app.storage.path(source.filesystem_id)) - current_app.crypto_util.genkeypair(source.filesystem_id, codename) - - self.sources.append(source.id) - - def new_submission(self, source_id: int) -> None: - source = Source.query.get(source_id) - - source.interaction_count += 1 - fpath = current_app.storage.save_message_submission( - source.filesystem_id, - source.interaction_count, - source.journalist_filename, - next(submissions), - ) - submission = Submission(source, fpath) - db.session.add(submission) - - source.pending = False - source.last_updated = datetime.utcnow() - - db.session.flush() - - def new_source_star(self, source_id: int) -> None: - source = Source.query.get(source_id) - star = SourceStar(source, random.choice([True, False])) - db.session.add(star) - - def new_reply(self, journalist_id: int, source_id: int) -> None: - source = Source.query.get(source_id) - - journalist = Journalist.query.get(journalist_id) - - source.interaction_count += 1 - source.last_updated = datetime.utcnow() - - fname = "{}-{}-reply.gpg".format(source.interaction_count, source.journalist_filename) - current_app.crypto_util.encrypt( - next(replies), - [ - current_app.crypto_util.get_fingerprint(source.filesystem_id), - sdconfig.JOURNALIST_KEY - ], - current_app.storage.path(source.filesystem_id, fname), - ) - - reply = Reply(journalist, source, fname) - db.session.add(reply) - db.session.flush() - - def new_journalist_login_attempt(self, journalist_id: int) -> None: - journalist = Journalist.query.get(journalist_id) - attempt = JournalistLoginAttempt(journalist) - attempt.timestamp = random_datetime(nullable=True) - db.session.add(attempt) - - def load(self) -> None: - with self.app.app_context(): - print("Creating {:d} journalists...".format(self.journalist_count)) - for i in range(1, self.journalist_count + 1): - self.new_journalist() - if i % min(10, max(1, int(self.journalist_count / 10))) == 0: - sys.stdout.write("{}\r{}".format(" " * len(str(self.journalist_count + 1)), i)) - print("\n") - db.session.commit() - - print("Creating {:d} sources...".format(self.source_count)) - for i in range(1, self.source_count + 1): - self.new_source() - if i % min(10, max(1, int(self.source_count / 10))) == 0: - sys.stdout.write("{}\r{}".format(" " * len(str(self.source_count + 1)), i)) - print("\n") - db.session.commit() - - print( - "Creating submissions ({:d} each) for each source...".format( - self.submissions_per_source - ) - ) - for sid in self.sources: - for _ in range(1, self.submissions_per_source + 1): - self.new_submission(sid) - db.session.commit() - - print("Starring {:.2f}% of all sources...".format(self.source_star_fraction * 100)) - for sid in random.sample( - self.sources, int(self.source_count * self.source_star_fraction) - ): - self.new_source_star(sid) - db.session.commit() - - print( - "Creating replies ({:d} each) for {:.2f}% of sources...".format( - self.replies_per_source, self.source_reply_fraction * 100 - ) - ) - for sid in random.sample( - self.sources, int(self.source_count * self.source_reply_fraction) - ): - jid = random.choice(self.journalists) - for _ in range(self.replies_per_source): - self.new_reply(jid, sid) - db.session.commit() - - for jid in self.journalists: - self.new_journalist_login_attempt(jid) - db.session.commit() - - -def arg_parser() -> ArgumentParser: - parser = ArgumentParser( - path.basename(__file__), description="Loads data into the database for testing upgrades" - ) - parser.add_argument( - "--journalist-count", - type=positive_int, - default=10, - help=("Number of journalists to create"), - ) - parser.add_argument( - "--source-count", type=positive_int, default=50, help=("Number of sources to create") - ) - parser.add_argument( - "--submissions-per-source", - type=positive_int, - default=1, - help=("Number of submissions to create for each source"), - ) - parser.add_argument( - "--replies-per-source", - type=positive_int, - default=1, - help=("Number of replies to create for each source"), - ) - parser.add_argument( - "--source-star-fraction", - type=fraction, - default=0.1, - help=("Fraction of sources to star"), - ) - parser.add_argument( - "--source-reply-fraction", - type=fraction, - default=0.5, - help=("Fraction of sources to reply to"), - ) - return parser - - -def main() -> None: - args = arg_parser().parse_args() - print("Loading data. This may take a while.") - QaLoader( - sdconfig, - args.journalist_count, - args.source_count, - args.submissions_per_source, - args.replies_per_source, - args.source_star_fraction, - args.source_reply_fraction, - ).load() - - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - print("") # for prompt on a newline - sys.exit(1)
diff --git a/securedrop/tests/functional/README.md b/securedrop/tests/functional/README.md --- a/securedrop/tests/functional/README.md +++ b/securedrop/tests/functional/README.md @@ -3,7 +3,7 @@ - `sudo -u www-data bash` - `cd /var/www/securedrop/` - `./manage.py reset` # This will clean the DB for testing -- `./create-dev-data.py --staging` +- `./loaddata.py` Update this information to the `tests/functional/instance_information.json` file. diff --git a/securedrop/tests/test_qa_loader.py b/securedrop/tests/test_qa_loader.py deleted file mode 100644 --- a/securedrop/tests/test_qa_loader.py +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- - -from qa_loader import QaLoader - - -def test_load_data(journalist_app, config): - # Use the journalist_app fixture to init the DB - QaLoader(config).load()
Add `seen` data to `qa_loader` #5505 will add the tables to support the seen/unseen feature in the SecureDrop Client (https://github.com/freedomofpress/securedrop-client/issues/187). To test this feature, it will be helpful to have some `seen` annotations for submissions generated through the loader.
I would suggest that all replies generated by the scripts should be marked as seen by one user, because there will never be a situation under which they are not at least seen by the sender. Given the heavy focus on SecureDrop Workstation template consolidation and the SecureDrop Core release this sprint, we've agreed to defer work on this for now during the 10/1-10/15 sprint period, likely until the next sprint. Contributor help welcome before then, though, so tagging accordingly :) Whoops closed this by saying `partially resolves` this issue in the pr that was merged above. Reopening because we still need to update qa_loader to show seen data (and file submissions so we can test file-specific changes, but this can be done separately if one so chooses). I updated the title and description of this issue accordingly.
2020-11-18T20:51:10Z
[]
[]
freedomofpress/securedrop
5,651
freedomofpress__securedrop-5651
[ "4421" ]
95f0d7ea5dc4cbb9cca8b060c4a8a993c94e60f2
diff --git a/securedrop/source_app/info.py b/securedrop/source_app/info.py --- a/securedrop/source_app/info.py +++ b/securedrop/source_app/info.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import flask -from flask import Blueprint, render_template, send_file, current_app +from flask import Blueprint, render_template, send_file, current_app, redirect, url_for +import werkzeug from io import BytesIO # noqa @@ -18,8 +19,8 @@ def tor2web_warning() -> str: def recommend_tor_browser() -> str: return render_template("use-tor-browser.html") - @view.route('/journalist-key') - def download_journalist_pubkey() -> flask.Response: + @view.route('/public-key') + def download_public_key() -> flask.Response: journalist_pubkey = current_app.crypto_util.gpg.export_keys( config.JOURNALIST_KEY) data = BytesIO(journalist_pubkey.encode('utf-8')) @@ -28,8 +29,12 @@ def download_journalist_pubkey() -> flask.Response: attachment_filename=config.JOURNALIST_KEY + ".asc", as_attachment=True) - @view.route('/why-journalist-key') - def why_download_journalist_pubkey() -> str: - return render_template("why-journalist-key.html") + @view.route('/journalist-key') + def download_journalist_key() -> werkzeug.wrappers.Response: + return redirect(url_for('.download_public_key'), code=301) + + @view.route('/why-public-key') + def why_download_public_key() -> str: + return render_template("why-public-key.html") return view
diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -223,7 +223,7 @@ def _source_tor2web_warning(self): self.driver.get(self.source_location + "/tor2web-warning") def _source_why_journalist_key(self): - self.driver.get(self.source_location + "/why-journalist-key") + self.driver.get(self.source_location + "/why-public-key") def _source_waits_for_session_to_timeout(self): time.sleep(self.session_expiration + 2) diff --git a/securedrop/tests/functional/test_source.py b/securedrop/tests/functional/test_source.py --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -48,7 +48,7 @@ class TestDownloadKey( def test_journalist_key_from_source_interface(self): data = self.return_downloaded_content(self.source_location + - "/journalist-key", None) + "/public-key", None) data = data.decode('utf-8') assert "BEGIN PGP PUBLIC KEY BLOCK" in data diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -5,7 +5,7 @@ import time from io import BytesIO, StringIO -from flask import session, escape, current_app, url_for, g +from flask import session, escape, current_app, url_for, g, request from mock import patch, ANY import crypto_util @@ -204,11 +204,21 @@ def test_lookup(source_app): text = resp.data.decode('utf-8') assert "public key" in text # download the public key - resp = app.get(url_for('info.download_journalist_pubkey')) + resp = app.get(url_for('info.download_public_key')) text = resp.data.decode('utf-8') assert "BEGIN PGP PUBLIC KEY BLOCK" in text +def test_journalist_key_redirects_to_public_key(source_app): + """Test that the /journalist-key route redirects to /public-key.""" + with source_app.test_client() as app: + resp = app.get(url_for('info.download_journalist_key')) + assert resp.status_code == 301 + resp = app.get(url_for('info.download_journalist_key'), follow_redirects=True) + assert request.path == url_for('info.download_public_key') + assert "BEGIN PGP PUBLIC KEY BLOCK" in resp.data.decode('utf-8') + + def test_login_and_logout(source_app): with source_app.test_client() as app: resp = app.get(url_for('main.login')) @@ -576,7 +586,7 @@ def test_why_use_tor_browser(source_app): def test_why_journalist_key(source_app): with source_app.test_client() as app: - resp = app.get(url_for('info.why_download_journalist_pubkey')) + resp = app.get(url_for('info.why_download_public_key')) assert resp.status_code == 200 text = resp.data.decode('utf-8') assert "Why download the team's public key?" in text
"Journalist key" in source interface is not (typically) a journalist key The *Source Interface* refers to "the journalist's public key", both through the `/journalist-key` and `/why-journalist-key` route names, and in the page heading on the `/why-journalist-key` page, "Why download the journalist's public key?" This is very misleading wording, as most SecureDrops are operated by news organizations employing more than one journalist. This key is in fact the SecureDrop Submission Key for this installation, the _exact same_ key that messages/files will be encrypted to upon submission. (See #4413 for terminology standardization.) Offering technical users the option to pre-encrypt is essentially a workaround until we establish a reasonable method for automatic client-side encryption (see #92). To avoid messing up people's mental model of how SecureDrop works, we should rename this route, especially given that we do refer to managing individual journalist keys in parts of the documentation (for completely different reasons: to securely export files from the *Secure Viewing Station*).
@DrGFreeman Are you potentially interested in helping with this, as well? @eloquence, sure, I can get on it shortly. So my understanding is that only the routes need renaming as the Source Interface now refers to the key as "our public key" (on `/lookup` and "the team's public key" on `/why-journalist-key`.
2020-11-25T01:02:41Z
[]
[]
freedomofpress/securedrop
5,679
freedomofpress__securedrop-5679
[ "5672" ]
0454478edb8d97f53e0659013261c68bbfca5aeb
diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -53,8 +53,13 @@ def create_app(config: 'SDConfig') -> Flask: app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI db.init_app(app) - v2_enabled = path.exists(path.join(config.SECUREDROP_DATA_ROOT, 'source_v2_url')) - v3_enabled = path.exists(path.join(config.SECUREDROP_DATA_ROOT, 'source_v3_url')) + def _url_exists(u: str) -> bool: + return path.exists(path.join(config.SECUREDROP_DATA_ROOT, u)) + + v2_enabled = _url_exists('source_v2_url') or ((not _url_exists('source_v2_url')) + and (not _url_exists('source_v3_url'))) + v3_enabled = _url_exists('source_v3_url') + app.config.update(V2_ONION_ENABLED=v2_enabled, V3_ONION_ENABLED=v3_enabled) # TODO: Attaching a Storage dynamically like this disables all type checking (and @@ -161,9 +166,12 @@ def setup_g() -> 'Optional[Response]': else: g.organization_name = gettext('SecureDrop') - if not app.config['V3_ONION_ENABLED'] or app.config['V2_ONION_ENABLED']: + if app.config['V2_ONION_ENABLED'] and not app.config['V3_ONION_ENABLED']: g.show_v2_onion_eol_warning = True + if app.config['V2_ONION_ENABLED'] and app.config['V3_ONION_ENABLED']: + g.show_v2_onion_migration_warning = True + if request.path.split('/')[1] == 'api': pass # We use the @token_required decorator for the API endpoints else: # We are not using the API
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -76,7 +76,8 @@ def test_user_sees_v2_eol_warning_if_only_v2_is_enabled(config, journalist_app, resp = app.get(url_for('main.index')) text = resp.data.decode('utf-8') - assert "v2-onion-eol" in text, text + assert 'id="v2-onion-eol"' in text, text + assert 'id="v2-complete-migration"' not in text, text def test_user_sees_v2_eol_warning_if_both_v2_and_v3_enabled(config, journalist_app, test_journo): @@ -91,7 +92,8 @@ def test_user_sees_v2_eol_warning_if_both_v2_and_v3_enabled(config, journalist_a resp = app.get(url_for('main.index')) text = resp.data.decode('utf-8') - assert "v2-onion-eol" in text, text + assert 'id="v2-onion-eol"' not in text, text + assert 'id="v2-complete-migration"' in text, text def test_user_does_not_see_v2_eol_warning_if_only_v3_enabled(config, journalist_app, test_journo): @@ -106,22 +108,8 @@ def test_user_does_not_see_v2_eol_warning_if_only_v3_enabled(config, journalist_ resp = app.get(url_for('main.index')) text = resp.data.decode('utf-8') - assert "v2-onion-eol" not in text, text - - -def test_user_sees_v2_eol_warning_if_both_urls_do_not_exist(config, journalist_app, test_journo): - journalist_app.config.update(V2_ONION_ENABLED=False, V3_ONION_ENABLED=False) - with journalist_app.test_client() as app: - _login_user( - app, - test_journo['username'], - test_journo['password'], - test_journo['otp_secret']) - - resp = app.get(url_for('main.index')) - - text = resp.data.decode('utf-8') - assert "v2-onion-eol" in text, text + assert 'id="v2-onion-eol"' not in text, text + assert 'id="v2-complete-migration"' not in text, text def test_user_with_whitespace_in_username_can_login(journalist_app):
Add clearer action reminder in Journalist Interface to enable v3 As part of the 1.7.0 release, we've agreed that we want to improve our reminder in the Journalist Interface to enable v3 onion services. The current banner looks as follows: ![Screen Shot 2020-12-15 at 15 18 06-fullpage](https://user-images.githubusercontent.com/213636/102284729-913e1880-3ee9-11eb-9518-8b685d2b0e5a.png) You can also see it on https://demo-journalist.securedrop.org/ after logging in using the dev credentials. The plan of record is as follows: - SecureDrop 1.7.0 (released in January) will still fully support v2 onion services - SecureDrop 1.8.0 (released in February) will support Ubuntu 20.04 (#4768), and _exclusively_ support v3 onion services for Focal installs, without changing the behavior on Xenial. - After April 30 (Ubuntu 16.04 EOL), instances not upgraded to Ubuntu 20.04 will self-disable. In other words, the v3 switch is unavoidable due to the Xenial end-of-life. Our goal with the 1.7.0 release is to get more admins to make the switch prior to a reinstall on Focal, to make the process a bit easier for them. The specific action we need to motivate: 1) *If v3 is already enabled, but v2 services are still available:* Disable v2 services, ensure that all journalists/admins have v3 creds, and ensure that landing page points to v3 onion. 2) *If v3 is not enabled yet:* Enable v3 services (can still run them alongside v2 for a bit, per docs, then go v3-only). We've discussed that this could potentially be done via different banners for 1) and 2) in the Journalist Interface. Let's kick around language/UX a bit in the comments, and I'll add the final agreed upon spec to the top-level issue. ## User Story As an administrator, I want to be reminded of critical actions I must take to keep my instance running, so that I'm not caught by surprise.
Some initial suggestions re: UX & language: - I think a more urgent banner color is appropriate in either case. - For case 1: **Action Required:** Your SecureDrop servers are still reachable via v2 and v3 onion services. Make sure admins, journalists and sources are using v3 onion services, then disable v2 onion services. [Learn more] - For case 2: **Action Required:** You must switch your SecureDrop to v3 onion services to ensure that it is reachable after April 30, 2021. [Learn more] The omission of "April 30" in case 1 is intentional; IMO here it is most important to emphasize internal action vis-a-vis journalists & sources. Bear in mind that these banners would be swapped out again with the 1.8.0 release a few weeks later, which would emphasize the Ubuntu 20.04 transition and the April 30 deadline.
2020-12-21T16:45:31Z
[]
[]
freedomofpress/securedrop
5,697
freedomofpress__securedrop-5697
[ "5069" ]
baf0bfa82b15990513cdd18cdc1aa68739b991ee
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -15,151 +15,222 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # -from flask import Flask -from flask import request, session -from flask_babel import Babel -from babel import core - import collections -import os -import re -from typing import List +from typing import Dict, List -from typing import Dict +from babel.core import ( + Locale, + UnknownLocaleError, + get_locale_identifier, + negotiate_locale, + parse_locale, +) +from flask import Flask, g, request, session +from flask_babel import Babel from sdconfig import SDConfig -LOCALE_SPLIT = re.compile('(-|_)') -LOCALES = ['en_US'] -babel = None +class RequestLocaleInfo: + """ + Convenience wrapper around a babel.core.Locale. + """ -class LocaleNotFound(Exception): + def __init__(self, locale: str): + self.locale = Locale.parse(locale) - """Raised when the desired locale is not in the translations directory""" + def __str__(self) -> str: + """ + The Babel string representation of the locale. + """ + return str(self.locale) + @property + def text_direction(self) -> str: + """ + The Babel text direction: ltr or rtl. + + Used primarily to set text direction in HTML via the "dir" + attribute. + """ + return self.locale.text_direction + + @property + def language(self) -> str: + """ + The Babel language name. + + Just the language, without subtag info like region or script. + """ + return self.locale.language + + @property + def id(self) -> str: + """ + The Babel string representation of the locale. + + This should match the name of the directory containing its + translations. + """ + return str(self.locale) + + @property + def language_tag(self) -> str: + """ + Returns a BCP47/RFC5646 language tag for the locale. + + Language tags are used in HTTP headers and the HTML lang + attribute. + """ + return get_locale_identifier(parse_locale(str(self.locale)), sep="-") -def setup_app(config: SDConfig, app: Flask) -> None: - global LOCALES - global babel - # `babel.translation_directories` is a nightmare - # We need to set this manually via an absolute path - app.config['BABEL_TRANSLATION_DIRECTORIES'] = str(config.TRANSLATION_DIRS.absolute()) +def configure_babel(config: SDConfig, app: Flask) -> None: + """ + Set up Flask-Babel according to the SecureDrop configuration. + """ + # Tell Babel where to find our translations. + translations_directory = str(config.TRANSLATION_DIRS.absolute()) + app.config["BABEL_TRANSLATION_DIRECTORIES"] = translations_directory + # Create the app's Babel instance. Passing the app to the + # constructor causes the instance to attach itself to the app. babel = Babel(app) - if len(list(babel.translation_directories)) != 1: - raise AssertionError( - 'Expected exactly one translation directory but got {}.' - .format(babel.translation_directories)) - - translation_directories = next(babel.translation_directories) - for dirname in os.listdir(translation_directories): - if dirname != 'messages.pot': - LOCALES.append(dirname) - - LOCALES = _get_supported_locales( - LOCALES, - config.SUPPORTED_LOCALES, - config.DEFAULT_LOCALE, - translation_directories) + # verify that Babel is only using the translations we told it about + if list(babel.translation_directories) != [translations_directory]: + raise ValueError( + "Babel translation directories ({}) do not match SecureDrop configuration ({})".format( + babel.translation_directories, [translations_directory] + ) + ) + + # register the function used to determine the locale of a request babel.localeselector(lambda: get_locale(config)) +def validate_locale_configuration(config: SDConfig, app: Flask) -> None: + """ + Ensure that the configured locales are valid and translated. + """ + if config.DEFAULT_LOCALE not in config.SUPPORTED_LOCALES: + raise ValueError( + 'The default locale "{}" is not included in the set of supported locales "{}"'.format( + config.DEFAULT_LOCALE, config.SUPPORTED_LOCALES + ) + ) + + translations = app.babel_instance.list_translations() + for locale in config.SUPPORTED_LOCALES: + if locale == "en_US": + continue + + parsed = Locale.parse(locale) + if parsed not in translations: + raise ValueError( + 'Configured locale "{}" is not in the set of translated locales "{}"'.format( + parsed, translations + ) + ) + + +LOCALES = collections.OrderedDict() # type: collections.OrderedDict[str, str] + + +def map_locale_display_names(config: SDConfig) -> None: + """ + Create a map of locale identifiers to names for display. + + For most of our supported languages, we only provide one + translation, so including the full display name is not necessary + to distinguish them. For languages with more than one translation, + like Chinese, we do need the additional detail. + """ + language_locale_counts = collections.defaultdict(int) # type: Dict[str, int] + for l in sorted(config.SUPPORTED_LOCALES): + locale = Locale.parse(l) + language_locale_counts[locale.language_name] += 1 + + locale_map = collections.OrderedDict() + for l in sorted(config.SUPPORTED_LOCALES): + locale = Locale.parse(l) + if language_locale_counts[locale.language_name] == 1: + name = locale.language_name + else: + name = locale.display_name + locale_map[str(locale)] = name + + global LOCALES + LOCALES = locale_map + + +def configure(config: SDConfig, app: Flask) -> None: + configure_babel(config, app) + validate_locale_configuration(config, app) + map_locale_display_names(config) + + def get_locale(config: SDConfig) -> str: """ + Return the best supported locale for a request. + Get the locale as follows, by order of precedence: - l request argument or session['locale'] - browser suggested locale, from the Accept-Languages header - config.DEFAULT_LOCALE - - 'en_US' """ - accept_languages = [] - for l in list(request.accept_languages.values()): - if '-' in l: - sep = '-' - else: - sep = '_' - try: - accept_languages.append(str(core.Locale.parse(l, sep))) - except Exception: - pass - if 'l' in request.args: - if len(request.args['l']) == 0: - if 'locale' in session: - del session['locale'] - locale = core.negotiate_locale(accept_languages, LOCALES) - else: - locale = core.negotiate_locale([request.args['l']], LOCALES) - session['locale'] = locale - else: - if 'locale' in session: - locale = session['locale'] - else: - locale = core.negotiate_locale(accept_languages, LOCALES) + # Default to any locale set in the session. + locale = session.get("locale") - if locale: - return locale - else: - return config.DEFAULT_LOCALE + # A valid locale specified in request.args takes precedence. + if request.args.get("l"): + negotiated = negotiate_locale([request.args["l"]], LOCALES.keys()) + if negotiated: + locale = negotiated + # If the locale is not in the session or request.args, negotiate + # the best supported option from the browser's accepted languages. + if not locale: + locale = negotiate_locale(get_accepted_languages(), LOCALES.keys()) -def get_text_direction(locale: str) -> str: - return core.Locale.parse(locale).text_direction + # Finally, fall back to the default locale if necessary. + return locale or config.DEFAULT_LOCALE -def _get_supported_locales(locales: List[str], supported: List[str], default_locale: str, - translation_directories: str) -> List[str]: - """Sanity checks on locales and supported locales from config.py. - Return the list of supported locales. +def get_accepted_languages() -> List[str]: """ - - if not supported: - return [default_locale or 'en_US'] - unsupported = set(supported) - set(locales) - if unsupported: - raise LocaleNotFound( - "config.py SUPPORTED_LOCALES contains {} which is not among the " - "locales found in the {} directory: {}".format( - list(unsupported), - translation_directories, - locales)) - if default_locale and default_locale not in supported: - raise LocaleNotFound("config.py SUPPORTED_LOCALES contains {} " - "which does not include " - "the value of DEFAULT_LOCALE '{}'".format( - supported, default_locale)) - - return list(supported) - - -NAME_OVERRIDES = { - 'nb_NO': 'norsk', -} - - -def get_locale2name() -> Dict[str, str]: - locale2name = collections.OrderedDict() - for l in LOCALES: - if l in NAME_OVERRIDES: - locale2name[l] = NAME_OVERRIDES[l] - else: - locale = core.Locale.parse(l) - locale2name[l] = locale.languages[locale.language] - return locale2name - - -def locale_to_rfc_5646(locale: str) -> str: - lower = locale.lower() - if 'hant' in lower: - return 'zh-Hant' - elif 'hans' in lower: - return 'zh-Hans' - else: - return LOCALE_SPLIT.split(locale)[0] + Convert a request's list of accepted languages into locale identifiers. + """ + accept_languages = [] + for l in request.accept_languages.values(): + try: + parsed = Locale.parse(l, "-") + accept_languages.append(str(parsed)) + + # We only have two Chinese translations, simplified + # and traditional, based on script and not + # region. Browsers tend to send identifiers with + # region, e.g. zh-CN or zh-TW. Babel can generally + # infer the script from those, so we can fabricate a + # fallback entry without region, in the hope that it + # will match one of our translations and the site will + # at least be more legible at first contact than the + # probable default locale of English. + if parsed.language == "zh" and parsed.script: + accept_languages.append( + str(Locale(language=parsed.language, script=parsed.script)) + ) + except (ValueError, UnknownLocaleError): + pass + return accept_languages -def get_language(config: SDConfig) -> str: - return get_locale(config).split('_')[0] +def set_locale(config: SDConfig) -> None: + """ + Update locale info in request and session. + """ + locale = get_locale(config) + g.localeinfo = RequestLocaleInfo(locale) + session["locale"] = locale + g.locales = LOCALES diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -56,6 +56,7 @@ class I18NTool: 'sk': {'name': 'Slovak', 'desktop': 'sk', }, 'sv': {'name': 'Swedish', 'desktop': 'sv', }, 'tr': {'name': 'Turkish', 'desktop': 'tr', }, + 'zh_Hans': {'name': 'Chinese, Simplified', 'desktop': 'zh_Hans', }, 'zh_Hant': {'name': 'Chinese, Traditional', 'desktop': 'zh_Hant', }, } release_tag_re = re.compile(r"^\d+\.\d+\.\d+$") diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -102,7 +102,7 @@ def _handle_http_exception( for code in default_exceptions: app.errorhandler(code)(_handle_http_exception) - i18n.setup_app(config, app) + i18n.configure(config, app) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True @@ -156,10 +156,7 @@ def setup_g() -> 'Optional[Response]': if uid: g.user = Journalist.query.get(uid) - g.locale = i18n.get_locale(config) - g.text_direction = i18n.get_text_direction(g.locale) - g.html_lang = i18n.locale_to_rfc_5646(g.locale) - g.locales = i18n.get_locale2name() + i18n.set_locale(config) if app.instance_config.organization_name: g.organization_name = app.instance_config.organization_name diff --git a/securedrop/journalist_app/account.py b/securedrop/journalist_app/account.py --- a/securedrop/journalist_app/account.py +++ b/securedrop/journalist_app/account.py @@ -6,7 +6,6 @@ flash, session) from flask_babel import gettext -import i18n from db import db from journalist_app.utils import (set_diceware_password, set_name, validate_user, validate_hotp_secret) @@ -20,7 +19,7 @@ def make_blueprint(config: SDConfig) -> Blueprint: @view.route('/account', methods=('GET',)) def edit() -> str: password = PassphraseGenerator.get_default().generate_passphrase( - preferred_language=i18n.get_language(config) + preferred_language=g.localeinfo.language ) return render_template('edit_account.html', password=password) diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -11,7 +11,6 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound -import i18n from db import db from html import escape from models import (InstanceConfig, Journalist, InvalidUsernameException, @@ -153,7 +152,7 @@ def add_user() -> Union[str, werkzeug.Response]: uid=new_user.id)) password = PassphraseGenerator.get_default().generate_passphrase( - preferred_language=i18n.get_language(config) + preferred_language=g.localeinfo.language ) return render_template("admin_add_user.html", password=password, @@ -253,7 +252,7 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: commit_account_changes(user) password = PassphraseGenerator.get_default().generate_passphrase( - preferred_language=i18n.get_language(config) + preferred_language=g.localeinfo.language ) return render_template("edit_account.html", user=user, password=password) diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -5,7 +5,7 @@ from typing import Type import config as _config -from typing import List +from typing import Set class SDConfig: @@ -58,9 +58,11 @@ def __init__(self) -> None: self.DEFAULT_LOCALE = getattr( _config, "DEFAULT_LOCALE", "en_US" ) # type: str - self.SUPPORTED_LOCALES = getattr( + supported_locales = set(getattr( _config, "SUPPORTED_LOCALES", [self.DEFAULT_LOCALE] - ) # type: List[str] + )) # type: Set[str] + supported_locales.add(self.DEFAULT_LOCALE) + self.SUPPORTED_LOCALES = sorted(list(supported_locales)) translation_dirs_in_conf = getattr(_config, "TRANSLATION_DIRS", None) # type: Optional[str] if translation_dirs_in_conf: diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -34,6 +34,14 @@ def create_app(config: SDConfig) -> Flask: app.request_class = RequestThatSecuresFileUploads app.config.from_object(config.SOURCE_APP_FLASK_CONFIG_CLS) + i18n.configure(config, app) + + @app.before_request + @ignore_static + def setup_i18n() -> None: + """Store i18n-related values in Flask's special g object""" + i18n.set_locale(config) + # The default CSRF token expiration is 1 hour. Since large uploads can # take longer than an hour over Tor, we increase the valid window to 24h. app.config['WTF_CSRF_TIME_LIMIT'] = 60 * 60 * 24 @@ -71,8 +79,6 @@ def handle_csrf_error(e: CSRFError) -> werkzeug.Response: assets = Environment(app) app.config['assets'] = assets - i18n.setup_app(config, app) - app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals['version'] = version.__version__ @@ -86,15 +92,6 @@ def handle_csrf_error(e: CSRFError) -> werkzeug.Response: for module in [main, info, api]: app.register_blueprint(module.make_blueprint(config)) # type: ignore - @app.before_request - @ignore_static - def setup_i18n() -> None: - """Store i18n-related values in Flask's special g object""" - g.locale = i18n.get_locale(config) - g.text_direction = i18n.get_text_direction(g.locale) - g.html_lang = i18n.locale_to_rfc_5646(g.locale) - g.locales = i18n.get_locale2name() - @app.before_request @ignore_static def check_tor2web() -> None: diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -334,9 +334,8 @@ def logout() -> Union[str, werkzeug.Response]: # Clear the session after we render the message so it's localized # If a user specified a locale, save it and restore it - user_locale = g.locale session.clear() - session['locale'] = user_locale + session['locale'] = g.localeinfo.id return render_template('logout.html') else: diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -10,7 +10,6 @@ import typing -import i18n import re from crypto_util import CryptoUtil, CryptoException @@ -47,7 +46,7 @@ def generate_unique_codename(config: SDConfig) -> DicewarePassphrase: """Generate random codenames until we get an unused one""" while True: passphrase = PassphraseGenerator.get_default().generate_passphrase( - preferred_language=i18n.get_language(config) + preferred_language=g.localeinfo.language ) # scrypt (slow) filesystem_id = current_app.crypto_util.hash_codename(passphrase)
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -26,6 +26,7 @@ import journalist_app as journalist_app_module import pytest import source_app +from babel.core import Locale, UnknownLocaleError from flask import render_template from flask import render_template_string from flask import request @@ -54,7 +55,7 @@ def verify_i18n(app): {{ gettext('code hello i18n') }} ''').strip() == not_translated - for lang in ('fr_FR', 'fr', 'fr-FR'): + for lang in ('fr', 'fr-FR'): headers = Headers([('Accept-Language', lang)]) with app.test_request_context(headers=headers): assert not hasattr(request, 'babel_locale') @@ -96,47 +97,59 @@ def verify_i18n(app): ''').strip() == translated_ar with app.test_client() as c: + + # a request without Accept-Language or "l" argument gets the + # default locale page = c.get('/login') - assert session.get('locale') is None + assert session.get('locale') == 'en_US' assert not_translated == gettext(not_translated) assert b'?l=fr_FR' in page.data assert b'?l=en_US' not in page.data - page = c.get('/login?l=fr_FR', - headers=Headers([('Accept-Language', 'en_US')])) + # the session locale should change when the "l" request + # argument is present and valid + page = c.get('/login?l=fr_FR', headers=Headers([('Accept-Language', 'en_US')])) assert session.get('locale') == 'fr_FR' assert translated_fr == gettext(not_translated) assert b'?l=fr_FR' not in page.data assert b'?l=en_US' in page.data + # confirm that the chosen locale, now in the session, is used + # despite not matching the client's Accept-Language header c.get('/', headers=Headers([('Accept-Language', 'en_US')])) assert session.get('locale') == 'fr_FR' assert translated_fr == gettext(not_translated) + # the session locale should not change if an empty "l" request + # argument is sent c.get('/?l=') - assert session.get('locale') is None - assert not_translated == gettext(not_translated) + assert session.get('locale') == 'fr_FR' + assert translated_fr == gettext(not_translated) + + # the session locale should not change if no "l" request + # argument is sent + c.get('/') + assert session.get('locale') == 'fr_FR' + assert translated_fr == gettext(not_translated) + # sending an invalid locale identifier should not change the + # session locale + c.get('/?l=YY_ZZ') + assert session.get('locale') == 'fr_FR' + assert translated_fr == gettext(not_translated) + + # requesting a valid locale via the request argument "l" + # should change the session locale c.get('/?l=en_US', headers=Headers([('Accept-Language', 'fr_FR')])) assert session.get('locale') == 'en_US' assert not_translated == gettext(not_translated) + # again, the session locale should stick even if not included + # in the client's Accept-Language header c.get('/', headers=Headers([('Accept-Language', 'fr_FR')])) assert session.get('locale') == 'en_US' assert not_translated == gettext(not_translated) - c.get('/?l=', headers=Headers([('Accept-Language', 'fr_FR')])) - assert session.get('locale') is None - assert translated_fr == gettext(not_translated) - - c.get('/') - assert session.get('locale') is None - assert not_translated == gettext(not_translated) - - c.get('/?l=YY_ZZ') - assert session.get('locale') is None - assert not_translated == gettext(not_translated) - with app.test_request_context(): assert '' == render_template('locales.html') @@ -149,30 +162,6 @@ def verify_i18n(app): base = render_template('base.html') assert 'dir="rtl"' in base - # the canonical locale name is norsk bokmål but - # this is overriden with just norsk by i18n.NAME_OVERRIDES - with app.test_client() as c: - c.get('/?l=nb_NO') - base = render_template('base.html') - assert 'norsk' in base - assert 'norsk bo' not in base - - -def test_get_supported_locales(): - locales = ['en_US', 'fr_FR'] - assert ['en_US'] == i18n._get_supported_locales( - locales, None, None, None) - locales = ['en_US', 'fr_FR'] - supported = ['en_US', 'not_found'] - with pytest.raises(i18n.LocaleNotFound) as excinfo: - i18n._get_supported_locales(locales, supported, None, None) - assert "contains ['not_found']" in str(excinfo.value) - supported = ['fr_FR'] - locale = 'not_found' - with pytest.raises(i18n.LocaleNotFound) as excinfo: - i18n._get_supported_locales(locales, supported, locale, None) - assert "DEFAULT_LOCALE 'not_found'" in str(excinfo.value) - # Grab the journalist_app fixture to trigger creation of resources def test_i18n(journalist_app, config): @@ -197,7 +186,7 @@ def test_i18n(journalist_app, config): pybabel('init', '-i', pot, '-d', config.TEMP_DIR, '-l', 'en_US') for (l, s) in (('fr_FR', 'code bonjour'), - ('zh_Hans_CN', 'code chinese'), + ('zh_Hans', 'code chinese'), ('ar', 'code arabic'), ('nb_NO', 'code norwegian'), ('es_ES', 'code spanish')): @@ -215,8 +204,7 @@ def test_i18n(journalist_app, config): ]) fake_config = SDConfig() - fake_config.SUPPORTED_LOCALES = [ - 'en_US', 'fr_FR', 'zh_Hans_CN', 'ar', 'nb_NO'] + fake_config.SUPPORTED_LOCALES = ['ar', 'en_US', 'fr_FR', 'nb_NO', 'zh_Hans'] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) # Use our config (and not an app fixture) because the i18n module @@ -225,16 +213,42 @@ def test_i18n(journalist_app, config): source_app.create_app(fake_config)): with app.app_context(): db.create_all() - assert i18n.LOCALES == fake_config.SUPPORTED_LOCALES + assert list(i18n.LOCALES.keys()) == fake_config.SUPPORTED_LOCALES verify_i18n(app) -def test_locale_to_rfc_5646(): - assert i18n.locale_to_rfc_5646('en') == 'en' - assert i18n.locale_to_rfc_5646('en-US') == 'en' - assert i18n.locale_to_rfc_5646('en_US') == 'en' - assert i18n.locale_to_rfc_5646('en-us') == 'en' - assert i18n.locale_to_rfc_5646('zh-hant') == 'zh-Hant' +def test_supported_locales(config): + fake_config = SDConfig() + + # Check that an invalid locale raises an error during app + # configuration. + fake_config.SUPPORTED_LOCALES = ['en_US', 'yy_ZZ'] + fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) + + with pytest.raises(UnknownLocaleError): + journalist_app_module.create_app(fake_config) + + with pytest.raises(UnknownLocaleError): + source_app.create_app(fake_config) + + # Check that a valid but unsupported locale raises an error during + # app configuration. + fake_config.SUPPORTED_LOCALES = ['en_US', 'wae_CH'] + fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) + + with pytest.raises(ValueError, match="not in the set of translated locales"): + journalist_app_module.create_app(fake_config) + + with pytest.raises(ValueError, match="not in the set of translated locales"): + source_app.create_app(fake_config) + + +def test_language_tags(): + assert i18n.RequestLocaleInfo(Locale.parse('en')).language_tag == 'en' + assert i18n.RequestLocaleInfo(Locale.parse('en-US', sep="-")).language_tag == 'en-US' + assert i18n.RequestLocaleInfo(Locale.parse('en-us', sep="-")).language_tag == 'en-US' + assert i18n.RequestLocaleInfo(Locale.parse('en_US')).language_tag == 'en-US' + assert i18n.RequestLocaleInfo(Locale.parse('zh_Hant')).language_tag == 'zh-Hant' # Grab the journalist_app fixture to trigger creation of resources @@ -245,17 +259,17 @@ def test_html_en_lang_correct(journalist_app, config): app = journalist_app_module.create_app(config).test_client() resp = app.get('/', follow_redirects=True) html = resp.data.decode('utf-8') - assert re.compile('<html .*lang="en".*>').search(html), html + assert re.compile('<html lang="en-US".*>').search(html), html app = source_app.create_app(config).test_client() resp = app.get('/', follow_redirects=True) html = resp.data.decode('utf-8') - assert re.compile('<html .*lang="en".*>').search(html), html + assert re.compile('<html lang="en-US".*>').search(html), html # check '/generate' too because '/' uses a different template resp = app.get('/generate', follow_redirects=True) html = resp.data.decode('utf-8') - assert re.compile('<html .*lang="en".*>').search(html), html + assert re.compile('<html lang="en-US".*>').search(html), html # Grab the journalist_app fixture to trigger creation of resources @@ -269,14 +283,47 @@ def test_html_fr_lang_correct(journalist_app, config): app = journalist_app_module.create_app(config).test_client() resp = app.get('/?l=fr_FR', follow_redirects=True) html = resp.data.decode('utf-8') - assert re.compile('<html .*lang="fr".*>').search(html), html + assert re.compile('<html lang="fr-FR".*>').search(html), html app = source_app.create_app(config).test_client() resp = app.get('/?l=fr_FR', follow_redirects=True) html = resp.data.decode('utf-8') - assert re.compile('<html .*lang="fr".*>').search(html), html + assert re.compile('<html lang="fr-FR".*>').search(html), html # check '/generate' too because '/' uses a different template resp = app.get('/generate?l=fr_FR', follow_redirects=True) html = resp.data.decode('utf-8') - assert re.compile('<html .*lang="fr".*>').search(html), html + assert re.compile('<html lang="fr-FR".*>').search(html), html + + +# Grab the journalist_app fixture to trigger creation of resources +def test_html_attributes(journalist_app, config): + """Check that HTML lang and dir attributes respect locale.""" + + # Then delete it because using it won't test what we want + del journalist_app + + config.SUPPORTED_LOCALES = ['ar', 'en_US'] + app = journalist_app_module.create_app(config).test_client() + resp = app.get('/?l=ar', follow_redirects=True) + html = resp.data.decode('utf-8') + assert '<html lang="ar" dir="rtl">' in html + resp = app.get('/?l=en_US', follow_redirects=True) + html = resp.data.decode('utf-8') + assert '<html lang="en-US" dir="ltr">' in html + + app = source_app.create_app(config).test_client() + resp = app.get('/?l=ar', follow_redirects=True) + html = resp.data.decode('utf-8') + assert '<html lang="ar" dir="rtl">' in html + resp = app.get('/?l=en_US', follow_redirects=True) + html = resp.data.decode('utf-8') + assert '<html lang="en-US" dir="ltr">' in html + + # check '/generate' too because '/' uses a different template + resp = app.get('/generate?l=ar', follow_redirects=True) + html = resp.data.decode('utf-8') + assert '<html lang="ar" dir="rtl">' in html + resp = app.get('/generate?l=en_US', follow_redirects=True) + html = resp.data.decode('utf-8') + assert '<html lang="en-US" dir="ltr">' in html diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -545,6 +545,7 @@ def test_admin_edits_user_password_session_invalidate(journalist_app, # Also ensure that session is now invalid. session.pop('expires', None) session.pop('csrf_token', None) + session.pop('locale', None) assert not session, session @@ -2719,6 +2720,7 @@ def test_journalist_session_expiration(config, journalist_app, test_journo): # which is always present and 'csrf_token' which leaks no info) session.pop('expires', None) session.pop('csrf_token', None) + session.pop('locale', None) assert not session, session assert ('You have been logged out due to inactivity' in resp.data.decode('utf-8')) diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -740,6 +740,7 @@ def test_source_session_expiration(config, source_app): # which is always present and 'csrf_token' which leaks no info) session.pop('expires', None) session.pop('csrf_token', None) + session.pop('locale', None) session.pop('show_expiration_message', None) assert not session @@ -766,6 +767,7 @@ def test_source_session_expiration_create(config, source_app): # which is always present and 'csrf_token' which leaks no info) session.pop('expires', None) session.pop('csrf_token', None) + session.pop('locale', None) session.pop('show_expiration_message', None) assert not session diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -20,7 +20,7 @@ def verify_rel_datetime_format(app): with app.test_client() as c: c.get('/') - assert session.get('locale') is None + assert session.get('locale') == "en_US" result = template_filters.rel_datetime_format( datetime(2016, 1, 1, 1, 1, 1)) assert "Jan 01, 2016 01:01 AM" == result @@ -53,7 +53,7 @@ def verify_rel_datetime_format(app): def verify_filesizeformat(app): with app.test_client() as c: c.get('/') - assert session.get('locale') is None + assert session.get('locale') == "en_US" assert "1 byte" == template_filters.filesizeformat(1) assert "2 bytes" == template_filters.filesizeformat(2) value = 1024 * 3 @@ -116,6 +116,6 @@ def do_test(config, create_app): with app.app_context(): db.create_all() - assert i18n.LOCALES == config.SUPPORTED_LOCALES + assert list(i18n.LOCALES.keys()) == config.SUPPORTED_LOCALES verify_filesizeformat(app) verify_rel_datetime_format(app)
Add simplified Chinese (zh_Hans) to the list of supported languages ## Description We now have a reviewer for Simplified Chinese, so it can be added to the list of supported languages.
This dropped off the radar; let's get it into 1.7.0 if all looks good.
2021-01-11T19:43:12Z
[]
[]
freedomofpress/securedrop
5,759
freedomofpress__securedrop-5759
[ "5757" ]
c9646308192ee2a3bcb3d0141357fc6f5daf3b8e
diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -10,42 +10,107 @@ class SDConfig: def __init__(self) -> None: - self.JOURNALIST_APP_FLASK_CONFIG_CLS = \ - _config.JournalistInterfaceFlaskConfig # type: Type - - self.SOURCE_APP_FLASK_CONFIG_CLS = \ - _config.SourceInterfaceFlaskConfig # type: Type - - self.DATABASE_ENGINE = _config.DATABASE_ENGINE # type: str - self.DATABASE_FILE = _config.DATABASE_FILE # type: str + try: + self.JOURNALIST_APP_FLASK_CONFIG_CLS = ( + _config.JournalistInterfaceFlaskConfig + ) # type: Type + except AttributeError: + pass + + try: + self.SOURCE_APP_FLASK_CONFIG_CLS = _config.SourceInterfaceFlaskConfig # type: Type + except AttributeError: + pass + + try: + self.DATABASE_ENGINE = _config.DATABASE_ENGINE # type: str + except AttributeError: + pass + + try: + self.DATABASE_FILE = _config.DATABASE_FILE # type: str + except AttributeError: + pass self.DATABASE_USERNAME = getattr(_config, "DATABASE_USERNAME", None) # type: Optional[str] self.DATABASE_PASSWORD = getattr(_config, "DATABASE_PASSWORD", None) # type: Optional[str] self.DATABASE_HOST = getattr(_config, "DATABASE_HOST", None) # type: Optional[str] self.DATABASE_NAME = getattr(_config, "DATABASE_NAME", None) # type: Optional[str] - self.ADJECTIVES = _config.ADJECTIVES # type: str - self.NOUNS = _config.NOUNS # type: str - - self.GPG_KEY_DIR = _config.GPG_KEY_DIR # type: str - - self.JOURNALIST_KEY = _config.JOURNALIST_KEY # type: str - self.JOURNALIST_TEMPLATES_DIR = _config.JOURNALIST_TEMPLATES_DIR # type: str - - self.SCRYPT_GPG_PEPPER = _config.SCRYPT_GPG_PEPPER # type: str - self.SCRYPT_ID_PEPPER = _config.SCRYPT_ID_PEPPER # type: str - self.SCRYPT_PARAMS = _config.SCRYPT_PARAMS # type: Dict[str, int] - - self.SECUREDROP_DATA_ROOT = _config.SECUREDROP_DATA_ROOT # type: str - self.SECUREDROP_ROOT = _config.SECUREDROP_ROOT # type: str - - self.SESSION_EXPIRATION_MINUTES = _config.SESSION_EXPIRATION_MINUTES # type: int - - self.SOURCE_TEMPLATES_DIR = _config.SOURCE_TEMPLATES_DIR # type: str - self.TEMP_DIR = _config.TEMP_DIR # type: str - self.STORE_DIR = _config.STORE_DIR # type: str - - self.WORKER_PIDFILE = _config.WORKER_PIDFILE # type: str + try: + self.ADJECTIVES = _config.ADJECTIVES # type: str + except AttributeError: + pass + + try: + self.NOUNS = _config.NOUNS # type: str + except AttributeError: + pass + + try: + self.GPG_KEY_DIR = _config.GPG_KEY_DIR # type: str + except AttributeError: + pass + + try: + self.JOURNALIST_KEY = _config.JOURNALIST_KEY # type: str + except AttributeError: + pass + + try: + self.JOURNALIST_TEMPLATES_DIR = _config.JOURNALIST_TEMPLATES_DIR # type: str + except AttributeError: + pass + + try: + self.SCRYPT_GPG_PEPPER = _config.SCRYPT_GPG_PEPPER # type: str + except AttributeError: + pass + + try: + self.SCRYPT_ID_PEPPER = _config.SCRYPT_ID_PEPPER # type: str + except AttributeError: + pass + + try: + self.SCRYPT_PARAMS = _config.SCRYPT_PARAMS # type: Dict[str, int] + except AttributeError: + pass + + try: + self.SECUREDROP_DATA_ROOT = _config.SECUREDROP_DATA_ROOT # type: str + except AttributeError: + pass + + try: + self.SECUREDROP_ROOT = _config.SECUREDROP_ROOT # type: str + except AttributeError: + pass + + try: + self.SESSION_EXPIRATION_MINUTES = _config.SESSION_EXPIRATION_MINUTES # type: int + except AttributeError: + pass + + try: + self.SOURCE_TEMPLATES_DIR = _config.SOURCE_TEMPLATES_DIR # type: str + except AttributeError: + pass + + try: + self.TEMP_DIR = _config.TEMP_DIR # type: str + except AttributeError: + pass + + try: + self.STORE_DIR = _config.STORE_DIR # type: str + except AttributeError: + pass + + try: + self.WORKER_PIDFILE = _config.WORKER_PIDFILE # type: str + except AttributeError: + pass self.env = getattr(_config, 'env', 'prod') # type: str if self.env == 'test': @@ -54,7 +119,7 @@ def __init__(self) -> None: self.RQ_WORKER_NAME = 'default' # Config entries used by i18n.py - # Use en_US as the default local if the key is not defined in _config + # Use en_US as the default locale if the key is not defined in _config self.DEFAULT_LOCALE = getattr( _config, "DEFAULT_LOCALE", "en_US" ) # type: str @@ -68,7 +133,10 @@ def __init__(self) -> None: if translation_dirs_in_conf: self.TRANSLATION_DIRS = Path(translation_dirs_in_conf) # type: Path else: - self.TRANSLATION_DIRS = Path(_config.SECUREDROP_ROOT) / "translations" + try: + self.TRANSLATION_DIRS = Path(_config.SECUREDROP_ROOT) / "translations" + except AttributeError: + pass @property def DATABASE_URI(self) -> str:
diff --git a/securedrop/tests/test_config.py b/securedrop/tests/test_config.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_config.py @@ -0,0 +1,47 @@ +import importlib + +import config as _config + + +def test_missing_config_attribute_is_handled(): + """ + Test handling of incomplete configurations. + + Long-running SecureDrop instances might not have ever updated + config.py, so could be missing newer settings. This tests that + sdconfig.SDConfig can be initialized without error with such a + configuration. + """ + attributes_to_test = ( + "JournalistInterfaceFlaskConfig", + "SourceInterfaceFlaskConfig", + "DATABASE_ENGINE", + "DATABASE_FILE", + "ADJECTIVES", + "NOUNS", + "GPG_KEY_DIR", + "JOURNALIST_KEY", + "JOURNALIST_TEMPLATES_DIR", + "SCRYPT_GPG_PEPPER", + "SCRYPT_ID_PEPPER", + "SCRYPT_PARAMS", + "SECUREDROP_DATA_ROOT", + "SECUREDROP_ROOT", + "SESSION_EXPIRATION_MINUTES", + "SOURCE_TEMPLATES_DIR", + "TEMP_DIR", + "STORE_DIR", + "WORKER_PIDFILE", + ) + + try: + importlib.reload(_config) + + for a in attributes_to_test: + delattr(_config, a) + + from sdconfig import SDConfig + + SDConfig() + finally: + importlib.reload(_config)
Error 500 on source interface and journalist interface after 1.7.0 upgrade ## Description Initially reported by forum user jonas.franzen in https://forum.securedrop.org/t/issues-after-update-to-1-7-0/1391 Some due to a missing variable in config.py ``` Jan 27 12:48:07 applicationserver python[1136]: AttributeError: module ‘config’ has no attribute ‘SESSION_EXPIRATION_MINUTES’ ``` ## Steps to reproduce TBD ## Comments Forum user dachary reports that simply adding the value to config.py resolves
This looks to be the result of recent changes in `securedrop/sdconfig.py` , specifically in how missing configuration values in `config.py` are handled. Previously all attempts to set values to their `config.py` values were wrapped in try/except blocks, but this was removed as part of work to support type annotation - probably with the assumption that these values would always be present, which isn't the case for older instances or instances which have an older `config.py` restored from a backup. Editing `config.py` in live instances via an application update is risky - we don't want to overwrite cryptography values generated at install time! - so instead the safest approach is to restore the old try/except logic for now. A point release will be required to address this issue and will be forthcoming ASAP.
2021-01-27T17:03:37Z
[]
[]
freedomofpress/securedrop
5,760
freedomofpress__securedrop-5760
[ "5757" ]
509127a37a9b47c9de76abaa4e526c07f24fef64
diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -10,42 +10,107 @@ class SDConfig: def __init__(self) -> None: - self.JOURNALIST_APP_FLASK_CONFIG_CLS = \ - _config.JournalistInterfaceFlaskConfig # type: Type - - self.SOURCE_APP_FLASK_CONFIG_CLS = \ - _config.SourceInterfaceFlaskConfig # type: Type - - self.DATABASE_ENGINE = _config.DATABASE_ENGINE # type: str - self.DATABASE_FILE = _config.DATABASE_FILE # type: str + try: + self.JOURNALIST_APP_FLASK_CONFIG_CLS = ( + _config.JournalistInterfaceFlaskConfig + ) # type: Type + except AttributeError: + pass + + try: + self.SOURCE_APP_FLASK_CONFIG_CLS = _config.SourceInterfaceFlaskConfig # type: Type + except AttributeError: + pass + + try: + self.DATABASE_ENGINE = _config.DATABASE_ENGINE # type: str + except AttributeError: + pass + + try: + self.DATABASE_FILE = _config.DATABASE_FILE # type: str + except AttributeError: + pass self.DATABASE_USERNAME = getattr(_config, "DATABASE_USERNAME", None) # type: Optional[str] self.DATABASE_PASSWORD = getattr(_config, "DATABASE_PASSWORD", None) # type: Optional[str] self.DATABASE_HOST = getattr(_config, "DATABASE_HOST", None) # type: Optional[str] self.DATABASE_NAME = getattr(_config, "DATABASE_NAME", None) # type: Optional[str] - self.ADJECTIVES = _config.ADJECTIVES # type: str - self.NOUNS = _config.NOUNS # type: str - - self.GPG_KEY_DIR = _config.GPG_KEY_DIR # type: str - - self.JOURNALIST_KEY = _config.JOURNALIST_KEY # type: str - self.JOURNALIST_TEMPLATES_DIR = _config.JOURNALIST_TEMPLATES_DIR # type: str - - self.SCRYPT_GPG_PEPPER = _config.SCRYPT_GPG_PEPPER # type: str - self.SCRYPT_ID_PEPPER = _config.SCRYPT_ID_PEPPER # type: str - self.SCRYPT_PARAMS = _config.SCRYPT_PARAMS # type: Dict[str, int] - - self.SECUREDROP_DATA_ROOT = _config.SECUREDROP_DATA_ROOT # type: str - self.SECUREDROP_ROOT = _config.SECUREDROP_ROOT # type: str - - self.SESSION_EXPIRATION_MINUTES = _config.SESSION_EXPIRATION_MINUTES # type: int - - self.SOURCE_TEMPLATES_DIR = _config.SOURCE_TEMPLATES_DIR # type: str - self.TEMP_DIR = _config.TEMP_DIR # type: str - self.STORE_DIR = _config.STORE_DIR # type: str - - self.WORKER_PIDFILE = _config.WORKER_PIDFILE # type: str + try: + self.ADJECTIVES = _config.ADJECTIVES # type: str + except AttributeError: + pass + + try: + self.NOUNS = _config.NOUNS # type: str + except AttributeError: + pass + + try: + self.GPG_KEY_DIR = _config.GPG_KEY_DIR # type: str + except AttributeError: + pass + + try: + self.JOURNALIST_KEY = _config.JOURNALIST_KEY # type: str + except AttributeError: + pass + + try: + self.JOURNALIST_TEMPLATES_DIR = _config.JOURNALIST_TEMPLATES_DIR # type: str + except AttributeError: + pass + + try: + self.SCRYPT_GPG_PEPPER = _config.SCRYPT_GPG_PEPPER # type: str + except AttributeError: + pass + + try: + self.SCRYPT_ID_PEPPER = _config.SCRYPT_ID_PEPPER # type: str + except AttributeError: + pass + + try: + self.SCRYPT_PARAMS = _config.SCRYPT_PARAMS # type: Dict[str, int] + except AttributeError: + pass + + try: + self.SECUREDROP_DATA_ROOT = _config.SECUREDROP_DATA_ROOT # type: str + except AttributeError: + pass + + try: + self.SECUREDROP_ROOT = _config.SECUREDROP_ROOT # type: str + except AttributeError: + pass + + try: + self.SESSION_EXPIRATION_MINUTES = _config.SESSION_EXPIRATION_MINUTES # type: int + except AttributeError: + pass + + try: + self.SOURCE_TEMPLATES_DIR = _config.SOURCE_TEMPLATES_DIR # type: str + except AttributeError: + pass + + try: + self.TEMP_DIR = _config.TEMP_DIR # type: str + except AttributeError: + pass + + try: + self.STORE_DIR = _config.STORE_DIR # type: str + except AttributeError: + pass + + try: + self.WORKER_PIDFILE = _config.WORKER_PIDFILE # type: str + except AttributeError: + pass self.env = getattr(_config, 'env', 'prod') # type: str if self.env == 'test': @@ -54,7 +119,7 @@ def __init__(self) -> None: self.RQ_WORKER_NAME = 'default' # Config entries used by i18n.py - # Use en_US as the default local if the key is not defined in _config + # Use en_US as the default locale if the key is not defined in _config self.DEFAULT_LOCALE = getattr( _config, "DEFAULT_LOCALE", "en_US" ) # type: str @@ -68,7 +133,10 @@ def __init__(self) -> None: if translation_dirs_in_conf: self.TRANSLATION_DIRS = Path(translation_dirs_in_conf) # type: Path else: - self.TRANSLATION_DIRS = Path(_config.SECUREDROP_ROOT) / "translations" + try: + self.TRANSLATION_DIRS = Path(_config.SECUREDROP_ROOT) / "translations" + except AttributeError: + pass @property def DATABASE_URI(self) -> str: diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '1.7.0' +__version__ = '1.7.1' diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="1.7.0", + version="1.7.1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-xenial/tests/vars.yml b/molecule/builder-xenial/tests/vars.yml --- a/molecule/builder-xenial/tests/vars.yml +++ b/molecule/builder-xenial/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "1.7.0" +securedrop_version: "1.7.1" ossec_version: "3.6.0" keyring_version: "0.1.4" config_version: "0.1.3" diff --git a/securedrop/tests/test_config.py b/securedrop/tests/test_config.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_config.py @@ -0,0 +1,47 @@ +import importlib + +import config as _config + + +def test_missing_config_attribute_is_handled(): + """ + Test handling of incomplete configurations. + + Long-running SecureDrop instances might not have ever updated + config.py, so could be missing newer settings. This tests that + sdconfig.SDConfig can be initialized without error with such a + configuration. + """ + attributes_to_test = ( + "JournalistInterfaceFlaskConfig", + "SourceInterfaceFlaskConfig", + "DATABASE_ENGINE", + "DATABASE_FILE", + "ADJECTIVES", + "NOUNS", + "GPG_KEY_DIR", + "JOURNALIST_KEY", + "JOURNALIST_TEMPLATES_DIR", + "SCRYPT_GPG_PEPPER", + "SCRYPT_ID_PEPPER", + "SCRYPT_PARAMS", + "SECUREDROP_DATA_ROOT", + "SECUREDROP_ROOT", + "SESSION_EXPIRATION_MINUTES", + "SOURCE_TEMPLATES_DIR", + "TEMP_DIR", + "STORE_DIR", + "WORKER_PIDFILE", + ) + + try: + importlib.reload(_config) + + for a in attributes_to_test: + delattr(_config, a) + + from sdconfig import SDConfig + + SDConfig() + finally: + importlib.reload(_config)
Error 500 on source interface and journalist interface after 1.7.0 upgrade ## Description Initially reported by forum user jonas.franzen in https://forum.securedrop.org/t/issues-after-update-to-1-7-0/1391 Some due to a missing variable in config.py ``` Jan 27 12:48:07 applicationserver python[1136]: AttributeError: module ‘config’ has no attribute ‘SESSION_EXPIRATION_MINUTES’ ``` ## Steps to reproduce TBD ## Comments Forum user dachary reports that simply adding the value to config.py resolves
This looks to be the result of recent changes in `securedrop/sdconfig.py` , specifically in how missing configuration values in `config.py` are handled. Previously all attempts to set values to their `config.py` values were wrapped in try/except blocks, but this was removed as part of work to support type annotation - probably with the assumption that these values would always be present, which isn't the case for older instances or instances which have an older `config.py` restored from a backup. Editing `config.py` in live instances via an application update is risky - we don't want to overwrite cryptography values generated at install time! - so instead the safest approach is to restore the old try/except logic for now. A point release will be required to address this issue and will be forthcoming ASAP.
2021-01-27T19:25:08Z
[]
[]
freedomofpress/securedrop
5,770
freedomofpress__securedrop-5770
[ "5767" ]
88ac049022a9d4d9c89d6123cae4125597b43a45
diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -13,6 +13,8 @@ request, send_file, url_for, + Markup, + escape, ) import werkzeug from flask_babel import gettext @@ -24,7 +26,7 @@ from journalist_app.utils import (make_star_true, make_star_false, get_source, delete_collection, col_download_unread, col_download_all, col_star, col_un_star, - col_delete, mark_seen) + col_delete, col_delete_data, mark_seen) from sdconfig import SDConfig @@ -61,18 +63,35 @@ def delete_single(filesystem_id: str) -> werkzeug.Response: current_app.logger.error("error deleting collection: %s", e) abort(500) - flash(gettext("{source_name}'s collection deleted.") - .format(source_name=source.journalist_designation), - "notification") + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Success!" appears before a message + # confirming the success of an operation. + escape(gettext("Success!")), + escape(gettext( + "The account and data for the source {} has been deleted.").format( + source.journalist_designation)) + ) + ), 'success') + return redirect(url_for('main.index')) @view.route('/process', methods=('POST',)) def process() -> werkzeug.Response: actions = {'download-unread': col_download_unread, 'download-all': col_download_all, 'star': col_star, - 'un-star': col_un_star, 'delete': col_delete} + 'un-star': col_un_star, 'delete': col_delete, + 'delete-data': col_delete_data} if 'cols_selected' not in request.form: - flash(gettext('No collections selected.'), 'error') + flash( + Markup("<b>{}</b> {}".format( + # Translators: Here, "Nothing Selected" appears before a message + # asking the user to select one or more items. + escape(gettext('Nothing Selected')), + escape(gettext('You must select one or more items.')) + ) + ), 'error') return redirect(url_for('main.index')) # getlist is cgi.FieldStorage.getlist diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -6,7 +6,7 @@ import werkzeug from flask import (Blueprint, request, current_app, session, url_for, redirect, - render_template, g, flash, abort) + render_template, g, flash, abort, Markup, escape) from flask_babel import gettext import store @@ -138,8 +138,16 @@ def reply() -> werkzeug.Response: g.user.id, exc.__class__)) else: - flash(gettext("Thanks. Your reply has been stored."), - "notification") + + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Success!" appears before a message + # confirming the success of an operation. + escape(gettext("Success!")), + escape(gettext("Your reply has been stored.")) + ) + ), 'success') finally: return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) @@ -159,11 +167,26 @@ def bulk() -> Union[str, werkzeug.Response]: if doc.filename in doc_names_selected] if selected_docs == []: if action == 'download': - flash(gettext("No collections selected for download."), - "error") + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Nothing Selected" appears before a message + # asking the users to select one or more items + escape(gettext("Nothing Selected")), + escape(gettext("You must select one or more items for download")) + ) + ), 'error') elif action in ('delete', 'confirm_delete'): - flash(gettext("No collections selected for deletion."), - "error") + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Nothing Selected" appears before a message + # asking the users to select one or more items + escape(gettext("Nothing Selected")), + escape(gettext("You must select one or more items for deletion")) + ) + ), 'error') + return redirect(error_redirect) if action == 'download': diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -7,7 +7,7 @@ import flask import werkzeug from flask import (g, flash, current_app, abort, send_file, redirect, url_for, - render_template, Markup, sessions, request) + render_template, Markup, sessions, request, escape) from flask_babel import gettext, ngettext from sqlalchemy.exc import IntegrityError @@ -99,7 +99,7 @@ def validate_user( InvalidPasswordLength) as e: current_app.logger.error("Login for '{}' failed: {}".format( username, e)) - login_flashed_msg = error_message if error_message else gettext('Login failed.') + login_flashed_msg = error_message if error_message else gettext('<b>Login failed.</b>') if isinstance(e, LoginThrottledException): login_flashed_msg += " " @@ -123,7 +123,7 @@ def validate_user( except Exception: pass - flash(login_flashed_msg, "error") + flash(Markup(login_flashed_msg), "error") return None @@ -253,14 +253,17 @@ def bulk_delete( deletion_errors += 1 num_selected = len(items_selected) + success_message = ngettext( + "The item has been deleted.", "{num} items have been deleted.", + num_selected).format(num=num_selected) + flash( - ngettext( - "Submission deleted.", - "{num} submissions deleted.", - num_selected - ).format(num=num_selected), - "notification" - ) + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Success!" appears before a message + # indicating a successful deletion + escape(gettext("Success!")), escape(success_message))), 'success') + if deletion_errors > 0: current_app.logger.error("Disconnected submission entries (%d) were detected", deletion_errors) @@ -319,14 +322,64 @@ def col_delete(cols_selected: List[str]) -> werkzeug.Response: db.session.commit() num = len(cols_selected) - flash(ngettext('{num} collection deleted', '{num} collections deleted', - num).format(num=num), - "notification") + + success_message = ngettext( + "The account and all data for {n} source have been deleted.", + "The accounts and all data for {n} sources have been deleted.", + num).format(n=num) + + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Success!" appears before a message + # indicating a successful deletion + escape(gettext("Success!")), escape(success_message))), 'success') + + return redirect(url_for('main.index')) + + +def delete_source_files(filesystem_id: str) -> None: + """deletes submissions and replies for specified source""" + source = get_source(filesystem_id, include_deleted=True) + if source is not None: + # queue all files for deletion and remove them from the database + for f in source.collection: + try: + delete_file_object(f) + except Exception: + pass + + +def col_delete_data(cols_selected: List[str]) -> werkzeug.Response: + """deletes store data for selected sources""" + if len(cols_selected) < 1: + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Nothing Selected" appears before a message + # asking the user to select one or more items + escape(gettext("Nothing Selected")), + escape(gettext("You must select one or more items for deletion."))) + ), 'error') + else: + + for filesystem_id in cols_selected: + delete_source_files(filesystem_id) + + flash( + Markup( + "<b>{}</b> {}".format( + # Translators: Here, "Success" appears before a message + # indicating a successful deletion + escape(gettext("Success!")), + escape(gettext("The files and messages have been deleted."))) + ), 'success') return redirect(url_for('main.index')) def delete_collection(filesystem_id: str) -> None: + """deletes source account including files and reply key""" # Delete the source's collection of submissions path = current_app.storage.path(filesystem_id) if os.path.exists(path):
diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -140,6 +140,12 @@ def _journalist_selects_first_doc(self): def _journalist_clicks_on_modal(self, click_id): self.safe_click_by_id(click_id) + def _journalist_clicks_delete_collections_cancel_on_first_modal(self): + self._journalist_clicks_on_modal("delete-menu-dialog-cancel") + + def _journalist_clicks_delete_collections_cancel_on_second_modal(self): + self._journalist_clicks_on_modal("cancel-collections-deletions") + def _journalist_clicks_delete_collections_cancel_on_modal(self): self._journalist_clicks_on_modal("cancel-collections-deletions") @@ -149,13 +155,21 @@ def _journalist_clicks_delete_selected_cancel_on_modal(self): def _journalist_clicks_delete_collection_cancel_on_modal(self): self._journalist_clicks_on_modal("cancel-collection-deletions") - def _journalist_clicks_delete_collections_on_modal(self): + def _journalist_clicks_delete_files_on_first_modal(self): + self._journalist_clicks_on_modal("delete-files-and-messages") + + def _journalist_clicks_delete_collections_on_first_modal(self): self._journalist_clicks_on_modal("delete-collections") + self.wait_for(lambda: self.driver.find_element_by_id("delete-collections-confirm")) + + def _journalist_clicks_delete_collections_on_second_modal(self): + self._journalist_clicks_on_modal("delete-collections-confirm") + def collection_deleted(): if not self.accept_languages: flash_msg = self.driver.find_element_by_css_selector(".flash") - assert "1 collection deleted" in flash_msg.text + assert "The account and all data for 1 source have been deleted." in flash_msg.text self.wait_for(collection_deleted) @@ -165,7 +179,7 @@ def _journalist_clicks_delete_selected_on_modal(self): def submission_deleted(): if not self.accept_languages: flash_msg = self.driver.find_element_by_css_selector(".flash") - assert "Submission deleted." in flash_msg.text + assert "The item has been deleted." in flash_msg.text self.wait_for(submission_deleted) @@ -181,7 +195,7 @@ def _journalist_clicks_delete_selected_link(self): self.wait_for(lambda: self.driver.find_element_by_id("delete-selected-confirmation-modal")) def _journalist_clicks_delete_collections_link(self): - self._journalist_clicks_delete_link("delete-collections-link", "delete-confirmation-modal") + self._journalist_clicks_delete_link("delete-collections-link", "delete-sources-modal") def _journalist_clicks_delete_collection_link(self): self._journalist_clicks_delete_link( @@ -226,13 +240,18 @@ def _journalist_uses_delete_collections_button_confirmation(self): self.safe_click_all_by_css_selector('input[type="checkbox"][name="cols_selected"]') self._journalist_clicks_delete_collections_link() - self._journalist_clicks_delete_collections_cancel_on_modal() + self._journalist_clicks_delete_collections_cancel_on_first_modal() sources = self.driver.find_elements_by_class_name("code-name") assert len(sources) > 0 self._journalist_clicks_delete_collections_link() - self._journalist_clicks_delete_collections_on_modal() + self._journalist_clicks_delete_collections_on_first_modal() + self._journalist_clicks_delete_collections_cancel_on_second_modal() + + self._journalist_clicks_delete_collections_link() + self._journalist_clicks_delete_collections_on_first_modal() + self._journalist_clicks_delete_collections_on_second_modal() # We should be redirected to the index without those boxes selected. def no_sources(): @@ -240,6 +259,46 @@ def no_sources(): self.wait_for(no_sources) + def _journalist_uses_index_delete_files_button_confirmation(self): + sources = self.driver.find_elements_by_class_name("code-name") + assert len(sources) > 0 + + try: + # If JavaScript is enabled, use the select_all button. + self.driver.find_element_by_id("select_all") + self.safe_click_by_id("select_all") + except NoSuchElementException: + self.safe_click_all_by_css_selector('input[type="checkbox"][name="cols_selected"]') + + self._journalist_clicks_delete_collections_link() + time.sleep(5) + self._journalist_clicks_delete_collections_cancel_on_first_modal() + time.sleep(5) + + sources = self.driver.find_elements_by_class_name("code-name") + assert len(sources) > 0 + + self._journalist_clicks_delete_collections_link() + time.sleep(5) + self._journalist_clicks_delete_files_on_first_modal() + time.sleep(5) + + # We should be redirected to the index with the source present, files + # and messages zeroed, and a success flash message present + + def one_source_no_files(): + assert len(self.driver.find_elements_by_class_name("code-name")) == 1 + if not self.accept_languages: + flash_msg = self.driver.find_element_by_css_selector(".flash") + assert "The files and messages have been deleted" in flash_msg.text + if not self.accept_languages: + count_div = self.driver.find_element_by_css_selector(".submission-count") + assert "0 docs" in count_div.text + assert "0 messages" in count_div.text + + self.wait_for(one_source_no_files) + time.sleep(5) + def _admin_logs_in(self): self.admin = self.admin_user["name"] self.admin_pw = self.admin_user["password"] @@ -790,7 +849,7 @@ def _journalist_sends_reply_to_source(self): def reply_stored(): if not self.accept_languages: - assert "Thanks. Your reply has been stored." in self.driver.page_source + assert "Your reply has been stored." in self.driver.page_source self.wait_for(reply_stored) diff --git a/securedrop/tests/functional/test_journalist.py b/securedrop/tests/functional/test_journalist.py --- a/securedrop/tests/functional/test_journalist.py +++ b/securedrop/tests/functional/test_journalist.py @@ -63,6 +63,22 @@ def test_journalist_uses_index_delete_collections_button_modal(self): self._journalist_logs_in() self._journalist_uses_delete_collections_button_confirmation() + def test_journalist_uses_index_delete_files_button_modal(self): + # This deletion button is displayed on the index page + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_submits_a_file() + self._source_submits_a_message() + self._source_logs_out() + self._journalist_logs_in() + self._journalist_uses_index_delete_files_button_confirmation() + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_submits_a_message() + self._source_logs_out() + def test_journalist_interface_ui_with_modal(self): self._source_visits_source_homepage() self._source_chooses_to_submit_documents() diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -128,13 +128,13 @@ def test_submit_message(source_app, journalist_app, test_journo): assert resp.status_code == 200 text = resp.data.decode('utf-8') soup = BeautifulSoup(text, 'html.parser') - assert "Submission deleted." in text + assert "The item has been deleted." in text # confirm that submission deleted and absent in list of submissions resp = app.get(col_url) assert resp.status_code == 200 text = resp.data.decode('utf-8') - assert "No documents to display." in text + assert "No submissions to display." in text # the file should be deleted from the filesystem # since file deletion is handled by a polling worker, this test @@ -231,14 +231,14 @@ def test_submit_file(source_app, journalist_app, test_journo): ), follow_redirects=True) assert resp.status_code == 200 text = resp.data.decode('utf-8') - assert "Submission deleted." in text + assert "The item has been deleted." in text soup = BeautifulSoup(resp.data, 'html.parser') # confirm that submission deleted and absent in list of submissions resp = app.get(col_url) assert resp.status_code == 200 text = resp.data.decode('utf-8') - assert "No documents to display." in text + assert "No submissions to display." in text # the file should be deleted from the filesystem # since file deletion is handled by a polling worker, this test @@ -321,7 +321,7 @@ def assertion(): pass else: text = resp.data.decode('utf-8') - assert "Thanks. Your reply has been stored." in text + assert "Your reply has been stored." in text resp = app.get(col_url) text = resp.data.decode('utf-8') @@ -406,7 +406,7 @@ def _helper_filenames_delete(journalist_app, soup, i): doc_names_selected=checkbox_values ), follow_redirects=True) assert resp.status_code == 200 - assert "Submission deleted." in resp.data.decode('utf-8') + assert "The item has been deleted." in resp.data.decode('utf-8') # Make sure the files were deleted from the filesystem def assertion(): @@ -506,7 +506,9 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): assert resp.status_code == 200 text = resp.data.decode('utf-8') - assert escape("{}'s collection deleted".format(col_name)) in text + assert escape( + "The account and data for the source {} has been deleted.".format(col_name)) in text + assert "No documents have been submitted!" in text assert async_genkey.called @@ -549,7 +551,7 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): ), follow_redirects=True) assert resp.status_code == 200 text = resp.data.decode('utf-8') - assert "{} collections deleted".format(num_sources) in text + assert "The accounts and all data for {} sources".format(num_sources) in text assert async_genkey.called # simulate the source_deleter's work diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -1952,6 +1952,30 @@ def test_edit_hotp(journalist_app, test_journo): ins.assert_redirects(resp, url_for('account.new_two_factor')) +def test_delete_data_deletes_submissions_retaining_source(journalist_app, + test_journo, + test_source): + """Verify that when only a source's data is deleted, the submissions + are deleted but the source is not.""" + + with journalist_app.app_context(): + source = Source.query.get(test_source['id']) + journo = Journalist.query.get(test_journo['id']) + + utils.db_helper.submit(source, 2) + utils.db_helper.reply(journo, source, 2) + + assert len(source.collection) == 4 + + journalist_app_module.utils.delete_source_files( + test_source['filesystem_id']) + + res = Source.query.filter_by(id=test_source['id']).one_or_none() + assert res is not None + + assert len(source.collection) == 0 + + def test_delete_source_deletes_submissions(journalist_app, test_journo, test_source):
Update JI/AI Flash Messaging Styles _Child issue w/in #5766_ ## Description Update existing CSS classes so Journalist and Admin users can more quickly grok the gist of flash messages through semiotics alone, relying less on having to read stuff. Most urgently, this issue was created to track the updating of the `flash-success` style, but follow-up community PRs to update the _Info_ and _Warning styles_, would be lovely follow-up opportunities. ## User Research Evidence From Safe Delete. Recognition of semiotics w/o requiring user to "read" anything, proved to reduce cognitive friction and facilitate smoother execution of tasks; most noticably, with alleviating "omg am I doing this right?" anxiety. [Summary Here](https://docs.google.com/document/d/1XT-hQej462e9NtQn08MW0aFkK_exSlpKYY2A2JJGuEs/edit?usp=sharing) on first page, with more details around messaging mid-document. More details, on Synthesis Spreadsheet linked-to in Summary. ## User Stories - I am working on Safe Delete and only need to update the Success messaging stuff. - I am a community contributor and would like to add the additional few lines of CSS to update the other two message types (error and info). - I am a Journalist, Admin, or Source user, and want to be able to more quickly parse a flash messages on page-reload, as that helps manage my anxiety when doing such sensitive tasks as working with SecureDrop always is. - Semiotic recognition, first: Did I do it right or wrong? Actually reading the content, an optional second: Ok, what are the details...
2021-02-03T16:50:36Z
[]
[]
freedomofpress/securedrop
5,788
freedomofpress__securedrop-5788
[ "5317" ]
b56c6b0b020baec6844ae62c322dd17e64b86cd4
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -24,6 +24,7 @@ """ import argparse +import functools import ipaddress import logging import os @@ -45,6 +46,9 @@ from pkg_resources import parse_version from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import x25519 + +from typing import cast + from typing import List from typing import Set @@ -80,6 +84,11 @@ class JournalistAlertEmailException(Exception): # The type of each entry within SiteConfig.desc _T = TypeVar('_T', bound=Union[int, str, bool]) + +# The function type used for the @update_check_required decorator; see +# https://mypy.readthedocs.io/en/stable/generics.html#declaring-decorators +_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) + # (var, default, type, prompt, validator, transform, condition) _DescEntryType = Tuple[str, _T, Type[_T], str, Optional[Validator], Optional[Callable], Callable] @@ -516,7 +525,7 @@ def user_prompt_config(self) -> Dict[str, Any]: self._config_in_progress[var] = '' continue self._config_in_progress[var] = self.user_prompt_config_one(desc, - self.config.get(var)) # noqa: E501 + self.config.get(var)) # noqa: E501 return self._config_in_progress def user_prompt_config_one( @@ -690,6 +699,57 @@ def setup_logger(verbose: bool = False) -> None: sdlog.addHandler(stdout) +def update_check_required(cmd_name: str) -> Callable[[_FuncT], _FuncT]: + """ + This decorator can be added to any subcommand that is part of securedrop-admin + via `@update_check_required("name_of_subcommand")`. It forces a check for + updates, and aborts if the locally installed code is out of date. It should + be generally added to all subcommands that make modifications on the + server or on the Admin Workstation. + + The user can override this check by specifying the --force argument before + any subcommand. + """ + def decorator_update_check(func: _FuncT) -> _FuncT: + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + cli_args = args[0] + if cli_args.force: + sdlog.info("Skipping update check because --force argument was provided.") + return func(*args, **kwargs) + + update_status, latest_tag = check_for_updates(cli_args) + if update_status is True: + + # Useful for troubleshooting + branch_status = get_git_branch(cli_args) + + sdlog.error("You are not running the most recent signed SecureDrop release " + "on this workstation.") + sdlog.error("Latest available version: {}".format(latest_tag)) + + if branch_status is not None: + sdlog.error("Current branch status: {}".format(branch_status)) + else: + sdlog.error("Problem determining current branch status.") + + sdlog.error("Running outdated or mismatched code can cause significant " + "technical issues.") + sdlog.error("To display more information about your repository state, run:\n\n\t" + "git status\n") + sdlog.error("If you are certain you want to proceed, run:\n\n\t" + "./securedrop-admin --force {}\n".format(cmd_name)) + sdlog.error("To apply the latest updates, run:\n\n\t" + "./securedrop-admin update\n") + sdlog.error("If this fails, see the latest upgrade guide on " + "https://docs.securedrop.org/ for instructions.") + sys.exit(1) + return func(*args, **kwargs) + return cast(_FuncT, wrapper) + return decorator_update_check + + +@update_check_required("sdconfig") def sdconfig(args: argparse.Namespace) -> int: """Configure SD site settings""" SiteConfig(args).load_and_update_config(validate=False) @@ -752,8 +812,10 @@ def find_or_generate_new_torv3_keys(args: argparse.Namespace) -> int: return 0 +@update_check_required("install") def install_securedrop(args: argparse.Namespace) -> int: """Install/Update SecureDrop""" + SiteConfig(args).load_and_update_config(prompt=False) sdlog.info("Now installing SecureDrop on remote servers.") @@ -767,6 +829,7 @@ def install_securedrop(args: argparse.Namespace) -> int: ) +@update_check_required("verify") def verify_install(args: argparse.Namespace) -> int: """Run configuration tests against SecureDrop servers""" @@ -776,6 +839,7 @@ def verify_install(args: argparse.Namespace) -> int: cwd=os.getcwd()) +@update_check_required("backup") def backup_securedrop(args: argparse.Namespace) -> int: """Perform backup of the SecureDrop Application Server. Creates a tarball of submissions and server config, and fetches @@ -789,6 +853,7 @@ def backup_securedrop(args: argparse.Namespace) -> int: return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) +@update_check_required("restore") def restore_securedrop(args: argparse.Namespace) -> int: """Perform restore of the SecureDrop Application Server. Requires a tarball of submissions and server config, created via @@ -825,6 +890,7 @@ def restore_securedrop(args: argparse.Namespace) -> int: return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) +@update_check_required("tailsconfig") def run_tails_config(args: argparse.Namespace) -> int: """Configure Tails environment post SD install""" sdlog.info("Configuring Tails workstation environment") @@ -851,7 +917,10 @@ def check_for_updates(args: argparse.Namespace) -> Tuple[bool, str]: """Check for SecureDrop updates""" sdlog.info("Checking for SecureDrop updates...") - # Determine what branch we are on + # Determine what tag we are likely to be on. Caveat: git describe + # may produce very surprising results, because it will locate the most recent + # _reachable_ tag. However, in our current branching model, it can be + # relied on to determine if we're on the latest tag or not. current_tag = subprocess.check_output(['git', 'describe'], cwd=args.root).decode('utf-8').rstrip('\n') # noqa: E501 @@ -879,6 +948,19 @@ def check_for_updates(args: argparse.Namespace) -> Tuple[bool, str]: return False, latest_tag +def get_git_branch(args: argparse.Namespace) -> Optional[str]: + """ + Returns the starred line of `git branch` output. + """ + git_branch_raw = subprocess.check_output(['git', 'branch'], + cwd=args.root).decode('utf-8') + match = re.search(r"\* (.*)\n", git_branch_raw) + if match is not None and len(match.groups()) > 0: + return match.group(1) + else: + return None + + def get_release_key_from_keyserver( args: argparse.Namespace, keyserver: Optional[str] = None, timeout: int = 45 ) -> None: @@ -972,6 +1054,7 @@ def update(args: argparse.Namespace) -> int: return 0 +@update_check_required("logs") def get_logs(args: argparse.Namespace) -> int: """Get logs for forensics and debugging purposes""" sdlog.info("Gathering logs for forensics and debugging") @@ -998,6 +1081,7 @@ def set_default_paths(args: argparse.Namespace) -> argparse.Namespace: return args +@update_check_required("reset_admin_access") def reset_admin_access(args: argparse.Namespace) -> int: """Resets SSH access to the SecureDrop servers, locking it to this Admin Workstation.""" @@ -1021,6 +1105,8 @@ class ArgParseFormatterCombo(argparse.ArgumentDefaultsHelpFormatter, help="Increase verbosity on output") parser.add_argument('-d', action='store_true', default=False, help="Developer mode. Not to be used in production.") + parser.add_argument('--force', action='store_true', required=False, + help="force command execution without update check") parser.add_argument('--root', required=True, help="path to the root of the SecureDrop repository") parser.add_argument('--site-config',
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -359,7 +359,7 @@ def verify_install_has_valid_config(): Checks that securedrop-admin install validates the configuration. """ cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} install'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} install'.format(cmd, SD_DIR)) child.expect(b"SUDO password:", timeout=5) child.close() @@ -369,7 +369,7 @@ def test_install_with_no_config(): Checks that securedrop-admin install complains about a missing config file. """ cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} install'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} install'.format(cmd, SD_DIR)) child.expect(b'ERROR: Please run "securedrop-admin sdconfig" first.', timeout=5) child.expect(pexpect.EOF, timeout=5) child.close() @@ -380,7 +380,7 @@ def test_install_with_no_config(): def test_sdconfig_on_first_run(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} sdconfig'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) verify_username_prompt(child) child.sendline('') verify_reboot_prompt(child) @@ -444,7 +444,7 @@ def test_sdconfig_on_first_run(): def test_sdconfig_both_v2_v3_true(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} sdconfig'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) verify_username_prompt(child) child.sendline('') verify_reboot_prompt(child) @@ -508,7 +508,7 @@ def test_sdconfig_both_v2_v3_true(): def test_sdconfig_only_v2_true(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} sdconfig'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) verify_username_prompt(child) child.sendline('') verify_reboot_prompt(child) @@ -572,7 +572,7 @@ def test_sdconfig_only_v2_true(): def test_sdconfig_enable_journalist_alerts(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} sdconfig'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) verify_username_prompt(child) child.sendline('') verify_reboot_prompt(child) @@ -641,7 +641,7 @@ def test_sdconfig_enable_journalist_alerts(): def test_sdconfig_enable_https_on_source_interface(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --root {1} sdconfig'.format(cmd, SD_DIR)) + child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) verify_username_prompt(child) child.sendline('') verify_reboot_prompt(child) diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -55,6 +55,80 @@ def test_not_verbose(self, capsys): assert 'HIDDEN' not in out assert 'VISIBLE' in out + def test_update_check_decorator_when_no_update_needed(self, caplog): + """ + When a function decorated with `@update_check_required` is run + And the `--force` argument was not given + And no update is required + Then the update check should run to completion + And no errors should be displayed + And the program should not exit + And the decorated function should be run + """ + with mock.patch( + "securedrop_admin.check_for_updates", side_effect=[[False, "1.5.0"]] + ) as mocked_check, mock.patch( + "securedrop_admin.get_git_branch", side_effect=["develop"] + ), mock.patch("sys.exit") as mocked_exit: + # The decorator itself interprets --force + args = argparse.Namespace(force=False) + rv = securedrop_admin.update_check_required("update_check_test")( + lambda _: 100 + )(args) + assert mocked_check.called + assert not mocked_exit.called + assert rv == 100 + assert caplog.text == '' + + def test_update_check_decorator_when_update_needed(self, caplog): + """ + When a function decorated with `@update_check_required` is run + And the `--force` argument was not given + And an update is required + Then the update check should run to completion + And an error referencing the command should be displayed + And the current branch state should be included in the output + And the program should exit + """ + with mock.patch( + "securedrop_admin.check_for_updates", side_effect=[[True, "1.5.0"]] + ) as mocked_check, mock.patch( + "securedrop_admin.get_git_branch", side_effect=["bad_branch"] + ), mock.patch("sys.exit") as mocked_exit: + # The decorator itself interprets --force + args = argparse.Namespace(force=False) + securedrop_admin.update_check_required("update_check_test")( + lambda _: _ + )(args) + assert mocked_check.called + assert mocked_exit.called + assert "update_check_test" in caplog.text + assert "bad_branch" in caplog.text + + def test_update_check_decorator_when_skipped(self, caplog): + """ + When a function decorated with `@update_check_required` is run + And the `--force` argument was given + Then the update check should not run + And a message should be displayed acknowledging this + And the program should not exit + And the decorated function should be run + """ + with mock.patch( + "securedrop_admin.check_for_updates", side_effect=[[True, "1.5.0"]] + ) as mocked_check, mock.patch( + "securedrop_admin.get_git_branch", side_effect=["develop"] + ), mock.patch("sys.exit") as mocked_exit: + # The decorator itself interprets --force + args = argparse.Namespace(force=True) + rv = securedrop_admin.update_check_required("update_check_test")( + lambda _: 100 + )(args) + assert not mocked_check.called + assert not mocked_exit.called + assert "--force" in caplog.text + assert rv == 100 + def test_check_for_updates_update_needed(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) @@ -128,6 +202,40 @@ def test_check_for_updates_if_most_recent_tag_is_rc(self, tmpdir, caplog): assert update_status is False assert tag == '0.6.1' + @pytest.mark.parametrize( + "git_output, expected_rv", + [ + (b'* develop\n', + 'develop'), + (b' develop\n' + b'* release/1.7.0\n', + 'release/1.7.0'), + (b'* (HEAD detached at 1.7.0)\n' + b' develop\n' + b' release/1.7.0\n', + '(HEAD detached at 1.7.0)'), + (b' main\n' + b'* valid_+!@#$%&_branch_name\n', + 'valid_+!@#$%&_branch_name'), + (b'Unrecognized output.', + None) + ] + ) + def test_get_git_branch(self, git_output, expected_rv): + """ + When `git branch` completes with exit code 0 + And the output conforms to the expected format + Then `get_git_branch` should return a description of the current HEAD + + When `git branch` completes with exit code 0 + And the output does not conform to the expected format + Then `get_git_branch` should return `None` + """ + args = argparse.Namespace(root=None) + with mock.patch('subprocess.check_output', side_effect=[git_output]): + rv = securedrop_admin.get_git_branch(args) + assert rv == expected_rv + def test_update_exits_if_not_needed(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path)
Warn or fail when running outdated playbook It's not uncommon that admins run an outdated playbook, because they've not updated their Admin Workstation for whatever reason (e.g. due to an update failure). Running an outdated playbook can have harmful consequences, reinstating changed configurations, or even breaking functionality. For an existing install, `securedrop-admin install` should attempt to obtain the version info from the server, and fail or warn if it doesn't correspond to the version info running on the workstation. ## User Story As an administrator, I don't want to accidentally mess up the configuration of my SecureDrop installation, so that I can avoid spending the rest of my afternoon debugging what I just did.
See the older issue #2964 for some ideas for how this could be implemented. Tentatively adding for consideration to the Focal epic, as this would potentially mark a nice cutoff for us to ensure that all new installs on Focal have this logic in place. Anecdata supports this issue! ## Implementation proposal After evaluating several options, I would propose a pragmatic implementation within `securedrop-admin` that relies on our existing `check_for_updates` code, hardened with additional error checks, and with more user-friendly output. We would perform a `check_for_updates` run before any `securedrop-admin` subcommand that connects to the server (e.g., `backup`, `install`, `restore`). If it detects a mismatch with the latest git tag or the update check fails (e.g., GitHub not reachable), it would print an informative error message, asking the user to specify a `--force` argument if they are certain that they want to proceed. Advantages of this approach: - It will work regardless of whether SecureDrop is already installed or not, and regardless of whether the server is reachable or not, preventing any potentially harmful uses of an outdated playbook - It relies on existing version check logic, minimizing our maintenance and testing footprint - It's easy to make this user-friendly without asking the user to parse Ansible's typically noisy output, and we can add additional messages or interactivity as we see fit - As far as I can tell, it's a relatively small diff Disadvantages: - We would have to use `--force` routinely during QA due to the `~rc` version mismatch (arguable whether it's a disadvantage -- we're running unreleased code against the server during QA, so a `--force` argument may be warranted) - Doesn't handle some edge cases well (both of which can already arise due to auto-updates of workstations, so I do not view this as a regression) - Server has fallen behind for an unclear reason - Admin runs `securedrop-admin` subcommands after a new release has been tagged but before their server has been updated ## Alternatives worth considering - Running an Ansible task which fetches `version.py` (or checks the `securedrop-app-code` package version) and compares its output with the local `git status` output - Can't handle outdated playbook for fresh install (at least not without falling back on `securedrop-admin` logic to check git tags) - Error output may be noisy and difficult to interpret - Ansible's version check behavior is [not clearly specified](https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html#comparing-versions), and its behavior may differ in edge cases from our existing version checks - In `securedrop-admin`, hitting the metadata endpoint if we have a local onion service definition we can `curl` - Could be _combined_ with a git version check in `securedrop-admin`, but seems overly complicated, slow, and potentially error-prone if server is not reachable
2021-02-12T06:42:45Z
[]
[]
freedomofpress/securedrop
5,806
freedomofpress__securedrop-5806
[ "5795" ]
489457237ec8f494154d9439b1608f5ac98514a4
diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -9,8 +9,11 @@ import io import os import yaml +from typing import Any, Dict + import testutils + # The config tests target staging by default. It's possible to override # for e.g. prod, but the associated vars files are not yet ported. target_host = os.environ.get('SECUREDROP_TESTINFRA_TARGET_HOST', 'staging') @@ -50,25 +53,30 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): return hostvars -def lookup_molecule_info(): - """ - Molecule automatically writes YAML files documenting dynamic host info - such as remote IPs. Read that file and pass back the config dict. - """ - molecule_instance_config_path = os.path.abspath( - os.environ['MOLECULE_INSTANCE_CONFIG']) - with open(molecule_instance_config_path, 'r') as f: - molecule_instance_config = yaml.safe_load(f) - return molecule_instance_config +class TestVars(dict): + managed_attrs = {} # type: Dict[str, Any] + + def __init__(self, initial: Dict[str, Any]) -> None: + self.securedrop_target_distribution = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") + self.managed_attrs.update(initial) + def __getattr__(self, name: str) -> Any: + """ + If the requested attribute names a dict in managed_attrs and that + contains a key with the name of the target distribution, + e.g. "focal", return that. Otherwise return the entire item + under the requested name. + """ + try: + attr = self.managed_attrs[name] + if isinstance(attr, dict) and self.securedrop_target_distribution in attr: + return attr[self.securedrop_target_distribution] + return attr + except KeyError: + raise AttributeError(name) -class Myvalues: - def __init__(self): - pass + def __str__(self) -> str: + return str(self.managed_attrs) -value = securedrop_import_testinfra_vars(target_host) -res = Myvalues() -for key, value in value.items(): - setattr(res, key, value) -testutils.securedrop_test_vars = res +testutils.securedrop_test_vars = TestVars(securedrop_import_testinfra_vars(target_host))
diff --git a/molecule/testinfra/app/test_app_network.py b/molecule/testinfra/app/test_app_network.py --- a/molecule/testinfra/app/test_app_network.py +++ b/molecule/testinfra/app/test_app_network.py @@ -16,12 +16,19 @@ def test_app_iptables_rules(host): local = host.get_host("local://") + time_service_user = ( + host.check_output("id -u systemd-timesync") + if securedrop_test_vars.securedrop_target_distribution == "focal" + else 0 + ) + # Build a dict of variables to pass to jinja for iptables comparison kwargs = dict( mon_ip=os.environ.get('MON_IP', securedrop_test_vars.mon_ip), default_interface=host.check_output("ip r | head -n 1 | " "awk '{ print $5 }'"), tor_user_id=host.check_output("id -u debian-tor"), + time_service_user=time_service_user, securedrop_user_id=host.check_output("id -u www-data"), ssh_group_gid=host.check_output("getent group ssh | cut -d: -f3"), dns_server=securedrop_test_vars.dns_server) diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -19,7 +19,7 @@ def test_automatic_updates_dependencies(host): """ apt_dependencies = { 'xenial': ['cron-apt', 'ntp'], - 'focal': ['unattended-upgrades', 'ntp'] + 'focal': ['unattended-upgrades'] } for package in apt_dependencies[host.system_info.codename]: diff --git a/molecule/testinfra/common/test_basic_configuration.py b/molecule/testinfra/common/test_basic_configuration.py new file mode 100644 --- /dev/null +++ b/molecule/testinfra/common/test_basic_configuration.py @@ -0,0 +1,39 @@ +from testinfra.host import Host + +import testutils + + +test_vars = testutils.securedrop_test_vars +testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] + + +def test_system_time(host: Host) -> None: + if host.system_info.codename == "xenial": + assert host.package("ntp").is_installed + assert host.package("ntpdate").is_installed + + # TODO: The staging setup timing is too erratic for the + # following check. If we do want to reinstate it before + # dropping Xenial support, it should be done in a loop to give + # ntpd time to sync after the machines are created. + + # c = host.run("ntpq -c rv") + # assert "leap_none" in c.stdout + # assert "sync_ntp" in c.stdout + # assert "refid" in c.stdout + else: + assert not host.package("ntp").is_installed + assert not host.package("ntpdate").is_installed + + s = host.service("systemd-timesyncd") + assert s.is_running + assert s.is_enabled + assert not s.is_masked + + # File will be touched on every successful synchronization, + # see 'man systemd-timesyncd'` + assert host.file("/run/systemd/timesync/synchronized").exists + + c = host.run("timedatectl show") + assert "NTP=yes" in c.stdout + assert "NTPSynchronized=yes" in c.stdout diff --git a/molecule/testinfra/mon/test_mon_network.py b/molecule/testinfra/mon/test_mon_network.py --- a/molecule/testinfra/mon/test_mon_network.py +++ b/molecule/testinfra/mon/test_mon_network.py @@ -15,12 +15,19 @@ def test_mon_iptables_rules(host): local = host.get_host("local://") + time_service_user = ( + host.check_output("id -u systemd-timesync") + if securedrop_test_vars.securedrop_target_distribution == "focal" + else 0 + ) + # Build a dict of variables to pass to jinja for iptables comparison kwargs = dict( app_ip=os.environ.get('APP_IP', securedrop_test_vars.app_ip), default_interface=host.check_output( "ip r | head -n 1 | awk '{ print $5 }'"), tor_user_id=host.check_output("id -u debian-tor"), + time_service_user=time_service_user, ssh_group_gid=host.check_output("getent group ssh | cut -d: -f3"), postfix_user_id=host.check_output("id -u postfix"), dns_server=securedrop_test_vars.dns_server)
Apparmor denial for ntpd on Focal ## Description `ntpd` throws grsec denial message. ## Steps to Reproduce - [ ] Install focal on hardware (I hope the same will show up in vm too) - [ ] check `/var/log/syslog` ## Expected Behavior - no grsec error from ntpd ## Actual Behavior ``` Feb 17 03:43:33 app systemd[1]: Starting Network Time Service... Feb 17 03:43:33 app kernel: [ 202.428911] audit: type=1400 audit(1613533413.416:46): apparmor="DENIED" operation="open" profile="/usr/sbin/ntpd" name="/snap/bin/" pid=3303 comm="ntpd" requested_mask="r" denied_mask="r" fsuid=0 ouid=0 Feb 17 03:43:33 app ntpd[3303]: ntpd [email protected] (1): Starting Feb 17 03:43:33 app ntpd[3303]: Command line: /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 112:117 Feb 17 03:43:33 app ntpd[3306]: proto: precision = 0.175 usec (-22) -- ``` ## Comments Suggestions to fix, any other relevant information.
2021-02-19T22:18:22Z
[]
[]
freedomofpress/securedrop
5,827
freedomofpress__securedrop-5827
[ "5824" ]
94fdaacc4ff86c3da51af4fee295535770800e1b
diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -70,7 +70,7 @@ def delete_single(filesystem_id: str) -> werkzeug.Response: # confirming the success of an operation. escape(gettext("Success!")), escape(gettext( - "The account and data for the source {} has been deleted.").format( + "The account and data for the source {} have been deleted.").format( source.journalist_designation)) ) ), 'success')
diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -507,7 +507,7 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): text = resp.data.decode('utf-8') assert escape( - "The account and data for the source {} has been deleted.".format(col_name)) in text + "The account and data for the source {} have been deleted.".format(col_name)) in text assert "No documents have been submitted!" in text assert async_genkey.called
1.8.0 translation feedback: Focal upgrade warning ## Description AO [suggested](https://weblate.securedrop.org/translate/securedrop/securedrop/en/?checksum=c775f74150ac3872) changing `A manual update is urgently required to remain safe.` to `A manual upgrade is urgently required to remain safe.` in: ``` <strong>Critical Security:</strong>&nbsp;&nbsp;The operating system used by your SecureDrop servers will reach its end-of-life on April 30, 2021. A manual update is urgently required to remain safe. Please contact your adminstrator. <a href="//securedrop.org/xenial-eol" rel="noreferrer">Learn More</a> ``` as well as [here](https://weblate.securedrop.org/translate/securedrop/securedrop/en/?checksum=60e0284e103e2c51): ``` <strong>Critical Security:</strong>&nbsp;&nbsp;The operating system used by your SecureDrop servers has reached its end-of-life. A manual update is required to re-enable the Source Interface and remain safe. Please contact your administrator. <a href="//securedrop.org/xenial-eol" rel="noreferrer">Learn More</a> ``` There's also a typo in the first string: "adminstrator" needs another "i".
:+1: to update->upgrade and typo fix (good catch!)
2021-02-25T22:44:53Z
[]
[]
freedomofpress/securedrop
5,839
freedomofpress__securedrop-5839
[ "5825" ]
6e4676b5d117cb115ec004edff1a946c38d4d99c
diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -43,9 +43,11 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): if testing_focal: hostvars['securedrop_venv_site_packages'] = hostvars["securedrop_venv_site_packages"].format("3.8") # noqa: E501 hostvars['python_version'] = "3.8" + hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['focal'] else: hostvars['securedrop_venv_site_packages'] = hostvars["securedrop_venv_site_packages"].format("3.5") # noqa: E501 hostvars['python_version'] = "3.5" + hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['xenial'] if with_header: hostvars = dict(securedrop_test_vars=hostvars)
diff --git a/molecule/testinfra/app/test_apparmor.py b/molecule/testinfra/app/test_apparmor.py --- a/molecule/testinfra/app/test_apparmor.py +++ b/molecule/testinfra/app/test_apparmor.py @@ -88,7 +88,7 @@ def test_app_apparmor_complain_count(host): assert c == str(len(sdvars.apparmor_complain)) [email protected]('aa_enforced', sdvars.apparmor_enforce) [email protected]('aa_enforced', sdvars.apparmor_enforce_actual) def test_apparmor_enforced(host, aa_enforced): awk = ("awk '/[0-9]+ profiles.*enforce./" "{flag=1;next}/^[0-9]+.*/{flag=0}flag'") diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -192,9 +192,7 @@ def test_unattended_upgrades_config(host): Ensures the 50unattended-upgrades config is correct only under Ubuntu Focal """ f = host.file('/etc/apt/apt.conf.d/50unattended-upgrades') - if host.system_info.codename == "xenial": - assert not f.exists - else: + if host.system_info.codename != "xenial": assert f.is_file assert f.user == "root" assert f.mode == 0o644 diff --git a/molecule/testinfra/common/test_grsecurity.py b/molecule/testinfra/common/test_grsecurity.py --- a/molecule/testinfra/common/test_grsecurity.py +++ b/molecule/testinfra/common/test_grsecurity.py @@ -173,7 +173,10 @@ def test_paxctld_xenial(host): """ if host.system_info.codename != "xenial": return True - hostname = host.ansible.get_variables()["inventory_hostname"] + + hostname = host.check_output('hostname -s') + assert (("app" in hostname) or ("mon" in hostname)) + # Under Xenial, apache2 pax flags managed by securedrop-app-code. if "app" not in hostname: return True @@ -209,7 +212,9 @@ def test_paxctld_focal(host): # out of /opt/ to ensure the file is always clobbered on changes. assert host.file("/opt/securedrop/paxctld.conf").is_file - hostname = host.ansible.get_variables()["inventory_hostname"] + hostname = host.check_output('hostname -s') + assert (("app" in hostname) or ("mon" in hostname)) + # Under Focal, apache2 pax flags managed by securedrop-grsec metapackage. # Both hosts, app & mon, should have the same exemptions. Check precedence # between install-local-packages & apt-test repo for securedrop-grsec.
Several testinfra tests failing against 1.8.0-rc1 Focal production instances: ## Description `./securedrop-admin verify` against a 1.8.0-rc1 instance results in 11 test failures (of which 2 are expected) ``` ============================================================================================= short test summary info ============================================================================================= FAILED app/test_apparmor.py::test_apparmor_enforced[paramiko:/app-xenial] - AssertionError: assert 'xenial' in ' /usr/bin/man\n /usr/lib/NetworkManager/nm-dhcp-client.action\n /usr/lib/NetworkManager/nm... FAILED app/test_apparmor.py::test_apparmor_enforced[paramiko:/app-focal] - AssertionError: assert 'focal' in ' /usr/bin/man\n /usr/lib/NetworkManager/nm-dhcp-client.action\n /usr/lib/NetworkManager/nm-d... FAILED app-code/test_securedrop_rqrequeue.py::test_securedrop_rqrequeue_service[paramiko:/app] - assert '[Unit]\nDesc...user.target\n' == '[Unit]\nDesc...user.target\n' FAILED app-code/test_securedrop_rqworker.py::test_securedrop_rqworker_service[paramiko:/app] - assert '[Unit]\nDesc...user.target\n' == '[Unit]\nDesc...user.target\n' FAILED app-code/test_securedrop_shredder_configuration.py::test_securedrop_shredder_service[paramiko:/app] - assert '[Unit]\nDesc...user.target\n' == '[Unit]\nDesc...user.target\n' FAILED app-code/test_securedrop_source_deleter_configuration.py::test_securedrop_source_deleter_service[paramiko:/app] - assert '[Unit]\nDesc...user.target\n' == '[Unit]\nDesc...user.target\n' FAILED app-code/test_securedrop_app_code.py::test_securedrop_application_apt_dependencies[paramiko:/app-libpython3.5] - AssertionError: assert False (expected failure) FAILED common/test_fpf_apt_repo.py::test_fpf_apt_repo_present[paramiko:/app] - AssertionError: Unexpected exit code 2 for CommandResult(command=b"grep -qs -- '^deb \\[arch=amd64\\] https://apt\\.freedom\\.pre... (expected failure) FAILED common/test_fpf_apt_repo.py::test_fpf_apt_repo_present[paramiko:/mon] - AssertionError: Unexpected exit code 2 for CommandResult(command=b"grep -qs -- '^deb \\[arch=amd64\\] https://apt\\.freedom\\.pre... FAILED common/test_grsecurity.py::test_paxctld_focal[paramiko:/mon] - RuntimeError: Ansible module is only available with ansible connection backend FAILED common/test_grsecurity.py::test_paxctld_focal[paramiko:/app] - RuntimeError: Ansible module is only available with ansible connection backend ============================================================= 11 failed, 441 passed, 7 skipped, 3 xfailed, 1 xpassed, 8 warnings in 842.46s (0:14:02) ============================================================= ```
2021-03-03T16:47:27Z
[]
[]
freedomofpress/securedrop
5,881
freedomofpress__securedrop-5881
[ "5755" ]
84dfbfddc87c910f95ca40a847a30aef2e503ff5
diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -94,9 +94,8 @@ def create_app(config: 'SDConfig') -> Flask: @app.errorhandler(CSRFError) def handle_csrf_error(e: CSRFError) -> 'Response': - # render the message first to ensure it's localized. - msg = gettext('You have been logged out due to inactivity.') session.clear() + msg = gettext('You have been logged out due to inactivity.') flash(msg, 'error') return redirect(url_for('main.login')) diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -52,8 +52,8 @@ def manage_config() -> Union[str, werkzeug.Response]: f.save(custom_logo_filepath) flash(gettext("Image updated."), "logo-success") except Exception: - flash("Unable to process the image file." - " Try another one.", "logo-error") + # Translators: This error is shown when an uploaded image cannot be used. + flash(gettext("Unable to process the image file. Try another one."), "logo-error") finally: return redirect(url_for("admin.manage_config") + "#config-logoimage") else: @@ -131,13 +131,16 @@ def add_user() -> Union[str, werkzeug.Response]: form_valid = False except InvalidUsernameException as e: form_valid = False - flash('Invalid username: ' + str(e), "error") + # Translators: Here, "{message}" explains the problem with the username. + flash(gettext('Invalid username: {message}').format(message=e), "error") except IntegrityError as e: db.session.rollback() form_valid = False if "UNIQUE constraint failed: journalists.username" in str(e): - flash(gettext('Username "{user}" already taken.'.format( - user=username)), "error") + flash( + gettext('Username "{username}" already taken.').format(username=username), + "error" + ) else: flash(gettext("An error occurred saving this user" " to the database." @@ -214,7 +217,7 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: try: Journalist.check_username_acceptable(new_username) except InvalidUsernameException as e: - flash('Invalid username: ' + str(e), 'error') + flash(gettext('Invalid username: {message}').format(message=e), "error") return redirect(url_for("admin.edit_user", user_id=user_id)) @@ -222,10 +225,12 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: pass elif Journalist.query.filter_by( username=new_username).one_or_none(): - flash(gettext( - 'Username "{user}" already taken.').format( - user=new_username), - "error") + flash( + gettext('Username "{username}" already taken.').format( + username=new_username + ), + "error" + ) return redirect(url_for("admin.edit_user", user_id=user_id)) else: @@ -236,7 +241,8 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: Journalist.check_name_acceptable(first_name) user.first_name = first_name except FirstOrLastNameError as e: - flash(gettext('Name not updated: {}'.format(e)), "error") + # Translators: Here, "{message}" explains the problem with the name. + flash(gettext('Name not updated: {message}').format(message=e), "error") return redirect(url_for("admin.edit_user", user_id=user_id)) try: @@ -244,7 +250,7 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: Journalist.check_name_acceptable(last_name) user.last_name = last_name except FirstOrLastNameError as e: - flash(gettext('Name not updated: {}'.format(e)), "error") + flash(gettext('Name not updated: {message}').format(message=e), "error") return redirect(url_for("admin.edit_user", user_id=user_id)) user.is_admin = bool(request.form.get('is_admin')) diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -99,7 +99,7 @@ def validate_user( InvalidPasswordLength) as e: current_app.logger.error("Login for '{}' failed: {}".format( username, e)) - login_flashed_msg = error_message if error_message else gettext('<b>Login failed.</b>') + login_flashed_msg = error_message if error_message else gettext('Login failed.') if isinstance(e, LoginThrottledException): login_flashed_msg += " " @@ -123,7 +123,7 @@ def validate_user( except Exception: pass - flash(Markup(login_flashed_msg), "error") + flash(login_flashed_msg, "error") return None @@ -414,7 +414,7 @@ def set_name(user: Journalist, first_name: Optional[str], last_name: Optional[st db.session.commit() flash(gettext('Name updated.'), "success") except FirstOrLastNameError as e: - flash(gettext('Name not updated: {}'.format(e)), "error") + flash(gettext('Name not updated: {message}').format(message=e), "error") def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: @@ -437,11 +437,20 @@ def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: return False # using Markup so the HTML isn't escaped - flash(Markup("<p>" + gettext( - "Password updated. Don't forget to " - "save it in your KeePassX database. New password:") + - ' <span><code>{}</code></span></p>'.format(password)), - 'success') + flash( + Markup( + "<p>{message} <span><code>{password}</code></span></p>".format( + message=Markup.escape( + gettext( + "Password updated. Don't forget to save it in your KeePassX database. " + "New password:" + ) + ), + password=Markup.escape("" if password is None else password) + ) + ), + 'success' + ) return True diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -12,6 +12,7 @@ from io import BytesIO from flask import current_app, url_for +from flask_babel import gettext, ngettext from itsdangerous import TimedJSONWebSignatureSerializer, BadData from jinja2 import Markup from passlib.hash import argon2 @@ -342,10 +343,8 @@ def __init__(self, msg: str) -> None: class InvalidNameLength(FirstOrLastNameError): """Raised when attempting to create a Journalist with an invalid name length.""" - def __init__(self, name: str) -> None: - name_len = len(name) - msg = "Name too long (len={})".format(name_len) - super(InvalidNameLength, self).__init__(msg) + def __init__(self) -> None: + super(InvalidNameLength, self).__init__(gettext("Name too long")) class LoginThrottledException(Exception): @@ -380,11 +379,9 @@ def __init__(self, passphrase: str) -> None: def __str__(self) -> str: if self.passphrase_len > Journalist.MAX_PASSWORD_LEN: - return "Password too long (len={})".format(self.passphrase_len) + return "Password is too long." if self.passphrase_len < Journalist.MIN_PASSWORD_LEN: - return "Password needs to be at least {} characters".format( - Journalist.MIN_PASSWORD_LEN - ) + return "Password is too short." return "" # return empty string that can be appended harmlessly @@ -496,18 +493,25 @@ def set_name(self, first_name: Optional[str], last_name: Optional[str]) -> None: def check_username_acceptable(cls, username: str) -> None: if len(username) < cls.MIN_USERNAME_LEN: raise InvalidUsernameException( - 'Username "{}" must be at least {} characters long.' - .format(username, cls.MIN_USERNAME_LEN)) + ngettext( + 'Must be at least {num} character long.', + 'Must be at least {num} characters long.', + cls.MIN_USERNAME_LEN + ).format(num=cls.MIN_USERNAME_LEN) + ) if username in cls.INVALID_USERNAMES: raise InvalidUsernameException( + gettext( "This username is invalid because it is reserved " - "for internal use by the software.") + "for internal use by the software." + ) + ) @classmethod def check_name_acceptable(cls, name: str) -> None: # Enforce a reasonable maximum length for names if len(name) > cls.MAX_NAME_LEN: - raise InvalidNameLength(name) + raise InvalidNameLength() @classmethod def check_password_acceptable(cls, password: str) -> None: @@ -675,13 +679,11 @@ def login(cls, try: user = Journalist.query.filter_by(username=username).one() except NoResultFound: - raise InvalidUsernameException( - "invalid username '{}'".format(username)) + raise InvalidUsernameException(gettext("Invalid username")) if user.username in Journalist.INVALID_USERNAMES and \ user.uuid in Journalist.INVALID_USERNAMES: - raise InvalidUsernameException( - "Invalid username") + raise InvalidUsernameException(gettext("Invalid username")) if LOGIN_HARDENING: cls.throttle_login(user) @@ -876,9 +878,9 @@ def get_current(cls) -> "InstanceConfig": def check_name_acceptable(cls, name: str) -> None: # Enforce a reasonable maximum length for names if name is None or len(name) == 0: - raise InvalidNameLength(name) + raise InvalidNameLength() if len(name) > cls.MAX_ORG_NAME_LEN: - raise InvalidNameLength(name) + raise InvalidNameLength() @classmethod def set_organization_name(cls, name: str) -> None: diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -3,7 +3,7 @@ from typing import Optional import werkzeug -from flask import (Flask, render_template, flash, Markup, request, g, session, +from flask import (Flask, render_template, escape, flash, Markup, request, g, session, url_for, redirect) from flask_babel import gettext from flask_assets import Environment @@ -127,14 +127,21 @@ def check_tor2web() -> None: # ignore_static here so we only flash a single message warning # about Tor2Web, corresponding to the initial page load. if 'X-tor2web' in request.headers: - flash(Markup(gettext( - '<strong>WARNING:&nbsp;</strong> ' - 'You appear to be using Tor2Web. ' - 'This <strong>&nbsp;does not&nbsp;</strong> ' - 'provide anonymity. ' - '<a href="{url}">Why is this dangerous?</a>') - .format(url=url_for('info.tor2web_warning'))), - "banner-warning") + flash( + Markup( + '<strong>{}</strong>&nbsp;{}&nbsp;<a href="{}">{}</a>'.format( + escape(gettext("WARNING:")), + escape( + gettext( + 'You appear to be using Tor2Web, which does not provide anonymity.' + ) + ), + url_for('info.tor2web_warning'), + escape(gettext('Why is this dangerous?')), + ) + ), + "banner-warning" + ) @app.before_request @ignore_static
diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -32,6 +32,7 @@ import models from source_app import create_app as create_source_app from . import utils +from .utils import i18n # The PID file for the redis worker is hard-coded below. # Ideally this constant would be provided by a test harness. @@ -130,6 +131,8 @@ def config(gpg_key_dir: Path) -> Generator[SDConfig, None, None]: config.DATABASE_FILE = str(sqlite_db_path) subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) + config.SUPPORTED_LOCALES = i18n.get_test_locales() + yield config diff --git a/securedrop/tests/pageslayout/functional_test.py b/securedrop/tests/pageslayout/functional_test.py --- a/securedrop/tests/pageslayout/functional_test.py +++ b/securedrop/tests/pageslayout/functional_test.py @@ -30,8 +30,8 @@ def list_locales(): - if "PAGE_LAYOUT_LOCALES" in os.environ: - locales = os.environ["PAGE_LAYOUT_LOCALES"].split(",") + if "TEST_LOCALES" in os.environ: + locales = os.environ["TEST_LOCALES"].split() else: locales = ["en_US"] return locales diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +# flake8: noqa: E741 import base64 import binascii import io @@ -11,7 +12,9 @@ from base64 import b64decode from io import BytesIO +from flaky import flaky from flask import current_app, escape, g, session, url_for +from flask_babel import gettext, ngettext from mock import patch from pyotp import TOTP from sqlalchemy.exc import IntegrityError @@ -38,6 +41,7 @@ from sdconfig import config from .utils.instrument import InstrumentedApp +from .utils.i18n import get_plural_tests, get_test_locales, language_tag, page_language, xfail_untranslated_messages from . import utils @@ -47,12 +51,6 @@ VALID_PASSWORD = 'correct horse battery staple generic passphrase hooray' VALID_PASSWORD_2 = 'another correct horse battery staple generic passphrase' -# These are factored out of the tests because some test have a -# postive/negative case under varying conditions, and we don't want -# false postives after modifying a string in the application. -EMPTY_REPLY_TEXT = "You cannot send an empty reply." -ADMIN_LINK = '<a href="/admin/" id="link-admin-index">' - def _login_user(app, username, password, otp_secret): resp = app.post(url_for('main.login'), @@ -166,7 +164,9 @@ def test_reply_error_logging(journalist_app, test_journo, test_source): exception_class)) -def test_reply_error_flashed_message(journalist_app, test_journo, test_source): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_reply_error_flashed_message(config, journalist_app, test_journo, test_source, locale): exception_class = StaleDataError with journalist_app.test_client() as app: @@ -176,43 +176,58 @@ def test_reply_error_flashed_message(journalist_app, test_journo, test_source): with InstrumentedApp(app) as ins: with patch.object(db.session, 'commit', side_effect=exception_class()): - app.post(url_for('main.reply'), - data={'filesystem_id': test_source['filesystem_id'], - 'message': '_'}) + resp = app.post( + url_for('main.reply', l=locale), + data={'filesystem_id': test_source['filesystem_id'], 'message': '_'}, + follow_redirects=True + ) - ins.assert_message_flashed( - 'An unexpected error occurred! Please ' - 'inform your admin.', 'error') + assert page_language(resp.data) == language_tag(locale) + msgids = ['An unexpected error occurred! Please inform your admin.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'error') -def test_empty_replies_are_rejected(journalist_app, test_journo, test_source): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_empty_replies_are_rejected(config, journalist_app, test_journo, test_source, locale): with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('main.reply'), + resp = app.post(url_for('main.reply', l=locale), data={'filesystem_id': test_source['filesystem_id'], 'message': ''}, follow_redirects=True) - text = resp.data.decode('utf-8') - assert EMPTY_REPLY_TEXT in text + assert page_language(resp.data) == language_tag(locale) + msgids = ['You cannot send an empty reply.'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_nonempty_replies_are_accepted(journalist_app, test_journo, - test_source): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_nonempty_replies_are_accepted(config, journalist_app, test_journo, test_source, locale): with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('main.reply'), - data={'filesystem_id': test_source['filesystem_id'], - 'message': '_'}, - follow_redirects=True) + resp = app.post( + url_for('main.reply', l=locale), + data={'filesystem_id': test_source['filesystem_id'], 'message': '_'}, + follow_redirects=True + ) - text = resp.data.decode('utf-8') - assert EMPTY_REPLY_TEXT not in text + assert page_language(resp.data) == language_tag(locale) + msgids = ['You cannot send an empty reply.'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) not in resp.data.decode('utf-8') -def test_successful_reply_marked_as_seen_by_sender(journalist_app, test_journo, test_source): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_successful_reply_marked_as_seen_by_sender( + config, journalist_app, test_journo, test_source, locale +): with journalist_app.test_client() as app: journo = test_journo['journalist'] _login_user(app, journo.username, test_journo['password'], test_journo['otp_secret']) @@ -221,13 +236,15 @@ def test_successful_reply_marked_as_seen_by_sender(journalist_app, test_journo, assert not seen_reply resp = app.post( - url_for('main.reply'), + url_for('main.reply', l=locale), data={'filesystem_id': test_source['filesystem_id'], 'message': '_'}, follow_redirects=True ) - text = resp.data.decode('utf-8') - assert EMPTY_REPLY_TEXT not in text + assert page_language(resp.data) == language_tag(locale) + msgids = ['You cannot send an empty reply.'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) not in resp.data.decode('utf-8') seen_reply = SeenReply.query.filter_by(journalist_id=journo.id).one_or_none() assert seen_reply @@ -239,36 +256,60 @@ def test_unauthorized_access_redirects_to_login(journalist_app): ins.assert_redirects(resp, url_for('main.login')) -def test_login_throttle(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_login_throttle(config, journalist_app, test_journo, locale): # Overwrite the default value used during testing original_hardening = models.LOGIN_HARDENING models.LOGIN_HARDENING = True try: with journalist_app.test_client() as app: - for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): - resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password='invalid', - token='invalid')) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Login failed" in text + with InstrumentedApp(app) as ins: + for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): + resp = app.post( + url_for('main.login'), + data=dict( + username=test_journo['username'], + password='invalid', + token='invalid' + ) + ) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Login failed" in text - resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password='invalid', - token='invalid')) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert ("Please wait at least {} seconds".format( - Journalist._LOGIN_ATTEMPT_PERIOD) in text) + resp = app.post( + url_for('main.login', l=locale), + data=dict( + username=test_journo['username'], + password='invalid', + token='invalid' + ) + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Login failed.", + "Please wait at least {num} second before logging in again." + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + "{} {}".format( + gettext(msgids[0]), + ngettext( + msgids[1], + "Please wait at least {num} seconds before logging in again.", + Journalist._LOGIN_ATTEMPT_PERIOD + ).format(num=Journalist._LOGIN_ATTEMPT_PERIOD) + ), + 'error' + ) finally: models.LOGIN_HARDENING = original_hardening -def test_login_throttle_is_not_global(journalist_app, test_journo, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_login_throttle_is_not_global(config, journalist_app, test_journo, test_admin, locale): """The login throttling should be per-user, not global. Global login throttling can prevent all users logging into the application.""" @@ -278,71 +319,106 @@ def test_login_throttle_is_not_global(journalist_app, test_journo, test_admin): models.LOGIN_HARDENING = True try: with journalist_app.test_client() as app: - for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): - resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password='invalid', - token='invalid')) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Login failed" in text + with InstrumentedApp(app) as ins: + for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): + resp = app.post( + url_for('main.login', l=locale), + data=dict( + username=test_journo['username'], + password='invalid', + token='invalid' + ) + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Login failed.'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') - resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password='invalid', - token='invalid')) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert ("Please wait at least {} seconds".format( - Journalist._LOGIN_ATTEMPT_PERIOD) in text) + resp = app.post( + url_for('main.login', l=locale), + data=dict( + username=test_journo['username'], + password='invalid', + token='invalid' + ) + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Login failed.", + "Please wait at least {num} second before logging in again." + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + "{} {}".format( + gettext(msgids[0]), + ngettext( + msgids[1], + "Please wait at least {num} seconds before logging in again.", + Journalist._LOGIN_ATTEMPT_PERIOD + ).format(num=Journalist._LOGIN_ATTEMPT_PERIOD) + ), + 'error' + ) # A different user should be able to login resp = app.post( - url_for('main.login'), + url_for('main.login', l=locale), data=dict(username=test_admin['username'], password=test_admin['password'], token=TOTP(test_admin['otp_secret']).now()), follow_redirects=True) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Sources" in text + assert page_language(resp.data) == language_tag(locale) + msgids = ['All Sources'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') finally: models.LOGIN_HARDENING = original_hardening -def test_login_invalid_credentials(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_login_invalid_credentials(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: - resp = app.post(url_for('main.login'), + resp = app.post(url_for('main.login', l=locale), data=dict(username=test_journo['username'], password='invalid', token='mocked')) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Login failed" in text + assert page_language(resp.data) == language_tag(locale) + msgids = ['Login failed.'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_validate_redirect(journalist_app): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_validate_redirect(config, journalist_app, locale): with journalist_app.test_client() as app: - resp = app.post(url_for('main.index'), follow_redirects=True) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Login to access" in text + resp = app.post(url_for('main.index', l=locale), follow_redirects=True) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Login to access the journalist interface'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_login_valid_credentials(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_login_valid_credentials(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: resp = app.post( - url_for('main.login'), + url_for('main.login', l=locale), data=dict(username=test_journo['username'], password=test_journo['password'], token=TOTP(test_journo['otp_secret']).now()), follow_redirects=True) - assert resp.status_code == 200 # successful login redirects to index - text = resp.data.decode('utf-8') - assert "Sources" in text - assert "No documents have been submitted!" in text + assert page_language(resp.data) == language_tag(locale) + msgids = [ + 'All Sources', + 'No documents have been submitted!' + ] + with xfail_untranslated_messages(config, locale, msgids): + resp_text = resp.data.decode('utf-8') + for msgid in msgids: + assert gettext(msgid) in resp_text def test_admin_login_redirects_to_index(journalist_app, test_admin): @@ -409,7 +485,7 @@ def test_admin_has_link_to_admin_index_page_in_index_page(journalist_app, token=TOTP(test_admin['otp_secret']).now()), follow_redirects=True) text = resp.data.decode('utf-8') - assert ADMIN_LINK in text + assert '<a href="/admin/" id="link-admin-index">' in text def test_user_lacks_link_to_admin_index_page_in_index_page(journalist_app, @@ -422,7 +498,7 @@ def test_user_lacks_link_to_admin_index_page_in_index_page(journalist_app, token=TOTP(test_journo['otp_secret']).now()), follow_redirects=True) text = resp.data.decode('utf-8') - assert ADMIN_LINK not in text + assert '<a href="/admin/" id="link-admin-index">' not in text def test_admin_logout_redirects_to_index(journalist_app, test_admin): @@ -445,17 +521,22 @@ def test_user_logout_redirects_to_index(journalist_app, test_journo): ins.assert_redirects(resp, url_for('main.index')) -def test_admin_index(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_index(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.get(url_for('admin.index')) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Admin Interface" in text + resp = app.get(url_for('admin.index', l=locale)) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Admin Interface'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_admin_delete_user(journalist_app, test_admin, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_delete_user(config, journalist_app, test_admin, test_journo, locale): # Verify journalist is in the database with journalist_app.app_context(): assert Journalist.query.get(test_journo['id']) is not None @@ -463,22 +544,28 @@ def test_admin_delete_user(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.delete_user', - user_id=test_journo['id']), - follow_redirects=True) + with InstrumentedApp(journalist_app) as ins: + resp = app.post( + url_for('admin.delete_user', user_id=test_journo['id'], l=locale), + follow_redirects=True + ) - # Assert correct interface behavior - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert escape("Deleted user '{}'".format(test_journo['username'])) \ - in text + assert page_language(resp.data) == language_tag(locale) + msgids = ["Deleted user '{user}'."] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + gettext(msgids[0]).format(user=test_journo['username']), + 'notification' + ) # Verify journalist is no longer in the database with journalist_app.app_context(): assert Journalist.query.get(test_journo['id']) is None -def test_admin_cannot_delete_self(journalist_app, test_admin, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_cannot_delete_self(config, journalist_app, test_admin, test_journo, locale): # Verify journalist is in the database with journalist_app.app_context(): assert Journalist.query.get(test_journo['id']) is not None @@ -486,48 +573,70 @@ def test_admin_cannot_delete_self(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.delete_user', - user_id=test_admin['id']), - follow_redirects=True) + resp = app.post( + url_for('admin.delete_user', user_id=test_admin['id'], l=locale), + follow_redirects=True + ) # Assert correct interface behavior assert resp.status_code == 403 - resp = app.get(url_for('admin.index'), follow_redirects=True) + resp = app.get(url_for('admin.index', l=locale), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Admin Interface" in text - - # The user can be edited and deleted - assert escape("Edit user {}".format(test_journo['username'])) in text - assert escape("Delete user {}".format(test_journo['username'])) in text - # The admin can be edited but cannot deleted - assert escape("Edit user {}".format(test_admin['username'])) in text - assert escape("Delete user {}".format(test_admin['username'])) \ - not in text - - -def test_admin_edits_user_password_success_response(journalist_app, - test_admin, - test_journo): + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Admin Interface", + "Edit user {username}", + "Delete user {username}" + ] + with xfail_untranslated_messages(config, locale, msgids): + resp_text = resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp_text + + # The user can be edited and deleted + assert escape( + gettext("Edit user {username}").format(username=test_journo['username']) + ) in resp_text + assert escape( + gettext("Delete user {username}").format(username=test_journo['username']) + ) in resp_text + # The admin can be edited but cannot deleted + assert escape( + gettext("Edit user {username}").format(username=test_admin['username']) + ) in resp_text + assert escape( + gettext("Delete user {username}").format(username=test_admin['username']) + ) not in resp_text + + +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_edits_user_password_success_response( + config, journalist_app, test_admin, test_journo, locale +): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.new_password', - user_id=test_journo['id']), + resp = app.post(url_for('admin.new_password', user_id=test_journo['id'], l=locale), data=dict(password=VALID_PASSWORD_2), follow_redirects=True) assert resp.status_code == 200 - - text = resp.data.decode('utf-8') - assert 'Password updated.' in text - assert VALID_PASSWORD_2 in text - - -def test_admin_edits_user_password_session_invalidate(journalist_app, - test_admin, - test_journo): + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Password updated. Don't forget to save it in your KeePassX database. New password:" + ] + with xfail_untranslated_messages(config, locale, msgids): + resp_text = resp.data.decode('utf-8') + assert escape(gettext(msgids[0])) in resp_text + assert VALID_PASSWORD_2 in resp_text + + +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_edits_user_password_session_invalidate( + config, journalist_app, test_admin, test_journo, locale +): # Start the journalist session. with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], @@ -538,20 +647,28 @@ def test_admin_edits_user_password_session_invalidate(journalist_app, _login_user(admin_app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = admin_app.post(url_for('admin.new_password', - user_id=test_journo['id']), - data=dict(password=VALID_PASSWORD_2), - follow_redirects=True) + resp = admin_app.post( + url_for('admin.new_password', user_id=test_journo['id'], l=locale), + data=dict(password=VALID_PASSWORD_2), + follow_redirects=True + ) assert resp.status_code == 200 - - text = resp.data.decode('utf-8') - assert 'Password updated.' in text - assert VALID_PASSWORD_2 in text + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Password updated. Don't forget to save it in your KeePassX database. New password:" + ] + with xfail_untranslated_messages(config, locale, msgids): + resp_text = resp.data.decode('utf-8') + assert escape(gettext(msgids[0])) in resp_text + assert VALID_PASSWORD_2 in resp_text # Now verify the password change error is flashed. - resp = app.get(url_for('main.index'), follow_redirects=True) - text = resp.data.decode('utf-8') - assert 'You have been logged out due to password change' in text + with InstrumentedApp(journalist_app) as ins: + resp = app.get(url_for('main.index', l=locale), follow_redirects=True) + msgids = ['You have been logged out due to password change'] + assert page_language(resp.data) == language_tag(locale) + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'error') # Also ensure that session is now invalid. session.pop('expires', None) @@ -571,26 +688,36 @@ def test_admin_deletes_invalid_user_404(journalist_app, test_admin): assert resp.status_code == 404 -def test_admin_edits_user_password_error_response(journalist_app, - test_admin, - test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_edits_user_password_error_response( + config, journalist_app, test_admin, test_journo, locale +): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) with patch('sqlalchemy.orm.scoping.scoped_session.commit', side_effect=Exception()): - resp = app.post(url_for('admin.new_password', - user_id=test_journo['id']), - data=dict(password=VALID_PASSWORD_2), - follow_redirects=True) - - text = resp.data.decode('utf-8') - assert ('There was an error, and the new password might not have ' - 'been saved correctly.') in text - - -def test_user_edits_password_success_response(journalist_app, test_journo): + with InstrumentedApp(journalist_app) as ins: + resp = app.post( + url_for('admin.new_password', user_id=test_journo['id'], l=locale), + data=dict(password=VALID_PASSWORD_2), + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + 'There was an error, and the new password might not have been ' + 'saved correctly. To prevent you from getting locked ' + 'out of your account, you should reset your password again.' + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'error') + + +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_user_edits_password_success_response(config, journalist_app, test_journo, locale): original_hardening = models.LOGIN_HARDENING try: # Set this to false because we login then immediately reuse the same @@ -602,15 +729,20 @@ def test_user_edits_password_success_response(journalist_app, test_journo): _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) token = TOTP(test_journo['otp_secret']).now() - resp = app.post(url_for('account.new_password'), + resp = app.post(url_for('account.new_password', l=locale), data=dict(current_password=test_journo['password'], token=token, password=VALID_PASSWORD_2), follow_redirects=True) - text = resp.data.decode('utf-8') - assert "Password updated." in text - assert VALID_PASSWORD_2 in text + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Password updated. Don't forget to save it in your KeePassX database. New password:" + ] + with xfail_untranslated_messages(config, locale, msgids): + resp_text = resp.data.decode('utf-8') + assert escape(gettext(msgids[0])) in resp_text + assert VALID_PASSWORD_2 in resp_text finally: models.LOGIN_HARDENING = original_hardening @@ -643,7 +775,9 @@ def test_user_edits_password_expires_session(journalist_app, test_journo): models.LOGIN_HARDENING = original_hardening -def test_user_edits_password_error_reponse(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_user_edits_password_error_response(config, journalist_app, test_journo, locale): original_hardening = models.LOGIN_HARDENING try: # Set this to false because we login then immediately reuse the same @@ -660,31 +794,57 @@ def test_user_edits_password_error_reponse(journalist_app, test_journo): with patch.object(Journalist, 'verify_token', return_value=True): with patch.object(db.session, 'commit', side_effect=Exception()): - resp = app.post( - url_for('account.new_password'), - data=dict(current_password=test_journo['password'], - token='mocked', - password=VALID_PASSWORD_2), - follow_redirects=True) - - text = resp.data.decode('utf-8') - assert ('There was an error, and the new password might not have ' - 'been saved correctly.') in text + with InstrumentedApp(journalist_app) as ins: + resp = app.post( + url_for('account.new_password', l=locale), + data=dict( + current_password=test_journo['password'], + token='mocked', + password=VALID_PASSWORD_2 + ), + follow_redirects=True + ) + + assert page_language(resp.data) == language_tag(locale) + msgids = [ + ( + 'There was an error, and the new password might not have been ' + 'saved correctly. To prevent you from getting locked ' + 'out of your account, you should reset your password again.' + ) + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'error') finally: models.LOGIN_HARDENING = original_hardening -def test_admin_add_user_when_username_already_taken(journalist_app, test_admin): - with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username=test_admin['username'], - first_name='', - last_name='', - password=VALID_PASSWORD, - is_admin=None)) - text = resp.data.decode('utf-8') - assert 'already taken' in text +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_when_username_already_taken(config, journalist_app, test_admin, locale): + with journalist_app.test_client() as client: + _login_user( + client, test_admin['username'], test_admin['password'], test_admin['otp_secret'] + ) + with InstrumentedApp(journalist_app) as ins: + resp = client.post( + url_for('admin.add_user', l=locale), + data=dict( + username=test_admin['username'], + first_name='', + last_name='', + password=VALID_PASSWORD, + is_admin=None + ), + ) + assert page_language(resp.data) == language_tag(locale) + + msgids = ['Username "{username}" already taken.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + gettext(msgids[0]).format(username=test_admin["username"]), + 'error' + ) def test_max_password_length(): @@ -708,8 +868,8 @@ def test_login_password_too_long(journalist_app, test_journo, mocker): text = resp.data.decode('utf-8') assert "Login failed" in text mocked_error_logger.assert_called_once_with( - "Login for '{}' failed: Password too long (len={})".format( - test_journo['username'], Journalist.MAX_PASSWORD_LEN + 1)) + "Login for '{}' failed: Password is too long.".format(test_journo['username']) + ) def test_min_password_length(): @@ -772,7 +932,9 @@ def test_user_edits_password_too_long_warning(journalist_app, test_journo): 'Password not changed.', 'error') -def test_admin_add_user_password_too_long_warning(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_password_too_long_warning(config, journalist_app, test_admin, locale): overly_long_password = VALID_PASSWORD + \ 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) with journalist_app.test_client() as app: @@ -780,71 +942,91 @@ def test_admin_add_user_password_too_long_warning(journalist_app, test_admin): test_admin['otp_secret']) with InstrumentedApp(journalist_app) as ins: - app.post( - url_for('admin.add_user'), - data=dict(username='dellsberg', - first_name='', - last_name='', - password=overly_long_password, - is_admin=None)) + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='dellsberg', + first_name='', + last_name='', + password=overly_long_password, + is_admin=None + ), + ) - ins.assert_message_flashed( + assert page_language(resp.data) == language_tag(locale) + msgids = [ 'There was an error with the autogenerated password. User not ' - 'created. Please try again.', 'error') + 'created. Please try again.' + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'error') -def test_admin_add_user_first_name_too_long_warning(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_first_name_too_long_warning(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username=test_admin['username'], - first_name=overly_long_name, - last_name='', - password=VALID_PASSWORD, - is_admin=None)) - text = resp.data.decode('utf-8') - assert 'Cannot be longer than' in text + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username=test_admin['username'], + first_name=overly_long_name, + last_name='', + password=VALID_PASSWORD, + is_admin=None + ), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Cannot be longer than {num} character.'] + with xfail_untranslated_messages(config, locale, msgids): + assert ( + ngettext( + 'Cannot be longer than {num} character.', + 'Cannot be longer than {num} characters.', + Journalist.MAX_NAME_LEN + ).format(num=Journalist.MAX_NAME_LEN) + in resp.data.decode('utf-8') + ) -def test_admin_add_user_last_name_too_long_warning(journalist_app, test_admin): + +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_last_name_too_long_warning(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username=test_admin['username'], - first_name='', - last_name=overly_long_name, - password=VALID_PASSWORD, - is_admin=None)) - text = resp.data.decode('utf-8') - assert 'Cannot be longer than' in text - - -def test_admin_edits_user_invalid_username( - journalist_app, test_admin, test_journo): - """Test expected error message when admin attempts to change a user's - username to a username that is taken by another user.""" - new_username = test_journo['username'] - with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - with InstrumentedApp(journalist_app) as ins: - app.post( - url_for('admin.edit_user', user_id=test_admin['id']), - data=dict(username=new_username, - first_name='', - last_name='', - is_admin=None)) - - ins.assert_message_flashed( - 'Username "{}" already taken.'.format(new_username), - 'error') + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username=test_admin['username'], + first_name='', + last_name=overly_long_name, + password=VALID_PASSWORD, + is_admin=None + ), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Cannot be longer than {num} character.'] + with xfail_untranslated_messages(config, locale, msgids): + assert ( + ngettext( + 'Cannot be longer than {num} character.', + 'Cannot be longer than {num} characters.', + Journalist.MAX_NAME_LEN + ).format(num=Journalist.MAX_NAME_LEN) + in resp.data.decode('utf-8') + ) +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) def test_admin_edits_user_invalid_username_deleted( - journalist_app, test_admin, test_journo): + config, journalist_app, test_admin, test_journo, locale +): """Test expected error message when admin attempts to change a user's username to deleted""" new_username = "deleted" @@ -853,17 +1035,27 @@ def test_admin_edits_user_invalid_username_deleted( test_admin['otp_secret']) with InstrumentedApp(journalist_app) as ins: - app.post( - url_for('admin.edit_user', user_id=test_admin['id']), - data=dict(username=new_username, - first_name='', - last_name='', - is_admin=None)) + resp = app.post( + url_for('admin.edit_user', user_id=test_admin['id'], l=locale), + data=dict( + username=new_username, + first_name='', + last_name='', + is_admin=None + ), + follow_redirects=True + ) - ins.assert_message_flashed( - 'Invalid username: This username is invalid because it ' - 'is reserved for internal use by the software.', - 'error') + assert page_language(resp.data) == language_tag(locale) + msgids = [ + 'Invalid username: {message}', + 'This username is invalid because it is reserved for internal use by the software.' + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + gettext(msgids[0]).format(message=gettext(msgids[1])), + 'error' + ) def test_admin_resets_user_hotp_format_non_hexa( @@ -1119,16 +1311,21 @@ def test_user_resets_totp(journalist_app, test_journo): assert new_secret != old_secret - -def test_admin_resets_hotp_with_missing_otp_secret_key(journalist_app, - test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_resets_hotp_with_missing_otp_secret_key(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_admin['id'])) + resp = app.post( + url_for('admin.reset_two_factor_hotp', l=locale), + data=dict(uid=test_admin['id']), + ) - assert 'Change Secret' in resp.data.decode('utf-8') + assert page_language(resp.data) == language_tag(locale) + msgids = ['Change Secret'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') def test_admin_new_user_2fa_redirect(journalist_app, test_admin, test_journo): @@ -1142,25 +1339,39 @@ def test_admin_new_user_2fa_redirect(journalist_app, test_admin, test_journo): ins.assert_redirects(resp, url_for('admin.index')) +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) def test_http_get_on_admin_new_user_two_factor_page( - journalist_app, - test_admin, - test_journo): + config, + journalist_app, + test_admin, + test_journo, + locale +): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.get(url_for('admin.new_user_two_factor', uid=test_journo['id'])) - # any GET req should take a user to the admin.new_user_two_factor page - assert 'FreeOTP' in resp.data.decode('utf-8') + resp = app.get( + url_for('admin.new_user_two_factor', uid=test_journo['id'], l=locale), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Enable FreeOTP'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_http_get_on_admin_add_user_page(journalist_app, test_admin): + +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_http_get_on_admin_add_user_page(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.get(url_for('admin.add_user')) - # any GET req should take a user to the admin_add_user page - assert 'ADD USER' in resp.data.decode('utf-8') + resp = app.get(url_for('admin.add_user', l=locale)) + assert page_language(resp.data) == language_tag(locale) + msgids = ['ADD USER'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') def test_admin_add_user(journalist_app, test_admin): @@ -1182,24 +1393,35 @@ def test_admin_add_user(journalist_app, test_admin): uid=new_user.id)) -def test_admin_add_user_with_invalid_username(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_with_invalid_username(config, journalist_app, test_admin, locale): username = 'deleted' with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username=username, - first_name='', - last_name='', - password=VALID_PASSWORD, - is_admin=None)) - - assert "This username is invalid because it is reserved for internal use by the software." \ - in resp.data.decode('utf-8') + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username=username, + first_name='', + last_name='', + password=VALID_PASSWORD, + is_admin=None + ), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "This username is invalid because it is reserved for internal use by the software." + ] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode("utf-8") -def test_deleted_user_cannot_login(journalist_app): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_deleted_user_cannot_login(config, journalist_app, locale): username = 'deleted' uuid = 'deleted' @@ -1212,18 +1434,38 @@ def test_deleted_user_cannot_login(journalist_app): db.session.add(user) db.session.commit() - # Verify that deleted user is not able to login - with journalist_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(username=username, - password=password, - token=otp_secret)) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Login failed" in text + with InstrumentedApp(journalist_app) as ins: + # Verify that deleted user is not able to login + with journalist_app.test_client() as app: + resp = app.post( + url_for('main.login', l=locale), + data=dict( + username=username, + password=password, + token=otp_secret + ), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Login failed.", + ( + "Please wait for a new code from your two-factor mobile" + " app or security key before trying again." + ) + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + "{} {}".format( + gettext(msgids[0]), + gettext(msgids[1]), + ), + 'error' + ) -def test_deleted_user_cannot_login_exception(journalist_app): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_deleted_user_cannot_login_exception(journalist_app, locale): username = 'deleted' uuid = 'deleted' @@ -1236,102 +1478,159 @@ def test_deleted_user_cannot_login_exception(journalist_app): db.session.add(user) db.session.commit() - with pytest.raises(InvalidUsernameException): - Journalist.login(username, - password, - TOTP(otp_secret).now()) + with journalist_app.test_request_context('/'): + with pytest.raises(InvalidUsernameException): + Journalist.login(username, password, TOTP(otp_secret).now()) -def test_admin_add_user_without_username(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_without_username(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username='', - password=VALID_PASSWORD, - is_admin=None)) + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict(username='', password=VALID_PASSWORD, is_admin=None), + ) - assert 'This field is required.' in resp.data.decode('utf-8') + assert page_language(resp.data) == language_tag(locale) + msgids = ['This field is required.'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_admin_add_user_too_short_username(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_too_short_username(config, journalist_app, test_admin, locale): username = 'a' * (Journalist.MIN_USERNAME_LEN - 1) with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username=username, - password='pentagonpapers', - password_again='pentagonpapers', - is_admin=None)) - msg = 'Must be at least {} characters long' - assert (msg.format(Journalist.MIN_USERNAME_LEN) in resp.data.decode('utf-8')) + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username=username, + password='pentagonpapers', + password_again='pentagonpapers', + is_admin=None + ), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Must be at least {num} character long.'] + with xfail_untranslated_messages(config, locale, msgids): + assert( + ngettext( + 'Must be at least {num} character long.', + 'Must be at least {num} characters long.', + Journalist.MIN_USERNAME_LEN + ).format(num=Journalist.MIN_USERNAME_LEN) + in resp.data.decode('utf-8') + ) -def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]( + "locale, secret", + ( + (locale, "a" * i) + for locale in get_test_locales() + for i in get_plural_tests()[locale] if i != 0 + ) +) +def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username='dellsberg', - first_name='', - last_name='', - password=VALID_PASSWORD, - password_again=VALID_PASSWORD, - is_admin=None, - is_hotp=True, - otp_secret='123')) - assert 'HOTP secrets are 40 characters' in resp.data.decode('utf-8') + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='dellsberg', + first_name='', + last_name='', + password=VALID_PASSWORD, + password_again=VALID_PASSWORD, + is_admin=None, + is_hotp=True, + otp_secret=secret + ), + ) + journalist_app.logger.critical("response: %s", resp.data) + assert page_language(resp.data) == language_tag(locale) + msgids = ['HOTP secrets are 40 characters long - you have entered {num}.'] + with xfail_untranslated_messages(config, locale, msgids): + assert ( + ngettext( + 'HOTP secrets are 40 characters long - you have entered {num}.', + 'HOTP secrets are 40 characters long - you have entered {num}.', + len(secret) + ).format(num=len(secret)) + in resp.data.decode("utf-8") + ) -def test_admin_add_user_yubikey_valid_length(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_yubikey_valid_length(journalist_app, test_admin, locale): otp = '1234567890123456789012345678901234567890' with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username='dellsberg', - first_name='', - last_name='', - password=VALID_PASSWORD, - password_again=VALID_PASSWORD, - is_admin=None, - is_hotp=True, - otp_secret=otp), - follow_redirects=True) - - # Should redirect to the token verification page - assert 'Enable YubiKey (OATH-HOTP)' in resp.data.decode('utf-8') + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='dellsberg', + first_name='', + last_name='', + password=VALID_PASSWORD, + password_again=VALID_PASSWORD, + is_admin=None, + is_hotp=True, + otp_secret=otp + ), + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Enable YubiKey (OATH-HOTP)'] + with xfail_untranslated_messages(config, locale, msgids): + # Should redirect to the token verification page + assert gettext(msgids[0]) in resp.data.decode('utf-8') -def test_admin_add_user_yubikey_correct_length_with_whitespace( - journalist_app, - test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_yubikey_correct_length_with_whitespace(journalist_app, test_admin, locale): otp = '12 34 56 78 90 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90' with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) - resp = app.post(url_for('admin.add_user'), - data=dict(username='dellsberg', - first_name='', - last_name='', - password=VALID_PASSWORD, - password_again=VALID_PASSWORD, - is_admin=None, - is_hotp=True, - otp_secret=otp), - follow_redirects=True) - - # Should redirect to the token verification page - assert 'Enable YubiKey (OATH-HOTP)' in resp.data.decode('utf-8') + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='dellsberg', + first_name='', + last_name='', + password=VALID_PASSWORD, + password_again=VALID_PASSWORD, + is_admin=None, + is_hotp=True, + otp_secret=otp + ), + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Enable YubiKey (OATH-HOTP)'] + with xfail_untranslated_messages(config, locale, msgids): + # Should redirect to the token verification page + assert gettext(msgids[0]) in resp.data.decode('utf-8') def test_admin_sets_user_to_admin(journalist_app, test_admin): @@ -1415,34 +1714,58 @@ def test_admin_adds_first_name_last_name_to_user(journalist_app, test_admin): Journalist.query.filter(Journalist.username == new_user).one() -def test_admin_adds_invalid_first_last_name_to_user(journalist_app, test_admin): - new_user = 'admin-invalid-first-name-last-name-user-test' +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_adds_invalid_first_last_name_to_user(config, journalist_app, test_admin, locale): + with journalist_app.test_client() as client: + new_user = 'admin-invalid-first-name-last-name-user-test' - with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user( + client, test_admin['username'], test_admin['password'], test_admin['otp_secret'] + ) - resp = app.post(url_for('admin.add_user'), - data=dict(username=new_user, - first_name='', - last_name='', - password=VALID_PASSWORD, - is_admin=None)) - assert resp.status_code in (200, 302) + resp = client.post( + url_for('admin.add_user'), + data=dict( + username=new_user, + first_name='', + last_name='', + password=VALID_PASSWORD, + is_admin=None + ) + ) + assert resp.status_code == 302 journo = Journalist.query.filter(Journalist.username == new_user).one() overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) - resp = app.post(url_for('admin.edit_user', user_id=journo.id), - data=dict(username=overly_long_name, - first_name=overly_long_name, - last_name='test name'), - follow_redirects=True) - assert resp.status_code in (200, 302) - text = resp.data.decode('utf-8') - assert 'Name not updated' in text + with InstrumentedApp(journalist_app) as ins: + resp = client.post( + url_for('admin.edit_user', user_id=journo.id, l=locale), + data=dict( + username=new_user, + first_name=overly_long_name, + last_name='test name' + ), + follow_redirects=True, + ) + assert resp.status_code == 200 + assert page_language(resp.data) == language_tag(locale) + + msgids = [ + "Name not updated: {message}", + "Name too long" + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + gettext(msgids[0]).format(message=gettext("Name too long")), + 'error' + ) -def test_admin_add_user_integrity_error(journalist_app, test_admin, mocker): + +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_admin_add_user_integrity_error(config, journalist_app, test_admin, mocker, locale): mocked_error_logger = mocker.patch('journalist_app.admin.current_app.logger.error') mocker.patch('journalist_app.admin.Journalist', side_effect=IntegrityError('STATEMENT', 'PARAMETERS', None)) @@ -1452,23 +1775,32 @@ def test_admin_add_user_integrity_error(journalist_app, test_admin, mocker): test_admin['otp_secret']) with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.add_user'), - data=dict(username='username', - first_name='', - last_name='', - password=VALID_PASSWORD, - is_admin=None)) - ins.assert_message_flashed( - "An error occurred saving this user to the database." - " Please inform your admin.", - "error") + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='username', + first_name='', + last_name='', + password=VALID_PASSWORD, + is_admin=None + ), + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "An error occurred saving this user to the database. " + "Please inform your admin." + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), "error") log_event = mocked_error_logger.call_args[0][0] assert ("Adding user 'username' failed: (builtins.NoneType) " "None\n[SQL: STATEMENT]\n[parameters: 'PARAMETERS']") in log_event -def test_prevent_document_uploads(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_prevent_document_uploads(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) @@ -1479,13 +1811,20 @@ def test_prevent_document_uploads(journalist_app, test_admin): follow_redirects=True) assert InstanceConfig.get_current().allow_document_uploads is False with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) - ins.assert_message_flashed('Preferences saved.', 'submission-preferences-success') + resp = app.post( + url_for('admin.update_submission_preferences', l=locale), + data=form.data, + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Preferences saved.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'submission-preferences-success') -def test_no_prevent_document_uploads(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_no_prevent_document_uploads(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) @@ -1493,10 +1832,15 @@ def test_no_prevent_document_uploads(journalist_app, test_admin): follow_redirects=True) assert InstanceConfig.get_current().allow_document_uploads is True with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.update_submission_preferences'), - follow_redirects=True) - ins.assert_message_flashed('Preferences saved.', 'submission-preferences-success') + resp = app.post( + url_for('admin.update_submission_preferences', l=locale), + follow_redirects=True + ) assert InstanceConfig.get_current().allow_document_uploads is True + assert page_language(resp.data) == language_tag(locale) + msgids = ['Preferences saved.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'submission-preferences-success') def test_prevent_document_uploads_invalid(journalist_app, test_admin): @@ -1533,7 +1877,9 @@ class dummy_current(): assert g.organization_name == "SecureDrop" -def test_orgname_valid_succeeds(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_orgname_valid_succeeds(config, journalist_app, test_admin, locale): test_name = "Walden Inquirer" with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], @@ -1542,14 +1888,21 @@ def test_orgname_valid_succeeds(journalist_app, test_admin): organization_name=test_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.update_org_name'), - data=form.data, - follow_redirects=True) - ins.assert_message_flashed('Preferences saved.', 'org-name-success') + resp = app.post( + url_for('admin.update_org_name', l=locale), + data=form.data, + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Preferences saved.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'org-name-success') assert InstanceConfig.get_current().organization_name == test_name -def test_orgname_null_fails(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_orgname_null_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) @@ -1557,14 +1910,21 @@ def test_orgname_null_fails(journalist_app, test_admin): organization_name=None) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.update_org_name'), - data=form.data, - follow_redirects=True) - ins.assert_message_flashed('This field is required.', 'org-name-error') + resp = app.post( + url_for('admin.update_org_name', l=locale), + data=form.data, + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['This field is required.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'org-name-error') assert InstanceConfig.get_current().organization_name == "SecureDrop" -def test_orgname_oversized_fails(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_orgname_oversized_fails(config, journalist_app, test_admin, locale): test_name = "1234567812345678123456781234567812345678123456781234567812345678a" with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], @@ -1572,15 +1932,28 @@ def test_orgname_oversized_fails(journalist_app, test_admin): form = journalist_app_module.forms.OrgNameForm( organization_name=test_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" - with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.update_org_name'), - data=form.data, - follow_redirects=True) - ins.assert_message_flashed('Cannot be longer than 64 characters.', 'org-name-error') - assert InstanceConfig.get_current().organization_name == "SecureDrop" + resp = app.post( + url_for('admin.update_org_name', l=locale), + data=form.data, + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Cannot be longer than {num} character.'] + with xfail_untranslated_messages(config, locale, msgids): + assert ( + ngettext( + 'Cannot be longer than {num} character.', + 'Cannot be longer than {num} characters.', + InstanceConfig.MAX_ORG_NAME_LEN + ).format(num=InstanceConfig.MAX_ORG_NAME_LEN) + in resp.data.decode('utf-8') + ) + assert InstanceConfig.get_current().organization_name == "SecureDrop" -def test_orgname_html_escaped(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_orgname_html_escaped(config, journalist_app, test_admin, locale): t_name = '"> <a href=foo>' with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], @@ -1589,10 +1962,15 @@ def test_orgname_html_escaped(journalist_app, test_admin): organization_name=t_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.update_org_name'), - data=form.data, - follow_redirects=True) - ins.assert_message_flashed('Preferences saved.', 'org-name-success') + resp = app.post( + url_for('admin.update_org_name', l=locale), + data=form.data, + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Preferences saved.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'org-name-success') assert InstanceConfig.get_current().organization_name == htmlescape(t_name, quote=True) @@ -1609,7 +1987,9 @@ def test_logo_default_available(journalist_app): assert response.status_code == 200 -def test_logo_upload_with_valid_image_succeeds(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admin, locale): # Save original logo to restore after test run logo_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") @@ -1630,11 +2010,16 @@ def test_logo_upload_with_valid_image_succeeds(journalist_app, test_admin): logo=(BytesIO(logo_bytes), 'test.png') ) with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.manage_config'), - data=form.data, - follow_redirects=True) + resp = app.post( + url_for('admin.manage_config', l=locale), + data=form.data, + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Image updated.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'logo-success') - ins.assert_message_flashed("Image updated.", "logo-success") with journalist_app.test_client() as app: logo_url = journalist_app_module.get_logo_url(journalist_app) assert logo_url.endswith("/static/i/custom_logo.png") @@ -1647,7 +2032,9 @@ def test_logo_upload_with_valid_image_succeeds(journalist_app, test_admin): logo_file.write(original_image) -def test_logo_upload_with_invalid_filetype_fails(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_logo_upload_with_invalid_filetype_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) @@ -1656,16 +2043,21 @@ def test_logo_upload_with_invalid_filetype_fails(journalist_app, test_admin): logo=(BytesIO(b'filedata'), 'bad.exe') ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.manage_config'), - data=form.data, - follow_redirects=True) - ins.assert_message_flashed("You can only upload PNG image files.", - "logo-error") - text = resp.data.decode('utf-8') - assert "You can only upload PNG image files." in text + resp = app.post( + url_for('admin.manage_config', l=locale), + data=form.data, + follow_redirects=True + ) + + assert page_language(resp.data) == language_tag(locale) + msgids = ["You can only upload PNG image files."] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), "logo-error") -def test_logo_upload_save_fails(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): # Save original logo to restore after test run logo_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") @@ -1685,12 +2077,16 @@ def test_logo_upload_save_fails(journalist_app, test_admin): with InstrumentedApp(journalist_app) as ins: with patch('werkzeug.datastructures.FileStorage.save') as sMock: sMock.side_effect = Exception - app.post(url_for('admin.manage_config'), - data=form.data, - follow_redirects=True) + resp = app.post( + url_for('admin.manage_config', l=locale), + data=form.data, + follow_redirects=True + ) - ins.assert_message_flashed("Unable to process the image file." - " Try another one.", "logo-error") + assert page_language(resp.data) == language_tag(locale) + msgids = ["Unable to process the image file. Try another one."] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), "logo-error") finally: # Restore original image to logo location for subsequent tests with io.open(logo_image_location, 'wb') as logo_file: @@ -1709,7 +2105,9 @@ def test_creation_of_ossec_test_log_event(journalist_app, test_admin, mocker): ) -def test_logo_upload_with_empty_input_field_fails(journalist_app, test_admin): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_logo_upload_with_empty_input_field_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) @@ -1719,12 +2117,16 @@ def test_logo_upload_with_empty_input_field_fails(journalist_app, test_admin): ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.manage_config'), - data=form.data, - follow_redirects=True) + resp = app.post( + url_for('admin.manage_config', l=locale), + data=form.data, + follow_redirects=True + ) - ins.assert_message_flashed("File required.", "logo-error") - assert 'File required.' in resp.data.decode('utf-8') + assert page_language(resp.data) == language_tag(locale) + msgids = ["File required."] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), "logo-error") def test_admin_page_restriction_http_gets(journalist_app, test_journo): @@ -1785,18 +2187,31 @@ def test_user_authorization_for_posts(journalist_app): assert resp.status_code == 302 -def test_incorrect_current_password_change(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_incorrect_current_password_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('account.new_password'), - data=dict(password=VALID_PASSWORD, - token='mocked', - current_password='badpw'), - follow_redirects=True) - - text = resp.data.decode('utf-8') - assert 'Incorrect password or two-factor code' in text + with InstrumentedApp(journalist_app) as ins: + resp = app.post( + url_for('account.new_password', l=locale), + data=dict( + password=VALID_PASSWORD, + token='mocked', + current_password='badpw' + ), + follow_redirects=True) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + 'Incorrect password or two-factor code.', + ( + "Please wait for a new code from your two-factor mobile" + " app or security key before trying again." + ) + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]) + " " + gettext(msgids[1]), "error") # need a journalist app for the app context @@ -1863,7 +2278,9 @@ def test_journalist_reply_view(journalist_app, test_source, test_journo): assert resp.status_code == 302 -def test_too_long_user_password_change(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_too_long_user_password_change(config, journalist_app, test_journo, locale): overly_long_password = VALID_PASSWORD + \ 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) @@ -1872,56 +2289,96 @@ def test_too_long_user_password_change(journalist_app, test_journo): test_journo['otp_secret']) with InstrumentedApp(journalist_app) as ins: - app.post(url_for('account.new_password'), - data=dict(password=overly_long_password, - token=TOTP(test_journo['otp_secret']).now(), - current_password=test_journo['password']), - follow_redirects=True) + resp = app.post( + url_for('account.new_password', l=locale), + data=dict( + password=overly_long_password, + token=TOTP(test_journo['otp_secret']).now(), + current_password=test_journo['password'] + ), + follow_redirects=True) - ins.assert_message_flashed( - 'The password you submitted is invalid. ' - 'Password not changed.', 'error') + assert page_language(resp.data) == language_tag(locale) + msgids = ['The password you submitted is invalid. Password not changed.'] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed(gettext(msgids[0]), 'error') -def test_valid_user_password_change(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_valid_user_password_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('account.new_password'), + resp = app.post(url_for('account.new_password', l=locale), data=dict(password=VALID_PASSWORD_2, token=TOTP(test_journo['otp_secret']).now(), current_password=test_journo['password']), follow_redirects=True) - assert 'Password updated.' in resp.data.decode('utf-8') + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Password updated. Don't forget to save it in your KeePassX database. New password:" + ] + with xfail_untranslated_messages(config, locale, msgids): + assert escape(gettext(msgids[0])) in resp.data.decode('utf-8') + -def test_valid_user_first_last_name_change(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_valid_user_first_last_name_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('account.change_name'), - data=dict(first_name='test', - last_name='test'), - follow_redirects=True) + with InstrumentedApp(journalist_app) as ins: + resp = app.post( + url_for('account.change_name', l=locale), + data=dict(first_name='test', last_name='test'), + follow_redirects=True + ) - assert 'Name updated.' in resp.data.decode('utf-8') + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Name updated.", + "Name too long" + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + gettext(msgids[0]).format(gettext("Name too long")), + 'success' + ) -def test_valid_user_invalid_first_last_name_change(journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_valid_user_invalid_first_last_name_change(journalist_app, test_journo, locale): with journalist_app.test_client() as app: overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('account.change_name'), - data=dict(first_name=overly_long_name, - last_name=overly_long_name), - follow_redirects=True) - - assert 'Name not updated' in resp.data.decode('utf-8') + with InstrumentedApp(journalist_app) as ins: + resp = app.post( + url_for('account.change_name', l=locale), + data=dict( + first_name=overly_long_name, + last_name=overly_long_name + ), + follow_redirects=True + ) + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "Name not updated: {message}", + "Name too long" + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + gettext(msgids[0]).format(message=gettext("Name too long")), + 'error' + ) def test_regenerate_totp(journalist_app, test_journo): @@ -2735,7 +3192,9 @@ def test_single_source_is_successfully_unstarred(journalist_app, assert not source.star.starred -def test_journalist_session_expiration(config, journalist_app, test_journo): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_journalist_session_expiration(config, journalist_app, test_journo, locale): # set the expiration to ensure we trigger an expiration config.SESSION_EXPIRATION_MINUTES = -1 with journalist_app.test_client() as app: @@ -2749,7 +3208,11 @@ def test_journalist_session_expiration(config, journalist_app, test_journo): ins.assert_redirects(resp, url_for('main.index')) assert 'uid' in session - resp = app.get(url_for('account.edit'), follow_redirects=True) + resp = app.get(url_for('account.edit', l=locale), follow_redirects=True) + # because the session is being cleared when it expires, the + # response should always be in English. + assert page_language(resp.data) == 'en-US' + assert 'You have been logged out due to inactivity.' in resp.data.decode('utf-8') # check that the session was cleared (apart from 'expires' # which is always present and 'csrf_token' which leaks no info) @@ -2757,11 +3220,19 @@ def test_journalist_session_expiration(config, journalist_app, test_journo): session.pop('csrf_token', None) session.pop('locale', None) assert not session, session - assert ('You have been logged out due to inactivity' in - resp.data.decode('utf-8')) -def test_csrf_error_page(journalist_app): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_csrf_error_page(config, journalist_app, locale): + # get the locale into the session + with journalist_app.test_client() as app: + resp = app.get(url_for('main.login', l=locale)) + assert page_language(resp.data) == language_tag(locale) + msgids = ['Show password'] + with xfail_untranslated_messages(config, locale, msgids): + assert gettext(msgids[0]) in resp.data.decode('utf-8') + journalist_app.config['WTF_CSRF_ENABLED'] = True with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: @@ -2770,8 +3241,10 @@ def test_csrf_error_page(journalist_app): resp = app.post(url_for('main.login'), follow_redirects=True) - text = resp.data.decode('utf-8') - assert 'You have been logged out due to inactivity' in text + # because the session is being cleared when it expires, the + # response should always be in English. + assert page_language(resp.data) == 'en-US' + assert 'You have been logged out due to inactivity.' in resp.data.decode('utf-8') def test_col_process_aborts_with_bad_action(journalist_app, test_journo): diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +# flake8: noqa: E741 import gzip import re import subprocess @@ -9,8 +10,11 @@ from io import BytesIO, StringIO from pathlib import Path +from flaky import flaky from flask import session, escape, url_for, g, request +from flask_babel import gettext from mock import patch, ANY +import pytest import crypto_util import source @@ -26,6 +30,7 @@ from source_app import api as source_app_api from source_app import get_logo_url from .utils.db_helper import new_codename, submit +from .utils.i18n import get_test_locales, language_tag, page_language, xfail_untranslated_messages from .utils.instrument import InstrumentedApp from sdconfig import config @@ -634,13 +639,30 @@ def test_submit_sanitizes_filename(source_app): mtime=0) -def test_tor2web_warning_headers(source_app): +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) +def test_tor2web_warning_headers(config, source_app, locale): with source_app.test_client() as app: - resp = app.get(url_for('main.index'), - headers=[('X-tor2web', 'encrypted')]) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "You appear to be using Tor2Web." in text + with InstrumentedApp(app) as ins: + resp = app.get(url_for('main.index', l=locale), headers=[('X-tor2web', 'encrypted')]) + assert resp.status_code == 200 + + assert page_language(resp.data) == language_tag(locale) + msgids = [ + "WARNING:", + "You appear to be using Tor2Web, which does not provide anonymity.", + "Why is this dangerous?", + ] + with xfail_untranslated_messages(config, locale, msgids): + ins.assert_message_flashed( + '<strong>{}</strong>&nbsp;{}&nbsp;<a href="{}">{}</a>'.format( + escape(gettext(msgids[0])), + escape(gettext(msgids[1])), + url_for('info.tor2web_warning'), + escape(gettext(msgids[2])), + ), + 'banner-warning' + ) def test_tor2web_warning(source_app): diff --git a/securedrop/tests/utils/__init__.py b/securedrop/tests/utils/__init__.py --- a/securedrop/tests/utils/__init__.py +++ b/securedrop/tests/utils/__init__.py @@ -8,6 +8,17 @@ from . import env # noqa +def flaky_filter_xfail(err, *args): + """ + Tell the pytest flaky plugin to not retry XFailed errors. + + If the test is expected to fail, let's not run it again. + """ + return '_pytest.outcomes.XFailed' == '{}.{}'.format( + err[0].__class__.__module__, err[0].__class__.__qualname__ + ) + + def login_user(app, test_user): resp = app.post('/login', data={'username': test_user['username'], diff --git a/securedrop/tests/utils/i18n.py b/securedrop/tests/utils/i18n.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/utils/i18n.py @@ -0,0 +1,106 @@ +import collections +import contextlib +import functools +import os +from typing import Dict, Generator, Iterable, List, Optional, Tuple + +import pytest +from babel.core import ( + get_locale_identifier, + parse_locale, +) +from babel.messages.catalog import Catalog +from babel.messages.pofile import read_po +from bs4 import BeautifulSoup +from flask_babel import force_locale + +from sdconfig import SDConfig + + [email protected]_cache(maxsize=None) +def get_test_locales(default_locale: str = "en_US") -> List[str]: + locales = set(os.environ.get("TEST_LOCALES", "ar en_US").split()) + locales.add(default_locale) + return sorted(list(locales)) + + [email protected]_cache(maxsize=None) +def get_plural_tests() -> Dict[str, Tuple[int, ...]]: + return collections.defaultdict( + lambda: (0, 1, 2), + ar=(0, 1, 2, 3, 11, 100), + cs=(1, 2, 5), + ro=(0, 1, 2, 20), + ru=(0, 1, 2, 20), + sk=(0, 1, 2, 5, 10), + zh_Hans=(1,), + zh_Hant=(1,), + ) + + +def language_tag(locale: str) -> str: + """ + Returns a BCP47/RFC5646 language tag for the locale. + + For example, it will convert "fr_FR" to "fr-FR". + """ + return get_locale_identifier(parse_locale(locale), sep="-") + + [email protected]_cache(maxsize=None) +def message_catalog(config: SDConfig, locale: str) -> Catalog: + """ + Returns the gettext message catalog for the given locale. + + With the catalog, tests can check whether a gettext call returned + an actual translation or merely the result of falling back to the + default locale. + + >>> german = message_catalog(config, 'de_DE') + >>> m = german.get("a string that has been added to the catalog but not translated") + >>> m.string + '' + >>> german.get("Password").string + 'Passwort' + """ + return read_po(open(str(config.TRANSLATION_DIRS / locale / "LC_MESSAGES/messages.po"))) + + +def page_language(page_text: str) -> Optional[str]: + """ + Returns the "lang" attribute of the page's "html" element. + """ + soup = BeautifulSoup(page_text, "html.parser") + return soup.find("html").get("lang") + + [email protected] +def xfail_untranslated_messages(config: SDConfig, locale: str, msgids: Iterable[str]) -> Generator: + """ + Trigger pytest.xfail for untranslated strings. + + Given a list of gettext message IDs (strings marked for + translation with gettext or ngettext in source code) used in this + context manager's block, check that each has been translated in + `locale`. Call pytest.xfail if any has not. + + Without this, to detect when gettext fell back to English, we'd + have to hard-code the expected translations, which has obvious + maintenance problems. You also can't just check that the result of + a gettext call isn't the source string, because some translations + are the same. + """ + with force_locale(locale): + if locale != "en_US": + catalog = message_catalog(config, locale) + for msgid in msgids: + m = catalog.get(msgid) + if not m: + pytest.xfail( + "locale {} message catalog lacks msgid: {}".format(locale, msgid) + ) + if not m.string: + pytest.xfail( + "locale {} has no translation for msgid: {}".format(locale, msgid) + ) + yield
gettext calls containing formatted strings produce untranslated text ## Description There are a few places where we do `gettext('something about {}'.format('blah'))` instead of `gettext('something about {}').format('blah')` and the misplaced `.format` call has `gettext` looking for the formatted string in the message catalogs. When it can't be found, English appears in the user interface. ## Steps to Reproduce - `make dev` - visit the JI admin interface, choose a language other than English, and add a user or edit `dellsberg`. - try to change the first name to something longer than 100 characters. ## Expected Behavior The flashed error message should be in the selected language. ## Actual Behavior It's in English. ![name-too-long-english](https://user-images.githubusercontent.com/47430598/105930007-cbd1bf80-6016-11eb-82c3-accfe9a55fcc.png) ## Comments There are at least these occurrences: - https://github.com/freedomofpress/securedrop/blob/7f4076b36298475da15dde826e204310888b773d/securedrop/journalist_app/admin.py#L139 - https://github.com/freedomofpress/securedrop/blob/7f4076b36298475da15dde826e204310888b773d/securedrop/journalist_app/admin.py#L239 - https://github.com/freedomofpress/securedrop/blob/7f4076b36298475da15dde826e204310888b773d/securedrop/journalist_app/admin.py#L247 - https://github.com/freedomofpress/securedrop/blob/7f4076b36298475da15dde826e204310888b773d/securedrop/journalist_app/utils.py#L368
2021-03-26T15:08:22Z
[]
[]
freedomofpress/securedrop
5,890
freedomofpress__securedrop-5890
[ "5835" ]
4dd4d4b526270568e83bcfb56ca6fc7dc20a0bb7
diff --git a/install_files/ansible-base/roles/backup/files/backup.py b/install_files/ansible-base/roles/backup/files/backup.py --- a/install_files/ansible-base/roles/backup/files/backup.py +++ b/install_files/ansible-base/roles/backup/files/backup.py @@ -1,8 +1,11 @@ #!/opt/venvs/securedrop-app-code/bin/python """ -This script is copied to the App server and run by the Ansible playbook. When -run (as root), it collects all of the necessary information to backup the 0.3 -system and stores it in /tmp/sd-backup-0.3-TIME_STAMP.tar.gz. +This script is copied to the App server (to /tmp) and run by the Ansible playbook, +typically via `securedrop-admin`. + +The backup file in the format sd-backup-$TIMESTAMP.tar.gz is then copied to the +Admin Workstation by the playbook, and removed on the server. For further +information and limitations, see https://docs.securedrop.org/en/stable/backup_and_restore.html """ from datetime import datetime @@ -19,14 +22,17 @@ def main(): sd_code = '/var/www/securedrop' sd_config = os.path.join(sd_code, "config.py") - sd_custom_logo = os.path.join(sd_code, "static/i/logo.png") + sd_custom_logo = os.path.join(sd_code, "static/i/custom_logo.png") tor_hidden_services = "/var/lib/tor/services" torrc = "/etc/tor/torrc" with tarfile.open(backup_filename, 'w:gz') as backup: backup.add(sd_config) - backup.add(sd_custom_logo) + + # If no custom logo has been configured, the file will not exist + if os.path.exists(sd_custom_logo): + backup.add(sd_custom_logo) backup.add(sd_data) backup.add(tor_hidden_services) backup.add(torrc) diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '1.8.0' +__version__ = '1.8.1~rc1' diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="1.8.0", + version="1.8.1~rc1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-xenial/tests/vars.yml b/molecule/builder-xenial/tests/vars.yml --- a/molecule/builder-xenial/tests/vars.yml +++ b/molecule/builder-xenial/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "1.8.0" +securedrop_version: "1.8.1~rc1" ossec_version: "3.6.0" keyring_version: "0.1.4" config_version: "0.1.4"
fwupd error in syslog, ossec alert for Focal ## Description On both a Mac mini and a NUC5PYH running Ubuntu Focal, I receive the following ossec alerts (and associated syslog entries) 1. On the mac mini, 2 errors ``` OSSEC HIDS Notification. 2021 Mar 01 13:22:55 Received From: (app) 10.20.2.2->/var/log/syslog Rule: 1002 fired (level 2) -> "Unknown problem somewhere in the system." Portion of the log(s): Mar 1 13:22:53 app fwupd[133921]: 13:22:53:0576 FuEngine Failed to load SMBIOS: invalid DMI data size, got 2527 bytes, expected 2745 --END OF NOTIFICATION OSSEC HIDS Notification. 2021 Mar 01 13:22:55 Received From: (app) 10.20.2.2->/var/log/syslog Rule: 1002 fired (level 2) -> "Unknown problem somewhere in the system." Portion of the log(s): Mar 1 13:22:53 app fwupd[133921]: 13:22:53:0883 FuPluginUefi Error opening directory “/sys/firmware/efi/esrt/entries”: No such file or directory --END OF NOTIFICATION ``` 2. On the NUC, only 1 of the two errors ``` OSSEC HIDS Notification. 2021 Mar 01 11:51:47 Received From: mon->/var/log/syslog Rule: 1002 fired (level 2) -> "Unknown problem somewhere in the system." Portion of the log(s): Mar 1 11:51:46 mon fwupd[133502]: 11:51:46:0509 FuPluginUefi Error opening directory “/sys/firmware/efi/esrt/entries”: No such file or directory --END OF NOTIFICATION ``` ## Comments The errors observed are likely a result of my machines either not supported by fwupd or perhaps legacy boot enabled. We should ensure fwupd is properly configured or supported on the hosts on which it is running, or remove the package entirely.
reproducible on nuc7: ``` Received From: mon->/var/log/syslog Rule: 1002 fired (level 2) -> "Unknown problem somewhere in the system." Portion of the log(s): Mar 4 14:03:02 mon fwupd[134631]: 14:03:02:0629 FuPluginUefi Error opening directory “/sys/firmware/efi/esrt/entries”: No such file or directory ``` Seeing this in my prod logs as well on Ubuntu 20.04 (haven't checked OSSEC alerts yet).
2021-04-07T16:09:01Z
[]
[]
freedomofpress/securedrop
5,911
freedomofpress__securedrop-5911
[ "5725" ]
14c9d3a8f2ed7abc5eddd95a0ec8142efed45400
diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -31,23 +31,9 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): with io.open(filepath, 'r') as f: hostvars = yaml.safe_load(f) - # Testing against both Focal and Xenial must be supported for now in both - # staging scenarios, and in prod via `USE_FOCAL=1 ./securedrop-admin verify` - testing_focal = False - scenario_env = "MOLECULE_SCENARIO_NAME" - if scenario_env in os.environ and os.environ.get(scenario_env).endswith("focal"): - testing_focal = True - if "USE_FOCAL" in os.environ: - testing_focal = True - - if testing_focal: - hostvars['securedrop_venv_site_packages'] = hostvars["securedrop_venv_site_packages"].format("3.8") # noqa: E501 - hostvars['python_version'] = "3.8" - hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['focal'] - else: - hostvars['securedrop_venv_site_packages'] = hostvars["securedrop_venv_site_packages"].format("3.5") # noqa: E501 - hostvars['python_version'] = "3.5" - hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['xenial'] + hostvars['securedrop_venv_site_packages'] = hostvars["securedrop_venv_site_packages"].format("3.8") # noqa: E501 + hostvars['python_version'] = "3.8" + hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['focal'] if with_header: hostvars = dict(securedrop_test_vars=hostvars) diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -23,7 +23,6 @@ JournalistInterfaceSessionInterface, cleanup_expired_revoked_tokens) from models import InstanceConfig, Journalist -from server_os import is_os_near_eol, is_os_past_eol from store import Storage import typing @@ -72,8 +71,6 @@ def create_app(config: 'SDConfig') -> Flask: app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI db.init_app(app) - app.config.update(OS_PAST_EOL=is_os_past_eol(), OS_NEAR_EOL=is_os_near_eol()) - # TODO: Attaching a Storage dynamically like this disables all type checking (and # breaks code analysis tools) for code that uses current_app.storage; it should be refactored app.storage = Storage(config.STORE_DIR, @@ -179,11 +176,6 @@ def setup_g() -> 'Optional[Response]': except FileNotFoundError: app.logger.error("Site logo not found.") - if app.config["OS_PAST_EOL"]: - g.show_os_past_eol_warning = True - elif app.config["OS_NEAR_EOL"]: - g.show_os_near_eol_warning = True - if request.path.split('/')[1] == 'api': pass # We use the @token_required decorator for the API endpoints else: # We are not using the API diff --git a/securedrop/server_os.py b/securedrop/server_os.py --- a/securedrop/server_os.py +++ b/securedrop/server_os.py @@ -1,38 +1,14 @@ import functools import subprocess -from datetime import date FOCAL_VERSION = "20.04" [email protected]_cache() -def get_xenial_eol_date() -> date: - return date(2021, 4, 30) - - @functools.lru_cache() def get_os_release() -> str: return subprocess.run( - ["lsb_release", "--release", "--short"], + ["/usr/bin/lsb_release", "--release", "--short"], check=True, stdout=subprocess.PIPE, universal_newlines=True ).stdout.strip() - - -def is_os_past_eol() -> bool: - """ - Assumption: Any OS that is not Focal is an earlier version of the OS. - """ - if get_os_release() != FOCAL_VERSION and date.today() > get_xenial_eol_date(): - return True - return False - - -def is_os_near_eol() -> bool: - """ - Assumption: Any OS that is not Focal is an earlier version of the OS. - """ - if get_os_release() != FOCAL_VERSION and date.today() <= get_xenial_eol_date(): - return True - return False diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -26,7 +26,6 @@ from source_app.decorators import ignore_static from source_app.utils import logged_in, was_in_generate_flow from store import Storage -from server_os import is_os_past_eol def get_logo_url(app: Flask) -> str: @@ -60,17 +59,6 @@ def setup_i18n() -> None: """Store i18n-related values in Flask's special g object""" i18n.set_locale(config) - app.config.update(OS_PAST_EOL=is_os_past_eol()) - - @app.before_request - @ignore_static - def disable_ui() -> Optional[str]: - if app.config["OS_PAST_EOL"]: - session.clear() - g.show_offline_message = True - return render_template("base.html") - return None - # The default CSRF token expiration is 1 hour. Since large uploads can # take longer than an hour over Tor, we increase the valid window to 24h. app.config['WTF_CSRF_TIME_LIMIT'] = 60 * 60 * 24
diff --git a/molecule/builder-xenial/tests/conftest.py b/molecule/builder-focal/tests/conftest.py similarity index 100% rename from molecule/builder-xenial/tests/conftest.py rename to molecule/builder-focal/tests/conftest.py diff --git a/molecule/builder-xenial/tests/test_build_dependencies.py b/molecule/builder-focal/tests/test_build_dependencies.py similarity index 95% rename from molecule/builder-xenial/tests/test_build_dependencies.py rename to molecule/builder-focal/tests/test_build_dependencies.py --- a/molecule/builder-xenial/tests/test_build_dependencies.py +++ b/molecule/builder-focal/tests/test_build_dependencies.py @@ -48,7 +48,7 @@ def test_dh_virtualenv(host): """ Confirm the expected version of dh-virtualenv is found. """ - expected_version = "0.11" if host.system_info.codename == "xenial" else "1.2.1" + expected_version = "1.2.1" version_string = "dh_virtualenv {}".format(expected_version) c = host.run("dh_virtualenv --version") assert c.stdout.startswith(version_string) diff --git a/molecule/builder-xenial/tests/test_legacy_paths.py b/molecule/builder-focal/tests/test_legacy_paths.py similarity index 100% rename from molecule/builder-xenial/tests/test_legacy_paths.py rename to molecule/builder-focal/tests/test_legacy_paths.py diff --git a/molecule/builder-xenial/tests/test_securedrop_deb_package.py b/molecule/builder-focal/tests/test_securedrop_deb_package.py similarity index 93% rename from molecule/builder-xenial/tests/test_securedrop_deb_package.py rename to molecule/builder-focal/tests/test_securedrop_deb_package.py --- a/molecule/builder-xenial/tests/test_securedrop_deb_package.py +++ b/molecule/builder-focal/tests/test_securedrop_deb_package.py @@ -62,16 +62,10 @@ def make_deb_paths() -> Dict[str, Path]: reuse vars in other var values, as is the case with Ansible). """ - if SECUREDROP_TARGET_DISTRIBUTION == "xenial": - grsec_version = "{}+{}".format( - securedrop_test_vars["grsec_version_xenial"], - SECUREDROP_TARGET_DISTRIBUTION - ) - else: - grsec_version = "{}+{}".format( - securedrop_test_vars["grsec_version_focal"], - SECUREDROP_TARGET_DISTRIBUTION - ) + grsec_version = "{}+{}".format( + securedrop_test_vars["grsec_version_focal"], + SECUREDROP_TARGET_DISTRIBUTION + ) substitutions = dict( securedrop_version=securedrop_test_vars["securedrop_version"], @@ -417,14 +411,8 @@ def test_grsec_metapackage(host: Host): c = host.run("dpkg-deb --contents {}".format(deb_paths["securedrop_grsec"])) contents = c.stdout - if SECUREDROP_TARGET_DISTRIBUTION == "xenial": - # Post-install kernel hook for managing PaX flags must exist. - assert re.search(r"^.*\./etc/kernel/postinst.d/paxctl-grub$", contents, re.M) - # Config file for paxctld should not be present - assert not re.search(r"^.*\./opt/securedrop/paxctld.conf$", contents, re.M) - else: - assert not re.search(r"^.*\./etc/kernel/postinst.d/paxctl-grub$", contents, re.M) - assert re.search(r"^.*\./opt/securedrop/paxctld.conf$", contents, re.M) + assert not re.search(r"^.*\./etc/kernel/postinst.d/paxctl-grub$", contents, re.M) + assert re.search(r"^.*\./opt/securedrop/paxctld.conf$", contents, re.M) # Custom sysctl options should be present assert re.search(r"^.*\./etc/sysctl.d/30-securedrop.conf$", contents, re.M) @@ -550,18 +538,12 @@ def test_config_package_contains_expected_files(host: Host) -> None: Inspect the package contents to ensure all config files are included in the package. """ - if SECUREDROP_TARGET_DISTRIBUTION == "xenial": - wanted_files = [ - "/etc/cron-apt/action.d/9-remove", - "/etc/profile.d/securedrop_additions.sh", - ] - else: - wanted_files = [ - "/etc/profile.d/securedrop_additions.sh", - "/opt/securedrop/20auto-upgrades", - "/opt/securedrop/50unattended-upgrades", - "/opt/securedrop/reboot-flag", - ] + wanted_files = [ + "/etc/profile.d/securedrop_additions.sh", + "/opt/securedrop/20auto-upgrades", + "/opt/securedrop/50unattended-upgrades", + "/opt/securedrop/reboot-flag", + ] c = host.run("dpkg-deb --contents {}".format(deb_paths["securedrop_config"])) for wanted_file in wanted_files: assert re.search( diff --git a/molecule/builder-xenial/tests/test_security_updates.py b/molecule/builder-focal/tests/test_security_updates.py similarity index 100% rename from molecule/builder-xenial/tests/test_security_updates.py rename to molecule/builder-focal/tests/test_security_updates.py diff --git a/molecule/builder-xenial/tests/vars.yml b/molecule/builder-focal/tests/vars.yml similarity index 97% rename from molecule/builder-xenial/tests/vars.yml rename to molecule/builder-focal/tests/vars.yml --- a/molecule/builder-xenial/tests/vars.yml +++ b/molecule/builder-focal/tests/vars.yml @@ -3,7 +3,6 @@ securedrop_version: "1.9.0~rc1" ossec_version: "3.6.0" keyring_version: "0.1.4" config_version: "0.1.4" -grsec_version_xenial: "4.14.188" grsec_version_focal: "5.4.97" # These values will be interpolated with values populated above diff --git a/molecule/fetch-tor-packages/tests/test_tor_packages.py b/molecule/fetch-tor-packages/tests/test_tor_packages.py --- a/molecule/fetch-tor-packages/tests/test_tor_packages.py +++ b/molecule/fetch-tor-packages/tests/test_tor_packages.py @@ -3,7 +3,6 @@ testinfra_hosts = [ - "docker://tor-package-fetcher-xenial", "docker://tor-package-fetcher-focal", ] TOR_DOWNLOAD_DIR = "/tmp/tor-debs" @@ -46,10 +45,9 @@ def test_tor_package_versions(host, pkg): def test_tor_package_platform(host): """ Sanity check to ensure we're running on a version of Ubuntu - that is supported by the upstream Tor Project, i.e. Xenial or Focal. - The Trusty channel was disabled by Tor Project on 2019-01-08. + that is supported by the upstream Tor Project, i.e. Focal. """ assert host.system_info.type == "linux" assert host.system_info.distribution == "ubuntu" - assert host.system_info.codename in ("xenial", "focal") - assert host.system_info.release in ("16.04", "20.04") + assert host.system_info.codename == "focal" + assert host.system_info.release == "20.04" diff --git a/molecule/testinfra/app/apache/test_apache_journalist_interface.py b/molecule/testinfra/app/apache/test_apache_journalist_interface.py --- a/molecule/testinfra/app/apache/test_apache_journalist_interface.py +++ b/molecule/testinfra/app/apache/test_apache_journalist_interface.py @@ -17,14 +17,10 @@ def test_apache_headers_journalist_interface(host, header, value): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - if host.system_info.codename == "focal": - header_unset = "Header onsuccess unset {}".format(header) - assert f.contains(header_unset) - header_set = "Header always set {} \"{}\"".format(header, value) - assert f.contains(header_set) - else: - header_regex = "^Header set {}.*{}.*$".format(re.escape(header), re.escape(value)) - assert re.search(header_regex, f.content_string, re.M) + header_unset = "Header onsuccess unset {}".format(header) + assert f.contains(header_unset) + header_set = "Header always set {} \"{}\"".format(header, value) + assert f.contains(header_set) # declare journalist-specific Apache configs @@ -68,19 +64,13 @@ def test_apache_config_journalist_interface(host, apache_opt): def test_apache_config_journalist_interface_headers_per_distro(host): """ During migration to Focal, we updated the syntax for forcing HTTP headers. - Honor the old Xenial syntax until EOL. """ f = host.file("/etc/apache2/sites-available/journalist.conf") - if host.system_info.codename == "xenial": - assert f.contains("Header always append X-Frame-Options: DENY") - assert f.contains('Header set Referrer-Policy "no-referrer"') - assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') - else: - assert f.contains("Header onsuccess unset X-Frame-Options") - assert f.contains('Header always set X-Frame-Options "DENY"') - assert f.contains('Header onsuccess unset Referrer-Policy') - assert f.contains('Header always set Referrer-Policy "no-referrer"') - assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') + assert f.contains("Header onsuccess unset X-Frame-Options") + assert f.contains('Header always set X-Frame-Options "DENY"') + assert f.contains('Header onsuccess unset Referrer-Policy') + assert f.contains('Header always set Referrer-Policy "no-referrer"') + assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') def test_apache_logging_journalist_interface(host): @@ -137,57 +127,10 @@ def test_apache_logging_journalist_interface(host): </Directory> """.strip('\n').format(securedrop_test_vars.securedrop_code), ]) -def test_apache_config_journalist_interface_access_control_focal(host, apache_opt): +def test_apache_config_journalist_interface_access_control(host, apache_opt): """ Verifies the access control directives for the Journalist Interface. - Using a separate test because Xenial / Focal syntax differs. """ - if host.system_info.codename != "focal": - return True - f = host.file("/etc/apache2/sites-available/journalist.conf") - regex = "^{}$".format(re.escape(apache_opt)) - assert re.search(regex, f.content_string, re.M) - - [email protected]("apache_opt", [ - """ -<Directory /> - Options None - AllowOverride None - Order deny,allow - Deny from all -</Directory> -""".strip('\n'), - """ -<Directory {}/static> - Order allow,deny - Allow from all - # Cache static resources for 1 hour - Header set Cache-Control "max-age=3600" -</Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), - """ -<Directory {}> - Options None - AllowOverride None - <Limit GET POST HEAD DELETE> - Order allow,deny - allow from 127.0.0.1 - </Limit> - <LimitExcept GET POST HEAD DELETE> - Order deny,allow - Deny from all - </LimitExcept> -</Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), -]) -def test_apache_config_journalist_interface_access_control_xenial(host, apache_opt): - """ - Verifies the access control directives for the Source Interface. - Using a separate test because Xenial / Focal syntax differs. - """ - if host.system_info.codename != "xenial": - return True f = host.file("/etc/apache2/sites-available/journalist.conf") regex = "^{}$".format(re.escape(apache_opt)) assert re.search(regex, f.content_string, re.M) diff --git a/molecule/testinfra/app/apache/test_apache_source_interface.py b/molecule/testinfra/app/apache/test_apache_source_interface.py --- a/molecule/testinfra/app/apache/test_apache_source_interface.py +++ b/molecule/testinfra/app/apache/test_apache_source_interface.py @@ -17,14 +17,10 @@ def test_apache_headers_source_interface(host, header, value): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - if host.system_info.codename == "focal": - header_unset = "Header onsuccess unset {}".format(header) - assert f.contains(header_unset) - header_set = "Header always set {} \"{}\"".format(header, value) - assert f.contains(header_set) - else: - header_regex = "^Header set {}.*{}.*$".format(re.escape(header), re.escape(value)) - assert re.search(header_regex, f.content_string, re.M) + header_unset = "Header onsuccess unset {}".format(header) + assert f.contains(header_unset) + header_set = "Header always set {} \"{}\"".format(header, value) + assert f.contains(header_set) @pytest.mark.parametrize("apache_opt", [ @@ -62,19 +58,13 @@ def test_apache_config_source_interface(host, apache_opt): def test_apache_config_source_interface_headers_per_distro(host): """ During migration to Focal, we updated the syntax for forcing HTTP headers. - Honor the old Xenial syntax until EOL. """ f = host.file("/etc/apache2/sites-available/source.conf") - if host.system_info.codename == "xenial": - assert f.contains("Header always append X-Frame-Options: DENY") - assert f.contains('Header set Referrer-Policy "same-origin"') - assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') - else: - assert f.contains("Header onsuccess unset X-Frame-Options") - assert f.contains('Header always set X-Frame-Options "DENY"') - assert f.contains('Header onsuccess unset Referrer-Policy') - assert f.contains('Header always set Referrer-Policy "same-origin"') - assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') + assert f.contains("Header onsuccess unset X-Frame-Options") + assert f.contains('Header always set X-Frame-Options "DENY"') + assert f.contains('Header onsuccess unset Referrer-Policy') + assert f.contains('Header always set Referrer-Policy "same-origin"') + assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') @pytest.mark.parametrize("apache_opt", [ @@ -105,57 +95,10 @@ def test_apache_config_source_interface_headers_per_distro(host): </Directory> """.strip('\n').format(securedrop_test_vars.securedrop_code), ]) -def test_apache_config_source_interface_access_control_focal(host, apache_opt): +def test_apache_config_source_interface_access_control(host, apache_opt): """ Verifies the access control directives for the Source Interface. - Using a separate test because Xenial / Focal syntax differs. """ - if host.system_info.codename != "focal": - return True - f = host.file("/etc/apache2/sites-available/source.conf") - regex = "^{}$".format(re.escape(apache_opt)) - assert re.search(regex, f.content_string, re.M) - - [email protected]("apache_opt", [ - """ -<Directory /> - Options None - AllowOverride None - Order deny,allow - Deny from all -</Directory> -""".strip('\n'), - """ -<Directory {}/static> - Order allow,deny - Allow from all - # Cache static resources for 1 hour - Header set Cache-Control "max-age=3600" -</Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), - """ -<Directory {}> - Options None - AllowOverride None - <Limit GET POST HEAD> - Order allow,deny - allow from 127.0.0.1 - </Limit> - <LimitExcept GET POST HEAD> - Order deny,allow - Deny from all - </LimitExcept> -</Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), -]) -def test_apache_config_source_interface_access_control_xenial(host, apache_opt): - """ - Verifies the access control directives for the Source Interface. - Using a separate test because Xenial / Focal syntax differs. - """ - if host.system_info.codename != "xenial": - return True f = host.file("/etc/apache2/sites-available/source.conf") regex = "^{}$".format(re.escape(apache_opt)) assert re.search(regex, f.content_string, re.M) diff --git a/molecule/testinfra/app/test_apparmor.py b/molecule/testinfra/app/test_apparmor.py --- a/molecule/testinfra/app/test_apparmor.py +++ b/molecule/testinfra/app/test_apparmor.py @@ -102,8 +102,6 @@ def test_apparmor_total_profiles(host): complaining profiles """ with host.sudo(): total_expected = len(sdvars.apparmor_enforce) + len(sdvars.apparmor_complain) - # Xenial about ~20 profiles, so let's expect - # *at least* the sum. assert int(host.check_output("aa-status --profiled")) >= total_expected diff --git a/molecule/testinfra/app/test_ossec_agent.py b/molecule/testinfra/app/test_ossec_agent.py --- a/molecule/testinfra/app/test_ossec_agent.py +++ b/molecule/testinfra/app/test_ossec_agent.py @@ -23,16 +23,11 @@ def test_hosts_files(host): def test_ossec_service_start_style(host): """ - Ensure that the OSSEC services are managed by systemd under Focal, - but by sysv under Xenial. + Ensure that the OSSEC services are managed by systemd. """ - if host.system_info.codename == "focal": - value = "/etc/systemd/system/ossec.service" - else: - value = "/etc/init.d/ossec" with host.sudo(): c = host.check_output("systemctl status ossec") - assert value in c + assert "/etc/systemd/system/ossec.service" in c def test_hosts_duplicate(host): diff --git a/molecule/testinfra/app/test_paxctld.py b/molecule/testinfra/app/test_paxctld.py deleted file mode 100644 --- a/molecule/testinfra/app/test_paxctld.py +++ /dev/null @@ -1,39 +0,0 @@ -import re -import testutils - -securedrop_test_vars = testutils.securedrop_test_vars -testinfra_hosts = [securedrop_test_vars.app_hostname] - - -def test_paxctld_installed(host): - """ - Ensure the paxctld package is installed. - """ - # Only relevant to Xenial installs - if host.system_info.codename == "xenial": - pkg = host.package("paxctld") - assert pkg.is_installed - - -def test_paxctld_config(host): - """ - Ensure the relevant binaries have appropriate flags set in paxctld config. - """ - f = host.file("/etc/paxctld.conf") - - # Only relevant to Xenial installs - if host.system_info.codename == "xenial": - assert f.is_file - regex = r"^/usr/sbin/apache2\s+m$" - assert re.search(regex, f.content_string, re.M) - - -def test_paxctld_service(host): - """ - Ensure the paxctld service is enabled and running. - """ - # Only relevant to Xenial installs - if host.system_info.codename == "xenial": - s = host.service("paxctld") - assert s.is_running - assert s.is_enabled diff --git a/molecule/testinfra/app/test_tor_config.py b/molecule/testinfra/app/test_tor_config.py --- a/molecule/testinfra/app/test_tor_config.py +++ b/molecule/testinfra/app/test_tor_config.py @@ -22,8 +22,7 @@ def test_tor_packages(host, package): def test_tor_service_running(host): """ Ensure Tor is running and enabled. Tor is required for SSH access, - so it must be enabled to start on boot. Checks systemd-style services, - used by Xenial. + so it must be enabled to start on boot. """ s = host.service("tor") assert s.is_running diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -11,61 +11,24 @@ def test_automatic_updates_dependencies(host): """ Ensure critical packages are installed. If any of these are missing, the system will fail to receive automatic updates. - - In Xenial, the apt config uses cron-apt, rather than unattended-upgrades. - Previously the apt.freedom.press repo was not reporting any "Origin" field, - making use of unattended-upgrades problematic. In Focal, the apt config uses unattended-upgrades. """ - apt_dependencies = { - 'xenial': ['cron-apt', 'ntp'], - 'focal': ['unattended-upgrades'] - } - - for package in apt_dependencies[host.system_info.codename]: - assert host.package(package).is_installed + assert host.package("unattended-upgrades").is_installed + assert not host.package("cron-apt").is_installed + assert not host.package("ntp").is_installed def test_cron_apt_config(host): """ - Ensure custom cron-apt config file is present in Xenial, and absent in Focal - """ - f = host.file('/etc/cron-apt/config') - if host.system_info.codename == "xenial": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - assert f.contains('^SYSLOGON="always"$') - assert f.contains('^EXITON=error$') - else: - assert not f.exists - - [email protected]('repo', [ - 'deb http://security.ubuntu.com/ubuntu {securedrop_target_distribution}-security main', - 'deb-src http://security.ubuntu.com/ubuntu {securedrop_target_distribution}-security main', - 'deb http://security.ubuntu.com/ubuntu {securedrop_target_distribution}-security universe', - 'deb-src http://security.ubuntu.com/ubuntu {securedrop_target_distribution}-security universe', - 'deb [arch=amd64] {fpf_apt_repo_url} {securedrop_target_distribution} main', -]) -def test_cron_apt_repo_list(host, repo): - """ - Ensure the correct apt repositories are specified - in the security list for apt. + Ensure custom cron-apt config is absent, as of Focal """ - repo_config = repo.format( - fpf_apt_repo_url=test_vars.fpf_apt_repo_url, - securedrop_target_distribution=host.system_info.codename - ) - f = host.file('/etc/apt/security.list') - if host.system_info.codename == "xenial": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - repo_regex = '^{}$'.format(re.escape(repo_config)) - assert f.contains(repo_regex) - else: - assert not f.exists + assert not host.file("/etc/cron-apt/config").exists + assert not host.file('/etc/cron-apt/action.d/0-update').exists + assert not host.file('/etc/cron-apt/action.d/5-security').exists + assert not host.file('/etc/cron-apt/action.d/9-remove').exists + assert not host.file('/etc/cron.d/cron-apt').exists + assert not host.file("/etc/apt/security.list").exists + assert not host.file("/etc/cron-apt/action.d/3-download").exists @pytest.mark.parametrize('repo', [ @@ -83,108 +46,11 @@ def test_sources_list(host, repo): securedrop_target_platform=host.system_info.codename ) f = host.file('/etc/apt/sources.list') - if host.system_info.codename == "focal": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - repo_regex = '^{}$'.format(re.escape(repo_config)) - assert f.contains(repo_regex) - - -def test_cron_apt_repo_config_update(host): - """ - Ensure cron-apt updates repos from the security.list config for Xenial. - """ - - f = host.file('/etc/cron-apt/action.d/0-update') - if host.system_info.codename == "xenial": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - repo_config = str('update -o quiet=2' - ' -o Dir::Etc::SourceList=/etc/apt/security.list' - ' -o Dir::Etc::SourceParts=""') - assert f.contains('^{}$'.format(repo_config)) - else: - assert not f.exists - - -def test_cron_apt_delete_vanilla_kernels(host): - """ - Ensure cron-apt removes generic linux image packages when installed. This - file is provisioned via ansible and via the securedrop-config package. We - should remove it once Xenial is fully deprecated. In the meantime, it will - not impact Focal systems running unattended-upgrades - """ - - f = host.file('/etc/cron-apt/action.d/9-remove') - if host.system_info.codename == "xenial": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - command = str('remove -y' - ' linux-image-generic-lts-xenial linux-image-.*generic' - ' -o quiet=2') - assert f.contains('^{}$'.format(command)) - else: - assert not f.exists - - -def test_cron_apt_repo_config_upgrade(host): - """ - Ensure cron-apt upgrades packages from the security.list config. - """ - f = host.file('/etc/cron-apt/action.d/5-security') - if host.system_info.codename == "xenial": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - assert f.contains('^autoclean -y$') - repo_config = str('dist-upgrade -y -o APT::Get::Show-Upgraded=true' - ' -o Dir::Etc::SourceList=/etc/apt/security.list' - ' -o Dpkg::Options::=--force-confdef' - ' -o Dpkg::Options::=--force-confold') - assert f.contains(re.escape(repo_config)) - else: - assert not f.exists - - -def test_cron_apt_config_deprecated(host): - """ - Ensure default cron-apt file to download all updates does not exist. - """ - f = host.file('/etc/cron-apt/action.d/3-download') - assert not f.exists - - [email protected]('cron_job', [ - {'job': '0 4 * * * root /usr/bin/test -x /usr/sbin/cron-apt && /usr/sbin/cron-apt && /sbin/reboot', # noqa - 'state': 'present'}, - {'job': '0 4 * * * root /usr/bin/test -x /usr/sbin/cron-apt && /usr/sbin/cron-apt', # noqa - 'state': 'absent'}, - {'job': '0 5 * * * root /sbin/reboot', - 'state': 'absent'}, -]) -def test_cron_apt_cron_jobs(host, cron_job): - """ - Check for correct cron job for upgrading all packages and rebooting. - We'll also check for absence of previous versions of the cron job, - to make sure those have been cleaned up via the playbooks. - """ - f = host.file('/etc/cron.d/cron-apt') - - if host.system_info.codename == "xenial": - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - - regex_job = '^{}$'.format(re.escape(cron_job['job'])) - if cron_job['state'] == 'present': - assert f.contains(regex_job) - else: - assert not f.contains(regex_job) - else: - assert not f.exists + assert f.is_file + assert f.user == "root" + assert f.mode == 0o644 + repo_regex = '^{}$'.format(re.escape(repo_config)) + assert f.contains(repo_regex) apt_config_options = { @@ -215,8 +81,6 @@ def test_unattended_upgrades_config(host, k, v): """ Ensures the apt and unattended-upgrades config is correct only under Ubuntu Focal """ - if host.system_info.codename == "xenial": - return True # Dump apt config to inspect end state, apt will build config # from all conf files on disk, e.g. 80securedrop. c = host.run("apt-config dump --format '%v%n' {}".format(k)) @@ -240,10 +104,7 @@ def test_unattended_securedrop_specific(host): assert f.user == "root" assert f.mode == 0o644 assert f.contains('APT::Install-Recommends "false";') - if host.system_info.codename == "focal": - assert f.contains("Automatic-Reboot-Time") - else: - assert not f.contains("Automatic-Reboot-Time") + assert f.contains("Automatic-Reboot-Time") def test_unattended_upgrades_functional(host): @@ -251,19 +112,18 @@ def test_unattended_upgrades_functional(host): Ensure unatteded-upgrades completes successfully and ensures all packages are up-to-date. """ - if host.system_info.codename != "xenial": - c = host.run('sudo unattended-upgrades --dry-run --debug') - assert c.rc == 0 - expected_origins = ( - "Allowed origins are: origin=Ubuntu,archive=focal, origin=Ubuntu,archive=focal-security" - ", origin=Ubuntu,archive=focal-updates, origin=SecureDrop,codename=focal" - ) - expected_result = ( - "No packages found that can be upgraded unattended and no pending auto-removals" - ) + c = host.run('sudo unattended-upgrades --dry-run --debug') + assert c.rc == 0 + expected_origins = ( + "Allowed origins are: origin=Ubuntu,archive=focal, origin=Ubuntu,archive=focal-security" + ", origin=Ubuntu,archive=focal-updates, origin=SecureDrop,codename=focal" + ) + expected_result = ( + "No packages found that can be upgraded unattended and no pending auto-removals" + ) - assert expected_origins in c.stdout - assert expected_result in c.stdout + assert expected_origins in c.stdout + assert expected_result in c.stdout @pytest.mark.parametrize('service', [ @@ -277,11 +137,10 @@ def test_apt_daily_services_and_timers_enabled(host, service): Ensure the services and timers used for unattended upgrades are enabled in Ubuntu 20.04 Focal. """ - if host.system_info.codename != "xenial": - with host.sudo(): - # The services are started only when the upgrades are being performed. - s = host.service(service) - assert s.is_enabled + with host.sudo(): + # The services are started only when the upgrades are being performed. + s = host.service(service) + assert s.is_enabled def test_apt_daily_timer_schedule(host): @@ -289,10 +148,9 @@ def test_apt_daily_timer_schedule(host): Timer for running apt-daily, i.e. 'apt-get update', should be 2h before the daily_reboot_time. """ - if host.system_info.codename != "xenial": - c = host.run("systemctl show apt-daily.timer") - assert "TimersCalendar={ OnCalendar=*-*-* 02:00:00 ;" in c.stdout - assert "RandomizedDelayUSec=20m" in c.stdout + c = host.run("systemctl show apt-daily.timer") + assert "TimersCalendar={ OnCalendar=*-*-* 02:00:00 ;" in c.stdout + assert "RandomizedDelayUSec=20m" in c.stdout def test_apt_daily_upgrade_timer_schedule(host): @@ -300,10 +158,9 @@ def test_apt_daily_upgrade_timer_schedule(host): Timer for running apt-daily-upgrade, i.e. 'apt-get upgrade', should be 1h before the daily_reboot_time, and 1h after the apt-daily time. """ - if host.system_info.codename != "xenial": - c = host.run("systemctl show apt-daily-upgrade.timer") - assert "TimersCalendar={ OnCalendar=*-*-* 03:00:00 ;" in c.stdout - assert "RandomizedDelayUSec=20m" in c.stdout + c = host.run("systemctl show apt-daily-upgrade.timer") + assert "TimersCalendar={ OnCalendar=*-*-* 03:00:00 ;" in c.stdout + assert "RandomizedDelayUSec=20m" in c.stdout def test_reboot_required_cron(host): @@ -314,16 +171,12 @@ def test_reboot_required_cron(host): is rebooted every day at the scheduled time. """ f = host.file('/etc/cron.d/reboot-flag') + assert f.is_file + assert f.user == "root" + assert f.mode == 0o644 - if host.system_info.codename == "xenial": - assert not f.exists - else: - assert f.is_file - assert f.user == "root" - assert f.mode == 0o644 - - line = '^{}$'.format(re.escape("0 */12 * * * root touch /var/run/reboot-required")) - assert f.contains(line) + line = '^{}$'.format(re.escape("0 */12 * * * root touch /var/run/reboot-required")) + assert f.contains(line) def test_all_packages_updated(host): diff --git a/molecule/testinfra/common/test_basic_configuration.py b/molecule/testinfra/common/test_basic_configuration.py --- a/molecule/testinfra/common/test_basic_configuration.py +++ b/molecule/testinfra/common/test_basic_configuration.py @@ -8,32 +8,18 @@ def test_system_time(host: Host) -> None: - if host.system_info.codename == "xenial": - assert host.package("ntp").is_installed - assert host.package("ntpdate").is_installed - - # TODO: The staging setup timing is too erratic for the - # following check. If we do want to reinstate it before - # dropping Xenial support, it should be done in a loop to give - # ntpd time to sync after the machines are created. - - # c = host.run("ntpq -c rv") - # assert "leap_none" in c.stdout - # assert "sync_ntp" in c.stdout - # assert "refid" in c.stdout - else: - assert not host.package("ntp").is_installed - assert not host.package("ntpdate").is_installed - - s = host.service("systemd-timesyncd") - assert s.is_running - assert s.is_enabled - assert not s.is_masked - - # File will be touched on every successful synchronization, - # see 'man systemd-timesyncd'` - assert host.file("/run/systemd/timesync/synchronized").exists - - c = host.run("timedatectl show") - assert "NTP=yes" in c.stdout - assert "NTPSynchronized=yes" in c.stdout + assert not host.package("ntp").is_installed + assert not host.package("ntpdate").is_installed + + s = host.service("systemd-timesyncd") + assert s.is_running + assert s.is_enabled + assert not s.is_masked + + # File will be touched on every successful synchronization, + # see 'man systemd-timesyncd'` + assert host.file("/run/systemd/timesync/synchronized").exists + + c = host.run("timedatectl show") + assert "NTP=yes" in c.stdout + assert "NTPSynchronized=yes" in c.stdout diff --git a/molecule/testinfra/common/test_grsecurity.py b/molecule/testinfra/common/test_grsecurity.py --- a/molecule/testinfra/common/test_grsecurity.py +++ b/molecule/testinfra/common/test_grsecurity.py @@ -31,10 +31,7 @@ def test_grsecurity_apt_packages(host, package): Includes the FPF-maintained metapackage, as well as paxctl, for managing PaX flags on binaries. """ - if host.system_info.codename == "xenial": - KERNEL_VERSION = sdvars.grsec_version_xenial - else: - KERNEL_VERSION = sdvars.grsec_version_focal + KERNEL_VERSION = sdvars.grsec_version_focal if package.startswith("linux-image"): package = package.format(KERNEL_VERSION) assert host.package(package).is_installed @@ -80,10 +77,7 @@ def test_grsecurity_kernel_is_running(host): """ Make sure the currently running kernel is specific grsec kernel. """ - if host.system_info.codename == "xenial": - KERNEL_VERSION = sdvars.grsec_version_xenial - else: - KERNEL_VERSION = sdvars.grsec_version_focal + KERNEL_VERSION = sdvars.grsec_version_focal c = host.run('uname -r') assert c.stdout.strip().endswith('-grsec-securedrop') assert c.stdout.strip() == '{}-grsec-securedrop'.format(KERNEL_VERSION) @@ -171,36 +165,7 @@ def test_paxctl(host): As of Focal, paxctl is not used, and shouldn't be installed. """ p = host.package("paxctl") - if host.system_info.codename == "xenial": - assert p.is_installed - else: - assert not p.is_installed - - -def test_paxctld_xenial(host): - """ - Xenial-specific paxctld config checks. - Ensures paxctld is running and enabled, and relevant - exemptions are present in the config file. - """ - if host.system_info.codename != "xenial": - return True - - hostname = host.check_output('hostname -s') - assert (("app" in hostname) or ("mon" in hostname)) - - # Under Xenial, apache2 pax flags managed by securedrop-app-code. - if "app" not in hostname: - return True - - assert host.package("paxctld").is_installed - f = host.file("/etc/paxctld.conf") - assert f.is_file - assert f.contains("^/usr/sbin/apache2\tm") - - s = host.service("paxctld") - assert s.is_enabled - assert s.is_running + assert not p.is_installed def test_paxctld_focal(host): @@ -209,9 +174,6 @@ def test_paxctld_focal(host): Ensures paxctld is running and enabled, and relevant exemptions are present in the config file. """ - if host.system_info.codename != "focal": - return True - assert host.package("paxctld").is_installed f = host.file("/etc/paxctld.conf") assert f.is_file @@ -249,10 +211,7 @@ def test_wireless_disabled_in_kernel_config(host, kernel_opts): remove wireless support from the kernel. Let's make sure wireless is disabled in the running kernel config! """ - if host.system_info.codename == "xenial": - KERNEL_VERSION = sdvars.grsec_version_xenial - else: - KERNEL_VERSION = sdvars.grsec_version_focal + KERNEL_VERSION = sdvars.grsec_version_focal with host.sudo(): kernel_config_path = "/boot/config-{}-grsec-securedrop".format(KERNEL_VERSION) kernel_config = host.file(kernel_config_path).content_string @@ -271,10 +230,7 @@ def test_kernel_options_enabled_config(host, kernel_opts): Tests kernel config for options that should be enabled """ - if host.system_info.codename == "xenial": - KERNEL_VERSION = sdvars.grsec_version_xenial - else: - KERNEL_VERSION = sdvars.grsec_version_focal + KERNEL_VERSION = sdvars.grsec_version_focal with host.sudo(): kernel_config_path = "/boot/config-{}-grsec-securedrop".format(KERNEL_VERSION) kernel_config = host.file(kernel_config_path).content_string diff --git a/molecule/testinfra/common/test_ip6tables.py b/molecule/testinfra/common/test_ip6tables.py --- a/molecule/testinfra/common/test_ip6tables.py +++ b/molecule/testinfra/common/test_ip6tables.py @@ -4,34 +4,12 @@ testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] -def test_ip6tables_drop_everything_xenial(host): - """ - Ensure that all IPv6 packets are dropped by default. - The IPv4 rules are more complicated, and tested separately. - This test is Xenial-specific, given that on Focal we disable - IPv6 functionality completely. - """ - if host.system_info.codename != "xenial": - return True - desired_ip6tables_output = """ --P INPUT DROP --P FORWARD DROP --P OUTPUT DROP -""".lstrip().rstrip() - - with host.sudo(): - c = host.check_output("ip6tables -S") - assert c == desired_ip6tables_output - - def test_ip6tables_drop_everything_focal(host): """ Ensures that IPv6 firewall settings are inaccessible, due to fully disabling IPv6 functionality at boot-time, via boot options. """ - if host.system_info.codename != "focal": - return True with host.sudo(): c = host.run("ip6tables -S") assert c.rc != 0 diff --git a/molecule/testinfra/common/test_platform.py b/molecule/testinfra/common/test_platform.py --- a/molecule/testinfra/common/test_platform.py +++ b/molecule/testinfra/common/test_platform.py @@ -3,18 +3,10 @@ test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] -# We expect Ubuntu Xenial -SUPPORTED_CODENAMES = ('xenial', 'focal') -SUPPORTED_RELEASES = ('16.04', '20.04') - def test_ansible_version(host): """ Check that a supported version of Ansible is being used. - - The project has long used the Ansible 1.x series, ans now - requires the 2.x series starting with the 0.4 release. Ensure - installation is not being performed with an outdated ansible version. """ localhost = host.get_host("local://") c = localhost.check_output("ansible --version") @@ -23,9 +15,9 @@ def test_ansible_version(host): def test_platform(host): """ - SecureDrop requires Ubuntu Ubuntu 16.04 or 20.04 LTS + SecureDrop requires Ubuntu 20.04 LTS """ assert host.system_info.type == "linux" assert host.system_info.distribution == "ubuntu" - assert host.system_info.codename in SUPPORTED_CODENAMES - assert host.system_info.release in SUPPORTED_RELEASES + assert host.system_info.codename == "focal" + assert host.system_info.release == "20.04" diff --git a/molecule/testinfra/common/test_release_upgrades.py b/molecule/testinfra/common/test_release_upgrades.py --- a/molecule/testinfra/common/test_release_upgrades.py +++ b/molecule/testinfra/common/test_release_upgrades.py @@ -12,32 +12,18 @@ def test_release_manager_installed(host): remove it to make the boxes leaner. """ assert host.package("ubuntu-release-upgrader-core").is_installed + assert host.exists("do-release-upgrade") def test_release_manager_upgrade_channel(host): """ Ensures that the `do-release-upgrade` command will not - suggest upgrades from Xenial to Bionic (which is untested - and unsupported.) + suggest upgrades to a future LTS, until we test it and provide support. """ - expected_channels = { - "xenial": "never", - "focal": "never", - } - config_path = "/etc/update-manager/release-upgrades" assert host.file(config_path).is_file raw_output = host.check_output("grep '^Prompt' {}".format(config_path)) _, channel = raw_output.split("=") - expected_channel = expected_channels[host.system_info.codename] - assert channel == expected_channel - - -def test_do_release_upgrade_is_installed(host): - """ - Ensure the `do-release-upgrade` command is present on target systems, - so that instance Admins can upgrade from Trusty to Xenial. - """ - assert host.exists("do-release-upgrade") + assert channel == "never" diff --git a/molecule/testinfra/common/test_system_hardening.py b/molecule/testinfra/common/test_system_hardening.py --- a/molecule/testinfra/common/test_system_hardening.py +++ b/molecule/testinfra/common/test_system_hardening.py @@ -22,20 +22,13 @@ ('net.ipv4.ip_forward', 0), ('net.ipv4.tcp_max_syn_backlog', 4096), ('net.ipv4.tcp_syncookies', 1), - ('net.ipv6.conf.all.disable_ipv6', 1), - ('net.ipv6.conf.default.disable_ipv6', 1), - ('net.ipv6.conf.lo.disable_ipv6', 1), ]) def test_sysctl_options(host, sysctl_opt): """ Ensure sysctl flags are set correctly. Most of these checks - are disabling IPv6 and hardening IPv4, which is appropriate - due to the heavy use of Tor. + are hardening IPv4, which is appropriate due to the heavy use of Tor. """ with host.sudo(): - # For Focal, we disable IPv6 entirely, so the IPv6 sysctl options won't exist - if sysctl_opt[0].startswith("net.ipv6") and host.system_info.codename == "focal": - return True assert host.sysctl(sysctl_opt[0]) == sysctl_opt[1] @@ -43,11 +36,7 @@ def test_dns_setting(host): """ Ensure DNS service is hard-coded in resolv.conf config. """ - if host.system_info.codename == "focal": - fpath = "/etc/resolv.conf" - else: - fpath = "/etc/resolvconf/resolv.conf.d/base" - f = host.file(fpath) + f = host.file("/etc/resolv.conf") assert f.is_file assert f.user == "root" assert f.group == "root" @@ -88,8 +77,8 @@ def test_swap_disabled(host): # A leading slash will indicate full path to a swapfile. assert not re.search("^/", c, re.M) - # On Xenial, swapon 2.27.1 shows blank output, with no headers, so - # check for empty output as confirmation of no swap. + # Since swapon 2.27.1, the summary shows blank output, with no headers, + # when no swap is configured, check for empty output as confirmation disabled. rgx = re.compile("^$") assert re.search(rgx, c) @@ -160,7 +149,7 @@ def test_no_ecrypt_messages_in_logs(host, logfile): ]) def test_unused_packages_are_removed(host, package): """ Check if unused package is present """ - assert host.package(package).is_installed is False + assert not host.package(package).is_installed def test_iptables_packages(host): @@ -168,10 +157,7 @@ def test_iptables_packages(host): Focal hosts should use iptables-persistent for enforcing firewall config across reboots. """ - if host.system_info.codename == "focal": - assert host.package("iptables-persistent").is_installed - else: - assert not host.package("iptables-persistent").is_installed + assert host.package("iptables-persistent").is_installed def test_snapd_absent(host): diff --git a/molecule/testinfra/common/test_user_config.py b/molecule/testinfra/common/test_user_config.py --- a/molecule/testinfra/common/test_user_config.py +++ b/molecule/testinfra/common/test_user_config.py @@ -73,35 +73,6 @@ def test_sudoers_tmux_env(host): fi""" ) - expected_content_xenial = textwrap.dedent( - """\ - [[ $- != *i* ]] && return - - which tmux >/dev/null 2>&1 || return - - tmux_attach_via_proc() { - # If the tmux package is upgraded during the lifetime of a - # session, attaching with the new binary can fail due to different - # protocol versions. This function attaches using the reference to - # the old executable found in the /proc tree of an existing - # session. - pid=$(pgrep --newest tmux) - if test -n "$pid" - then - /proc/$pid/exe attach - fi - return 1 - } - - if test -z "$TMUX" - then - (tmux attach || tmux_attach_via_proc || tmux new-session) - fi""" - ) - - if host.system_info.codename == "xenial": - expected_content = expected_content_xenial - assert host_file.content_string.strip() == expected_content diff --git a/molecule/testinfra/mon/test_ossec_server.py b/molecule/testinfra/mon/test_ossec_server.py --- a/molecule/testinfra/mon/test_ossec_server.py +++ b/molecule/testinfra/mon/test_ossec_server.py @@ -24,16 +24,11 @@ def test_ossec_connectivity(host): def test_ossec_service_start_style(host): """ - Ensure that the OSSEC services are managed by systemd under Focal, - but by sysv under Xenial. + Ensure that the OSSEC services are managed by systemd. """ - if host.system_info.codename == "focal": - value = "/etc/systemd/system/ossec.service" - else: - value = "/etc/init.d/ossec" with host.sudo(): c = host.check_output("systemctl status ossec") - assert value in c + assert "/etc/systemd/system/ossec.service" in c # Permissions don't match between Ansible and OSSEC deb packages postinst. diff --git a/molecule/testinfra/mon/test_postfix.py b/molecule/testinfra/mon/test_postfix.py --- a/molecule/testinfra/mon/test_postfix.py +++ b/molecule/testinfra/mon/test_postfix.py @@ -37,12 +37,8 @@ def test_postfix_generic_maps(host): """ assert not host.file("/etc/postfix/generic").exists assert not host.file("/etc/postfix/main.cf").contains("^smtp_generic_maps") - if host.system_info.codename == "focal": - assert host.file("/etc/postfix/main.cf").contains( - "^smtpd_recipient_restrictions = reject_unauth_destination") - if host.system_info.codename == "xenial": - assert not host.file("/etc/postfix/main.cf").contains( - "^smtpd_recipient_restrictions = reject_unauth_destination") + assert host.file("/etc/postfix/main.cf").contains( + "^smtpd_recipient_restrictions = reject_unauth_destination") def test_postfix_service(host): diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -62,65 +62,6 @@ def _login_user(app, username, password, otp_secret): assert hasattr(g, 'user') # ensure logged in -def test_user_sees_os_warning_if_server_past_eol(config, journalist_app, test_journo): - journalist_app.config.update(OS_PAST_EOL=True, OS_NEAR_EOL=False) - with journalist_app.test_client() as app: - _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] - ) - - resp = app.get(url_for("main.index")) - - text = resp.data.decode("utf-8") - assert 'id="os-past-eol"' in text, text - assert 'id="os-near-eol"' not in text, text - - -def test_user_sees_os_warning_if_server_past_eol_sanity_check(config, journalist_app, test_journo): - """ - Sanity check (both conditions cannot be True but test guard against developer error) - """ - journalist_app.config.update(OS_PAST_EOL=True, OS_NEAR_EOL=True) - with journalist_app.test_client() as app: - _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] - ) - - resp = app.get(url_for("main.index")) - - text = resp.data.decode("utf-8") - assert 'id="os-past-eol"' in text, text - assert 'id="os-near-eol"' not in text, text - - -def test_user_sees_os_warning_if_server_close_to_eol(config, journalist_app, test_journo): - journalist_app.config.update(OS_PAST_EOL=False, OS_NEAR_EOL=True) - with journalist_app.test_client() as app: - _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] - ) - - resp = app.get(url_for("main.index")) - - text = resp.data.decode("utf-8") - assert 'id="os-past-eol"' not in text, text - assert 'id="os-near-eol"' in text, text - - -def test_user_does_not_see_os_warning_if_server_is_current(config, journalist_app, test_journo): - journalist_app.config.update(OS_PAST_EOL=False, OS_NEAR_EOL=False) - with journalist_app.test_client() as app: - _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] - ) - - resp = app.get(url_for("main.index")) - - text = resp.data.decode("utf-8") - assert 'id="os-past-eol"' not in text, text - assert 'id="os-near-eol"' not in text, text - - def test_user_with_whitespace_in_username_can_login(journalist_app): # Create a user with whitespace at the end of the username with journalist_app.app_context(): diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -38,86 +38,6 @@ overly_long_codename = 'a' * (PassphraseGenerator.MAX_PASSPHRASE_LENGTH + 1) -def test_source_interface_is_disabled_when_xenial_is_eol(config, source_app): - disabled_endpoints = [ - "main.index", - "main.generate", - "main.login", - "info.download_public_key", - "info.tor2web_warning", - "info.recommend_tor_browser", - "info.why_download_public_key", - ] - static_assets = [ - "css/source.css", - "i/custom_logo.png", - "i/font-awesome/fa-globe-black.png", - "i/favicon.png", - ] - with patch("server_os.get_os_release", return_value="16.04"): - with patch("server_os.get_xenial_eol_date", return_value=date(2020, 1, 1)): - app = source_app_module.create_app(config) - with app.test_client() as test_client: - for endpoint in disabled_endpoints: - resp = test_client.get(url_for(endpoint)) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "We're sorry, our SecureDrop is currently offline." in text - # Ensure static assets are properly served - for asset in static_assets: - resp = test_client.get(url_for("static", filename=asset)) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "We're sorry, our SecureDrop is currently offline." not in text - - -def test_source_interface_is_not_disabled_before_xenial_eol(config, source_app): - disabled_endpoints = [ - "main.index", - "main.generate", - "main.login", - "info.download_public_key", - "info.tor2web_warning", - "info.recommend_tor_browser", - "info.why_download_public_key", - ] - with patch("server_os.get_os_release", return_value="16.04"): - with patch("server_os.get_xenial_eol_date", return_value=date(2200, 1, 1)): - app = source_app_module.create_app(config) - with app.test_client() as test_client: - print( - "OS_RELEASE: {} EOL DATE: {}".format( - server_os.get_os_release(), server_os.get_xenial_eol_date() - ) - ) - for endpoint in disabled_endpoints: - resp = test_client.get(url_for(endpoint), follow_redirects=True) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "We're sorry, our SecureDrop is currently offline." not in text - - -def test_source_interface_is_not_disabled_for_focal(config, source_app): - disabled_endpoints = [ - "main.index", - "main.generate", - "main.login", - "info.download_public_key", - "info.tor2web_warning", - "info.recommend_tor_browser", - "info.why_download_public_key", - ] - with patch("server_os.get_os_release", return_value="20.04"): - with patch("server_os.get_xenial_eol_date", return_value=date(2020, 1, 1)): - app = source_app_module.create_app(config) - with app.test_client() as test_client: - for endpoint in disabled_endpoints: - resp = test_client.get(url_for(endpoint)) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "We're sorry, our SecureDrop is currently offline." not in text - - def test_logo_default_available(source_app): # if the custom image is available, this test will fail custom_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png")
Remove all Xenial-specific code from the codebase SecureDrop 2.0.0 will be the first release to no longer support Ubuntu 16.04 (Xenial). As part of that release (but no sooner), we should remove all Xenial-specific code from the codebase, including any Xenial-specific application code, provisioning logic, or developer tooling. ## Next steps - [x] Update Vagrantfile - [x] Remove the following molecule scenarios - [x] `builder-xenial`, `libvirt-staging-xenial`, `qubes-staging-xenial`, `virtualbox-staging-xenial` - [x] Update `make build-debs` to `make build-debs-focal` and remove the second - [x] Update `make build-debs-notest` to `make build-debs-notest-focal` and remove the second - [x] Update `make staging` to same of `make staging-focal` and remove the second - [x] Update `make dev` to same of `make dev-focal` and remove the second - [x] Update `ci-deb-tests` to `ci-deb-tests-focal` and remove the second - [x] Update CI to remove all `Xenial` based jobs, make sure that all scripts have `focal` as default - [ ] Next, look at the source and journalist code to find all Python3.5 related points
Suggestions for how this work could potentially be divided up would be appreciated ahead of Thursday's sprint planning discussion. One potential division @emkll and I discussed is: - packaging / packaging tests - provisioning / provisioning tests - CI This is one of our top 3 priorities for the 4/15 sprint, with @kushaldas @creviera and @zenmonkeykstop collaborating on this and the v2 onion service removal (#5731).
2021-04-21T14:20:26Z
[]
[]
freedomofpress/securedrop
5,915
freedomofpress__securedrop-5915
[ "5731" ]
14c9d3a8f2ed7abc5eddd95a0ec8142efed45400
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -64,7 +64,7 @@ sdlog = logging.getLogger(__name__) RELEASE_KEY = '22245C81E3BAEB4138B36061310F561200F4AD77' DEFAULT_KEYSERVER = 'hkps://keys.openpgp.org' -SUPPORT_ONION_URL = 'http://support6kv2242qx.onion' +SUPPORT_ONION_URL = 'http://sup6h5iyiyenvjkfxbgrjynm5wsgijjoatvnvdgyyi7je3xqm4kh6uqd.onion' SUPPORT_URL = 'https://support.freedom.press' EXIT_SUCCESS = 0 EXIT_SUBPROCESS_ERROR = 1 @@ -193,23 +193,6 @@ def validate(self, document: Document) -> bool: return True raise ValidationError(message="Must be either yes or no") - class ValidateYesNoForV3(Validator): - - def __init__(self, *args: Any, **kwargs: Any) -> None: - Validator.__init__(*args, **kwargs) - self.caller = args[0] - - def validate(self, document: Document) -> bool: - text = document.text.lower() - # Raise error if admin tries to disable v3 when v2 - # is already disabled. - if text == 'no' and \ - not self.caller._config_in_progress.get("v2_onion_services"): # noqa: E501 - raise ValidationError(message="Since you disabled v2 onion services, you must enable v3 onion services.") # noqa: E501 - if text == 'yes' or text == 'no': - return True - raise ValidationError(message="Must be either yes or no") - class ValidateFingerprint(Validator): def validate(self, document: Document) -> bool: text = document.text.replace(' ', '') @@ -457,17 +440,6 @@ def __init__(self, args: argparse.Namespace) -> None: SiteConfig.ValidateLocales(self.args.app_path), str.split, lambda config: True), - ('v2_onion_services', self.check_for_v2_onion(), bool, - 'WARNING: v2 onion services cannot be installed on servers ' + - 'running Ubuntu 20.04. Do you want to enable v2 onion services?', - SiteConfig.ValidateYesNo(), - lambda x: x.lower() == 'yes', - lambda config: True), - ('v3_onion_services', self.check_for_v3_onion, bool, - 'Do you want to enable v3 onion services (recommended)?', - SiteConfig.ValidateYesNoForV3(self), - lambda x: x.lower() == 'yes', - lambda config: True), ] # type: List[_DescEntryType] def load_and_update_config(self, validate: bool = True, prompt: bool = True) -> bool: @@ -485,52 +457,8 @@ def update_config(self, prompt: bool = True) -> bool: self.save() self.validate_gpg_keys() self.validate_journalist_alert_email() - self.validate_https_and_v3() return True - def validate_https_and_v3(self) -> bool: - """ - Checks if https is enabled with v3 onion service. - - :returns: False if both v3 and https enabled, True otherwise. - """ - warning_msg = ("You have configured HTTPS on your source interface " - "and v3 onion services. " - "IMPORTANT: Ensure that you update your certificate " - "to include your v3 source URL before advertising " - "it to sources! ") - - if self.config.get("v3_onion_services", False) and \ - self.config.get("securedrop_app_https_certificate_cert_src"): - print(warning_msg) - return False - return True - - def check_for_v2_onion(self) -> bool: - """ - Check if v2 onion services are already enabled or not. - """ - source_ths = os.path.join(self.args.ansible_path, "app-source-ths") - if os.path.exists(source_ths): # Means old installation - data = "" - with open(source_ths) as fobj: - data = fobj.read() - - data = data.strip() - if len(data) < 56: # Old v2 onion address - return True - return False - - def check_for_v3_onion(self) -> bool: - """ - Check if v3 onion services should be enabled by default or not. - """ - v2_value = self._config_in_progress.get("v2_onion_services", False) - # We need to see the value in the configuration file - # for v3_onion_services - v3_value = self.config.get("v3_onion_services", True) - return v3_value or not v2_value - def user_prompt_config(self) -> Dict[str, Any]: self._config_in_progress = {} for desc in self.desc: @@ -547,10 +475,7 @@ def user_prompt_config_one( self, desc: _DescEntryType, from_config: Optional[Any] ) -> Any: (var, default, type, prompt, validator, transform, condition) = desc - if from_config is not None and var != "v3_onion_services": - # v3_onion_services must be true if v2 is disabled by the admin - # otherwise, we may end up in a situation where both v2 and v3 - # are disabled by the admin (by mistake). + if from_config is not None: default = from_config prompt += ': '
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -47,76 +47,6 @@ smtp_relay: smtp.gmail.com smtp_relay_port: 587 ssh_users: sd -v2_onion_services: false -v3_onion_services: true -''' - -WHEN_BOTH_TRUE = '''app_hostname: app -app_ip: 10.20.2.2 -daily_reboot_time: 5 -dns_server: -- 8.8.8.8 -- 8.8.4.4 -enable_ssh_over_tor: true -journalist_alert_email: '' -journalist_alert_gpg_public_key: '' -journalist_gpg_fpr: '' -monitor_hostname: mon -monitor_ip: 10.20.3.2 -ossec_alert_email: [email protected] -ossec_alert_gpg_public_key: sd_admin_test.pub -ossec_gpg_fpr: 1F544B31C845D698EB31F2FF364F1162D32E7E58 -sasl_domain: gmail.com -sasl_password: testpassword -sasl_username: testuser -securedrop_app_gpg_fingerprint: 1F544B31C845D698EB31F2FF364F1162D32E7E58 -securedrop_app_gpg_public_key: sd_admin_test.pub -securedrop_app_https_certificate_cert_src: '' -securedrop_app_https_certificate_chain_src: '' -securedrop_app_https_certificate_key_src: '' -securedrop_app_https_on_source_interface: false -securedrop_supported_locales: -- de_DE -- es_ES -smtp_relay: smtp.gmail.com -smtp_relay_port: 587 -ssh_users: sd -v2_onion_services: true -v3_onion_services: true -''' - -WHEN_ONLY_V2 = '''app_hostname: app -app_ip: 10.20.2.2 -daily_reboot_time: 5 -dns_server: -- 8.8.8.8 -- 8.8.4.4 -enable_ssh_over_tor: true -journalist_alert_email: '' -journalist_alert_gpg_public_key: '' -journalist_gpg_fpr: '' -monitor_hostname: mon -monitor_ip: 10.20.3.2 -ossec_alert_email: [email protected] -ossec_alert_gpg_public_key: sd_admin_test.pub -ossec_gpg_fpr: 1F544B31C845D698EB31F2FF364F1162D32E7E58 -sasl_domain: gmail.com -sasl_password: testpassword -sasl_username: testuser -securedrop_app_gpg_fingerprint: 1F544B31C845D698EB31F2FF364F1162D32E7E58 -securedrop_app_gpg_public_key: sd_admin_test.pub -securedrop_app_https_certificate_cert_src: '' -securedrop_app_https_certificate_chain_src: '' -securedrop_app_https_certificate_key_src: '' -securedrop_app_https_on_source_interface: false -securedrop_supported_locales: -- de_DE -- es_ES -smtp_relay: smtp.gmail.com -smtp_relay_port: 587 -ssh_users: sd -v2_onion_services: true -v3_onion_services: false ''' JOURNALIST_ALERT_OUTPUT = '''app_hostname: app @@ -149,8 +79,6 @@ smtp_relay: smtp.gmail.com smtp_relay_port: 587 ssh_users: sd -v2_onion_services: false -v3_onion_services: true ''' HTTPS_OUTPUT = '''app_hostname: app @@ -183,8 +111,6 @@ smtp_relay: smtp.gmail.com smtp_relay_port: 587 ssh_users: sd -v2_onion_services: false -v3_onion_services: true ''' @@ -339,21 +265,6 @@ def verify_locales_prompt(child): child.expect(rb'Space separated list of additional locales to support') # noqa: E501 -def verify_v2_onion_for_first_time(child): - child.expect(rb'Do you want to enable v2 onion services\?\:', timeout=2) # noqa: E501 - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'no' # noqa: E501 - - -def verify_v3_onion_for_first_time(child): - child.expect(rb'Do you want to enable v3 onion services \(recommended\)\?\:', timeout=2) # noqa: E501 - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'yes' # noqa: E501 - - -def verify_v3_onion_when_v2_is_enabled(child): - child.expect(rb'Do you want to enable v3 onion services \(recommended\)\?\:', timeout=2) # noqa: E501 - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'yes' # noqa: E501 - - def verify_install_has_valid_config(): """ Checks that securedrop-admin install validates the configuration. @@ -424,9 +335,7 @@ def test_sdconfig_on_first_run(): child.sendline('') verify_locales_prompt(child) child.sendline('de_DE es_ES') - verify_v2_onion_for_first_time(child) child.sendline('\b' * 3 + 'no') - verify_v3_onion_for_first_time(child) child.sendline('\b' * 4 + 'yes') child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur @@ -441,134 +350,6 @@ def test_sdconfig_on_first_run(): verify_install_has_valid_config() -def test_sdconfig_both_v2_v3_true(): - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) - verify_username_prompt(child) - child.sendline('') - verify_reboot_prompt(child) - child.sendline('\b5') # backspace and put 5 - verify_ipv4_appserver_prompt(child) - child.sendline('') - verify_ipv4_monserver_prompt(child) - child.sendline('') - verify_hostname_app_prompt(child) - child.sendline('') - verify_hostname_mon_prompt(child) - child.sendline('') - verify_dns_prompt(child) - child.sendline('') - verify_app_gpg_key_prompt(child) - child.sendline('\b' * 14 + 'sd_admin_test.pub') - verify_https_prompt(child) - # Default answer is no - child.sendline('') - verify_app_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') - verify_ossec_gpg_key_prompt(child) - child.sendline('\b' * 9 + 'sd_admin_test.pub') - verify_ossec_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') - verify_admin_email_prompt(child) - child.sendline('[email protected]') - verify_journalist_gpg_key_prompt(child) - child.sendline('') - verify_smtp_relay_prompt(child) - child.sendline('') - verify_smtp_port_prompt(child) - child.sendline('') - verify_sasl_domain_prompt(child) - child.sendline('') - verify_sasl_username_prompt(child) - child.sendline('testuser') - verify_sasl_password_prompt(child) - child.sendline('testpassword') - verify_ssh_over_lan_prompt(child) - child.sendline('') - verify_locales_prompt(child) - child.sendline('de_DE es_ES') - verify_v2_onion_for_first_time(child) - child.sendline('\b' * 3 + 'yes') - verify_v3_onion_when_v2_is_enabled(child) - child.sendline('\b' * 3 + 'yes') - - child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur - child.close() - assert child.exitstatus == 0 - assert child.signalstatus is None - - with open(os.path.join(SD_DIR, 'install_files/ansible-base/group_vars/all/site-specific')) as fobj: # noqa: E501 - data = fobj.read() - assert data == WHEN_BOTH_TRUE - - verify_install_has_valid_config() - - -def test_sdconfig_only_v2_true(): - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) - verify_username_prompt(child) - child.sendline('') - verify_reboot_prompt(child) - child.sendline('\b5') # backspace and put 5 - verify_ipv4_appserver_prompt(child) - child.sendline('') - verify_ipv4_monserver_prompt(child) - child.sendline('') - verify_hostname_app_prompt(child) - child.sendline('') - verify_hostname_mon_prompt(child) - child.sendline('') - verify_dns_prompt(child) - child.sendline('') - verify_app_gpg_key_prompt(child) - child.sendline('\b' * 14 + 'sd_admin_test.pub') - verify_https_prompt(child) - # Default answer is no - child.sendline('') - verify_app_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') - verify_ossec_gpg_key_prompt(child) - child.sendline('\b' * 9 + 'sd_admin_test.pub') - verify_ossec_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') - verify_admin_email_prompt(child) - child.sendline('[email protected]') - verify_journalist_gpg_key_prompt(child) - child.sendline('') - verify_smtp_relay_prompt(child) - child.sendline('') - verify_smtp_port_prompt(child) - child.sendline('') - verify_sasl_domain_prompt(child) - child.sendline('') - verify_sasl_username_prompt(child) - child.sendline('testuser') - verify_sasl_password_prompt(child) - child.sendline('testpassword') - verify_ssh_over_lan_prompt(child) - child.sendline('') - verify_locales_prompt(child) - child.sendline('de_DE es_ES') - verify_v2_onion_for_first_time(child) - child.sendline('\b' * 3 + 'yes') - verify_v3_onion_when_v2_is_enabled(child) - child.sendline('\b' * 3 + 'no') - - child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur - child.close() - assert child.exitstatus == 0 - assert child.signalstatus is None - - with open(os.path.join(SD_DIR, 'install_files/ansible-base/group_vars/all/site-specific')) as fobj: # noqa: E501 - data = fobj.read() - assert data == WHEN_ONLY_V2 - - verify_install_has_valid_config() - - def test_sdconfig_enable_journalist_alerts(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') @@ -621,10 +402,6 @@ def test_sdconfig_enable_journalist_alerts(): child.sendline('') verify_locales_prompt(child) child.sendline('de_DE es_ES') - verify_v2_onion_for_first_time(child) - child.sendline('\b' * 3 + 'no') - verify_v3_onion_for_first_time(child) - child.sendline('\b' * 4 + 'yes') child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur child.close() @@ -697,10 +474,6 @@ def test_sdconfig_enable_https_on_source_interface(): child.sendline('') verify_locales_prompt(child) child.sendline('de_DE es_ES') - verify_v2_onion_for_first_time(child) - child.sendline('\b' * 3 + 'no') - verify_v3_onion_for_first_time(child) - child.sendline('\b' * 4 + 'yes') child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur child.close() diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -814,15 +814,6 @@ def verify_desc_consistency_optional(self, site_config, desc): def verify_desc_consistency(self, site_config, desc): self.verify_desc_consistency_optional(site_config, desc) - (var, default, etype, prompt, validator, transform, condition) = desc - with pytest.raises(ValidationError): - site_config.user_prompt_config_one(desc, '') - # If we are testing v3_onion_services, that will create a default - # value of 'yes', means it will not raise the ValidationError. We - # are generating it below for test to behave properly with all - # other test cases. - if var == "v3_onion_services": - raise ValidationError() def verify_prompt_boolean( self, site_config, desc): @@ -833,34 +824,6 @@ def verify_prompt_boolean( assert site_config.user_prompt_config_one(desc, 'YES') is True assert site_config.user_prompt_config_one(desc, 'NO') is False - def verify_prompt_boolean_for_v3( - self, site_config, desc): - """As v3_onion_services input depends on input of - v2_onion_service, the answers will change. - """ - self.verify_desc_consistency(site_config, desc) - (var, default, etype, prompt, validator, transform, condition) = desc - assert site_config.user_prompt_config_one(desc, True) is True - # Because if no v2_onion_service, v3 will become True - assert site_config.user_prompt_config_one(desc, False) is True - assert site_config.user_prompt_config_one(desc, 'YES') is True - # Because if no v2_onion_service, v3 will become True - assert site_config.user_prompt_config_one(desc, 'NO') is True - - # Now we will set v2_onion_services as True so that we - # can set v3_onion_service as False. This is the case - # when an admin particularly marked v3 as False. - site_config._config_in_progress = {"v2_onion_services": True} - site_config.config = {"v3_onion_services": False} - - # The next two tests should use the default from the above line, - # means it will return False value. - assert site_config.user_prompt_config_one(desc, True) is False - assert site_config.user_prompt_config_one(desc, 'YES') is False - - assert site_config.user_prompt_config_one(desc, False) is False - assert site_config.user_prompt_config_one(desc, 'NO') is False - def test_desc_conditional(self): """Ensure that conditional prompts behave correctly. @@ -915,8 +878,6 @@ def auto_prompt(prompt, default, **kwargs): verify_prompt_enable_ssh_over_tor = verify_prompt_boolean verify_prompt_securedrop_app_gpg_public_key = verify_desc_consistency - verify_prompt_v2_onion_services = verify_prompt_boolean - verify_prompt_v3_onion_services = verify_prompt_boolean_for_v3 def verify_prompt_not_empty(self, site_config, desc): with pytest.raises(ValidationError): @@ -1094,22 +1055,3 @@ def test_find_or_generate_new_torv3_keys_subsequent_run(tmpdir, capsys): v3_onion_service_keys = json.load(f) assert v3_onion_service_keys == old_keys - - -def test_v3_and_https_cert_message(tmpdir, capsys): - args = argparse.Namespace(site_config='UNKNOWN', - ansible_path='tests/files', - app_path=dirname(__file__)) - site_config = securedrop_admin.SiteConfig(args) - site_config.config = {"v3_onion_services": False, - "securedrop_app_https_certificate_cert_src": "ab.crt"} # noqa: E501 - # This should return True as v3 is not setup - assert site_config.validate_https_and_v3() - - # This should return False as v3 and https are both setup - site_config.config.update({"v3_onion_services": True}) - assert not site_config.validate_https_and_v3() - - # This should return True as https is not setup - site_config.config.update({"securedrop_app_https_certificate_cert_src": ""}) # noqa: E501 - assert site_config.validate_https_and_v3() diff --git a/install_files/ansible-base/roles/app-test/tasks/extract_apptor_test_config.yml b/install_files/ansible-base/roles/app-test/tasks/extract_apptor_test_config.yml --- a/install_files/ansible-base/roles/app-test/tasks/extract_apptor_test_config.yml +++ b/install_files/ansible-base/roles/app-test/tasks/extract_apptor_test_config.yml @@ -21,7 +21,6 @@ - name: Gather apptest facts to dict to prepare for output set_fact: _tbb_selenium_dict: - hidserv_token: "{{ ansible_local.tor_app.hidserv_token }}" journalist_location: "{{ ansible_local.tor_app.journalist_location }}" source_location: "{{ ansible_local.tor_app.source_location }}" timeout: "{{ tbb_timeout }}" diff --git a/molecule/testinfra/app/test_tor_config.py b/molecule/testinfra/app/test_tor_config.py --- a/molecule/testinfra/app/test_tor_config.py +++ b/molecule/testinfra/app/test_tor_config.py @@ -64,14 +64,11 @@ def test_tor_torrc_sandbox(host): @pytest.mark.skip_in_prod -def test_tor_v2_onion_url_readable_by_app(host): +def test_tor_v2_onion_url_file_absent(host): v2_url_filepath = "/var/lib/securedrop/source_v2_url" with host.sudo(): f = host.file(v2_url_filepath) - assert f.is_file - assert f.user == "www-data" - assert f.mode == 0o644 - assert re.search(r"^[a-z0-9]{16}\.onion$", f.content_string) + assert not f.exists @pytest.mark.skip_in_prod diff --git a/molecule/testinfra/app/test_tor_hidden_services.py b/molecule/testinfra/app/test_tor_hidden_services.py --- a/molecule/testinfra/app/test_tor_hidden_services.py +++ b/molecule/testinfra/app/test_tor_hidden_services.py @@ -26,9 +26,8 @@ def test_tor_service_directories(host, tor_service): @pytest.mark.parametrize('tor_service', sdvars.tor_services) def test_tor_service_hostnames(host, tor_service): """ - Check contents of Tor service hostname file. For normal onion services, - the file should contain only hostname (.onion URL). For authenticated - onion services, it should also contain the HidServAuth cookie. + Check contents of Tor service hostname file. For v3 onion services, + the file should contain only hostname (.onion URL). """ # Declare regex only for THS; we'll build regex for ATHS only if # necessary, since we won't have the required values otherwise. @@ -46,22 +45,13 @@ def test_tor_service_hostnames(host, tor_service): # All hostnames should contain at *least* the hostname. assert re.search(ths_hostname_regex, f.content_string) - if tor_service['authenticated'] and tor_service['version'] == 2: - # HidServAuth regex is approximately [a-zA-Z0-9/+], but validating - # the entire entry is sane, and we don't need to nitpick the - # charset. - aths_hostname_regex = ths_hostname_regex + " .{22} # client: " + \ - tor_service['client'] - assert re.search("^{}$".format(aths_hostname_regex), f.content_string) - elif tor_service['authenticated'] and tor_service['version'] == 3: + if tor_service['authenticated'] and tor_service['version'] == 3: # For authenticated version 3 onion services, the authorized_client # directory will exist and contain a file called client.auth. client_auth = host.file( "/var/lib/tor/services/{}/authorized_clients/client.auth".format( tor_service['name'])) assert client_auth.is_file - elif tor_service['version'] == 2: - assert re.search("^{}$".format(ths_hostname_regex), f.content_string) else: assert re.search("^{}$".format(ths_hostname_regex_v3), f.content_string) @@ -75,12 +65,6 @@ def test_tor_services_config(host, tor_service): * HiddenServiceDir * HiddenServicePort - - Only v2 authenticated onion services must also include: - - * HiddenServiceAuthorizeClient - - Check for each as appropriate. """ f = host.file("/etc/tor/torrc") dir_regex = "HiddenServiceDir /var/lib/tor/services/{}".format( @@ -94,29 +78,12 @@ def test_tor_services_config(host, tor_service): except IndexError: local_port = remote_port - # Ensure that service is hardcoded to v2, for compatibility - # with newer versions of Tor, which default to v3. - if tor_service['version'] == 2: - version_string = "HiddenServiceVersion 2" - else: - version_string = "" - port_regex = "HiddenServicePort {} 127.0.0.1:{}".format( remote_port, local_port) assert f.contains("^{}$".format(dir_regex)) assert f.contains("^{}$".format(port_regex)) - if version_string: - service_regex = "\n".join([dir_regex, version_string, port_regex]) - else: - service_regex = "\n".join([dir_regex, port_regex]) - - if tor_service['authenticated'] and tor_service['version'] == 2: - auth_regex = "HiddenServiceAuthorizeClient stealth {}".format( - tor_service['client']) - assert f.contains("^{}$".format(auth_regex)) - service_regex += "\n{}".format(auth_regex) - # Check for block in file, to ensure declaration order + service_regex = "\n".join([dir_regex, port_regex]) assert service_regex in f.content_string
Remove support for v2 Onion Services ## Description Tor Onion Services V2 support will be disabled in clients on October 15th 2021 [1] In https://github.com/freedomofpress/securedrop/issues/2951, we introduced support for v3 onion services, and #4768 , we on restricting the use of Onion Services to v3-only This ticket is to track the removal of all onion service v2 functionality alongside the transition to Ubuntu 20.04. [1] https://blog.torproject.org/v2-deprecation-timeline
we should probably remove outdated tor2web logic as part of this effort as it no longer seems to be maintained. @redshiftzero pays closer attention to the ongoings in torland, mind providing feedback here? Since there isn't v3 support in tor2web and it hasn't had commits in a couple years (I also couldn't find any working relays), I think it's fine to remove... if Tor2Web sees a big resurgence of use you could add it back if/when that happens
2021-04-23T16:03:27Z
[]
[]
freedomofpress/securedrop
5,926
freedomofpress__securedrop-5926
[ "5731" ]
427675858c49ef67573bb002b37fce06c029a84d
diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -4,7 +4,7 @@ from flask import Blueprint, current_app, make_response from sdconfig import SDConfig -from source_app.utils import get_sourcev2_url, get_sourcev3_url +from source_app.utils import get_sourcev3_url import server_os import version @@ -22,7 +22,6 @@ def metadata() -> flask.Response: 'sd_version': version.__version__, 'server_os': server_os.get_os_release(), 'supported_languages': config.SUPPORTED_LOCALES, - 'v2_source_url': get_sourcev2_url(), 'v3_source_url': get_sourcev3_url() } resp = make_response(json.dumps(meta)) diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -118,7 +118,7 @@ def check_url_file(path: str, regexp: str) -> 'Optional[str]': """ Check that a file exists at the path given and contains a single line matching the regexp. Used for checking the source interface address - files at /var/lib/securedrop/source_{v2,v3}_url. + files in /var/lib/securedrop (as the Apache user can't read Tor config) """ try: f = open(path, "r") @@ -132,11 +132,6 @@ def check_url_file(path: str, regexp: str) -> 'Optional[str]': return None -def get_sourcev2_url() -> 'Optional[str]': - return check_url_file("/var/lib/securedrop/source_v2_url", - r"^[a-z0-9]{16}\.onion$") - - def get_sourcev3_url() -> 'Optional[str]': return check_url_file("/var/lib/securedrop/source_v3_url", r"^[a-z0-9]{56}\.onion$")
diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -32,7 +32,7 @@ def _source_visits_source_homepage(self): def _source_checks_instance_metadata(self): self.driver.get(self.source_location + "/metadata") j = json.loads(self.driver.find_element_by_tag_name("body").text) - assert j["server_os"] in ["16.04", "20.04"] + assert j["server_os"] == "20.04" assert j["sd_version"] == self.source_app.jinja_env.globals["version"] assert j["gpg_fpr"] != "" diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -619,7 +619,7 @@ def test_why_journalist_key(source_app): def test_metadata_route(config, source_app): - with patch("server_os.get_os_release", return_value="16.04"): + with patch("server_os.get_os_release", return_value="20.04"): with source_app.test_client() as app: resp = app.get(url_for('api.metadata')) assert resp.status_code == 200 @@ -627,22 +627,9 @@ def test_metadata_route(config, source_app): assert resp.json.get('allow_document_uploads') ==\ InstanceConfig.get_current().allow_document_uploads assert resp.json.get('sd_version') == version.__version__ - assert resp.json.get('server_os') == '16.04' + assert resp.json.get('server_os') == '20.04' assert resp.json.get('supported_languages') ==\ config.SUPPORTED_LOCALES - assert resp.json.get('v2_source_url') is None - assert resp.json.get('v3_source_url') is None - - -def test_metadata_v2_url(config, source_app): - onion_test_url = "abcdabcdabcdabcd.onion" - with patch.object(source_app_api, "get_sourcev2_url") as mocked_v2_url: - mocked_v2_url.return_value = (onion_test_url) - with source_app.test_client() as app: - resp = app.get(url_for('api.metadata')) - assert resp.status_code == 200 - assert resp.headers.get('Content-Type') == 'application/json' - assert resp.json.get('v2_source_url') == onion_test_url assert resp.json.get('v3_source_url') is None @@ -654,7 +641,6 @@ def test_metadata_v3_url(config, source_app): resp = app.get(url_for('api.metadata')) assert resp.status_code == 200 assert resp.headers.get('Content-Type') == 'application/json' - assert resp.json.get('v2_source_url') is None assert resp.json.get('v3_source_url') == onion_test_url
Remove support for v2 Onion Services ## Description Tor Onion Services V2 support will be disabled in clients on October 15th 2021 [1] In https://github.com/freedomofpress/securedrop/issues/2951, we introduced support for v3 onion services, and #4768 , we on restricting the use of Onion Services to v3-only This ticket is to track the removal of all onion service v2 functionality alongside the transition to Ubuntu 20.04. [1] https://blog.torproject.org/v2-deprecation-timeline
we should probably remove outdated tor2web logic as part of this effort as it no longer seems to be maintained. @redshiftzero pays closer attention to the ongoings in torland, mind providing feedback here? Since there isn't v3 support in tor2web and it hasn't had commits in a couple years (I also couldn't find any working relays), I think it's fine to remove... if Tor2Web sees a big resurgence of use you could add it back if/when that happens
2021-05-04T22:23:54Z
[]
[]
freedomofpress/securedrop
5,932
freedomofpress__securedrop-5932
[ "5931" ]
7b75db32dcd53bc95aaf4ea8131dfa0face348e9
diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -53,7 +53,10 @@ def manage_config() -> Union[str, werkzeug.Response]: flash(gettext("Image updated."), "logo-success") except Exception: # Translators: This error is shown when an uploaded image cannot be used. - flash(gettext("Unable to process the image file. Try another one."), "logo-error") + flash( + gettext("Unable to process the image file. Please try another one."), + "logo-error" + ) finally: return redirect(url_for("admin.manage_config") + "#config-logoimage") else:
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -2025,7 +2025,7 @@ def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): ) assert page_language(resp.data) == language_tag(locale) - msgids = ["Unable to process the image file. Try another one."] + msgids = ["Unable to process the image file. Please try another one."] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed(gettext(msgids[0]), "logo-error") finally:
Be nicer to admins when an uploaded logo doesn't work. ## Description If an uploaded logo can't be processed, the [error message shown to admins](https://github.com/freedomofpress/securedrop/blob/427675858c49ef67573bb002b37fce06c029a84d/securedrop/journalist_app/admin.py#L56) is curt: "Unable to process the image file. Try another one." Let's say "Please try another one." Thanks to AO on Weblate for [pointing it out](https://weblate.securedrop.org/translate/securedrop/securedrop/en/?checksum=c2a5a60aaa227c25#comments).
2021-05-07T14:41:08Z
[]
[]
freedomofpress/securedrop
5,954
freedomofpress__securedrop-5954
[ "1584" ]
c399374333fb870a425584d3ba526b4b64469d51
diff --git a/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py b/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py @@ -0,0 +1,70 @@ +"""drop Source.flagged + +Revision ID: b060f38c0c31 +Revises: 92fba0be98e9 +Create Date: 2021-05-10 18:15:56.071880 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "b060f38c0c31" +down_revision = "92fba0be98e9" +branch_labels = None +depends_on = None + + +def upgrade(): + with op.batch_alter_table("sources", schema=None) as batch_op: + batch_op.drop_column("flagged") + + +def downgrade(): + # You might be tempted to try Alembic's batch_ops for the + # downgrade too. Don't. SQLite's unnamed check constraints require + # kludges. + + conn = op.get_bind() + conn.execute("PRAGMA legacy_alter_table=ON") + + op.rename_table("sources", "sources_tmp") + + conn.execute( + sa.text( + """ + CREATE TABLE "sources" ( + id INTEGER NOT NULL, + uuid VARCHAR(36) NOT NULL, + filesystem_id VARCHAR(96), + journalist_designation VARCHAR(255) NOT NULL, + last_updated DATETIME, + pending BOOLEAN, + interaction_count INTEGER NOT NULL, + deleted_at DATETIME, + flagged BOOLEAN, + PRIMARY KEY (id), + CHECK (pending IN (0, 1)), + CHECK (flagged IN (0, 1)), + UNIQUE (filesystem_id), + UNIQUE (uuid) + ) + """ + ) + ) + + conn.execute( + """ + INSERT INTO sources ( + id, uuid, filesystem_id, journalist_designation, + last_updated, pending, interaction_count, deleted_at + ) SELECT + id, uuid, filesystem_id, journalist_designation, + last_updated, pending, interaction_count, deleted_at + FROM sources_tmp; + """ + ) + + # Now delete the old table. + op.drop_table("sources_tmp") diff --git a/securedrop/crypto_util.py b/securedrop/crypto_util.py --- a/securedrop/crypto_util.py +++ b/securedrop/crypto_util.py @@ -219,8 +219,6 @@ def find_source_key(self, fingerprint: str) -> Optional[Dict]: def delete_reply_keypair(self, source_filesystem_id: str) -> None: fingerprint = self.get_fingerprint(source_filesystem_id) - # If this source was never flagged for review, they won't have a reply - # keypair if not fingerprint: return diff --git a/securedrop/execution.py b/securedrop/execution.py new file mode 100644 --- /dev/null +++ b/securedrop/execution.py @@ -0,0 +1,11 @@ +from threading import Thread + + +def asynchronous(f): # type: ignore + """ + Wraps a + """ + def wrapper(*args, **kwargs): # type: ignore + thread = Thread(target=f, args=args, kwargs=kwargs) + thread.start() + return wrapper diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -4,7 +4,7 @@ from journalist_app import create_app from models import Source -from source_app.utils import asynchronous +from execution import asynchronous app = create_app(config) diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -175,11 +175,7 @@ def remove_star(source_uuid: str) -> Tuple[flask.Response, int]: @api.route('/sources/<source_uuid>/flag', methods=['POST']) @token_required def flag(source_uuid: str) -> Tuple[flask.Response, int]: - source = get_or_404(Source, source_uuid, - column=Source.uuid) - source.flagged = True - db.session.commit() - return jsonify({'message': 'Source flagged for reply'}), 200 + return jsonify({'message': 'Sources no longer need to be flagged for reply'}), 200 @api.route('/sources/<source_uuid>/submissions', methods=['GET']) @token_required diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -169,13 +169,6 @@ def reply() -> werkzeug.Response: finally: return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) - @view.route('/flag', methods=('POST',)) - def flag() -> str: - g.source.flagged = True - db.session.commit() - return render_template('flag.html', filesystem_id=g.filesystem_id, - codename=g.source.journalist_designation) - @view.route('/bulk', methods=('POST',)) def bulk() -> Union[str, werkzeug.Response]: action = request.form['action'] diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -56,7 +56,6 @@ class Source(db.Model): uuid = Column(String(36), unique=True, nullable=False) filesystem_id = Column(String(96), unique=True) journalist_designation = Column(String(255), nullable=False) - flagged = Column(Boolean, default=False) last_updated = Column(DateTime) star = relationship( "SourceStar", uselist=False, backref="source" @@ -132,7 +131,7 @@ def to_json(self) -> 'Dict[str, Union[str, bool, int, str]]': 'uuid': self.uuid, 'url': url_for('api.single_source', source_uuid=self.uuid), 'journalist_designation': self.journalist_designation, - 'is_flagged': self.flagged, + 'is_flagged': False, 'is_starred': starred, 'last_updated': last_updated, 'interaction_count': self.interaction_count, diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -19,8 +19,7 @@ from sdconfig import SDConfig from source_app.decorators import login_required from source_app.utils import (logged_in, generate_unique_codename, - async_genkey, normalize_timestamps, - valid_codename, get_entropy_estimate) + normalize_timestamps, valid_codename) from source_app.forms import LoginForm, SubmissionForm @@ -137,24 +136,15 @@ def lookup() -> str: replies.sort(key=operator.attrgetter('date'), reverse=True) # Generate a keypair to encrypt replies from the journalist - # Only do this if the journalist has flagged the source as one - # that they would like to reply to. (Issue #140.) - if not current_app.crypto_util.get_fingerprint(g.filesystem_id) and \ - g.source.flagged: - db_uri = current_app.config['SQLALCHEMY_DATABASE_URI'] - async_genkey(current_app.crypto_util, - db_uri, - g.filesystem_id, - g.codename) + if not current_app.crypto_util.get_fingerprint(g.filesystem_id): + current_app.crypto_util.genkeypair(g.filesystem_id, g.codename) return render_template( 'lookup.html', allow_document_uploads=current_app.instance_config.allow_document_uploads, codename=g.codename, replies=replies, - flagged=g.source.flagged, new_user=session.get('new_user', None), - haskey=current_app.crypto_util.get_fingerprint(g.filesystem_id), form=SubmissionForm(), ) @@ -236,26 +226,11 @@ def submit() -> werkzeug.Response: db.session.add(submission) new_submissions.append(submission) - if g.source.pending: + # If necessary, generate a keypair to encrypt replies from the journalist + if g.source.pending or not current_app.crypto_util.get_fingerprint(g.filesystem_id): + current_app.crypto_util.genkeypair(g.filesystem_id, g.codename) g.source.pending = False - # Generate a keypair now, if there's enough entropy (issue #303) - # (gpg reads 300 bytes from /dev/random) - entropy_avail = get_entropy_estimate() - if entropy_avail >= 2400: - db_uri = current_app.config['SQLALCHEMY_DATABASE_URI'] - - async_genkey(current_app.crypto_util, - db_uri, - g.filesystem_id, - g.codename) - current_app.logger.info("generating key, entropy: {}".format( - entropy_avail)) - else: - current_app.logger.warning( - "skipping key generation. entropy: {}".format( - entropy_avail)) - g.source.last_updated = datetime.utcnow() db.session.commit() diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -1,18 +1,12 @@ -import io -import logging import subprocess -from datetime import datetime from flask import session, current_app, abort, g -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from threading import Thread import typing import re -from crypto_util import CryptoUtil, CryptoException +from crypto_util import CryptoException from models import Source from passphrases import PassphraseGenerator, DicewarePassphrase from sdconfig import SDConfig @@ -57,44 +51,6 @@ def generate_unique_codename(config: SDConfig) -> DicewarePassphrase: return passphrase -def get_entropy_estimate() -> int: - with io.open('/proc/sys/kernel/random/entropy_avail') as f: - return int(f.read()) - - -def asynchronous(f): # type: ignore - def wrapper(*args, **kwargs): # type: ignore - thread = Thread(target=f, args=args, kwargs=kwargs) - thread.start() - return wrapper - - -@asynchronous -def async_genkey(crypto_util_: CryptoUtil, - db_uri: str, - filesystem_id: str, - codename: DicewarePassphrase) -> None: - # We pass in the `crypto_util_` so we don't have to reference `current_app` - # here. The app might not have a pushed context during testing which would - # cause this asynchronous function to break. - crypto_util_.genkeypair(filesystem_id, codename) - - # Register key generation as update to the source, so sources will - # filter to the top of the list in the journalist interface if a - # flagged source logs in and has a key generated for them. #789 - session = sessionmaker(bind=create_engine(db_uri))() - try: - source = session.query(Source).filter( - Source.filesystem_id == filesystem_id).one() - source.last_updated = datetime.utcnow() - session.commit() - except Exception as e: - logging.getLogger(__name__).error( - "async_genkey for source (filesystem_id={}): {}" - .format(filesystem_id, e)) - session.close() - - def normalize_timestamps(filesystem_id: str) -> None: """ Update the timestamps on all of the source's submissions. This
diff --git a/molecule/testinfra/app-code/test_haveged.py b/molecule/testinfra/app-code/test_haveged.py deleted file mode 100644 --- a/molecule/testinfra/app-code/test_haveged.py +++ /dev/null @@ -1,40 +0,0 @@ -import testutils - -sdvars = testutils.securedrop_test_vars -testinfra_hosts = [sdvars.app_hostname] - - -def test_haveged_config(host): - """ - Ensure haveged's low entrop watermark is sufficiently high. - """ - f = host.file('/etc/default/haveged') - assert f.is_file - assert f.user == 'root' - assert f.group == 'root' - assert f.mode == 0o644 - assert f.contains('^DAEMON_ARGS="-w 2400"$') - - -def test_haveged_no_duplicate_lines(host): - """ - Regression test to check for duplicate entries. Earlier playbooks - for configuring the SD instances needlessly appended the `DAEMON_ARGS` - line everytime the playbook was run. Fortunately the duplicate lines don't - break the service, but it's still poor form. - """ - c = host.run("uniq --repeated /etc/default/haveged") - assert c.rc == 0 - assert c.stdout == "" - - -def test_haveged_is_running(host): - """ - Ensure haveged service is running, to provide additional entropy. - """ - # sudo is necessary to read /proc when running under grsecurity, - # which the App hosts do. Not technically necessary under development. - with host.sudo(): - s = host.service("haveged") - assert s.is_running - assert s.is_enabled diff --git a/molecule/testinfra/app-code/test_securedrop_app_code.py b/molecule/testinfra/app-code/test_securedrop_app_code.py --- a/molecule/testinfra/app-code/test_securedrop_app_code.py +++ b/molecule/testinfra/app-code/test_securedrop_app_code.py @@ -22,7 +22,6 @@ def test_apache_default_docroot_is_absent(host): 'apparmor-utils', 'coreutils', 'gnupg2', - 'haveged', 'libapache2-mod-xsendfile', 'libpython{}'.format(python_version), 'paxctld', @@ -41,6 +40,22 @@ def test_securedrop_application_apt_dependencies(host, package): assert host.package(package).is_installed [email protected]('package', [ + 'cron-apt', + 'haveged', + 'libapache2-mod-wsgi', + 'ntp', + 'ntpdate', + 'supervisor' +]) +def test_unwanted_packages_absent(host, package): + """ + Ensure packages that conflict with `securedrop-app-code` + or are otherwise unwanted are not present. + """ + assert not host.package(package).is_installed + + @pytest.mark.skip_in_prod def test_securedrop_application_test_locale(host): """ diff --git a/securedrop/tests/functional/functional_test.py b/securedrop/tests/functional/functional_test.py --- a/securedrop/tests/functional/functional_test.py +++ b/securedrop/tests/functional/functional_test.py @@ -207,87 +207,84 @@ def sd_servers(self): # Patch the two-factor verification to avoid intermittent errors logging.info("Mocking models.Journalist.verify_token") with mock.patch("models.Journalist.verify_token", return_value=True): - logging.info("Mocking source_app.main.get_entropy_estimate") - with mock.patch("source_app.main.get_entropy_estimate", return_value=8192): - - try: - signal.signal(signal.SIGUSR1, lambda _, s: traceback.print_stack(s)) + try: + signal.signal(signal.SIGUSR1, lambda _, s: traceback.print_stack(s)) - source_port = self._unused_port() - journalist_port = self._unused_port() + source_port = self._unused_port() + journalist_port = self._unused_port() - self.source_location = "http://127.0.0.1:%d" % source_port - self.journalist_location = "http://127.0.0.1:%d" % journalist_port + self.source_location = "http://127.0.0.1:%d" % source_port + self.journalist_location = "http://127.0.0.1:%d" % journalist_port - self.source_app = source_app.create_app(config) - self.journalist_app = journalist_app.create_app(config) - self.journalist_app.config["WTF_CSRF_ENABLED"] = True + self.source_app = source_app.create_app(config) + self.journalist_app = journalist_app.create_app(config) + self.journalist_app.config["WTF_CSRF_ENABLED"] = True - self.__context = self.journalist_app.app_context() - self.__context.push() + self.__context = self.journalist_app.app_context() + self.__context.push() - env.create_directories() - db.create_all() - self.gpg = env.init_gpg() + env.create_directories() + db.create_all() + self.gpg = env.init_gpg() - # Add our test user - try: - valid_password = "correct horse battery staple profanity oil chewy" - user = Journalist( - username="journalist", password=valid_password, is_admin=True - ) - user.otp_secret = "JHCOGO7VCER3EJ4L" - db.session.add(user) - db.session.commit() - except IntegrityError: - logging.error("Test user already added") - db.session.rollback() - - # This user is required for our tests cases to login - self.admin_user = { - "name": "journalist", - "password": ("correct horse battery staple" " profanity oil chewy"), - "secret": "JHCOGO7VCER3EJ4L", - } - - self.admin_user["totp"] = pyotp.TOTP(self.admin_user["secret"]) - - def start_journalist_server(app): - app.run(port=journalist_port, debug=True, use_reloader=False, threaded=True) - - self.source_process = Process( - target=lambda: self.start_source_server(source_port) + # Add our test user + try: + valid_password = "correct horse battery staple profanity oil chewy" + user = Journalist( + username="journalist", password=valid_password, is_admin=True ) + user.otp_secret = "JHCOGO7VCER3EJ4L" + db.session.add(user) + db.session.commit() + except IntegrityError: + logging.error("Test user already added") + db.session.rollback() + + # This user is required for our tests cases to login + self.admin_user = { + "name": "journalist", + "password": ("correct horse battery staple" " profanity oil chewy"), + "secret": "JHCOGO7VCER3EJ4L", + } + + self.admin_user["totp"] = pyotp.TOTP(self.admin_user["secret"]) + + def start_journalist_server(app): + app.run(port=journalist_port, debug=True, use_reloader=False, threaded=True) + + self.source_process = Process( + target=lambda: self.start_source_server(source_port) + ) - self.journalist_process = Process( - target=lambda: start_journalist_server(self.journalist_app) - ) + self.journalist_process = Process( + target=lambda: start_journalist_server(self.journalist_app) + ) - self.source_process.start() - self.journalist_process.start() - - for tick in range(30): - try: - requests.get(self.source_location, timeout=1) - requests.get(self.journalist_location, timeout=1) - except Exception: - time.sleep(0.25) - else: - break - yield - finally: - try: - self.source_process.terminate() - except Exception as e: - logging.error("Error stopping source app: %s", e) + self.source_process.start() + self.journalist_process.start() + for tick in range(30): try: - self.journalist_process.terminate() - except Exception as e: - logging.error("Error stopping source app: %s", e) + requests.get(self.source_location, timeout=1) + requests.get(self.journalist_location, timeout=1) + except Exception: + time.sleep(0.25) + else: + break + yield + finally: + try: + self.source_process.terminate() + except Exception as e: + logging.error("Error stopping source app: %s", e) + + try: + self.journalist_process.terminate() + except Exception as e: + logging.error("Error stopping source app: %s", e) - env.teardown() - self.__context.pop() + env.teardown() + self.__context.pop() def wait_for_source_key(self, source_name): filesystem_id = self.source_app.crypto_util.hash_codename(source_name) diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -1065,9 +1065,6 @@ def _journalist_delete_one(self): el.location_once_scrolled_into_view ActionChains(self.driver).move_to_element(el).click().perform() - def _journalist_flags_source(self): - self.safe_click_by_id("flag-button") - def _journalist_visits_admin(self): self.driver.get(self.journalist_location + "/admin") diff --git a/securedrop/tests/i18n/securedrop/translations/de_DE/LC_MESSAGES/messages.po b/securedrop/tests/i18n/securedrop/translations/de_DE/LC_MESSAGES/messages.po --- a/securedrop/tests/i18n/securedrop/translations/de_DE/LC_MESSAGES/messages.po +++ b/securedrop/tests/i18n/securedrop/translations/de_DE/LC_MESSAGES/messages.po @@ -501,10 +501,6 @@ msgstr "" "Sie können der Person, die diese Dokumente eingereicht hat, eine sichere " "Antwort schreiben:" -#: journalist_templates/col.html:86 -msgid "You've flagged this source for reply." -msgstr "Sie haben diese Quelle für eine Antwort markiert." - #: journalist_templates/col.html:87 msgid "" "An encryption key will be generated for the source the next time they log " diff --git a/securedrop/tests/i18n/securedrop/translations/nl/LC_MESSAGES/messages.po b/securedrop/tests/i18n/securedrop/translations/nl/LC_MESSAGES/messages.po --- a/securedrop/tests/i18n/securedrop/translations/nl/LC_MESSAGES/messages.po +++ b/securedrop/tests/i18n/securedrop/translations/nl/LC_MESSAGES/messages.po @@ -495,10 +495,6 @@ msgid "" msgstr "" "U kunt beveiligd reageren naar de persoon die deze documenten gestuurd heeft:" -#: journalist_templates/col.html:86 -msgid "You've flagged this source for reply." -msgstr "U heeft deze bron gemarkeerd om te reageren." - #: journalist_templates/col.html:87 msgid "" "An encryption key will be generated for the source the next time they log " diff --git a/securedrop/tests/migrations/migration_b060f38c0c31.py b/securedrop/tests/migrations/migration_b060f38c0c31.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_b060f38c0c31.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- + +import random +import uuid +from typing import Any, Dict + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import OperationalError + +from db import db +from journalist_app import create_app +from .helpers import random_chars, random_datetime, bool_or_none + +random.seed("ᕕ( ᐛ )ᕗ") + + +def add_submission(source_id): + params = { + "uuid": str(uuid.uuid4()), + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "downloaded": bool_or_none(), + "checksum": random_chars(255, chars="0123456789abcdef") + } + sql = """ + INSERT INTO submissions (uuid, source_id, filename, size, downloaded, checksum) + VALUES (:uuid, :source_id, :filename, :size, :downloaded, :checksum) + """ + db.engine.execute(text(sql), **params) + + +class UpgradeTester: + """ + Verify that the Source.flagged column no longer exists. + """ + + source_count = 10 + original_sources = {} # type: Dict[str, Any] + source_submissions = {} # type: Dict[str, Any] + + def __init__(self, config): + self.config = config + self.app = create_app(config) + + def load_data(self): + with self.app.app_context(): + for i in range(self.source_count): + self.add_source() + + self.original_sources = { + s.uuid: s for s in db.engine.execute(text("SELECT * FROM sources")).fetchall() + } + + for s in self.original_sources.values(): + for i in range(random.randint(0, 3)): + add_submission(s.id) + + self.source_submissions[s.id] = db.engine.execute( + text("SELECT * FROM submissions WHERE source_id = :source_id"), + **{"source_id": s.id} + ).fetchall() + + def add_source(self): + params = { + "uuid": str(uuid.uuid4()), + "filesystem_id": random_chars(96), + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), + } + sql = """ + INSERT INTO sources (uuid, filesystem_id, + journalist_designation, flagged, last_updated, pending, + interaction_count) + VALUES (:uuid, :filesystem_id, :journalist_designation, + :flagged, :last_updated, :pending, :interaction_count) + """ + + db.engine.execute(text(sql), **params) + + def check_upgrade(self): + with self.app.app_context(): + + # check that the flagged column is gone + with pytest.raises(OperationalError, match=".*sources has no column named flagged.*"): + self.add_source() + + # check that the sources are otherwise unchanged + sources = db.engine.execute(text("SELECT * FROM sources")).fetchall() + assert len(sources) == len(self.original_sources) + for source in sources: + assert not hasattr(source, "flagged") + original_source = self.original_sources[source.uuid] + assert source.id == original_source.id + assert source.journalist_designation == original_source.journalist_designation + assert source.last_updated == original_source.last_updated + assert source.pending == original_source.pending + assert source.interaction_count == original_source.interaction_count + + source_submissions = db.engine.execute( + text("SELECT * FROM submissions WHERE source_id = :source_id"), + **{"source_id": source.id} + ).fetchall() + assert source_submissions == self.source_submissions[source.id] + + +class DowngradeTester: + """ + Verify that the Source.flagged column has been recreated properly. + """ + + source_count = 10 + original_sources = {} # type: Dict[str, Any] + source_submissions = {} # type: Dict[str, Any] + + def __init__(self, config): + self.config = config + self.app = create_app(config) + + def add_source(self): + params = { + "uuid": str(uuid.uuid4()), + "filesystem_id": random_chars(96), + "journalist_designation": random_chars(50), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), + "deleted_at": None, + } + sql = """ + INSERT INTO sources ( + uuid, filesystem_id, journalist_designation, last_updated, pending, + interaction_count + ) VALUES ( + :uuid, :filesystem_id, :journalist_designation, :last_updated, :pending, + :interaction_count + ) + """ + + db.engine.execute(text(sql), **params) + + def load_data(self): + with self.app.app_context(): + for i in range(self.source_count): + self.add_source() + + self.original_sources = { + s.uuid: s for s in db.engine.execute(text("SELECT * FROM sources")).fetchall() + } + + for s in self.original_sources.values(): + for i in range(random.randint(0, 3)): + add_submission(s.id) + + self.source_submissions[s.id] = db.engine.execute( + text("SELECT * FROM submissions WHERE source_id = :source_id"), + **{"source_id": s.id} + ).fetchall() + + def check_downgrade(self): + with self.app.app_context(): + # check that the sources are otherwise unchanged + sources = db.engine.execute(text("SELECT * FROM sources")).fetchall() + assert len(sources) == len(self.original_sources) + for source in sources: + assert hasattr(source, "flagged") + original_source = self.original_sources[source.uuid] + assert source.id == original_source.id + assert source.journalist_designation == original_source.journalist_designation + assert source.last_updated == original_source.last_updated + assert source.pending == original_source.pending + assert source.interaction_count == original_source.interaction_count + assert not hasattr(original_source, "flagged") + assert source.flagged is None + + source_submissions = db.engine.execute( + text("SELECT * FROM submissions WHERE source_id = :source_id"), + **{"source_id": source.id} + ).fetchall() + assert source_submissions == self.source_submissions[source.id] diff --git a/securedrop/tests/pageslayout/test_journalist.py b/securedrop/tests/pageslayout/test_journalist.py --- a/securedrop/tests/pageslayout/test_journalist.py +++ b/securedrop/tests/pageslayout/test_journalist.py @@ -135,19 +135,6 @@ def test_col_has_no_key(self): self._journalist_visits_col() self._screenshot('journalist-col_has_no_key.png') - def test_col_flagged(self): - self._source_visits_source_homepage() - self._source_chooses_to_submit_documents() - self._source_continues_to_submit_page() - self._source_submits_a_file() - self._source_logs_out() - self._journalist_logs_in() - self._source_delete_key() - self._journalist_visits_col() - self._journalist_flags_source() - self._journalist_continues_after_flagging() - self._screenshot('journalist-col_flagged.png') - def test_col(self): self._source_visits_source_homepage() self._source_chooses_to_submit_documents() @@ -274,18 +261,6 @@ def test_admin_interface_index(self): self._admin_visits_admin_interface() self._screenshot('journalist-admin_interface_index.png') - def test_flag(self): - self._source_visits_source_homepage() - self._source_chooses_to_submit_documents() - self._source_continues_to_submit_page() - self._source_submits_a_file() - self._source_logs_out() - self._journalist_logs_in() - self._source_delete_key() - self._journalist_visits_col() - self._journalist_flags_source() - self._screenshot('journalist-flag.png') - def test_index_no_documents(self): self._journalist_logs_in() self._screenshot('journalist-index_no_documents.png') diff --git a/securedrop/tests/pageslayout/test_source.py b/securedrop/tests/pageslayout/test_source.py --- a/securedrop/tests/pageslayout/test_source.py +++ b/securedrop/tests/pageslayout/test_source.py @@ -94,21 +94,6 @@ def test_source_checks_for_reply(self): self._source_deletes_a_journalist_reply() self._screenshot('source-deletes_reply.png') - def test_source_flagged(self): - self._source_visits_source_homepage() - self._source_chooses_to_submit_documents() - self._source_continues_to_submit_page() - self._source_submits_a_file() - self._source_logs_out() - self._journalist_logs_in() - self._source_delete_key() - self._journalist_visits_col() - self._journalist_flags_source() - self._source_visits_source_homepage() - self._source_chooses_to_login() - self._source_proceeds_to_login() - self._screenshot('source-flagged.png') - def test_notfound(self): self._source_not_found() self._screenshot('source-notfound.png') diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -10,8 +10,6 @@ from distutils.version import StrictVersion from io import BytesIO -import mock -import pytest from bs4 import BeautifulSoup from flask import current_app, escape, g, session from pyotp import HOTP, TOTP @@ -27,18 +25,6 @@ random.seed('ಠ_ಠ') [email protected](autouse=True, scope="module") -def patch_get_entropy_estimate(): - mock_get_entropy_estimate = mock.patch( - "source_app.main.get_entropy_estimate", - return_value=8192 - ).start() - - yield - - mock_get_entropy_estimate.stop() - - def _login_user(app, user_dict): resp = app.post('/login', data={'username': user_dict['username'], @@ -266,7 +252,6 @@ def _helper_test_reply(journalist_app, source_app, config, test_journo, fh=(BytesIO(b''), ''), ), follow_redirects=True) assert resp.status_code == 200 - assert not g.source.flagged app.get('/logout') with journalist_app.test_client() as app: @@ -281,31 +266,7 @@ def _helper_test_reply(journalist_app, source_app, config, test_journo, resp = app.get(col_url) assert resp.status_code == 200 - with source_app.test_client() as app: - resp = app.post('/login', data=dict( - codename=codename), follow_redirects=True) - assert resp.status_code == 200 - assert not g.source.flagged - app.get('/logout') - - with journalist_app.test_client() as app: - _login_user(app, test_journo) - resp = app.post('/flag', data=dict( - filesystem_id=filesystem_id)) - assert resp.status_code == 200 - - with source_app.test_client() as app: - resp = app.post('/login', data=dict( - codename=codename), follow_redirects=True) - assert resp.status_code == 200 - app.get('/lookup') - assert g.source.flagged - app.get('/logout') - - # Block up to 15s for the reply keypair, so we can test sending a reply - def assertion(): - assert current_app.crypto_util.get_fingerprint(filesystem_id) is not None - utils.asynchronous.wait_for_assertion(assertion, 15) + assert current_app.crypto_util.get_fingerprint(filesystem_id) is not None # Create 2 replies to test deleting on journalist and source interface with journalist_app.test_client() as app: @@ -472,7 +433,6 @@ def test_unicode_reply_with_ansi_env(journalist_app, def test_delete_collection(mocker, source_app, journalist_app, test_journo): """Test the "delete collection" button on each collection page""" - async_genkey = mocker.patch('source_app.main.async_genkey') # first, add a source with source_app.test_client() as app: @@ -510,7 +470,6 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): "The account and data for the source {} have been deleted.".format(col_name)) in text assert "No documents have been submitted!" in text - assert async_genkey.called # Make sure the collection is deleted from the filesystem def assertion(): @@ -522,7 +481,6 @@ def assertion(): def test_delete_collections(mocker, journalist_app, source_app, test_journo): """Test the "delete selected" checkboxes on the index page that can be used to delete multiple collections""" - async_genkey = mocker.patch('source_app.main.async_genkey') # first, add some sources with source_app.test_client() as app: @@ -552,7 +510,6 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): assert resp.status_code == 200 text = resp.data.decode('utf-8') assert "The accounts and all data for {} sources".format(num_sources) in text - assert async_genkey.called # simulate the source_deleter's work journalist_app_module.utils.purge_deleted_sources() diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -300,20 +300,6 @@ def test_get_non_existant_source_404s(journalist_app, journalist_api_token): assert response.status_code == 404 -def test_authorized_user_can_flag_a_source(journalist_app, test_source, - journalist_api_token): - with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - source_id = test_source['source'].id - response = app.post(url_for('api.flag', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) - - assert response.status_code == 200 - - # Verify that the source was flagged. - assert Source.query.get(source_id).flagged - - def test_authorized_user_can_star_a_source(journalist_app, test_source, journalist_api_token): with journalist_app.test_client() as app: diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -442,40 +442,6 @@ def test_submit_both(source_app): assert "Thanks! We received your message and document" in text -def test_submit_message_with_low_entropy(source_app): - with patch.object(source_app_main, 'async_genkey') as async_genkey: - with patch.object(source_app_main, 'get_entropy_estimate') \ - as get_entropy_estimate: - get_entropy_estimate.return_value = 300 - - with source_app.test_client() as app: - new_codename(app, session) - _dummy_submission(app) - resp = app.post( - url_for('main.submit'), - data=dict(msg="This is a test.", fh=(StringIO(''), '')), - follow_redirects=True) - assert resp.status_code == 200 - assert not async_genkey.called - - -def test_submit_message_with_enough_entropy(source_app): - with patch.object(source_app_main, 'async_genkey') as async_genkey: - with patch.object(source_app_main, 'get_entropy_estimate') \ - as get_entropy_estimate: - get_entropy_estimate.return_value = 2400 - - with source_app.test_client() as app: - new_codename(app, session) - _dummy_submission(app) - resp = app.post( - url_for('main.submit'), - data=dict(msg="This is a test.", fh=(StringIO(''), '')), - follow_redirects=True) - assert resp.status_code == 200 - assert async_genkey.called - - def test_delete_all_successfully_deletes_replies(source_app): with source_app.app_context(): journalist, _ = utils.db_helper.init_journalist() @@ -732,26 +698,25 @@ def test_failed_normalize_timestamps_logs_warning(source_app): still occur, but a warning should be logged (this will trigger an OSSEC alert).""" - with patch("source_app.main.get_entropy_estimate", return_value=8192): - with patch.object(source_app.logger, 'warning') as logger: - with patch.object(subprocess, 'call', return_value=1): - with source_app.test_client() as app: - new_codename(app, session) - _dummy_submission(app) - resp = app.post( - url_for('main.submit'), - data=dict( - msg="This is a test.", - fh=(StringIO(''), '')), - follow_redirects=True) - assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "Thanks! We received your message" in text - - logger.assert_called_once_with( - "Couldn't normalize submission " - "timestamps (touch exited with 1)" - ) + with patch.object(source_app.logger, 'warning') as logger: + with patch.object(subprocess, 'call', return_value=1): + with source_app.test_client() as app: + new_codename(app, session) + _dummy_submission(app) + resp = app.post( + url_for('main.submit'), + data=dict( + msg="This is a test.", + fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Thanks! We received your message" in text + + logger.assert_called_once_with( + "Couldn't normalize submission " + "timestamps (touch exited with 1)" + ) def test_source_is_deleted_while_logged_in(source_app):
Get rid of entropy checks In `source.py`, we [check](https://github.com/freedomofpress/securedrop/blob/46a948ebadfb9b14bb7e902eff9f2be3f0e91fac/securedrop/source.py#L322-L326) for "available entropy" before generating a key. This is done because GPG blocks on "sufficient entropy" from `/dev/random` to generate a GPG key, and we don't want to block returning the HTTP response. After discussing this with some more-knowledgeable security folks, a couple of things have come to my attention: * libgcrypt has apparently improved their DRBG code since I last investigated this issue. It now appears to allow the use of `urandom` (although this may require some configuration, and it's not clear to me how/when this is done), will use `getrandom` if it's available, etc. * libgcrypt has relaxed the formerly stringent checks to use `/dev/random` _and only_ `/dev/random`. So if we can't configure libgcrypt to use a non-blocking CSPRNG, we may now be able to trick it by symlinking `urandom`, or using `mknod`, etc. Making this change could have a variety of potential benefits: * Reduce code complexity and potential for bugs from `async_genkey` and the test helpers that wait for key generation. * Eliminate "intermittent test errors" due to `async_genkey` (#844) * Improve performance of tests that generate crypto keys However, we may need to use a more recent version of GPG/libgcrypt to take advantage of these recent improvements. This might require upgrading our entire stack from Ubuntu 14.04LTS - a change that we want to make anyway, but one that is non-trivial.
For the record * https://www.2uo.de/myths-about-urandom/ * https://github.com/freedomofpress/securedrop/pull/2583 According to [this upstream ticket](https://dev.gnupg.org/T3894) libgcrypt 1.8 and above will use `getrandom()` if it's available, but unfortunately @emkll found that [xenial is using libgcrypt 1.6](https://packages.ubuntu.com/search?keywords=libgcrypt&searchon=names&suite=xenial&section=all). However another option would be to use the `only-urandom` gcrypt config option. From [the docs](https://gnupg.org/documentation/manuals/gcrypt/Configuration.html) this option will: > Always use the non-blocking /dev/urandom or the respective system call instead of the blocking /dev/random. If Libgcrypt is used early in the boot process of the system, this option should only be used if the system also supports the getrandom system call. Since we're not generating source keys early in the boot process, this might be sufficient - if we want consider this path, we should next determine how long it takes for the entropy pool to be initialized. For the 6/12-6/26 sprint, we've committed to at least an 8 hour time-boxed investigation to determine whether removal of these checks is feasible (this may include some external outreach to security experts). Since removing the checks would obviate the need for the "Flag for reply" workflow, it would not only make journalists' lives easier, but also save quite a bit of time in client development (https://github.com/freedomofpress/securedrop-client/issues/247). > if it's available, but unfortunately @emkll found that xenial is using libgcrypt 1.6. Self-hosting that package is not on the table, so if that's the only solution we'll have to wait until all prod instances have migrated to Bionic before we can potentially fully remove entropy checks (with perhaps a transitional stage where Xenial/Bionic behavior will differ). > However another option would be to use the only-urandom gcrypt config option. @redshiftzero has committed to do a quick investigation during the 10/23-11/6 sprint into whether this or another workaround might indeed do the trick. Above I mentioned the possibility of using the `only_urandom` option (see the relevant discussion of this option [here](https://dev.gnupg.org/T3894#112928)). This option will use `getrandom()` if it is supported instead of `/dev/urandom` directly. We _are_ using a version of the kernel that supports the `getrandom()` syscall. This is what we want as it will block shortly after boot if the RNG is not yet seeded. Otherwise once `/dev/urandom` is seeded, it will return high quality randomness from `/dev/urandom` indefinitely ([here's a nice talk about `/dev/urandom` useful for application developers (PDF)](https://speakerd.s3.amazonaws.com/presentations/81e3194277914b21b7bc92425975ee9c/Entropy_32c3_16-9.pdf)). We should be able to use this config option and remove both the flag for reply and entropy check logic, but I think we'll want to keep the async key generation. Concretely I think we should: 0. Use the `only_urandom` configuration option. When we move to bionic, we'll land on the version of libgcrypt that uses the new `getrandom` syscall for key generation by default (using [this patch](https://dev.gnupg.org/rC7e662680c170968661ee0105d132813f8281d229)). At this time we no longer will need to set `only_urandom`. 1. Continue to generate keys asynchronously unless testing shows that key generation is _significantly_ faster. As seen by the plot below, currently key generation is not snappy enough to do synchronously (note that this was generated using `libgcrypt` out of the box, i.e. reading 300 bytes from `/dev/random`. It's worth checking again with the `only_urandom` option turned on but I didn't get a chance to do this): ![keygen](https://user-images.githubusercontent.com/7832803/71858879-d3948e00-30ba-11ea-9f17-06464e1e2c12.png) 2. Remove the entropy checks and the flag for reply flow. We can release v2 of the API without the flag API endpoint, we remove the corresponding flag view functions, and the `flagged` column in the `sources` table in the database. At this time, we should remove `haveged` also as we will be using `/dev/urandom` on modern Linux and as such it is not necessary (and may even [reduce security](https://blog.cr.yp.to/20140205-entropy.html)). 3. We will continue to need to handle the case in the UI where the source has submitted something but does not yet have a key. This can happen in cases even without the entropy checking logic, for example if the system is rebooted shortly right after a source submits and key generation has not completed yet. 4. When a source user signs back in, the logic will be much simpler: we check if they have a key, and if not, we attempt to generate their key again. This is the only time we can do the key generation since we require the user's codename for key generation, which we do not persistently store anywhere. Thanks for the summary, @redshiftzero! Aside from the reboot scenario your mention, did your investigation shed light on how likely key generation is to be skipped (the check in https://github.com/freedomofpress/securedrop/blob/develop/securedrop/source_app/main.py#L221-L234) on typical prod systems, in a denial of service attack or high traffic scenario? > When a source user signs back in, the logic will be much simpler: we check if they have a key, and if not, we attempt to generate their key again. This is the only time we can do the key generation since we require the user's codename for key generation, which we do not persistently store anywhere. Just leaving a note here that we should probably keep some version of the "Sorry we haven't responded yet" message in the UI, to make it clear to the source that the lack of response from the news org is not due to lack of interest. This could be a nice stretch goal for 2.0.0, tentatively adding to milestone. @rmol has committed to taking a stab at this during the 5/5-5/19 sprint, focusing on following up on Jen's earlier investigation and potentially removing the "Flag for reply" workflow.
2021-05-19T15:43:03Z
[]
[]
freedomofpress/securedrop
5,958
freedomofpress__securedrop-5958
[ "5933", "6070" ]
8fa4a1de30596fc91ae88af0fe0274a7e6fe04f9
diff --git a/securedrop/alembic/env.py b/securedrop/alembic/env.py --- a/securedrop/alembic/env.py +++ b/securedrop/alembic/env.py @@ -47,7 +47,7 @@ def run_migrations_offline(): """ url = config.get_main_option("sqlalchemy.url") context.configure( - url=url, target_metadata=target_metadata, literal_binds=True) + url=url, target_metadata=target_metadata, compare_type=True, literal_binds=True) with context.begin_transaction(): context.run_migrations() @@ -69,6 +69,7 @@ def run_migrations_online(): context.configure( connection=connection, target_metadata=target_metadata, + compare_type=True, render_as_batch=True ) diff --git a/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py b/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py @@ -0,0 +1,38 @@ +"""Updates journalists.otp_secret length from 16 to 32 + +Revision ID: de00920916bf +Revises: 1ddb81fb88c2 +Create Date: 2021-05-21 15:51:39.202368 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'de00920916bf' +down_revision = '1ddb81fb88c2' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('journalists', schema=None) as batch_op: + batch_op.alter_column('otp_secret', + existing_type=sa.VARCHAR(length=16), + type_=sa.String(length=32), + existing_nullable=True) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('journalists', schema=None) as batch_op: + batch_op.alter_column('otp_secret', + existing_type=sa.String(length=32), + type_=sa.VARCHAR(length=16), + existing_nullable=True) + + # ### end Alembic commands ### diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -27,7 +27,7 @@ from typing import Callable, Optional, Union, Dict, List, Any from logging import Logger -from pyotp import OTP +from pyotp import TOTP, HOTP LOGIN_HARDENING = True @@ -404,7 +404,7 @@ class Journalist(db.Model): is_admin = Column(Boolean) # type: Column[Optional[bool]] session_nonce = Column(Integer, nullable=False, default=0) - otp_secret = Column(String(16), default=pyotp.random_base32) + otp_secret = Column(String(32), default=pyotp.random_base32) is_totp = Column(Boolean, default=True) # type: Column[Optional[bool]] hotp_counter = Column(Integer, default=0) # type: Column[Optional[int]] last_token = Column(String(6)) @@ -556,6 +556,9 @@ def valid_password(self, passphrase: 'Optional[str]') -> bool: "Should never happen: pw_salt is none for legacy Journalist {}".format(self.id) ) + # For type checking + assert isinstance(self.pw_hash, bytes) + is_valid = pyotp.utils.compare_digest( self._scrypt_hash(passphrase, self.pw_salt), self.pw_hash) @@ -584,14 +587,14 @@ def set_hotp_secret(self, otp_secret: str) -> None: self.hotp_counter = 0 @property - def totp(self) -> 'OTP': + def totp(self) -> 'TOTP': if self.is_totp: return pyotp.TOTP(self.otp_secret) else: raise ValueError('{} is not using TOTP'.format(self)) @property - def hotp(self) -> 'OTP': + def hotp(self) -> 'HOTP': if not self.is_totp: return pyotp.HOTP(self.otp_secret) else: @@ -698,6 +701,8 @@ def login(cls, # Prevent TOTP token reuse if user.last_token is not None: + # For type checking + assert isinstance(token, str) if pyotp.utils.compare_digest(token, user.last_token): raise BadTokenException("previously used two-factor code " "{}".format(token))
diff --git a/securedrop/tests/migrations/migration_de00920916bf.py b/securedrop/tests/migrations/migration_de00920916bf.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_de00920916bf.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +import random +import uuid + +from sqlalchemy import text + +from db import db +from journalist_app import create_app +from .helpers import random_chars + +random.seed('くコ:彡') + + +class Helper: + + def __init__(self): + self.journalist_id = None + + def create_journalist(self, otp_secret="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"): + if self.journalist_id is not None: + raise RuntimeError('Journalist already created') + + params = { + 'uuid': str(uuid.uuid4()), + 'username': random_chars(50), + 'session_nonce': 0, + 'otp_secret': otp_secret + } + sql = '''INSERT INTO journalists (uuid, username, otp_secret, session_nonce) + VALUES (:uuid, :username, :otp_secret, :session_nonce) + ''' + self.journalist_id = db.engine.execute(text(sql), **params).lastrowid + + +class UpgradeTester(Helper): + """ + Checks schema to verify that the otp_secret varchar "length" has been updated. + Varchar specified length isn't enforced by sqlite but it's good to verify that + the migration worked as expected. + """ + + def __init__(self, config): + Helper.__init__(self) + self.config = config + self.app = create_app(config) + + def load_data(self): + with self.app.app_context(): + self.create_journalist() + + def check_upgrade(self): + with self.app.app_context(): + journalists_sql = "SELECT * FROM journalists" + journalist = db.engine.execute(text(journalists_sql)).first() + assert len(journalist['otp_secret']) == 32 # Varchar ignores length + + +class DowngradeTester(Helper): + + def __init__(self, config): + Helper.__init__(self) + self.config = config + self.app = create_app(config) + + def load_data(self): + with self.app.app_context(): + self.create_journalist() + + def check_downgrade(self): + with self.app.app_context(): + journalists_sql = "SELECT * FROM journalists" + journalist = db.engine.execute(text(journalists_sql)).first() + assert len(journalist['otp_secret']) == 32 # Varchar ignores length
Bump 2FA secret bit length from 80 bits to 160bits as recommended by RFC4226 While evaluating a patch for https://github.com/freedomofpress/securedrop/issues/5613 i noticed that pyotp seems to be still generating secrets of 80 bits length that is actually discouraged by [RFC4226](https://tools.ietf.org/html/rfc4226): ```R6 - The algorithm MUST use a strong shared secret. The length of the shared secret MUST be at least 128 bits. This document RECOMMENDs a shared secret length of 160 bits.``` The easily improve this I suggest we could just replace any call to pyotp.random_base32() in https://github.com/freedomofpress/securedrop/blob/fd2f5f86432005bdfc3c59119da98e442b7e4475/securedrop/models.py with a call to a simple function: ```python def generate_otp_secret(): return base64.b32encode(os.urandom(20)) ``` Debian Buster is now oldstable ## Description `apt update` on Debian Buster will now fail as it is now `oldstable`. We will have to explicitly approve update commands. I first noticed this on: https://app.circleci.com/pipelines/github/freedomofpress/securedrop/2847/workflows/cccc1ea9-3514-4138-a085-5074f12d3322/jobs/56132 ## Steps to Reproduce - [ ] `suod apt update` ## Expected Behavior - Update should finish normally ## Actual Behavior ``` Get:1 http://deb.debian.org/debian buster InRelease [122 kB] Get:2 http://security.debian.org/debian-security buster/updates InRelease [65.4 kB] Get:3 http://deb.debian.org/debian buster-updates InRelease [51.9 kB] Reading package lists... Done E: Repository 'http://security.debian.org/debian-security buster/updates InRelease' changed its 'Suite' value from 'stable' to 'oldstable' N: This must be accepted explicitly before updates for this repository can be applied. See apt-secure(8) manpage for details. N: Repository 'http://deb.debian.org/debian buster InRelease' changed its 'Version' value from '10.6' to '10.10' E: Repository 'http://deb.debian.org/debian buster InRelease' changed its 'Suite' value from 'stable' to 'oldstable' N: This must be accepted explicitly before updates for this repository can be applied. See apt-secure(8) manpage for details. E: Repository 'http://deb.debian.org/debian buster-updates InRelease' changed its 'Suite' value from 'stable-updates' to 'oldstable-updates' N: This must be accepted explicitly before updates for this repository can be applied. See apt-secure(8) manpage for details. Exited with code exit status 100 ``` ## Comments Suggestions to fix, any other relevant information.
2021-05-20T15:36:23Z
[]
[]
freedomofpress/securedrop
5,974
freedomofpress__securedrop-5974
[ "5973" ]
59da5b76cb8144f104c14bb0163987fb8437f490
diff --git a/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py b/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py @@ -0,0 +1,32 @@ +"""unique_index_for_instanceconfig_valid_until + +Revision ID: 1ddb81fb88c2 +Revises: 92fba0be98e9 +Create Date: 2021-06-04 17:28:25.725563 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '1ddb81fb88c2' +down_revision = '92fba0be98e9' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.create_index('ix_one_active_instance_config', [sa.text('valid_until IS NULL')], unique=True, sqlite_where=sa.text('valid_until IS NULL')) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.drop_index('ix_one_active_instance_config') + + # ### end Alembic commands ### diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -18,7 +18,8 @@ from passlib.hash import argon2 from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship, backref, Query, RelationshipProperty -from sqlalchemy import Column, Integer, String, Boolean, DateTime, LargeBinary +from sqlalchemy import Column, Index, Integer, String, Boolean, DateTime, LargeBinary +from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound from db import db @@ -833,7 +834,6 @@ class InstanceConfig(db.Model): __tablename__ = 'instance_config' version = Column(Integer, primary_key=True) valid_until = Column(DateTime, default=None, unique=True) - allow_document_uploads = Column(Boolean, default=True) organization_name = Column(String(255), nullable=True, default="SecureDrop") @@ -869,10 +869,13 @@ def get_current(cls) -> "InstanceConfig": try: return cls.query.filter(cls.valid_until == None).one() # lgtm [py/test-equals-none] # noqa: E711, E501 except NoResultFound: - current = cls() - db.session.add(current) - db.session.commit() - return current + try: + current = cls() + db.session.add(current) + db.session.commit() + return current + except IntegrityError: + return cls.query.filter(cls.valid_until == None).one() # lgtm [py/test-equals-none] # noqa: E711, E501 @classmethod def check_name_acceptable(cls, name: str) -> None: @@ -914,3 +917,11 @@ def set_allow_document_uploads(cls, value: bool) -> None: db.session.add(new) db.session.commit() + + +one_active_instance_config_index = Index( + 'ix_one_active_instance_config', + InstanceConfig.valid_until.is_(None), + unique=True, + sqlite_where=(InstanceConfig.valid_until.is_(None)) +)
diff --git a/securedrop/tests/migrations/migration_1ddb81fb88c2.py b/securedrop/tests/migrations/migration_1ddb81fb88c2.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_1ddb81fb88c2.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- + +from sqlalchemy import text + +from db import db +from journalist_app import create_app + + +index_definition = ( + "index", + "ix_one_active_instance_config", + "instance_config", + ( + "CREATE UNIQUE INDEX ix_one_active_instance_config " + "ON instance_config (valid_until IS NULL) WHERE valid_until IS NULL" + ), +) + + +def get_schema(app): + with app.app_context(): + result = list( + db.engine.execute(text("SELECT type, name, tbl_name, sql FROM sqlite_master")) + ) + + return ((x[0], x[1], x[2], x[3]) for x in result) + + +class UpgradeTester: + """ + Ensure that the new index is created. + """ + + def __init__(self, config): + self.app = create_app(config) + + def load_data(self): + pass + + def check_upgrade(self): + schema = get_schema(self.app) + print(schema) + assert index_definition in schema + + +class DowngradeTester: + """ + Ensure that the new index is removed. + """ + + def __init__(self, config): + self.app = create_app(config) + + def load_data(self): + pass + + def check_downgrade(self): + assert index_definition not in get_schema(self.app) diff --git a/securedrop/tests/test_db.py b/securedrop/tests/test_db.py --- a/securedrop/tests/test_db.py +++ b/securedrop/tests/test_db.py @@ -3,9 +3,19 @@ from mock import MagicMock +from sqlalchemy import create_engine +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import sessionmaker + from .utils import db_helper -from models import (Journalist, Submission, Reply, get_one_or_else, - LoginThrottledException) +from models import ( + InstanceConfig, + Journalist, + Submission, + Reply, + LoginThrottledException, + get_one_or_else +) def test_get_one_or_else_returns_one(journalist_app, test_journo): @@ -90,3 +100,32 @@ def test_journalist_string_representation(journalist_app, test_journo): def test_source_string_representation(journalist_app, test_source): with journalist_app.app_context(): test_source['source'].__repr__() + + +def test_only_one_active_instance_config_can_exist(config, source_app): + """ + Checks that attempts to add multiple active InstanceConfig records fail. + + InstanceConfig is supposed to be invalidated by setting + valid_until to the time the config was no longer in effect. Until + we added the partial index preventing multiple rows with a null + valid_until, it was possible for the system to create multiple + active records, which would cause MultipleResultsFound exceptions + in InstanceConfig.get_current. + """ + # create a separate session + engine = create_engine(source_app.config['SQLALCHEMY_DATABASE_URI']) + session = sessionmaker(bind=engine)() + + # in the separate session, create an InstanceConfig with default + # values, but don't commit it + conflicting_config = InstanceConfig() + session.add(conflicting_config) + + with source_app.app_context(): + # get_current will create another InstanceConfig with default values + InstanceConfig.get_current() + + # now the commit of the first instance should fail + with pytest.raises(IntegrityError): + session.commit()
In dev environment, multiple active InstanceConfig records can be created, breaking things ## Description If the database is created with `create_all` instead of migrations, there won't be a default `InstanceConfig` record. On first request the [source](https://github.com/freedomofpress/securedrop/blob/2971b91b31ba9abf0d6372f4f4db9d796f83e1c5/securedrop/source_app/__init__.py#L136) or [journalist](https://github.com/freedomofpress/securedrop/blob/2971b91b31ba9abf0d6372f4f4db9d796f83e1c5/securedrop/journalist_app/__init__.py#L127) apps will try to [create one](https://github.com/freedomofpress/securedrop/blob/2971b91b31ba9abf0d6372f4f4db9d796f83e1c5/securedrop/models.py#L862), and if there are simultaneous requests, it's possible that more than one active (with `valid_until` null) row can be created, causing problems on subsequent requests. Changing the dev environment to create the database the same way it's done in staging and production would ensure the presence of an `InstanceConfig` before the apps are started, but we should also try to prevent multiple active configs. A [partial index](https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#partial-indexes) should do that. ## Steps to Reproduce This should only happen in the dev environment, and it's tricky to reproduce _in vivo_; you have to submit simultaneous requests right after the dev servers are started. We saw this in the demo service when multiple scripts were testing the site. It's easier to demonstrate the problem with the `instance_config` schema alone: in one database session, add an `InstanceConfig` instance but don't commit, then in another session, call `InstanceConfig.get_current()` to create a record with the same default values, then commit the original session. This will work and you'll wind up with two active configurations in the table.
2021-06-04T20:07:08Z
[]
[]
freedomofpress/securedrop
5,998
freedomofpress__securedrop-5998
[ "5994" ]
9a811ef5629fca0a03f0320ef2828943852ef5b0
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -946,7 +946,9 @@ def update(args: argparse.Namespace) -> int: good_sig_text = ['Good signature from "SecureDrop Release Signing ' + 'Key"', 'Good signature from "SecureDrop Release Signing ' + - 'Key <[email protected]>"'] + 'Key <[email protected]>"', + 'Good signature from "SecureDrop Release Signing ' + + 'Key <[email protected]>"'] bad_sig_text = 'BAD signature' gpg_lines = sig_result.split('\n')
diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -274,6 +274,25 @@ def test_get_release_key_from_valid_keyserver(self, tmpdir, caplog): b'Signing Key ' b'<[email protected]>"\n', + b'gpg: Signature made Thu 20 Jul ' + b'2017 08:12:25 PM EDT\n' + b'gpg: using RSA key ' + b'2359E6538C0613E652955E6C188EDD3B7B22E6A3\n' + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key ' + b'<[email protected]>"\n', + + b'gpg: Signature made Thu 20 Jul ' + b'2017 08:12:25 PM EDT\n' + b'gpg: using RSA key ' + b'2359E6538C0613E652955E6C188EDD3B7B22E6A3\n' + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key" [unknown]\n' + b'gpg: aka "SecureDrop Release ' + b'Signing Key ' + b'<[email protected]>" ' + b'[unknown]\n', + b'gpg: Signature made Thu 20 Jul ' b'2017 08:12:25 PM EDT\n' b'gpg: using RSA key '
`securedrop-admin` does not include new UID in signature check ## Description `securedrop-admin` (which is used by the graphical updater) does not check for our new release key UID, here: https://github.com/freedomofpress/securedrop/blob/develop/admin/securedrop_admin/__init__.py#L946-L949 The new UID is `[email protected]`. This omission means that the tag verification will fail. (Note the closing quotation mark on the first line, which is not present when the key has a UID associated with it.) ## Steps to Reproduce A bit difficult as we currently don't have a tag signed with the new key up. I've so far only tested this by manually attempting to match signature output in the same manner as the updater does.
2021-06-16T22:24:50Z
[]
[]
freedomofpress/securedrop
6,020
freedomofpress__securedrop-6020
[ "5969" ]
14c90e0e32d5c99af0423671fc87e655ac33c1fd
diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '1.9.0~rc1' +__version__ = '2.1.0~rc1' diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="1.9.0~rc1", + version="2.1.0~rc1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-focal/tests/vars.yml b/molecule/builder-focal/tests/vars.yml --- a/molecule/builder-focal/tests/vars.yml +++ b/molecule/builder-focal/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "1.9.0~rc1" +securedrop_version: "2.1.0~rc1" ossec_version: "3.6.0" keyring_version: "0.1.5" config_version: "0.1.4"
Release SecureDrop 2.0.0 This is a tracking issue for the release of SecureDrop 2.0.0 Tentatively scheduled as follows: **String and feature freeze:** 2021-06-08 **String comment period:** 2021-06-08 - 2021-06-11 **Translation period:** 2021-06-11 - 2021-06-21 **Pre-release announcement:** 2021-06-15 **Release date:** ~2021-06-22 **Release manager:** @zenmonkeykstop **Deputy release manager:** @kushaldas **Localization manager**: @rmol **Deputy localization manager**: @kushaldas **Communications manager:**: @rocodes _SecureDrop maintainers and testers:_ As you QA 2.0.0, please report back your testing results as comments on this ticket. File GitHub issues for any problems found, tag them "QA: Release", and associate them with the [2.0.0 milestone](https://github.com/freedomofpress/securedrop/milestone/69) for tracking (or ask a maintainer to do so). Test debian packages will be posted on https://apt-test.freedom.press signed with [the test key](https://gist.githubusercontent.com/conorsch/ec4008b111bc3142fca522693f3cce7e/raw/2968621e8ad92db4505a31fcc5776422d7d26729/apt-test%2520apt%2520pubkey). An Ansible playbook testing the upgrade path is [here](https://TK/). # [QA Matrix for 2.0.0](https://docs.google.com/spreadsheets/d/18InCOYTfaETuLDP0w2mF6m_N_Qee12pjdJphCT9HcC4/edit#gid=1698153040) # [Test Plan for 2.0.0](https://github.com/freedomofpress/securedrop/wiki/2.0.0-Test-Plan) # Prepare release candidate (2.0.0~rc1) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Fetch Tor 0.4.5.8 (latest stable) packages and deploy to apt-test server - [x] Prepare 2.0.0~rc1 release changelog - [x] Branch off release/2.0.0 from develop - [x] Prepare 2.0.0~rc1 - [x] Build debs, preserving build log, and put up `2.0.0~rc1` on test apt server - [x] Commit build log. # Prepare release candidate (2.0.0~rc2) - [x] Prepare 2.0.0~rc2 release changelog - [x] Prepare 2.0.0~rc2 - [x] Build debs, preserving build log, and put up `2.0.0~rc2` on test apt server - [x] Commit build log. # Prepare release candidate (2.0.0~rc3) - [x] Prepare 2.0.0~rc3 release changelog - [x] Prepare 2.0.0~rc3 - [x] Build debs, preserving build log, and put up `2.0.0~rc3` on test apt server - [x] Commit build log. # Prepare release candidate (2.0.0~rc4) - [x] Prepare 2.0.0~rc4 release changelog - [x] Prepare 2.0.0~rc4 - [x] Build debs, preserving build log, and put up `2.0.0~rc4` on test apt server - [x] Commit build log. # Prepare release candidate (2.0.0~rc5) - [x] Prepare 2.0.0~rc5 release changelog - [x] Prepare 2.0.0~rc5 - [x] Build debs, preserving build log, and put up `2.0.0~rc5` on test apt server - [x] Commit build log. After each test, please update the QA matrix and post details for Basic Server Testing, Application Acceptance Testing and 1.8.0-specific testing below in comments to this ticket. # Final release - [x] Ensure builder in release branch is updated and/or update builder image - [x] Push signed tag - [x] Pre-Flight: Test updater logic in Tails (apt-qa tracks the `release` branch in the LFS repo) - [x] Build final Debian packages for 2.0.0 (and preserve build log) - [x] Commit package build log to https://github.com/freedomofpress/build-logs - [x] Upload Debian packages to apt-qa server (including Tor 0.4.5.8 packages) - [x] Pre-Flight: Test that install and upgrade from 1.8.2 to 2.0.0 works w/ prod repo debs (apt-qa.freedom.press polls the `release` branch in the LFS repo for the debs) - [x] Flip apt QA server to prod status (merge to `main` in the LFS repo) - [x] Merge Docs branch changes to ``main`` and verify new docs build in securedrop-docs repo - [x] Prepare release messaging # Post release - [x] Create GitHub release object - [x] Once release object is created, update versions in `securedrop-docs` and Wagtail - [x] Build readthedocs and verify new docs show up on https://docs.securedrop.org - [x] Publish announcements - [x] Merge changelog back to `develop` - [x] Update roadmap wiki page: https://github.com/freedomofpress/securedrop/wiki/Development-Roadmap
2021-06-24T18:27:35Z
[]
[]
freedomofpress/securedrop
6,032
freedomofpress__securedrop-6032
[ "6022" ]
0589168d0afe02e6ad82cf2fe72268a1e8ec7509
diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -14,8 +14,7 @@ import testutils -# The config tests target staging by default. It's possible to override -# for e.g. prod, but the associated vars files are not yet ported. +# The config tests target staging by default. target_host = os.environ.get('SECUREDROP_TESTINFRA_TARGET_HOST', 'staging') @@ -35,6 +34,34 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): hostvars['python_version'] = "3.8" hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['focal'] + # If the tests are run against a production environment, check local config + # and override as necessary. + prod_filepath = os.path.join(os.path.dirname(__file__), + "../../install_files/ansible-base/group_vars/all/site-specific") + if os.path.isfile(prod_filepath): + with io.open(prod_filepath, 'r') as f: + prodvars = yaml.safe_load(f) + + def _prod_override(vars_key, prod_key): + if prod_key in prodvars: + hostvars[vars_key] = prodvars[prod_key] + + _prod_override('app_ip', 'app_ip') + _prod_override('mon_ip', 'monitor_ip') + _prod_override('sasl_domain', 'sasl_domain') + _prod_override('sasl_username', 'sasl_username') + _prod_override('sasl_password', 'sasl_password') + _prod_override('daily_reboot_time', 'daily_reboot_time') + + # Check repo targeting, and update vars + repo_filepath = os.path.join(os.path.dirname(__file__), + "../../install_files/ansible-base/roles/install-fpf-repo/defaults/main.yml") # noqa: E501 + if os.path.isfile(repo_filepath): + with io.open(repo_filepath, 'r') as f: + repovars = yaml.safe_load(f) + if 'apt_repo_url' in repovars: + hostvars['fpf_apt_repo_url'] = repovars['apt_repo_url'] + if with_header: hostvars = dict(securedrop_test_vars=hostvars)
diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -6,6 +6,10 @@ test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] +# Updates and upgrades are scheduled at set times before a scheduled reboot +OFFSET_UPDATE = 2 +OFFSET_UPGRADE = 1 + def test_automatic_updates_dependencies(host): """ @@ -65,7 +69,7 @@ def test_sources_list(host, repo): "APT::Periodic::Enable": "1", "Unattended-Upgrade::AutoFixInterruptedDpkg": "true", "Unattended-Upgrade::Automatic-Reboot": "true", - "Unattended-Upgrade::Automatic-Reboot-Time": "4:00", + "Unattended-Upgrade::Automatic-Reboot-Time": "{}:00".format(test_vars.daily_reboot_time), "Unattended-Upgrade::Automatic-Reboot-WithUsers": "true", "Unattended-Upgrade::Origins-Pattern": [ "origin=${distro_id},archive=${distro_codename}", @@ -145,21 +149,23 @@ def test_apt_daily_services_and_timers_enabled(host, service): def test_apt_daily_timer_schedule(host): """ - Timer for running apt-daily, i.e. 'apt-get update', should be 2h + Timer for running apt-daily, i.e. 'apt-get update', should be OFFSET_UPDATE hrs before the daily_reboot_time. """ + t = (int(test_vars.daily_reboot_time) - OFFSET_UPDATE) % 24 c = host.run("systemctl show apt-daily.timer") - assert "TimersCalendar={ OnCalendar=*-*-* 02:00:00 ;" in c.stdout + assert "TimersCalendar={ OnCalendar=*-*-* " + "{:02d}".format(t) + ":00:00 ;" in c.stdout assert "RandomizedDelayUSec=20m" in c.stdout def test_apt_daily_upgrade_timer_schedule(host): """ - Timer for running apt-daily-upgrade, i.e. 'apt-get upgrade', should be 1h + Timer for running apt-daily-upgrade, i.e. 'apt-get upgrade', should be OFFSET_UPGRADE hrs before the daily_reboot_time, and 1h after the apt-daily time. """ + t = (int(test_vars.daily_reboot_time) - OFFSET_UPGRADE) % 24 c = host.run("systemctl show apt-daily-upgrade.timer") - assert "TimersCalendar={ OnCalendar=*-*-* 03:00:00 ;" in c.stdout + assert "TimersCalendar={ OnCalendar=*-*-* " + "{:02d}".format(t) + ":00:00 ;" in c.stdout assert "RandomizedDelayUSec=20m" in c.stdout
QA: Automate basic server testing The default QA test plan includes a basic testing section that mostly checks server configuration. These tests are duplicated in the production testinfra tests, so with some work to get `testinfra` to use production settings where available (via `install_files/ansible-base/group_vars/all/site-specific`), it should be possible to reduce tester workload by removing Basic testing in favour of `testinfra`.
2021-07-05T23:11:02Z
[]
[]
freedomofpress/securedrop
6,041
freedomofpress__securedrop-6041
[ "5986" ]
ba11676f1284632fa055643d867071cd4df2c3db
diff --git a/securedrop/source_app/forms.py b/securedrop/source_app/forms.py --- a/securedrop/source_app/forms.py +++ b/securedrop/source_app/forms.py @@ -24,8 +24,9 @@ class LoginForm(FlaskForm): class SubmissionForm(FlaskForm): - msg = TextAreaField("msg", render_kw={"placeholder": gettext("Write a message.")}) - fh = FileField("fh") + msg = TextAreaField("msg", render_kw={"placeholder": gettext("Write a message."), + "aria-label": gettext("Write a message.")}) + fh = FileField("fh", render_kw={"aria-label": gettext("Select a file to upload.")}) def validate_msg(self, field: wtforms.Field) -> None: if len(field.data) > Submission.MAX_MESSAGE_LEN: diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -157,7 +157,7 @@ def submit() -> werkzeug.Response: for field, errors in form.errors.items(): for error in errors: flash(error, "error") - return redirect(url_for('main.lookup')) + return redirect(f"{url_for('main.lookup')}#flashed") msg = request.form['msg'] fh = None @@ -172,7 +172,7 @@ def submit() -> werkzeug.Response: "error") else: flash(gettext("You must enter a message."), "error") - return redirect(url_for('main.lookup')) + return redirect(f"{url_for('main.lookup')}#flashed") fnames = [] journalist_filename = g.source.journalist_filename @@ -235,7 +235,7 @@ def submit() -> werkzeug.Response: normalize_timestamps(g.filesystem_id) - return redirect(url_for('main.lookup')) + return redirect(f"{url_for('main.lookup')}#flashed") @view.route('/delete', methods=('POST',)) @login_required
diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -58,25 +58,27 @@ def _source_chooses_to_submit_documents(self): self.source_name = codename.text def _source_shows_codename(self, verify_source_name=True): - content = self.driver.find_element_by_id("codename-hint-content") - assert not content.is_displayed() + # The DETAILS element will be missing the OPEN attribute if it is + # closed, hiding its contents. + content = self.driver.find_element_by_css_selector("details#codename-hint") + assert content.get_attribute("open") is None - self.safe_click_by_id("codename-hint-show") + self.safe_click_by_id("codename-hint") - self.wait_for(lambda: content.is_displayed()) - assert content.is_displayed() - content_content = self.driver.find_element_by_css_selector("#codename-hint-content p") + assert content.get_attribute("open") is not None + content_content = self.driver.find_element_by_css_selector("details#codename-hint mark") if verify_source_name: assert content_content.text == self.source_name def _source_hides_codename(self): - content = self.driver.find_element_by_id("codename-hint-content") - assert content.is_displayed() + # The DETAILS element will have the OPEN attribute if it is open, + # displaying its contents. + content = self.driver.find_element_by_css_selector("details#codename-hint") + assert content.get_attribute("open") is not None - self.safe_click_by_id("codename-hint-hide") + self.safe_click_by_id("codename-hint") - self.wait_for(lambda: not content.is_displayed()) - assert not content.is_displayed() + assert content.get_attribute("open") is None def _source_sees_no_codename(self): codename = self.driver.find_elements_by_css_selector(".code-reminder") diff --git a/securedrop/tests/functional/test_source.py b/securedrop/tests/functional/test_source.py --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -62,7 +62,7 @@ def get_codename_generate(self): return self.driver.find_element_by_css_selector("#codename").text def get_codename_lookup(self): - return self.driver.find_element_by_css_selector("#codename-hint-content p").text + return self.driver.find_element_by_css_selector("#codename-hint mark").text def test_duplicate_generate_pages(self): # Test generation of multiple codenames in different browser tabs, ref. issue 4458. diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -101,8 +101,8 @@ def _find_codename(html): """Find a source codename (diceware passphrase) in HTML""" # Codenames may contain HTML escape characters, and the wordlist # contains various symbols. - codename_re = (r'<p [^>]*id="codename"[^>]*>' - r'(?P<codename>[a-z0-9 &#;?:=@_.*+()\'"$%!-]+)</p>') + codename_re = (r'<mark [^>]*id="codename"[^>]*>' + r'(?P<codename>[a-z0-9 &#;?:=@_.*+()\'"$%!-]+)</mark>') codename_match = re.search(codename_re, html) assert codename_match is not None return codename_match.group('codename')
semantic (HTML5/ARIA) page structure in Source Interface ## Description [Accessibility Lab recommendations](https://docs.google.com/document/d/1jZlKco2YgOrrI4PmTkG_Q8lKuV5VxCds/edit#) include: - `h1`...`hn` hierarchy - HTML5 section elements - ARIA roles ("landmarks"), labels, and descriptions Our findings include: - moving decorative `img` elements to CSS styles on semantic elements ## User Research Evidence [WCAG 1.3.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html) per #5972. ## Progress To invert the way things are usually done :-): 1. [x] **First pass:** Refactor for semantic markup (test in developer tools and screen-readers) - [x] decorative `img`/`hr`/etc. elements: mark as `FIXME`s to move to CSS styles on semantic elements - [x] linters pass - [x] tests pass 2. [x] **Second pass:** Audit in validators and accessibility tools ([axe](https://www.deque.com/axe/), [WAVE](https://wave.webaim.org/)), e.g.: - `h1`...`hn` hierarchy - HTML5 section elements - ARIA roles ("landmarks"), labels, and descriptions 3. [x] **Third pass:** CSS and images broken in first pass (test visually in browser) - [x] `FIXME`s - [x] visual review | Path | First Pass | Second Pass | Third Pass | | --- | --- | --- | --- | `securedrop/source_templates` | ✓ | ✓ | ✓ | `├── banner_warning_flashed.html` | ✓ | ✓ | ✓ | `├── base.html` | ✓ | ✓ | ✓ | `├── error.html` | ✓ | ✓ | ✓ | `├── first_submission_flashed_message.html` | ✓ | ✓ | ✓ | `├── flashed.html` | ✓ | ✓ | ✓ | `├── footer.html` | ✓ | ✓ | ✓ | `├── generate.html` | ✓ | ✓ | ✓ | `├── index.html` | ✓ | ✓ | ✓ | `├── locales.html` | ✓ | ✓ | ✓ | `├── login.html` | ✓ | ✓ | ✓ | `├── logout.html` | ✓ | ✓ | ✓ | `├── lookup.html` | ✓ | ✓ | ✓ | `├── next_submission_flashed_message.html` | ✓ | ✓ | ✓| `├── notfound.html` | ✓ | ✓ | ✓ | `├── session_timeout.html` | ✓ | ✓ | ✓ | `├── tor2web-warning.html` | ✓ | ✓ | ✓ | `├── use-tor-browser.html` | ✓ | ✓ | ✓ | `└── why-public-key.html` | ✓ | ✓ | ✓ | ## Specific cases (could be filed as separate issues) - [x] `securedrop/source_templates/generate.html`: `p.explanation` should be associated with `p#codename`
@zenmonkeykstop, I'm starting work on this with the assumption that this and #5987 will each take the form of an omnibus PR consisting of: 1. refactored templates; and 2. stylesheets updated accordingly, with the goal of making it as close as possible to a pixel-perfect markup-only refactoring, with no (visually apparent) UI/UX consequences. Given this scope, is there a particular sequence or structure you'd like to see the PR follow for ease of review?
2021-07-13T18:46:15Z
[]
[]
freedomofpress/securedrop
6,066
freedomofpress__securedrop-6066
[ "6043" ]
46e993b56a744f0905613b1f88d399cb03918838
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -19,7 +19,8 @@ from sdconfig import SDConfig from source_app.decorators import login_required from source_app.utils import (logged_in, generate_unique_codename, - normalize_timestamps, valid_codename) + normalize_timestamps, valid_codename, + fit_codenames_into_cookie) from source_app.forms import LoginForm, SubmissionForm @@ -48,7 +49,7 @@ def generate() -> Union[str, werkzeug.Response]: tab_id = urlsafe_b64encode(os.urandom(64)).decode() codenames = session.get('codenames', {}) codenames[tab_id] = codename - session['codenames'] = codenames + session['codenames'] = fit_codenames_into_cookie(codenames) session['new_user'] = True return render_template('generate.html', codename=codename, tab_id=tab_id) diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -1,3 +1,4 @@ +import json import subprocess from flask import session, current_app, abort, g @@ -91,3 +92,23 @@ def check_url_file(path: str, regexp: str) -> 'Optional[str]': def get_sourcev3_url() -> 'Optional[str]': return check_url_file("/var/lib/securedrop/source_v3_url", r"^[a-z0-9]{56}\.onion$") + + +def fit_codenames_into_cookie(codenames: dict) -> dict: + """ + If `codenames` will approach `werkzeug.Response.max_cookie_size` once + serialized, incrementally pop off the oldest codename until the remaining + (newer) ones will fit. + """ + + serialized = json.dumps(codenames).encode() + if len(codenames) > 1 and len(serialized) > 4000: # werkzeug.Response.max_cookie_size = 4093 + if current_app: + current_app.logger.warn(f"Popping oldest of {len(codenames)} " + f"codenames ({len(serialized)} bytes) to " + f"fit within maximum cookie size") + del codenames[list(codenames)[0]] # FIFO + + return fit_codenames_into_cookie(codenames) + + return codenames
diff --git a/securedrop/tests/functional/test_source.py b/securedrop/tests/functional/test_source.py --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -1,3 +1,6 @@ +import werkzeug + +from ..test_journalist import VALID_PASSWORD from . import source_navigation_steps, journalist_navigation_steps from . import functional_test from sdconfig import config @@ -157,3 +160,15 @@ def test_refreshed_duplicate_generate_pages(self): codename_lookup_b = self.get_codename_lookup() assert codename_lookup_b == codename_a2 self._source_submits_a_message() + + def test_codenames_exceed_max_cookie_size(self): + # Test generation of enough codenames (from multiple tabs and/or serial + # refreshes) that the resulting cookie exceeds the recommended + # `werkzeug.Response.max_cookie_size` = 4093 bytes. (#6043) + + too_many = 2*(werkzeug.Response.max_cookie_size // len(VALID_PASSWORD)) + for i in range(too_many): + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + + self._source_continues_to_submit_page() diff --git a/securedrop/tests/test_source_utils.py b/securedrop/tests/test_source_utils.py --- a/securedrop/tests/test_source_utils.py +++ b/securedrop/tests/test_source_utils.py @@ -1,7 +1,11 @@ # -*- coding: utf-8 -*- +import json import os -from source_app.utils import check_url_file +import werkzeug + +from source_app.utils import check_url_file, fit_codenames_into_cookie +from .test_journalist import VALID_PASSWORD def test_check_url_file(config): @@ -28,3 +32,32 @@ def write_url_file(path, content): finally: if os.path.exists(url_path): os.unlink(url_path) + + +def test_fit_codenames_into_cookie(config): + # A single codename should never be truncated. + codenames = {'a': VALID_PASSWORD} + assert(fit_codenames_into_cookie(codenames) == codenames) + + # A reasonable number of codenames should never be truncated. + codenames = { + 'a': VALID_PASSWORD, + 'b': VALID_PASSWORD, + 'c': VALID_PASSWORD, + } + assert(fit_codenames_into_cookie(codenames) == codenames) + + # A single gargantuan codename is undefined behavior---but also should not + # be truncated. + codenames = {'a': werkzeug.Response.max_cookie_size*VALID_PASSWORD} + assert(fit_codenames_into_cookie(codenames) == codenames) + + # Too many codenames of the expected length should be truncated. + codenames = {} + too_many = 2*(werkzeug.Response.max_cookie_size // len(VALID_PASSWORD)) + for i in range(too_many): + codenames[i] = VALID_PASSWORD + serialized = json.dumps(codenames).encode() + assert(len(serialized) > werkzeug.Response.max_cookie_size) + serialized = json.dumps(fit_codenames_into_cookie(codenames)).encode() + assert(len(serialized) < werkzeug.Response.max_cookie_size)
`/create` fails after `/generate` has set per-`tab_id` codenames exceeding maximum cookie size ## Description RFC 6265 [states](https://www.rfc-editor.org/rfc/rfc6265.html#section-6.1) that "user agents SHOULD provide [support for] at least 4096 bytes per cookie". In practice, browsers [including Firefox](https://searchfox.org/mozilla-central/source/netwerk/cookie/CookieCommons.h#58) reject cookies larger than this size. If loaded repeatedly, `/generate` will accumulate per-`tab_id` codenames that are sent in a cookie larger than 4096 bytes, with this warning: /opt/venvs/securedrop-app-code/lib/python3.8/site-packages/werkzeug/wrappers/base_response.py:470: UserWarning: The "b'ss'" cookie is too large: the value was 4179 bytes but the header required 21 extra bytes. The final size was 4200 bytes but the limit is 4093 bytes. Browsers may silently ignore cookies larger than this. If the browser has indeed rejected this cookie, `/create` may subsequently fail, because the browser will return an older cookie that does not include the latest `tab_id` value, producing this error: File "/Users/cfm/work/securedrop/securedrop/source_app/main.py", line 66, in create codename = session['codenames'][tab_id] KeyError: 'xXOU8ChEZfCzeCN4cboAze9zMkJpPFfNpJ1ym54Jyc73b1leelikcdB-wI5U033QdTRrXELjNc_SqfQX2an7zg==' ## Steps to Reproduce 1. Load `/generate`. 2. In the same browser session, refresh repeatedly, via either the browser or the **Generate Codename** button, 30 or more times. 3. Click **Submit Documents**. Or run test: ```diff --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -157,3 +157,9 @@ class TestDuplicateSourceInterface( codename_lookup_b = self.get_codename_lookup() assert codename_lookup_b == codename_a2 self._source_submits_a_message() + + def test_too_many_codenames(self): + for i in range(50): # limit will be approximately n = 4096 bytes / length of average {tab_id: codename} pair + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() ``` ## Expected Behavior `/create` and `/lookup` load properly. ## Actual Behavior An HTTP `500` error is returned (in debug mode, a `KeyError`). ## Comments This is unlikely to occur in real-world use, but getting out of this state requires either deleting the `ss` cookie or resetting your (Tor) browser session. In `generate()`, the simplest solution will be to truncate `codenames` at `n = 4096 bytes / length of average {tab_id: codename} pair` entries, on the assumption that someone is unlikely to wind up calling `/create` with their 29th-newest (or older) codename. https://github.com/freedomofpress/securedrop/blob/1a2494d2b27129708e0da6b4278a7e888746daaf/securedrop/source_app/main.py#L49-L51 Now that [dictionary order is guaranteed to be insertion order](https://docs.python.org/3/library/stdtypes.html#dict), it may be possible to make this change in place, without refactoring the `codenames` session key as a list of `(tab_id, codename)` tuples (serialized to JSON as an array of arrays) for list operations.
2021-08-14T00:57:58Z
[]
[]
freedomofpress/securedrop
6,067
freedomofpress__securedrop-6067
[ "6056" ]
d3b0d363179aaca0d0b403a891d2b6e46589b459
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -40,12 +40,27 @@ class RequestLocaleInfo: def __init__(self, locale: str): self.locale = Locale.parse(locale) + # This attribute can be set to `True` to differentiate multiple + # locales currently available (supported) for the same language. + self.use_display_name = False + def __str__(self) -> str: """ The Babel string representation of the locale. """ return str(self.locale) + @property + def display_name(self) -> str: + """ + Give callers (i.e., templates) the `Locale` object's display name when + such resolution is warranted, otherwise the language name---as + determined by `map_locale_display_names()`. + """ + if self.use_display_name: + return self.locale.display_name + return self.locale.language_name + @property def text_direction(self) -> str: """ @@ -135,7 +150,7 @@ def validate_locale_configuration(config: SDConfig, app: Flask) -> None: ) -LOCALES = collections.OrderedDict() # type: collections.OrderedDict[str, str] +LOCALES = collections.OrderedDict() # type: collections.OrderedDict[str, RequestLocaleInfo] def map_locale_display_names(config: SDConfig) -> None: @@ -149,17 +164,15 @@ def map_locale_display_names(config: SDConfig) -> None: """ language_locale_counts = collections.defaultdict(int) # type: Dict[str, int] for l in sorted(config.SUPPORTED_LOCALES): - locale = Locale.parse(l) - language_locale_counts[locale.language_name] += 1 + locale = RequestLocaleInfo(l) + language_locale_counts[locale.language] += 1 locale_map = collections.OrderedDict() for l in sorted(config.SUPPORTED_LOCALES): - locale = Locale.parse(l) - if language_locale_counts[locale.language_name] == 1: - name = locale.language_name - else: - name = locale.display_name - locale_map[str(locale)] = name + locale = RequestLocaleInfo(l) + if language_locale_counts[locale.language] > 1: + locale.use_display_name = True + locale_map[str(locale)] = locale global LOCALES LOCALES = locale_map
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -158,6 +158,16 @@ def verify_i18n(app): locales = render_template('locales.html') assert '?l=fr_FR' in locales assert '?l=en_US' not in locales + + # Test that A[lang,hreflang] attributes (if present) will validate as + # BCP47/RFC5646 language tags from `i18n.RequestLocaleInfo.language_tag`. + if 'lang="' in locales: + assert 'lang="en-US"' in locales + assert 'lang="fr-FR"' in locales + if 'hreflang="' in locales: + assert 'hreflang="en-US"' in locales + assert 'hreflang="fr-FR"' in locales + c.get('/?l=ar') base = render_template('base.html') assert 'dir="rtl"' in base
make BCP47/RFC5646 `RequestLocaleInfo.language_tag` property available in locale selectors ## Description In `securedrop/source_templates/locales.html`, the `lang` and `hreflang` attributes require the value of the `RequestLocaleInfo.language_tag` property, which is not available in the `g.locales` dictionary. ## Steps to Reproduce After #6041, validate the HTML of a Source Interface page including the `locales.html` locale selector (i.e., in any of them). ## Expected Behavior The page validates. ## Actual Behavior Some locales' `lang` and `hreflang` attributes are invalid. ## Comments The trick will be to make the `RequestLocaleInfo.language_tag` property available to the Jinja template, which currently has access only to the contents of the `g.locales` dictionary. 1. [x] `securedrop/i18n.py`: `map_locale_display_names()`: return map of `RequestLocaleInfo` objects 2. [x] `securedrop/{journalist,source}_templates/locales.html`: `s/g.locales[locale]/g.locales[locale].display_name` (pending #6041) 3. [x] `securedrop/{journalist,source}_templates/locales.html`: use `g.locales[locale].language_tag` in `lang` and `hreflang` attributes (pending #6041)
2021-08-16T21:17:31Z
[]
[]
freedomofpress/securedrop
6,102
freedomofpress__securedrop-6102
[ "5828" ]
a6b478f67253accc58f5441dba194a2a8ab50a42
diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -163,7 +163,8 @@ def reply() -> werkzeug.Response: "<b>{}</b> {}".format( # Translators: Precedes a message confirming the success of an operation. escape(gettext("Success!")), - escape(gettext("Your reply has been stored.")) + escape(gettext("The source will receive your reply " + "next time they log in.")) ) ), 'success') finally:
diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -857,7 +857,7 @@ def _journalist_sends_reply_to_source(self): def reply_stored(): if not self.accept_languages: - assert "Your reply has been stored." in self.driver.page_source + assert "The source will receive your reply" in self.driver.page_source self.wait_for(reply_stored) diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -284,7 +284,7 @@ def _helper_test_reply(journalist_app, source_app, config, test_journo, pass else: text = resp.data.decode('utf-8') - assert "Your reply has been stored." in text + assert "The source will receive your reply" in text resp = app.get(col_url) text = resp.data.decode('utf-8')
1.8.0 translation feedback: say replies are saved, not stored ## Description From [AO](https://weblate.securedrop.org/translate/securedrop/securedrop/en/?checksum=a6f950dfa57047f3): "Your reply has been saved." might be better than "Your reply has been stored."
Fun fact - that language goes back to the AaronSw days of SecureDrop (8b1b3580137a57c76f27a9c90101926255da2b5b). I agree "has been saved" is a bit more friendly. I don't see that string having changed in the last development cycle though, am I missing something? If not I would be inclined to wait with this change until after 1.8.0. The language has not changed, but the construction of the flash message did, which resulted in the message being broken up into two, which now need to be translated separately. If we're going to change "stored" to "saved", it would save work to do it now. Discussed a bit more with @ninavizz. We don't think a single word change would make this message significantly more user-friendly, and would like to suggest revising it fully for a future release. The problem that `stored` and `saved` share is that they only speak to the technical completion of an operation, and don't clearly relate to the journalist's intent (talking to a source). In fact, `saved` is often associated with saving drafts (e.g., in email apps) that then later have to be sent. As jargon-y as it is, `stored` at least is not typically used in this fashion. That said, the message should definitely be improved. A message that more explicitly speaks to the journalist's intent (e.g., "Success! The source will be able to read your reply next time they log in" or something to that effect) would perhaps work better. We can discuss that a bit more here. Even though the structure of the message has changed for 1.8.0, the word `stored` has previous translations, so for now, I would suggest just retaining those translations. "posted" is also an option - implies that it has yet to be "delivered."
2021-09-21T18:14:23Z
[]
[]
freedomofpress/securedrop
6,130
freedomofpress__securedrop-6130
[ "5101" ]
b286ea674e31ab3f33e3f817a891e9676690b484
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -201,7 +201,10 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: fh.stream)) if first_submission: - flash_message = render_template('first_submission_flashed_message.html') + flash_message = render_template( + 'first_submission_flashed_message.html', + new_user_codename=session.get('new_user_codename', None), + ) flash(Markup(flash_message), "success") else:
diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -163,7 +163,9 @@ def file_submitted(): # allow time for reply key to be generated time.sleep(self.timeout) - def _source_submits_a_message(self): + def _source_submits_a_message( + self, verify_notification=False, first_submission=False, first_login=False + ): self._source_enters_text_in_message_field() self._source_clicks_submit_button_on_submission_page() @@ -172,6 +174,22 @@ def message_submitted(): notification = self.driver.find_element_by_css_selector(".success") assert "Thank" in notification.text + if verify_notification: + first_submission_text = ( + "Please check back later for replies." in notification.text + ) + first_login_text = "Forgot your codename?" in notification.text + + if first_submission: + assert first_submission_text + + if first_login: + assert first_login_text + else: + assert not first_login_text + else: + assert not first_submission_text + self.wait_for(message_submitted) # allow time for reply key to be generated diff --git a/securedrop/tests/functional/test_source.py b/securedrop/tests/functional/test_source.py --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -44,6 +44,33 @@ def test_lookup_codename_hint(self): self._source_proceeds_to_login() self._source_sees_no_codename() + def test_lookup_submit_notification_first_login(self): + """Test that on a first login, the submission notification includes the 'Please check back + later' and 'Forgot your codename?' messages. Also verify that those messages are not + present on a subsequent submission.""" + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_submits_a_message( + verify_notification=True, first_submission=True, first_login=True + ) + self._source_submits_a_message(verify_notification=True) + + def test_lookup_submit_notification_2nd_login(self): + """Test that on a second login, the first submission notification includes the 'Please + check back later' message but not the 'Forgot your codename?' message since the codename + hint section is not present on a second login (Ref. issue #5101). Also verify that none of + those messages are present on a subsequent submission.""" + self._source_visits_source_homepage() + self._source_chooses_to_submit_documents() + self._source_continues_to_submit_page() + self._source_logs_out() + self._source_visits_source_homepage() + self._source_chooses_to_login() + self._source_proceeds_to_login() + self._source_submits_a_message(verify_notification=True, first_submission=True) + self._source_submits_a_message(verify_notification=True) + class TestDownloadKey( functional_test.FunctionalTest,
Codename hint link visible in flash message but codename hint not displayed ## Description In the Source Interface, if a source generates a codename and proceeds to `/lookup` but elects not to submit anything at this time, the next time the source logs in and submits a message or document, the flash message includes the "Forgot your codename?" link but the `codename-hint` element of the page is missing so the link does not work. ## Steps to Reproduce 1. Run `make dev`. 1. Access the Source Interface and click "GET STARTED". 1. Take note of the codename on `/generate` and click "SUBMIT DOCUMENTS". 1. On `/lookup`, click "LOGOUT". 1. On `/index` click "LOG IN". 1. Enter the codename noted in 3 and click "CONTINUE". 1. On `/lookup` enter a message and click "SUBMIT". ## Expected Behavior The "Success!" flash message for a first submission is displayed, **without the "Forgot your codename" link**. ## Actual Behavior The "Success!" flash message for a first submission is displayed, **with the "Forgot your codename?" link** but the `codename-hint` element of the page is missing and therefore the link does not trigger anything. ![image](https://user-images.githubusercontent.com/22901938/72857503-cd420c80-3c8b-11ea-87ea-c1ed39b47e61.png) ## Comments Suggestions to fix: Use the `'new_user'` session key with an `if` statement in the template to determine whether the "Forgot your codename?" link should be displayed. This could be combined with the solution to #4401 which already involves some refactoring of the submission confirmation flash messages.
@DrGFreeman Belated thanks for the report! I just encountered the same issue and was wondering if we already had a report for it -- and there it was. Do you have bandwidth these days to attempt a fix yourself? Hi @eloquence. I was actually wanting to get back to contributing here (Hacktoberfest fever? Not sure...) so this will be a good place to start! Just need to refresh my dev environment and get back into it.
2021-10-08T03:44:08Z
[]
[]
freedomofpress/securedrop
6,151
freedomofpress__securedrop-6151
[ "6103" ]
31827894f89ec9a283fc93639bd5cefe31d198d8
diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '2.1.0~rc1' +__version__ = '2.2.0~rc1' diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="2.1.0~rc1", + version="2.2.0~rc1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-focal/tests/vars.yml b/molecule/builder-focal/tests/vars.yml --- a/molecule/builder-focal/tests/vars.yml +++ b/molecule/builder-focal/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "2.1.0~rc1" +securedrop_version: "2.2.0~rc1" ossec_version: "3.6.0" keyring_version: "0.1.5" config_version: "0.1.4"
Release SecureDrop 2.1.0 This is a tracking issue for the release of SecureDrop 2.1.0 Scheduled as follows: **Feature / string freeze:** 2021-09-28 **Pre-release announcement:** 2021-10-12 **Release date:** 2021-10-19 **Release manager:** @zenmonkeykstop **Deputy release manager:** @conorsch **Communications manager:** @eloquence **Localization manager:** @conorsch **Deputy LM:** @cfm [tentative] QA team: @creviera @tesitura @cfm @conorsch @zenmonkeykstop _SecureDrop maintainers and testers:_ As you QA 2.1.0, please report back your testing results as comments on this ticket. File GitHub issues for any problems found, tag them "QA: Release", and associate them with the [2.1.0 milestone](https://github.com/freedomofpress/securedrop/milestone/72) for tracking (or ask a maintainer to do so). Test debian packages will be posted on https://apt-test.freedom.press signed with [the test key](https://gist.githubusercontent.com/conorsch/ec4008b111bc3142fca522693f3cce7e/raw/2968621e8ad92db4505a31fcc5776422d7d26729/apt-test%2520apt%2520pubkey) # [QA Matrix for 2.1.0](https://docs.google.com/spreadsheets/d/1lcVmv9x0zTowIRS76Zha57U10fHP1evCK7NYDrSp5cg/edit#gid=2119608149) # [Test Plan for 2.1.0](https://github.com/freedomofpress/securedrop/wiki/2.1.0-Test-Plan) # Prepare release candidate (2.1.0~rc1) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.1.0~rc1 release changelog - [x] Branch off release/2.1.0 from release/2.0.2 - [x] Prepare 2.1.0~rc1 - [x] Build debs, preserving build log, and put up `2.1.0~rc1` on test apt server - [x] Commit build log. # Prepare release candidate (2.1.0~rc2) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.1.0~rc2, with changelog - [x] Build debs, preserving build log, and put up `2.1.0~rc2` on test apt server - https://github.com/freedomofpress/securedrop-dev-packages-lfs/pull/125 - [x] Commit build log. After each test, please update the QA matrix and post details for Basic Server Testing, Application Acceptance Testing and release-specific testing below in comments to this ticket. # Final release - [x] Ensure builder in release branch is updated and/or update builder image - [x] Push signed tag - [x] Pre-Flight: Test updater logic in Tails (apt-qa tracks the `release` branch in the LFS repo) - [x] Build final Debian packages for 2.1.0 (and preserve build log) - [x] Commit package build log to https://github.com/freedomofpress/build-logs - [x] Upload Debian packages to apt-qa server - [x] Pre-Flight: Test that install and upgrade from 2.0.2 to 2.1.0 works w/ prod repo debs (apt-qa.freedom.press polls the `release` branch in the LFS repo for the debs) - [x] Flip apt QA server to prod status (merge to `main` in the LFS repo) - [x] Merge Docs branch changes to ``main`` and verify new docs build in securedrop-docs repo - [x] Prepare release messaging # Post release - [x] Create GitHub release object - [x] Once release object is created, update version in `securedrop-docs` (version information in Wagtail is updated automatically) - [x] Build readthedocs and verify new docs show up on https://docs.securedrop.org - [x] Publish announcements - [ ] Merge changelog back to `develop` - [x] Update roadmap wiki page: https://github.com/freedomofpress/securedrop/wiki/Development-Roadmap
2021-10-20T14:36:55Z
[]
[]
freedomofpress/securedrop
6,165
freedomofpress__securedrop-6165
[ "5987" ]
3810e859d7bb83741f11f18369a4b3e2da50b4b9
diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -93,9 +93,13 @@ class NewUserForm(FlaskForm): username = StringField('username', validators=[ InputRequired(message=gettext('This field is required.')), minimum_length_validation, check_invalid_usernames - ]) - first_name = StringField('first_name', validators=[name_length_validation, Optional()]) - last_name = StringField('last_name', validators=[name_length_validation, Optional()]) + ], + render_kw={'aria-describedby': 'username-notes'}, + ) + first_name = StringField('first_name', validators=[name_length_validation, Optional()], + render_kw={'aria-describedby': 'name-notes'}) + last_name = StringField('last_name', validators=[name_length_validation, Optional()], + render_kw={'aria-describedby': 'name-notes'}) password = HiddenField('password') is_admin = BooleanField('is_admin') is_hotp = BooleanField('is_hotp')
diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -93,7 +93,7 @@ def _login_user(self, username, password, otp, maxtries=3): self._try_login_user(username, password, token) # Successful login should redirect to the index self.wait_for( - lambda: self.driver.find_element_by_id("logout"), timeout=self.timeout * 2 + lambda: self.driver.find_element_by_id("link-logout"), timeout=self.timeout * 2 ) if self.driver.current_url != self.journalist_location + "/": new_token = str(otp.now()) @@ -122,11 +122,11 @@ def _journalist_logs_in(self): assert self._is_on_journalist_homepage() def _journalist_visits_col(self): - self.wait_for(lambda: self.driver.find_element_by_id("cols")) + self.wait_for(lambda: self.driver.find_element_by_css_selector("table#collections")) self.safe_click_by_id("un-starred-source-link-1") - self.wait_for(lambda: self.driver.find_element_by_css_selector("ul#submissions")) + self.wait_for(lambda: self.driver.find_element_by_css_selector("table#submissions")) def _journalist_selects_first_doc(self): self.safe_click_by_css_selector('input[type="checkbox"][name="doc_names_selected"]') @@ -197,7 +197,7 @@ def _journalist_clicks_delete_link(self, click_id, displayed_id): self.wait_for(lambda: self.driver.find_element_by_id(displayed_id)) def _journalist_clicks_delete_selected_link(self): - self.safe_click_by_css_selector("a#delete-selected-link > button.danger") + self.safe_click_by_css_selector("a#delete-selected-link") self.wait_for(lambda: self.driver.find_element_by_id("delete-selected-confirmation-modal")) def _journalist_clicks_delete_collections_link(self): @@ -298,9 +298,9 @@ def one_source_no_files(): flash_msg = self.driver.find_element_by_css_selector(".flash") assert "The files and messages have been deleted" in flash_msg.text if not self.accept_languages: - count_div = self.driver.find_element_by_css_selector(".submission-count") - assert "0 docs" in count_div.text - assert "0 messages" in count_div.text + counts = self.driver.find_elements_by_css_selector(".submission-count") + assert "0 docs" in counts[0].text + assert "0 messages" in counts[1].text self.wait_for(one_source_no_files) time.sleep(5) @@ -471,7 +471,7 @@ def user_token_added(): def _admin_deletes_user(self): for i in range(CLICK_ATTEMPTS): try: - self.safe_click_by_css_selector(".delete-user") + self.safe_click_by_css_selector(".delete-user a") self.wait_for( lambda: expected_conditions.element_to_be_clickable((By.ID, "delete-selected")) ) @@ -570,11 +570,8 @@ def edit_page_loaded(): def _edit_user(self, username, is_admin=False): self.wait_for(lambda: self.driver.find_element_by_id("users")) - new_user_edit_links = [ - el - for el in self.driver.find_elements_by_tag_name("a") - if el.get_attribute("data-username") == username - ] + selector = 'a.edit-user[data-username="{}"]'.format(username) + new_user_edit_links = self.driver.find_elements_by_css_selector(selector) assert 1 == len(new_user_edit_links) new_user_edit_links[0].click() @@ -622,15 +619,12 @@ def _admin_editing_invalid_username(self): # Go to the admin interface self.safe_click_by_id("link-admin-index") - self.wait_for(lambda: self.driver.find_element_by_css_selector("button#add-user")) + self.wait_for(lambda: self.driver.find_element_by_id("add-user")) # Click the "edit user" link for the new user # self._edit_user(self.new_user['username']) - new_user_edit_links = [ - el - for el in self.driver.find_elements_by_tag_name("a") - if (el.get_attribute("data-username") == self.new_user["username"]) - ] + selector = 'a.edit-user[data-username="{}"]'.format(self.new_user["username"]) + new_user_edit_links = self.driver.find_elements_by_css_selector(selector) assert len(new_user_edit_links) == 1 new_user_edit_links[0].click() @@ -665,15 +659,12 @@ def _admin_can_edit_new_user(self): # Go to the admin interface self.safe_click_by_id("link-admin-index") - self.wait_for(lambda: self.driver.find_element_by_css_selector("button#add-user")) + self.wait_for(lambda: self.driver.find_element_by_id("add-user")) # Click the "edit user" link for the new user # self._edit_user(self.new_user['username']) - new_user_edit_links = [ - el - for el in self.driver.find_elements_by_tag_name("a") - if (el.get_attribute("data-username") == self.new_user["username"]) - ] + selector = 'a.edit-user[data-username="{}"]'.format(self.new_user["username"]) + new_user_edit_links = self.driver.find_elements_by_css_selector(selector) assert len(new_user_edit_links) == 1 new_user_edit_links[0].click() @@ -723,9 +714,9 @@ def can_edit_user2(): # Go to the admin interface self.safe_click_by_id("link-admin-index") - self.wait_for(lambda: self.driver.find_element_by_css_selector("button#add-user")) + self.wait_for(lambda: self.driver.find_element_by_id("add-user")) - selector = 'a[data-username="{}"]'.format(self.new_user["username"]) + selector = 'a.edit-user[data-username="{}"]'.format(self.new_user["username"]) new_user_edit_links = self.driver.find_elements_by_css_selector(selector) assert len(new_user_edit_links) == 1 self.safe_click_by_css_selector(selector) @@ -760,7 +751,7 @@ def _journalist_checks_messages(self): if not self.accept_languages: # There should be a "1 unread" span in the sole collection entry - unread_span = self.driver.find_element_by_css_selector("span.unread") + unread_span = self.driver.find_element_by_css_selector("tr.unread") assert "1 unread" in unread_span.text def _journalist_stars_and_unstars_single_message(self): @@ -808,7 +799,7 @@ def _journalist_selects_all_documents(self): def _journalist_downloads_message(self): self._journalist_selects_the_first_source() - self.wait_for(lambda: self.driver.find_element_by_css_selector("ul#submissions")) + self.wait_for(lambda: self.driver.find_element_by_css_selector("table#submissions")) submissions = self.driver.find_elements_by_css_selector("#submissions a") assert 1 == len(submissions) @@ -840,7 +831,7 @@ def cookie_string_from_selenium_cookies(cookies): def _journalist_downloads_message_missing_file(self): self._journalist_selects_the_first_source() - self.wait_for(lambda: self.driver.find_element_by_css_selector("ul#submissions")) + self.wait_for(lambda: self.driver.find_element_by_css_selector("table#submissions")) submissions = self.driver.find_elements_by_css_selector("#submissions a") assert 1 == len(submissions) @@ -915,14 +906,14 @@ def _visit_edit_totp_secret(self): ) def _admin_visits_add_user(self): - add_user_btn = self.driver.find_element_by_css_selector("button#add-user") + add_user_btn = self.driver.find_element_by_id("add-user") self.wait_for(lambda: add_user_btn.is_enabled() and add_user_btn.is_displayed()) add_user_btn.click() self.wait_for(lambda: self.driver.find_element_by_id("username")) def _admin_visits_edit_user(self): - selector = 'a[data-username="{}"]'.format(self.new_user["username"]) + selector = 'a.edit-user[data-username="{}"]'.format(self.new_user["username"]) new_user_edit_links = self.driver.find_elements_by_css_selector(selector) assert len(new_user_edit_links) == 1 self.safe_click_by_css_selector(selector) @@ -972,9 +963,9 @@ def _admin_visits_reset_2fa_hotp_step(): time.sleep(1) tip_opacity = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-hotp span")[0].value_of_css_property('opacity') + "#button-reset-two-factor-hotp span.tooltip")[0].value_of_css_property('opacity') tip_text = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-hotp span")[0].text + "#button-reset-two-factor-hotp span.tooltip")[0].text assert tip_opacity == "1" @@ -1005,9 +996,9 @@ def _admin_visits_reset_2fa_totp_step(): time.sleep(1) tip_opacity = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-totp span")[0].value_of_css_property('opacity') + "#button-reset-two-factor-totp span.tooltip")[0].value_of_css_property('opacity') tip_text = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-totp span")[0].text + "#button-reset-two-factor-totp span.tooltip")[0].text assert tip_opacity == "1" if not self.accept_languages: @@ -1068,7 +1059,7 @@ def _journalist_delete_none(self): def _journalist_delete_all_confirmation(self): self.safe_click_all_by_css_selector("[name=doc_names_selected]") - self.safe_click_by_css_selector("a#delete-selected-link > button.danger") + self.safe_click_by_css_selector("a#delete-selected-link") def _journalist_delete_one(self): self.safe_click_by_css_selector("[name=doc_names_selected]") @@ -1209,7 +1200,7 @@ def _journalist_sees_missing_file_error_message(self, single_file=False): ) if self.accept_languages is None: - assert notification.text == error_msg + assert notification.text in error_msg def _journalist_is_on_collection_page(self): return self.wait_for( @@ -1217,7 +1208,9 @@ def _journalist_is_on_collection_page(self): ) def _journalist_clicks_source_unread(self): - self.driver.find_element_by_css_selector("span.unread a").click() + self.driver.find_element_by_css_selector( + "table#collections tr.source > td.unread a" + ).click() def _journalist_selects_first_source_then_download_all(self): checkboxes = self.driver.find_elements_by_name("cols_selected") diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -68,19 +68,19 @@ def test_submit_message(journalist_app, source_app, test_journo): # The source should have a "download unread" link that # says "1 unread" - col = soup.select('ul#cols > li')[0] - unread_span = col.select('span.unread a')[0] + col = soup.select('table#collections tr.source')[0] + unread_span = col.select('td.unread a')[0] assert "1 unread" in unread_span.get_text() - col_url = soup.select('ul#cols > li a')[0]['href'] + col_url = soup.select('table#collections th.designation a')[0]['href'] resp = app.get(col_url) assert resp.status_code == 200 text = resp.data.decode('utf-8') soup = BeautifulSoup(text, 'html.parser') - submission_url = soup.select('ul#submissions li a')[0]['href'] + submission_url = soup.select('table#submissions th.filename a')[0]['href'] assert "-msg" in submission_url - span = soup.select('ul#submissions li span.info span')[0] - assert re.compile(r'\d+ bytes').match(span['title']) + size = soup.select('table#submissions td.info')[0] + assert re.compile(r'\d+ bytes').match(size['title']) resp = app.get(submission_url) assert resp.status_code == 200 @@ -97,7 +97,8 @@ def test_submit_message(journalist_app, source_app, test_journo): text = resp.data.decode('utf-8') soup = BeautifulSoup(text, 'html.parser') doc_name = soup.select( - 'ul > li > input[name="doc_names_selected"]')[0]['value'] + 'table#submissions > tr.submission > td.status input[name="doc_names_selected"]' + )[0]['value'] resp = app.post('/bulk', data=dict( action='confirm_delete', filesystem_id=filesystem_id, @@ -170,19 +171,19 @@ def test_submit_file(journalist_app, source_app, test_journo): # The source should have a "download unread" link that says # "1 unread" - col = soup.select('ul#cols > li')[0] - unread_span = col.select('span.unread a')[0] + col = soup.select('table#collections tr.source')[0] + unread_span = col.select('td.unread a')[0] assert "1 unread" in unread_span.get_text() - col_url = soup.select('ul#cols > li a')[0]['href'] + col_url = soup.select('table#collections th.designation a')[0]['href'] resp = app.get(col_url) assert resp.status_code == 200 text = resp.data.decode('utf-8') soup = BeautifulSoup(text, 'html.parser') - submission_url = soup.select('ul#submissions li a')[0]['href'] + submission_url = soup.select('table#submissions th.filename a')[0]['href'] assert "-doc" in submission_url - span = soup.select('ul#submissions li span.info span')[0] - assert re.compile(r'\d+ bytes').match(span['title']) + size = soup.select('table#submissions td.info')[0] + assert re.compile(r'\d+ bytes').match(size['title']) resp = app.get(submission_url) assert resp.status_code == 200 @@ -206,7 +207,8 @@ def test_submit_file(journalist_app, source_app, test_journo): text = resp.data.decode('utf-8') soup = BeautifulSoup(text, 'html.parser') doc_name = soup.select( - 'ul > li > input[name="doc_names_selected"]')[0]['value'] + 'table#submissions > tr.submission > td.status input[name="doc_names_selected"]' + )[0]['value'] resp = app.post('/bulk', data=dict( action='confirm_delete', filesystem_id=filesystem_id, @@ -273,7 +275,7 @@ def _helper_test_reply(journalist_app, source_app, config, test_journo, text = resp.data.decode('utf-8') assert "Sources" in text soup = BeautifulSoup(resp.data, 'html.parser') - col_url = soup.select('ul#cols > li a')[0]['href'] + col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] resp = app.get(col_url) assert resp.status_code == 200 @@ -458,7 +460,7 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): resp = app.get('/') # navigate to the collection page soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - first_col_url = soup.select('ul#cols > li a')[0]['href'] + first_col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] resp = app.get(first_col_url) assert resp.status_code == 200 @@ -561,7 +563,7 @@ def test_filenames(source_app, journalist_app, test_journo): _login_user(app, test_journo) resp = app.get('/') soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - first_col_url = soup.select('ul#cols > li a')[0]['href'] + first_col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] resp = app.get(first_col_url) assert resp.status_code == 200 @@ -569,7 +571,7 @@ def test_filenames(source_app, journalist_app, test_journo): soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') submission_filename_re = r'^{0}-[a-z0-9-_]+(-msg|-doc\.gz)\.gpg$' for i, submission_link in enumerate( - soup.select('ul#submissions li a .filename')): + soup.select('table#submissions tr.submission > th.filename a')): filename = str(submission_link.contents[0]) assert re.match(submission_filename_re.format(i + 1), filename) @@ -588,7 +590,7 @@ def test_filenames_delete(journalist_app, source_app, test_journo): _login_user(app, test_journo) resp = app.get('/') soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - first_col_url = soup.select('ul#cols > li a')[0]['href'] + first_col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] resp = app.get(first_col_url) assert resp.status_code == 200 soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') @@ -601,13 +603,13 @@ def test_filenames_delete(journalist_app, source_app, test_journo): # test filenames and sort order submission_filename_re = r'^{0}-[a-z0-9-_]+(-msg|-doc\.gz)\.gpg$' filename = str( - soup.select('ul#submissions li a .filename')[0].contents[0]) + soup.select('table#submissions tr.submission > th.filename a')[0].contents[0]) assert re.match(submission_filename_re.format(1), filename) filename = str( - soup.select('ul#submissions li a .filename')[1].contents[0]) + soup.select('table#submissions tr.submission > th.filename a')[1].contents[0]) assert re.match(submission_filename_re.format(3), filename) filename = str( - soup.select('ul#submissions li a .filename')[2].contents[0]) + soup.select('table#submissions tr.submission > th.filename a')[2].contents[0]) assert re.match(submission_filename_re.format(4), filename)
semantic (HTML5/ARIA) page structure in Journalist Interface # Description [Accessibility Lab recommendations](https://docs.google.com/document/d/1jZlKco2YgOrrI4PmTkG_Q8lKuV5VxCds/edit#) include: - `h1`...`hn` hierarchy - HTML5 section elements - ARIA roles ("landmarks"), labels, and descriptions Our findings include: - moving decorative `img` elements to CSS styles on semantic elements - Keep in mind per @eloquence in <https://github.com/freedomofpress/securedrop/issues/5972#issuecomment-947317684>: > One thing we may want to look into for the next round of changes is how to minimize the need to re-translate strings - e.g., should we generate our own translations in cases where only HTML elements or attributes change (can we do so in the main repo and then import these into Weblate?). ## User Research Evidence [WCAG 1.3.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html) per #5972. ## Progress To invert the way things are usually done :-): 1. [x] **First pass:** Refactor for semantic markup (test in developer tools and screen-readers) and keep `journalist.js` in sync - [x] decorative `img`/`hr`/etc. elements: comment out as `FIXME`s to move to CSS styles on semantic elements - [x] linters pass - [x] tests pass 2. [x] **Second pass:** Audit in validators and accessibility tools ([axe](https://www.deque.com/axe/), [WAVE](https://wave.webaim.org/)), e.g.: - `h1`...`hn` hierarchy - HTML5 section elements - ARIA roles ("landmarks"), labels, and descriptions 3. [x] Accessibility-focused review of draft PR before continuing further 4. [x] Review string changes for translation per <https://github.com/freedomofpress/securedrop/issues/5972#issuecomment-947317684> 5. [x] **Third pass:** CSS and images broken in first pass (test visually in Tor Browser) - [x] `FIXME`s - [x] Revert 6d4602da288b398dea3680dfb9faba67cf11e85a - [x] tests pass 6. [x] Write and run through test plan in #6165 | Path | First Pass | Second Pass | Third Pass | | --- | --- | --- | --- | | `securedrop/journalist_templates` | ✓ | ✓ | ✓ | | `├──_confirmation_modal.html` | ✓ | ✓| ✓ | | `├──_source_row.html` | ✓ | ✓ | ✓ | | `├──_sources_confirmation_final_modal.html` | ✓ | ✓ | ✓ | | `├──_sources_confirmation_modal.html` | ✓ | ✓ | ✓ | | `├──account_edit_hotp_secret.html` | ✓ | ✓ | ✓ | | `├──account_new_two_factor.html` | ✓ | ✓ | ✓ | | `├──admin.html` | ✓ | ✓ | ✓ | | `├──admin_add_user.html` | ✓ | ✓ | ✓ | | `├──admin_edit_hotp_secret.html` | ✓ | ✓ | ✓ | | `├──admin_new_user_two_factor.html` | ✓ | ✓ | ✓ | | `├──base.html` | ✓ | ✓ | ✓ | | `├──col.html` | ✓ | ✓ | ✓ | | `├──config.html` | ✓ | ✓ | ✓ | | `├──delete.html` | ✓ | ✓ | ✓ | | `├──edit_account.html` | ✓ | ✓ | ✓ | | `├──error.html` | ✓ | ✓ | ✓ | | `├──flashed.html` | ✓ | ✓ | ✓ | | `├──index.html` | ✓ | ✓ | ✓ | | `├──js-strings.html` | ✓ | ✓ | ✓ | | `├──locales.html` | ✓ | ✓ | ✓ | | `├──login.html` | ✓ | ✓ | ✓ | | `└──preferences_saved_flash.html` | ✓ | ✓ | ✓ | ## Specific cases - [x] Address review feedback in https://github.com/freedomofpress/securedrop/pull/6041#discussion_r673883016 - [x] Refactor `*modal.html` as `dialog`s à la Source Interface's `.{confirm,hidden}-prompt` ### `add_user.html` - [x] `h1` should not be `.visually-hidden` ### `col.html` - [x] Listing of a source collection could be a semantic `table` - [x] `securedrop/journalist_templates/col.html`: `p.breadcrumbs` is a set of unstructured inline elements; could be `ul` styled with `li:{before,after}` selectors - [x] `div dialog`s are still being read (unlike those in `index.html`) ### `index.html` - [x] List of sources could be a semantic `table` - [x] `td.filename` should wrap more elegantly (or not at all)
2021-11-10T06:01:27Z
[]
[]
freedomofpress/securedrop
6,191
freedomofpress__securedrop-6191
[ "6189" ]
eb046ca47933b6b03386955770ccb24b9f53b407
diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import os +import binascii from typing import Optional from typing import Union @@ -132,6 +133,17 @@ def add_user() -> Union[str, werkzeug.Response]: 'There was an error with the autogenerated password. ' 'User not created. Please try again.'), 'error') form_valid = False + except (binascii.Error, TypeError) as e: + if "Non-hexadecimal digit found" in str(e): + flash(gettext( + "Invalid HOTP secret format: " + "please only submit letters A-F and numbers 0-9."), + "error") + else: + flash(gettext( + "An unexpected error occurred! " + "Please inform your admin."), "error") + form_valid = False except InvalidUsernameException as e: form_valid = False # Translators: Here, "{message}" explains the problem with the username. diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -19,7 +19,8 @@ from journalist_app import utils from models import (Journalist, Reply, SeenReply, Source, Submission, LoginThrottledException, InvalidUsernameException, - BadTokenException, WrongPasswordException) + BadTokenException, InvalidOTPSecretException, + WrongPasswordException) from sdconfig import SDConfig from store import NotEncrypted @@ -133,7 +134,7 @@ def get_token() -> Tuple[flask.Response, int]: return response, 200 except (LoginThrottledException, InvalidUsernameException, - BadTokenException, WrongPasswordException): + BadTokenException, InvalidOTPSecretException, WrongPasswordException): return abort(403, 'Token authentication failed.') @api.route('/sources', methods=['GET']) diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -6,15 +6,41 @@ from wtforms import Field from wtforms import (TextAreaField, StringField, BooleanField, HiddenField, ValidationError) -from wtforms.validators import InputRequired, Optional +from wtforms.validators import InputRequired, Optional, DataRequired, StopValidation -from models import Journalist, InstanceConfig +from models import Journalist, InstanceConfig, HOTP_SECRET_LENGTH + +from typing import Any + + +class RequiredIf(DataRequired): + + def __init__(self, other_field_name: str, *args: Any, **kwargs: Any) -> None: + self.other_field_name = other_field_name + + def __call__(self, form: FlaskForm, field: Field) -> None: + if self.other_field_name in form: + other_field = form[self.other_field_name] + if bool(other_field.data): + self.message = gettext( + 'The "{name}" field is required when "{other_name}" is set.' + .format(other_name=self.other_field_name, name=field.name)) + super(RequiredIf, self).__call__(form, field) + else: + field.errors[:] = [] + raise StopValidation() + else: + raise ValidationError( + gettext( + 'The "{other_name}" field was not found - it is required by "{name}".' + .format(other_name=self.other_field_name, name=field.name)) + ) def otp_secret_validation(form: FlaskForm, field: Field) -> None: strip_whitespace = field.data.replace(' ', '') input_length = len(strip_whitespace) - if input_length != 40: + if input_length != HOTP_SECRET_LENGTH: raise ValidationError( ngettext( 'HOTP secrets are 40 characters long - you have entered {num}.', @@ -74,8 +100,8 @@ class NewUserForm(FlaskForm): is_admin = BooleanField('is_admin') is_hotp = BooleanField('is_hotp') otp_secret = StringField('otp_secret', validators=[ - otp_secret_validation, - Optional() + RequiredIf("is_hotp"), + otp_secret_validation ]) diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -16,6 +16,7 @@ BadTokenException, FirstOrLastNameError, InvalidPasswordLength, + InvalidOTPSecretException, InvalidUsernameException, Journalist, LoginThrottledException, @@ -30,6 +31,7 @@ Submission, WrongPasswordException, get_one_or_else, + HOTP_SECRET_LENGTH, ) from store import add_checksum_for_file @@ -93,6 +95,7 @@ def validate_user( try: return Journalist.login(username, password, token) except (InvalidUsernameException, + InvalidOTPSecretException, BadTokenException, WrongPasswordException, LoginThrottledException, @@ -111,6 +114,11 @@ def validate_user( "Please wait at least {num} seconds before logging in again.", period ).format(num=period) + elif isinstance(e, InvalidOTPSecretException): + login_flashed_msg += ' ' + login_flashed_msg += gettext( + "Your 2FA details are invalid" + " - please contact an administrator to reset them.") else: try: user = Journalist.query.filter_by( @@ -134,21 +142,26 @@ def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: :param otp_secret: the new HOTP secret :return: True if it validates, False if it does not """ + strip_whitespace = otp_secret.replace(' ', '') + secret_length = len(strip_whitespace) + + if secret_length != HOTP_SECRET_LENGTH: + flash(ngettext( + 'HOTP secrets are 40 characters long - you have entered {num}.', + 'HOTP secrets are 40 characters long - you have entered {num}.', + secret_length + ).format(num=secret_length), "error") + return False + try: user.set_hotp_secret(otp_secret) except (binascii.Error, TypeError) as e: if "Non-hexadecimal digit found" in str(e): flash(gettext( - "Invalid secret format: " + "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9."), "error") return False - elif "Odd-length string" in str(e): - flash(gettext( - "Invalid secret format: " - "odd-length secret. Did you mistype the secret?"), - "error") - return False else: flash(gettext( "An unexpected error occurred! " diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -36,6 +36,13 @@ ARGON2_PARAMS = dict(memory_cost=2**16, rounds=4, parallelism=2) +# Required length for hex-format HOTP secrets as input by users +HOTP_SECRET_LENGTH = 40 # 160 bits == 40 hex digits (== 32 ascii-encoded chars in db) + +# Minimum length for ascii-encoded OTP secrets - by default, secrets are now 160-bit (32 chars) +# but existing Journalist users may still have 80-bit (16-char) secrets +OTP_SECRET_MIN_ASCII_LENGTH = 16 # 80 bits == 40 hex digits (== 16 ascii-encoded chars in db) + def get_one_or_else(query: Query, logger: 'Logger', @@ -364,6 +371,11 @@ class BadTokenException(Exception): """Raised when a user logins in with an incorrect TOTP token""" +class InvalidOTPSecretException(Exception): + + """Raised when a user's OTP secret is invalid - for example, too short""" + + class PasswordError(Exception): """Generic error for passwords that are invalid. @@ -696,6 +708,9 @@ def login(cls, user.uuid in Journalist.INVALID_USERNAMES: raise InvalidUsernameException(gettext("Invalid username")) + if len(user.otp_secret) < OTP_SECRET_MIN_ASCII_LENGTH: + raise InvalidOTPSecretException(gettext("Invalid OTP secret")) + if LOGIN_HARDENING: cls.throttle_login(user)
diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -639,7 +639,7 @@ def test_user_change_password(journalist_app, test_journo): def test_login_after_regenerate_hotp(journalist_app, test_journo): """Test that journalists can login after resetting their HOTP 2fa""" - otp_secret = 'aaaaaa' + otp_secret = '0123456789abcdef0123456789abcdef01234567' b32_otp_secret = b32encode(unhexlify(otp_secret)) # edit hotp diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -52,14 +52,31 @@ VALID_PASSWORD_2 = 'another correct horse battery staple generic passphrase' -def _login_user(app, username, password, otp_secret): +def _login_user(app, username, password, otp_secret, success=True): resp = app.post(url_for('main.login'), data={'username': username, 'password': password, 'token': TOTP(otp_secret).now()}, follow_redirects=True) assert resp.status_code == 200 - assert hasattr(g, 'user') # ensure logged in + assert (success == hasattr(g, 'user')) # check logged-in vs expected + + [email protected]("otp_secret", ['', 'GA','GARBAGE','JHCOGO7VCER3EJ4']) +def test_user_with_invalid_otp_secret_cannot_login(journalist_app, otp_secret): + # Create a user with whitespace at the end of the username + with journalist_app.app_context(): + new_username = 'badotp' + otp_secret + user, password = utils.db_helper.init_journalist(is_admin=False) + user.otp_secret = otp_secret + user.username = new_username + db.session.add(user) + db.session.commit() + + # Verify that user is *not* able to login successfully + with journalist_app.test_client() as app: + _login_user(app, new_username, password, + otp_secret, success=False) def test_user_with_whitespace_in_username_can_login(journalist_app): @@ -1016,9 +1033,10 @@ def test_admin_resets_user_hotp_format_non_hexa( old_secret = journo.otp_secret + non_hexa_secret='0123456789ABCDZZ0123456789ABCDEF01234567' with InstrumentedApp(journalist_app) as ins: app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret='ZZ')) + data=dict(uid=test_journo['id'], otp_secret=non_hexa_secret)) # fetch altered DB object journo = Journalist.query.get(journo.id) @@ -1030,57 +1048,66 @@ def test_admin_resets_user_hotp_format_non_hexa( assert journo.is_totp ins.assert_message_flashed( - "Invalid secret format: please only submit letters A-F and " + "Invalid HOTP secret format: please only submit letters A-F and " "numbers 0-9.", "error") -def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): [email protected]("the_secret", [' ', ' ', '0123456789ABCDEF0123456789ABCDE']) +def test_admin_resets_user_hotp_format_too_short( + journalist_app, test_admin, test_journo, the_secret): + with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) journo = test_journo['journalist'] + # guard to ensure check below tests the correct condition + assert journo.is_totp + old_secret = journo.otp_secret with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], - otp_secret=123456)) + app.post(url_for('admin.reset_two_factor_hotp'), + data=dict(uid=test_journo['id'], otp_secret=the_secret)) # fetch altered DB object journo = Journalist.query.get(journo.id) new_secret = journo.otp_secret - assert old_secret != new_secret - assert not journo.is_totp + assert old_secret == new_secret - # Redirect to admin 2FA view - ins.assert_redirects(resp, url_for('admin.new_user_two_factor', - uid=journo.id)) + # ensure we didn't accidentally enable hotp + assert journo.is_totp + ins.assert_message_flashed( + "HOTP secrets are 40 characters long" + " - you have entered {num}.".format(num=len(the_secret.replace(' ', ''))), "error") -def test_admin_resets_user_hotp_format_odd(journalist_app, - test_admin, - test_journo): - old_secret = test_journo['otp_secret'] +def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + journo = test_journo['journalist'] + old_secret = journo.otp_secret + + valid_secret="DEADBEEF01234567DEADBEEF01234567DEADBEEF" with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret='Z')) + resp = app.post(url_for('admin.reset_two_factor_hotp'), + data=dict(uid=test_journo['id'], + otp_secret=valid_secret)) - ins.assert_message_flashed( - "Invalid secret format: " - "odd-length secret. Did you mistype the secret?", "error") + # fetch altered DB object + journo = Journalist.query.get(journo.id) - # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) - new_secret = user.otp_secret + new_secret = journo.otp_secret + assert old_secret != new_secret + assert not journo.is_totp - assert old_secret == new_secret + # Redirect to admin 2FA view + ins.assert_redirects(resp, url_for('admin.new_user_two_factor', + uid=journo.id)) def test_admin_resets_user_hotp_error(mocker, @@ -1088,7 +1115,7 @@ def test_admin_resets_user_hotp_error(mocker, test_admin, test_journo): - bad_secret = '1234' + bad_secret = '0123456789ABCDZZ0123456789ABCDZZ01234567' error_message = 'SOMETHING WRONG!' mocked_error_logger = mocker.patch('journalist.app.logger.error') old_secret = test_journo['otp_secret'] @@ -1120,7 +1147,7 @@ def test_admin_resets_user_hotp_error(mocker, def test_user_resets_hotp(journalist_app, test_journo): old_secret = test_journo['otp_secret'] - new_secret = 123456 + new_secret = '0123456789ABCDEF0123456789ABCDEF01234567' # Precondition assert new_secret != old_secret @@ -1142,39 +1169,19 @@ def test_user_resets_hotp(journalist_app, test_journo): assert old_secret != new_secret -def test_user_resets_user_hotp_format_odd(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] - - with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) - - with InstrumentedApp(journalist_app) as ins: - app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret='123')) - ins.assert_message_flashed( - "Invalid secret format: " - "odd-length secret. Did you mistype the secret?", "error") - - # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) - new_secret = user.otp_secret - - assert old_secret == new_secret - - def test_user_resets_user_hotp_format_non_hexa(journalist_app, test_journo): old_secret = test_journo['otp_secret'] + non_hexa_secret='0123456789ABCDZZ0123456789ABCDEF01234567' with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) with InstrumentedApp(journalist_app) as ins: app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret='ZZ')) + data=dict(otp_secret=non_hexa_secret)) ins.assert_message_flashed( - "Invalid secret format: " + "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9.", "error") # Re-fetch journalist to get fresh DB instance @@ -1187,7 +1194,7 @@ def test_user_resets_user_hotp_format_non_hexa(journalist_app, test_journo): def test_user_resets_user_hotp_error(mocker, journalist_app, test_journo): - bad_secret = '1234' + bad_secret = '0123456789ABCDZZ0123456789ABCDZZ01234567' old_secret = test_journo['otp_secret'] error_message = 'SOMETHING WRONG!' mocked_error_logger = mocker.patch('journalist.app.logger.error') @@ -1268,7 +1275,7 @@ def test_admin_resets_hotp_with_missing_otp_secret_key(config, journalist_app, t ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Change Secret'] + msgids = ['Change HOTP Secret'] with xfail_untranslated_messages(config, locale, msgids): assert gettext(msgids[0]) in resp.data.decode('utf-8') @@ -1528,6 +1535,40 @@ def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, s in resp.data.decode("utf-8") ) +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]( + "locale, secret", + ( + (locale, ' ' *i) + for locale in get_test_locales() + for i in range(3) + ) +) +def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, secret): + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='dellsberg', + first_name='', + last_name='', + password=VALID_PASSWORD, + password_again=VALID_PASSWORD, + is_admin=None, + is_hotp=True, + otp_secret=secret + ), + ) + + assert page_language(resp.data) == language_tag(locale) + msgids = ['The "otp_secret" field is required when "is_hotp" is set.'] + with xfail_untranslated_messages(config, locale, msgids): + # Should redirect to the token verification page + assert gettext(msgids[0]) in resp.data.decode('utf-8') + @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) @@ -2363,6 +2404,7 @@ def test_regenerate_totp(journalist_app, test_journo): def test_edit_hotp(journalist_app, test_journo): old_secret = test_journo['otp_secret'] + valid_secret="DEADBEEF01234567DEADBEEF01234567DADEFEEB" with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], @@ -2370,7 +2412,7 @@ def test_edit_hotp(journalist_app, test_journo): with InstrumentedApp(journalist_app) as ins: resp = app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret=123456)) + data=dict(otp_secret=valid_secret)) new_secret = Journalist.query.get(test_journo['id']).otp_secret
HOTP secrets are not validated correctly. ## Description HOTP secrets are not set up correctly in all cases: On the JI: - case 1: if an admin adds a user and selects the "is using a Yubikey [HOTP]" checkbox, but does not provide a HOTP secret, an error is not thrown and an account using TOTP is set up instead. - case 2: if an admin adds a user and selects the "is using a Yubikey [HOTP]" checkbox, and provides a HOTP secret containing only spaces, an error is not thrown and an account using HOTP is set up. ## Steps to Reproduce - log in to the JI as an admin user and go to **Admin** - case 1: add a user, enabling HOTP but leaving the HOTP Secret field empty - case 2: add a user, enabling HOTP and setting the HOTP Secret field to contain one or more spaces only ## Expected Behavior Both cases should fail, displaying the add user form again with a message about the length requirement for HOTP secrets ## Actual Behavior - case 1: user add succeeds, admin is redirected to TOTP setup screen - case 2: user add succeeds, admin is redirected to HOTP PIN verification screen. ## Comments Suggestions to fix, any other relevant information.
2021-12-07T23:17:04Z
[]
[]
freedomofpress/securedrop
6,217
freedomofpress__securedrop-6217
[ "6154" ]
3810e859d7bb83741f11f18369a4b3e2da50b4b9
diff --git a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py --- a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py +++ b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py @@ -17,7 +17,7 @@ try: from journalist_app import create_app from sdconfig import config - from store import NoFileFoundException, TooManyFilesException + from store import NoFileFoundException, TooManyFilesException, Storage except ImportError: # This is a fresh install, and config.py has not been created yet. if raise_errors: @@ -61,8 +61,8 @@ def upgrade(): """).bindparams(id=submission.id) ) - path = app.storage.path_without_filesystem_id(submission.filename) - app.storage.move_to_shredder(path) + path = Storage.get_default().path_without_filesystem_id(submission.filename) + Storage.get_default().move_to_shredder(path) except NoFileFoundException: # The file must have been deleted by the admin, remove the row conn.execute( @@ -83,8 +83,8 @@ def upgrade(): """).bindparams(id=reply.id) ) - path = app.storage.path_without_filesystem_id(reply.filename) - app.storage.move_to_shredder(path) + path = Storage.get_default().path_without_filesystem_id(reply.filename) + Storage.get_default().move_to_shredder(path) except NoFileFoundException: # The file must have been deleted by the admin, remove the row conn.execute( diff --git a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py --- a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py +++ b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py @@ -14,7 +14,7 @@ from journalist_app import create_app from models import Submission, Reply from sdconfig import config - from store import queued_add_checksum_for_file + from store import queued_add_checksum_for_file, Storage from worker import create_queue except: # noqa if raise_errors: @@ -58,7 +58,7 @@ def upgrade(): """ ) for (sub_id, filesystem_id, filename) in conn.execute(query): - full_path = app.storage.path(filesystem_id, filename) + full_path = Storage.get_default().path(filesystem_id, filename) create_queue().enqueue( queued_add_checksum_for_file, Submission, @@ -75,7 +75,7 @@ def upgrade(): """ ) for (rep_id, filesystem_id, filename) in conn.execute(query): - full_path = app.storage.path(filesystem_id, filename) + full_path = Storage.get_default().path(filesystem_id, filename) create_queue().enqueue( queued_add_checksum_for_file, Reply, diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -245,6 +245,6 @@ def set_locale(config: SDConfig) -> None: Update locale info in request and session. """ locale = get_locale(config) - g.localeinfo = RequestLocaleInfo(locale) + g.localeinfo = RequestLocaleInfo(locale) # pylint: disable=assigning-non-slot session["locale"] = locale - g.locales = LOCALES + g.locales = LOCALES # pylint: disable=assigning-non-slot diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from pathlib import Path from flask import (Flask, session, redirect, url_for, flash, g, request, @@ -21,7 +21,6 @@ JournalistInterfaceSessionInterface, cleanup_expired_revoked_tokens) from models import InstanceConfig, Journalist -from store import Storage import typing # https://www.python.org/dev/peps/pep-0484/#runtime-or-type-checking @@ -69,11 +68,9 @@ def create_app(config: 'SDConfig') -> Flask: app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI db.init_app(app) - # TODO: Attaching a Storage dynamically like this disables all type checking (and - # breaks code analysis tools) for code that uses current_app.storage; it should be refactored - app.storage = Storage(config.STORE_DIR, config.TEMP_DIR) - - @app.errorhandler(CSRFError) + # TODO: enable type checking once upstream Flask fix is available. See: + # https://github.com/pallets/flask/issues/4295 + @app.errorhandler(CSRFError) # type: ignore def handle_csrf_error(e: CSRFError) -> 'Response': app.logger.error("The CSRF token is invalid.") session.clear() @@ -86,9 +83,12 @@ def _handle_http_exception( ) -> 'Tuple[Union[Response, str], Optional[int]]': # Workaround for no blueprint-level 404/5 error handlers, see: # https://github.com/pallets/flask/issues/503#issuecomment-71383286 + # TODO: clean up API error handling such that all except 404/5s are + # registered in the blueprint and 404/5s are handled at the application + # level. handler = list(app.error_handler_spec['api'][error.code].values())[0] if request.path.startswith('/api/') and handler: - return handler(error) + return handler(error) # type: ignore return render_template('error.html', error=error), error.code @@ -111,13 +111,13 @@ def expire_blacklisted_tokens() -> None: cleanup_expired_revoked_tokens() @app.before_request - def load_instance_config() -> None: - app.instance_config = InstanceConfig.get_current() + def update_instance_config() -> None: + InstanceConfig.get_default(refresh=True) @app.before_request def setup_g() -> 'Optional[Response]': """Store commonly used values in Flask's special g object""" - if 'expires' in session and datetime.utcnow() >= session['expires']: + if 'expires' in session and datetime.now(timezone.utc) >= session['expires']: session.clear() flash(gettext('You have been logged out due to inactivity.'), 'error') @@ -131,24 +131,25 @@ def setup_g() -> 'Optional[Response]': flash(gettext('You have been logged out due to password change'), 'error') - session['expires'] = datetime.utcnow() + \ + session['expires'] = datetime.now(timezone.utc) + \ timedelta(minutes=getattr(config, 'SESSION_EXPIRATION_MINUTES', 120)) uid = session.get('uid', None) if uid: - g.user = Journalist.query.get(uid) + g.user = Journalist.query.get(uid) # pylint: disable=assigning-non-slot i18n.set_locale(config) - if app.instance_config.organization_name: - g.organization_name = app.instance_config.organization_name + if InstanceConfig.get_default().organization_name: + g.organization_name = \ + InstanceConfig.get_default().organization_name # pylint: disable=assigning-non-slot else: - g.organization_name = gettext('SecureDrop') + g.organization_name = gettext('SecureDrop') # pylint: disable=assigning-non-slot try: - g.logo = get_logo_url(app) + g.logo = get_logo_url(app) # pylint: disable=assigning-non-slot except FileNotFoundError: app.logger.error("Site logo not found.") @@ -161,8 +162,8 @@ def setup_g() -> 'Optional[Response]': if request.method == 'POST': filesystem_id = request.form.get('filesystem_id') if filesystem_id: - g.filesystem_id = filesystem_id - g.source = get_source(filesystem_id) + g.filesystem_id = filesystem_id # pylint: disable=assigning-non-slot + g.source = get_source(filesystem_id) # pylint: disable=assigning-non-slot return None diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -38,9 +38,9 @@ def index() -> str: def manage_config() -> Union[str, werkzeug.Response]: # The UI prompt ("prevent") is the opposite of the setting ("allow"): submission_preferences_form = SubmissionPreferencesForm( - prevent_document_uploads=not current_app.instance_config.allow_document_uploads) + prevent_document_uploads=not InstanceConfig.get_default().allow_document_uploads) organization_name_form = OrgNameForm( - organization_name=current_app.instance_config.organization_name) + organization_name=InstanceConfig.get_default().organization_name) logo_form = LogoForm() if logo_form.validate_on_submit(): f = logo_form.logo.data diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -1,12 +1,12 @@ import collections.abc import json -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Tuple, Callable, Any, Set, Union import flask import werkzeug -from flask import abort, Blueprint, current_app, jsonify, request +from flask import abort, Blueprint, jsonify, request from functools import wraps from sqlalchemy import Column @@ -22,7 +22,7 @@ BadTokenException, InvalidOTPSecretException, WrongPasswordException) from sdconfig import SDConfig -from store import NotEncrypted +from store import NotEncrypted, Storage TOKEN_EXPIRATION_MINS = 60 * 8 @@ -116,7 +116,7 @@ def get_token() -> Tuple[flask.Response, int]: try: journalist = Journalist.login(username, passphrase, one_time_code) - token_expiry = datetime.utcnow() + timedelta( + token_expiry = datetime.now(timezone.utc) + timedelta( seconds=TOKEN_EXPIRATION_MINS * 60) response = jsonify({ @@ -128,7 +128,7 @@ def get_token() -> Tuple[flask.Response, int]: }) # Update access metadata - journalist.last_access = datetime.utcnow() + journalist.last_access = datetime.now(timezone.utc) db.session.add(journalist) db.session.commit() @@ -253,7 +253,7 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: source.interaction_count += 1 try: - filename = current_app.storage.save_pre_encrypted_reply( + filename = Storage.get_default().save_pre_encrypted_reply( source.filesystem_id, source.interaction_count, source.journalist_filename, @@ -265,7 +265,7 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: # issue #3918 filename = path.basename(filename) - reply = Reply(user, source, filename) + reply = Reply(user, source, filename, Storage.get_default()) reply_uuid = data.get('uuid', None) if reply_uuid is not None: diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -29,6 +29,7 @@ col_download_all, col_star, col_un_star, col_delete, col_delete_data, mark_seen) from sdconfig import SDConfig +from store import Storage def make_blueprint(config: SDConfig) -> Blueprint: @@ -118,7 +119,7 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: if '..' in fn or fn.startswith('/'): abort(404) - file = current_app.storage.path(filesystem_id, fn) + file = Storage.get_default().path(filesystem_id, fn) if not Path(file).is_file(): flash( gettext( @@ -137,15 +138,15 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: reply = Reply.query.filter(Reply.filename == fn).one() mark_seen([reply], journalist) elif fn.endswith("-doc.gz.gpg") or fn.endswith("doc.zip.gpg"): - file = Submission.query.filter(Submission.filename == fn).one() - mark_seen([file], journalist) + submitted_file = Submission.query.filter(Submission.filename == fn).one() + mark_seen([submitted_file], journalist) else: message = Submission.query.filter(Submission.filename == fn).one() mark_seen([message], journalist) except NoResultFound as e: current_app.logger.error("Could not mark {} as seen: {}".format(fn, e)) - return send_file(current_app.storage.path(filesystem_id, fn), + return send_file(Storage.get_default().path(filesystem_id, fn), mimetype="application/pgp-encrypted") return view diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from datetime import datetime +from datetime import datetime, timezone from pathlib import Path from typing import Union @@ -19,6 +19,7 @@ from journalist_app.utils import (validate_user, bulk_delete, download, confirm_bulk_delete, get_source) from sdconfig import SDConfig +from store import Storage def make_blueprint(config: SDConfig) -> Blueprint: @@ -36,7 +37,7 @@ def login() -> Union[str, werkzeug.Response]: request.form['token'])) # Update access metadata - user.last_access = datetime.utcnow() + user.last_access = datetime.now(timezone.utc) db.session.add(user) db.session.commit() @@ -135,16 +136,16 @@ def reply() -> werkzeug.Response: EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=g.filesystem_id, reply_in=form.message.data, - encrypted_reply_path_out=Path(current_app.storage.path(g.filesystem_id, filename)), + encrypted_reply_path_out=Path(Storage.get_default().path(g.filesystem_id, filename)), ) try: - reply = Reply(g.user, g.source, filename) + reply = Reply(g.user, g.source, filename, Storage.get_default()) db.session.add(reply) seen_reply = SeenReply(reply=reply, journalist=g.user) db.session.add(seen_reply) db.session.commit() - store.async_add_checksum_for_file(reply) + store.async_add_checksum_for_file(reply, Storage.get_default()) except Exception as exc: flash(gettext( "An unexpected error occurred! Please " diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import binascii -import datetime +from datetime import datetime, timezone import os from typing import Optional, List, Union, Any @@ -34,7 +34,7 @@ get_one_or_else, HOTP_SECRET_LENGTH, ) -from store import add_checksum_for_file +from store import Storage, add_checksum_for_file def logged_in() -> bool: @@ -216,7 +216,7 @@ def download( include in the ZIP-file. """ try: - zf = current_app.storage.get_bulk_archive(submissions, zip_directory=zip_basename) + zf = Storage.get_default().get_bulk_archive(submissions, zip_directory=zip_basename) except FileNotFoundError: flash( ngettext( @@ -233,7 +233,7 @@ def download( return redirect(on_error_redirect) attachment_filename = "{}--{}.zip".format( - zip_basename, datetime.datetime.utcnow().strftime("%Y-%m-%d--%H-%M-%S") + zip_basename, datetime.now(timezone.utc).strftime("%Y-%m-%d--%H-%M-%S") ) mark_seen(submissions, g.user) @@ -247,9 +247,9 @@ def download( def delete_file_object(file_object: Union[Submission, Reply]) -> None: - path = current_app.storage.path(file_object.source.filesystem_id, file_object.filename) + path = Storage.get_default().path(file_object.source.filesystem_id, file_object.filename) try: - current_app.storage.move_to_shredder(path) + Storage.get_default().move_to_shredder(path) except ValueError as e: current_app.logger.error("could not queue file for deletion: %s", e) raise @@ -332,7 +332,7 @@ def col_delete(cols_selected: List[str]) -> werkzeug.Response: if len(cols_selected) < 1: flash(gettext("No collections selected for deletion."), "error") else: - now = datetime.datetime.utcnow() + now = datetime.now(timezone.utc) sources = Source.query.filter(Source.filesystem_id.in_(cols_selected)) sources.update({Source.deleted_at: now}, synchronize_session="fetch") db.session.commit() @@ -394,9 +394,9 @@ def col_delete_data(cols_selected: List[str]) -> werkzeug.Response: def delete_collection(filesystem_id: str) -> None: """deletes source account including files and reply key""" # Delete the source's collection of submissions - path = current_app.storage.path(filesystem_id) + path = Storage.get_default().path(filesystem_id) if os.path.exists(path): - current_app.storage.move_to_shredder(path) + Storage.get_default().move_to_shredder(path) # Delete the source's reply keypair EncryptionManager.get_default().delete_source_key_pair(filesystem_id) @@ -500,7 +500,7 @@ def col_download_all(cols_selected: List[str]) -> werkzeug.Response: def serve_file_with_etag(db_obj: Union[Reply, Submission]) -> flask.Response: - file_path = current_app.storage.path(db_obj.source.filesystem_id, db_obj.filename) + file_path = Storage.get_default().path(db_obj.source.filesystem_id, db_obj.filename) response = send_file(file_path, mimetype="application/pgp-encrypted", as_attachment=True, @@ -518,7 +518,7 @@ class JournalistInterfaceSessionInterface( sessions.SecureCookieSessionInterface): """A custom session interface that skips storing sessions for api requests but otherwise just uses the default behaviour.""" - def save_session(self, app: flask.Flask, session: Any, response: werkzeug.Response) -> None: + def save_session(self, app: flask.Flask, session: Any, response: flask.Response) -> None: # If this is an api request do not save the session if request.path.split("/")[1] == "api": return diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -17,7 +17,6 @@ from itertools import cycle from typing import Optional, Tuple -from flask import current_app from sqlalchemy.exc import IntegrityError import journalist_app @@ -38,6 +37,7 @@ from sdconfig import config from source_user import create_source_user from specialstrings import strings +from store import Storage messages = cycle(strings) replies = cycle(strings) @@ -180,13 +180,13 @@ def submit_message(source: Source, journalist_who_saw: Optional[Journalist]) -> Adds a single message submitted by a source. """ record_source_interaction(source) - fpath = current_app.storage.save_message_submission( + fpath = Storage.get_default().save_message_submission( source.filesystem_id, source.interaction_count, source.journalist_filename, next(messages), ) - submission = Submission(source, fpath) + submission = Submission(source, fpath, Storage.get_default()) db.session.add(submission) if journalist_who_saw: @@ -199,14 +199,14 @@ def submit_file(source: Source, journalist_who_saw: Optional[Journalist]) -> Non Adds a single file submitted by a source. """ record_source_interaction(source) - fpath = current_app.storage.save_file_submission( + fpath = Storage.get_default().save_file_submission( source.filesystem_id, source.interaction_count, source.journalist_filename, "memo.txt", io.BytesIO(b"This is an example of a plain text file upload."), ) - submission = Submission(source, fpath) + submission = Submission(source, fpath, Storage.get_default()) db.session.add(submission) if journalist_who_saw: @@ -225,9 +225,9 @@ def add_reply( EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=source.filesystem_id, reply_in=next(replies), - encrypted_reply_path_out=Path(current_app.storage.path(source.filesystem_id, fname)), + encrypted_reply_path_out=Path(Storage.get_default().path(source.filesystem_id, fname)), ) - reply = Reply(journalist, source, fname) + reply = Reply(journalist, source, fname, Storage.get_default()) db.session.add(reply) # Journalist who replied has seen the reply @@ -249,7 +249,7 @@ def add_source() -> Tuple[Source, str]: source_user = create_source_user( db_session=db.session, source_passphrase=codename, - source_app_storage=current_app.storage, + source_app_storage=Storage.get_default(), ) source = source_user.get_db_record() source.pending = False diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -30,6 +30,9 @@ from pyotp import TOTP, HOTP from encryption import EncryptionManager, GpgKeyNotFoundError +from store import Storage + +_default_instance_config: Optional["InstanceConfig"] = None LOGIN_HARDENING = True if os.environ.get('SECUREDROP_ENV') == 'test': @@ -130,7 +133,7 @@ def public_key(self) -> 'Optional[str]': except GpgKeyNotFoundError: return None - def to_json(self) -> 'Dict[str, Union[str, bool, int, str]]': + def to_json(self) -> 'Dict[str, object]': docs_msg_count = self.documents_messages_count() if self.last_updated: @@ -191,12 +194,11 @@ class Submission(db.Model): ''' checksum = Column(String(255)) - def __init__(self, source: Source, filename: str) -> None: + def __init__(self, source: Source, filename: str, storage: Storage) -> None: self.source_id = source.id self.filename = filename self.uuid = str(uuid.uuid4()) - self.size = os.stat(current_app.storage.path(source.filesystem_id, - filename)).st_size + self.size = os.stat(storage.path(source.filesystem_id, filename)).st_size def __repr__(self) -> str: return '<Submission %r>' % (self.filename) @@ -282,13 +284,13 @@ class Reply(db.Model): def __init__(self, journalist: 'Journalist', source: Source, - filename: str) -> None: + filename: str, + storage: Storage) -> None: self.journalist = journalist self.source_id = source.id self.uuid = str(uuid.uuid4()) self.filename = filename - self.size = os.stat(current_app.storage.path(source.filesystem_id, - filename)).st_size + self.size = os.stat(storage.path(source.filesystem_id, filename)).st_size def __repr__(self) -> str: return '<Reply %r>' % (self.filename) @@ -892,6 +894,13 @@ def copy(self) -> "InstanceConfig": return new + @classmethod + def get_default(cls, refresh: bool = False) -> "InstanceConfig": + global _default_instance_config + if (_default_instance_config is None) or (refresh is True): + _default_instance_config = InstanceConfig.get_current() + return _default_instance_config + @classmethod def get_current(cls) -> "InstanceConfig": '''If the database was created via db.create_all(), data migrations diff --git a/securedrop/request_that_secures_file_uploads.py b/securedrop/request_that_secures_file_uploads.py --- a/securedrop/request_that_secures_file_uploads.py +++ b/securedrop/request_that_secures_file_uploads.py @@ -1,5 +1,5 @@ from io import BytesIO -from typing import Optional, BinaryIO +from typing import Optional, IO from flask import wrappers from werkzeug.formparser import FormDataParser @@ -11,11 +11,11 @@ class RequestThatSecuresFileUploads(wrappers.Request): def _secure_file_stream( self, - total_content_length: int, + total_content_length: Optional[int], content_type: Optional[str], filename: Optional[str] = None, content_length: Optional[int] = None, - ) -> BinaryIO: + ) -> IO[bytes]: """Storage class for data streamed in from requests. If the data is relatively small (512KB), just store it in @@ -24,7 +24,7 @@ def _secure_file_stream( forensic recovery of the plaintext. """ - if total_content_length > 1024 * 512: + if total_content_length is None or total_content_length > 1024 * 512: # We don't use `config.TEMP_DIR` here because that # directory is exposed via X-Send-File and there is no # reason for these files to be publicly accessible. See diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -22,7 +22,6 @@ from source_app import main, info, api from source_app.decorators import ignore_static from source_app.utils import clear_session_and_redirect_to_logged_out_page -from store import Storage def get_logo_url(app: Flask) -> str: @@ -65,11 +64,9 @@ def setup_i18n() -> None: app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI db.init_app(app) - # TODO: Attaching a Storage dynamically like this disables all type checking (and - # breaks code analysis tools) for code that uses current_app.storage; it should be refactored - app.storage = Storage(config.STORE_DIR, config.TEMP_DIR) - - @app.errorhandler(CSRFError) + # TODO: enable typechecking once upstream Flask fix is available. See: + # https://github.com/pallets/flask/issues/4295 + @app.errorhandler(CSRFError) # type: ignore def handle_csrf_error(e: CSRFError) -> werkzeug.Response: return clear_session_and_redirect_to_logged_out_page(flask_session=session) @@ -113,21 +110,17 @@ def check_tor2web() -> None: "banner-warning" ) - @app.before_request - @ignore_static - def load_instance_config() -> None: - app.instance_config = InstanceConfig.get_current() - @app.before_request @ignore_static def setup_g() -> Optional[werkzeug.Response]: - if app.instance_config.organization_name: - g.organization_name = app.instance_config.organization_name + if InstanceConfig.get_default(refresh=True).organization_name: + g.organization_name = \ + InstanceConfig.get_default().organization_name # pylint: disable=assigning-non-slot else: - g.organization_name = gettext('SecureDrop') + g.organization_name = gettext('SecureDrop') # pylint: disable=assigning-non-slot try: - g.logo = get_logo_url(app) + g.logo = get_logo_url(app) # pylint: disable=assigning-non-slot except FileNotFoundError: app.logger.error("Site logo not found.") diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -1,9 +1,10 @@ import json import flask -from flask import Blueprint, current_app, make_response +from flask import Blueprint, make_response from sdconfig import SDConfig +from models import InstanceConfig from source_app.utils import get_sourcev3_url import server_os @@ -16,8 +17,8 @@ def make_blueprint(config: SDConfig) -> Blueprint: @view.route('/metadata') def metadata() -> flask.Response: meta = { - 'organization_name': current_app.instance_config.organization_name, - 'allow_document_uploads': current_app.instance_config.allow_document_uploads, + 'organization_name': InstanceConfig.get_default().organization_name, + 'allow_document_uploads': InstanceConfig.get_default().allow_document_uploads, 'gpg_fpr': config.JOURNALIST_KEY, 'sd_version': version.__version__, 'server_os': server_os.get_os_release(), diff --git a/securedrop/source_app/forms.py b/securedrop/source_app/forms.py --- a/securedrop/source_app/forms.py +++ b/securedrop/source_app/forms.py @@ -1,11 +1,10 @@ import wtforms -from flask import current_app from flask_babel import lazy_gettext as gettext from flask_wtf import FlaskForm from wtforms import FileField, PasswordField, TextAreaField from wtforms.validators import InputRequired, Regexp, Length, ValidationError -from models import Submission +from models import Submission, InstanceConfig from passphrases import PassphraseGenerator @@ -31,7 +30,7 @@ class SubmissionForm(FlaskForm): def validate_msg(self, field: wtforms.Field) -> None: if len(field.data) > Submission.MAX_MESSAGE_LEN: message = gettext("Message text too long.") - if current_app.instance_config.allow_document_uploads: + if InstanceConfig.get_default().allow_document_uploads: message = "{} {}".format( message, gettext( diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -3,7 +3,7 @@ import io from base64 import urlsafe_b64encode -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union import werkzeug @@ -13,11 +13,13 @@ import store +from store import Storage + from db import db from encryption import EncryptionManager, GpgKeyNotFoundError -from models import Submission, Reply, get_one_or_else -from passphrases import PassphraseGenerator +from models import Submission, Reply, get_one_or_else, InstanceConfig +from passphrases import PassphraseGenerator, DicewarePassphrase from sdconfig import SDConfig from source_app.decorators import login_required from source_app.session_manager import SessionManager @@ -56,7 +58,7 @@ def generate() -> Union[str, werkzeug.Response]: codenames = session.get('codenames', {}) codenames[tab_id] = codename session['codenames'] = fit_codenames_into_cookie(codenames) - session["codenames_expire"] = datetime.utcnow() + timedelta( + session["codenames_expire"] = datetime.now(timezone.utc) + timedelta( minutes=config.SESSION_EXPIRATION_MINUTES ) return render_template('generate.html', codename=codename, tab_id=tab_id) @@ -70,7 +72,7 @@ def create() -> werkzeug.Response: else: # Ensure the codenames have not expired date_codenames_expire = session.get("codenames_expire") - if not date_codenames_expire or datetime.utcnow() >= date_codenames_expire: + if not date_codenames_expire or datetime.now(timezone.utc) >= date_codenames_expire: return clear_session_and_redirect_to_logged_out_page(flask_session=session) tab_id = request.form['tab_id'] @@ -82,7 +84,7 @@ def create() -> werkzeug.Response: create_source_user( db_session=db.session, source_passphrase=codename, - source_app_storage=current_app.storage, + source_app_storage=Storage.get_default(), ) except (SourcePassphraseCollisionError, SourceDesignationCollisionError) as e: current_app.logger.error("Could not create a source: {}".format(e)) @@ -97,7 +99,8 @@ def create() -> werkzeug.Response: # All done - source user was successfully created current_app.logger.info("New source user created") session['new_user_codename'] = codename - SessionManager.log_user_in(db_session=db.session, supplied_passphrase=codename) + SessionManager.log_user_in(db_session=db.session, + supplied_passphrase=DicewarePassphrase(codename)) return redirect(url_for('.lookup')) @@ -111,7 +114,7 @@ def lookup(logged_in_source: SourceUser) -> str: ).all() for reply in source_inbox: - reply_path = current_app.storage.path( + reply_path = Storage.get_default().path( logged_in_source.filesystem_id, reply.filename, ) @@ -147,7 +150,7 @@ def lookup(logged_in_source: SourceUser) -> str: return render_template( 'lookup.html', is_user_logged_in=True, - allow_document_uploads=current_app.instance_config.allow_document_uploads, + allow_document_uploads=InstanceConfig.get_default().allow_document_uploads, replies=replies, new_user_codename=session.get('new_user_codename', None), form=SubmissionForm(), @@ -156,7 +159,7 @@ def lookup(logged_in_source: SourceUser) -> str: @view.route('/submit', methods=('POST',)) @login_required def submit(logged_in_source: SourceUser) -> werkzeug.Response: - allow_document_uploads = current_app.instance_config.allow_document_uploads + allow_document_uploads = InstanceConfig.get_default().allow_document_uploads form = SubmissionForm() if not form.validate(): for field, errors in form.errors.items(): @@ -183,15 +186,15 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: logged_in_source_in_db = logged_in_source.get_db_record() first_submission = logged_in_source_in_db.interaction_count == 0 - if not os.path.exists(current_app.storage.path(logged_in_source.filesystem_id)): + if not os.path.exists(Storage.get_default().path(logged_in_source.filesystem_id)): current_app.logger.debug("Store directory not found for source '{}', creating one." .format(logged_in_source_in_db.journalist_designation)) - os.mkdir(current_app.storage.path(logged_in_source.filesystem_id)) + os.mkdir(Storage.get_default().path(logged_in_source.filesystem_id)) if msg: logged_in_source_in_db.interaction_count += 1 fnames.append( - current_app.storage.save_message_submission( + Storage.get_default().save_message_submission( logged_in_source_in_db.filesystem_id, logged_in_source_in_db.interaction_count, logged_in_source_in_db.journalist_filename, @@ -199,7 +202,7 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: if fh: logged_in_source_in_db.interaction_count += 1 fnames.append( - current_app.storage.save_file_submission( + Storage.get_default().save_file_submission( logged_in_source_in_db.filesystem_id, logged_in_source_in_db.interaction_count, logged_in_source_in_db.journalist_filename, @@ -230,16 +233,16 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: new_submissions = [] for fname in fnames: - submission = Submission(logged_in_source_in_db, fname) + submission = Submission(logged_in_source_in_db, fname, Storage.get_default()) db.session.add(submission) new_submissions.append(submission) logged_in_source_in_db.pending = False - logged_in_source_in_db.last_updated = datetime.utcnow() + logged_in_source_in_db.last_updated = datetime.now(timezone.utc) db.session.commit() for sub in new_submissions: - store.async_add_checksum_for_file(sub) + store.async_add_checksum_for_file(sub, Storage.get_default()) normalize_timestamps(logged_in_source) @@ -289,7 +292,7 @@ def login() -> Union[str, werkzeug.Response]: try: SessionManager.log_user_in( db_session=db.session, - supplied_passphrase=request.form['codename'].strip() + supplied_passphrase=DicewarePassphrase(request.form['codename'].strip()) ) except InvalidPassphraseError: current_app.logger.info("Login failed for invalid codename") diff --git a/securedrop/source_app/session_manager.py b/securedrop/source_app/session_manager.py --- a/securedrop/source_app/session_manager.py +++ b/securedrop/source_app/session_manager.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING import sqlalchemy @@ -50,7 +50,8 @@ def log_user_in( # Save the session expiration date in the user's session cookie session_duration = timedelta(minutes=config.SESSION_EXPIRATION_MINUTES) - session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] = datetime.utcnow() + session_duration + session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] = datetime.now( + timezone.utc) + session_duration return source_user @@ -77,7 +78,7 @@ def get_logged_in_user(cls, db_session: sqlalchemy.orm.Session) -> SourceUser: cls.log_user_out() raise UserNotLoggedIn() - if datetime.utcnow() >= date_session_expires: + if datetime.now(timezone.utc) >= date_session_expires: cls.log_user_out() raise UserSessionExpired() diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -7,7 +7,9 @@ from flask import render_template from flask import current_app from flask import url_for +from flask.sessions import SessionMixin from markupsafe import Markup +from store import Storage import typing @@ -19,7 +21,7 @@ from typing import Optional -def clear_session_and_redirect_to_logged_out_page(flask_session: typing.Dict) -> werkzeug.Response: +def clear_session_and_redirect_to_logged_out_page(flask_session: SessionMixin) -> werkzeug.Response: msg = render_template('session_timeout.html') # Clear the session after we render the message so it's localized @@ -36,7 +38,7 @@ def normalize_timestamps(logged_in_source: SourceUser) -> None: #301. """ source_in_db = logged_in_source.get_db_record() - sub_paths = [current_app.storage.path(logged_in_source.filesystem_id, submission.filename) + sub_paths = [Storage.get_default().path(logged_in_source.filesystem_id, submission.filename) for submission in source_in_db.submissions] if len(sub_paths) > 1: args = ["touch", "--no-create"] diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -20,20 +20,21 @@ import rm from worker import create_queue - import typing + if typing.TYPE_CHECKING: # flake8 can not understand type annotation yet. # That is why all type annotation relative import # statements has to be marked as noqa. # http://flake8.pycqa.org/en/latest/user/error-codes.html?highlight=f401 - from typing import List, Type, Union # noqa: F401 + from typing import List, Type, Union, Optional, IO # noqa: F401 from tempfile import _TemporaryFileWrapper # type: ignore # noqa: F401 - from io import BufferedIOBase # noqa: F401 from sqlalchemy.orm import Session # noqa: F401 from models import Reply, Submission # noqa: F401 +_default_storage: typing.Optional["Storage"] = None + VALIDATE_FILENAME = re.compile( r"^(?P<index>\d+)\-[a-z0-9-_]*(?P<file_type>msg|doc\.(gz|zip)|reply)\.gpg$" @@ -112,6 +113,20 @@ def __init__(self, storage_path: str, temp_dir: str) -> None: if not rm.check_secure_delete_capability(): raise AssertionError("Secure file deletion is not possible.") + @classmethod + def get_default(cls) -> "Storage": + from sdconfig import config + + global _default_storage + + if _default_storage is None: + _default_storage = cls( + config.STORE_DIR, + config.TEMP_DIR + ) + + return _default_storage + @property def storage_path(self) -> str: return self.__storage_path @@ -314,9 +329,13 @@ def save_file_submission(self, filesystem_id: str, count: int, journalist_filename: str, - filename: str, - stream: 'BufferedIOBase') -> str: - sanitized_filename = secure_filename(filename) + filename: typing.Optional[str], + stream: 'IO[bytes]') -> str: + + if filename is not None: + sanitized_filename = secure_filename(filename) + else: + sanitized_filename = secure_filename("unknown.file") # We store file submissions in a .gz file for two reasons: # @@ -384,12 +403,12 @@ def save_message_submission(self, return filename -def async_add_checksum_for_file(db_obj: 'Union[Submission, Reply]') -> str: +def async_add_checksum_for_file(db_obj: 'Union[Submission, Reply]', storage: Storage) -> str: return create_queue().enqueue( queued_add_checksum_for_file, type(db_obj), db_obj.id, - current_app.storage.path(db_obj.source.filesystem_id, db_obj.filename), + storage.path(db_obj.source.filesystem_id, db_obj.filename), current_app.config['SQLALCHEMY_DATABASE_URI'], )
diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -34,6 +34,8 @@ from sdconfig import SDConfig, config as original_config +from store import Storage + from os import path from db import db @@ -197,41 +199,50 @@ def alembic_config(config: SDConfig) -> str: @pytest.fixture(scope='function') -def source_app(config: SDConfig) -> Generator[Flask, None, None]: +def app_storage(config: SDConfig) -> 'Storage': + return Storage(config.STORE_DIR, config.TEMP_DIR) + + [email protected](scope='function') +def source_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, None]: config.SOURCE_APP_FLASK_CONFIG_CLS.TESTING = True config.SOURCE_APP_FLASK_CONFIG_CLS.USE_X_SENDFILE = False # Disable CSRF checks to make writing tests easier config.SOURCE_APP_FLASK_CONFIG_CLS.WTF_CSRF_ENABLED = False - app = create_source_app(config) - app.config['SERVER_NAME'] = 'localhost.localdomain' - with app.app_context(): - db.create_all() - try: - yield app - finally: - db.session.rollback() - db.drop_all() + with mock.patch("store.Storage.get_default") as mock_storage_global: + mock_storage_global.return_value = app_storage + app = create_source_app(config) + app.config['SERVER_NAME'] = 'localhost.localdomain' + with app.app_context(): + db.create_all() + try: + yield app + finally: + db.session.rollback() + db.drop_all() @pytest.fixture(scope='function') -def journalist_app(config: SDConfig) -> Generator[Flask, None, None]: +def journalist_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, None]: config.JOURNALIST_APP_FLASK_CONFIG_CLS.TESTING = True config.JOURNALIST_APP_FLASK_CONFIG_CLS.USE_X_SENDFILE = False # Disable CSRF checks to make writing tests easier config.JOURNALIST_APP_FLASK_CONFIG_CLS.WTF_CSRF_ENABLED = False - app = create_journalist_app(config) - app.config['SERVER_NAME'] = 'localhost.localdomain' - with app.app_context(): - db.create_all() - try: - yield app - finally: - db.session.rollback() - db.drop_all() + with mock.patch("store.Storage.get_default") as mock_storage_global: + mock_storage_global.return_value = app_storage + app = create_journalist_app(config) + app.config['SERVER_NAME'] = 'localhost.localdomain' + with app.app_context(): + db.create_all() + try: + yield app + finally: + db.session.rollback() + db.drop_all() @pytest.fixture(scope='function') @@ -264,13 +275,13 @@ def test_admin(journalist_app: Flask) -> Dict[str, Any]: @pytest.fixture(scope='function') -def test_source(journalist_app: Flask) -> Dict[str, Any]: +def test_source(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: with journalist_app.app_context(): passphrase = PassphraseGenerator.get_default().generate_passphrase() source_user = create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=journalist_app.storage, + source_app_storage=app_storage, ) EncryptionManager.get_default().generate_source_key_pair(source_user) source = source_user.get_db_record() @@ -284,10 +295,10 @@ def test_source(journalist_app: Flask) -> Dict[str, Any]: @pytest.fixture(scope='function') -def test_submissions(journalist_app: Flask) -> Dict[str, Any]: +def test_submissions(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: with journalist_app.app_context(): - source, codename = utils.db_helper.init_source() - utils.db_helper.submit(source, 2) + source, codename = utils.db_helper.init_source(app_storage) + utils.db_helper.submit(app_storage, source, 2) return {'source': source, 'codename': codename, 'filesystem_id': source.filesystem_id, @@ -296,11 +307,11 @@ def test_submissions(journalist_app: Flask) -> Dict[str, Any]: @pytest.fixture(scope='function') -def test_files(journalist_app, test_journo): +def test_files(journalist_app, test_journo, app_storage): with journalist_app.app_context(): - source, codename = utils.db_helper.init_source() - utils.db_helper.submit(source, 2, submission_type="file") - utils.db_helper.reply(test_journo['journalist'], source, 1) + source, codename = utils.db_helper.init_source(app_storage) + utils.db_helper.submit(app_storage, source, 2, submission_type="file") + utils.db_helper.reply(app_storage, test_journo['journalist'], source, 1) return {'source': source, 'codename': codename, 'filesystem_id': source.filesystem_id, @@ -310,13 +321,13 @@ def test_files(journalist_app, test_journo): @pytest.fixture(scope='function') -def test_files_deleted_journalist(journalist_app, test_journo): +def test_files_deleted_journalist(journalist_app, test_journo, app_storage): with journalist_app.app_context(): - source, codename = utils.db_helper.init_source() - utils.db_helper.submit(source, 2) + source, codename = utils.db_helper.init_source(app_storage) + utils.db_helper.submit(app_storage, source, 2) test_journo['journalist'] juser, _ = utils.db_helper.init_journalist("f", "l", is_admin=False) - utils.db_helper.reply(juser, source, 1) + utils.db_helper.reply(app_storage, juser, source, 1) utils.db_helper.delete_journalist(juser) return {'source': source, 'codename': codename, diff --git a/securedrop/tests/functional/test_journalist.py b/securedrop/tests/functional/test_journalist.py --- a/securedrop/tests/functional/test_journalist.py +++ b/securedrop/tests/functional/test_journalist.py @@ -23,6 +23,7 @@ from . import functional_test as ft from . import journalist_navigation_steps from . import source_navigation_steps +from store import Storage from tbselenium.utils import SECURITY_LOW @@ -120,7 +121,7 @@ def missing_msg_file(self): filesystem_id = _SourceScryptManager.get_default().derive_source_filesystem_id( self.source_name ) - storage_path = Path(self.journalist_app.storage.storage_path) / filesystem_id + storage_path = Path(Storage.get_default().storage_path) / filesystem_id msg_files = [p for p in storage_path.glob("*-msg.gpg")] assert len(msg_files) == 1 msg_files[0].unlink() diff --git a/securedrop/tests/migrations/migration_b58139cfdc8c.py b/securedrop/tests/migrations/migration_b58139cfdc8c.py --- a/securedrop/tests/migrations/migration_b58139cfdc8c.py +++ b/securedrop/tests/migrations/migration_b58139cfdc8c.py @@ -3,6 +3,7 @@ import os import random import uuid +import mock from os import path from sqlalchemy import text @@ -10,6 +11,7 @@ from db import db from journalist_app import create_app +from store import Storage from .helpers import random_chars, random_datetime random.seed('ᕕ( ᐛ )ᕗ') @@ -123,25 +125,32 @@ def __init__(self, config): self.config = config self.app = create_app(config) + # as this class requires access to the Storage object, which is no longer + # attached to app, we create it here and mock the call to return it below. + self.storage = Storage(config.STORE_DIR, config.TEMP_DIR) + def load_data(self): global DATA - with self.app.app_context(): - self.create_journalist() - self.create_source() - - submission_id, submission_filename = self.create_submission() - reply_id, reply_filename = self.create_reply() - - # we need to actually create files and write data to them so the RQ worker can hash them - for fn in [submission_filename, reply_filename]: - full_path = self.app.storage.path(self.source_filesystem_id, fn) - - dirname = path.dirname(full_path) - if not path.exists(dirname): - os.mkdir(dirname) - - with io.open(full_path, 'wb') as f: - f.write(DATA) + with mock.patch("store.Storage.get_default") as mock_storage_global: + mock_storage_global.return_value = self.storage + with self.app.app_context(): + self.create_journalist() + self.create_source() + + submission_id, submission_filename = self.create_submission() + reply_id, reply_filename = self.create_reply() + + # we need to actually create files and write data to them so the + # RQ worker can hash them + for fn in [submission_filename, reply_filename]: + full_path = Storage.get_default().path(self.source_filesystem_id, fn) + + dirname = path.dirname(full_path) + if not path.exists(dirname): + os.mkdir(dirname) + + with io.open(full_path, 'wb') as f: + f.write(DATA) def check_upgrade(self): ''' diff --git a/securedrop/tests/test_db.py b/securedrop/tests/test_db.py --- a/securedrop/tests/test_db.py +++ b/securedrop/tests/test_db.py @@ -74,18 +74,19 @@ def test_throttle_login(journalist_app, test_journo): Journalist.throttle_login(journalist) -def test_submission_string_representation(journalist_app, test_source): +def test_submission_string_representation(journalist_app, test_source, app_storage): with journalist_app.app_context(): - db_helper.submit(test_source['source'], 2) + db_helper.submit(app_storage, test_source['source'], 2) test_submission = Submission.query.first() test_submission.__repr__() def test_reply_string_representation(journalist_app, test_journo, - test_source): + test_source, + app_storage): with journalist_app.app_context(): - db_helper.reply(test_journo['journalist'], + db_helper.reply(app_storage, test_journo['journalist'], test_source['source'], 2) test_reply = Reply.query.first() diff --git a/securedrop/tests/test_encryption.py b/securedrop/tests/test_encryption.py --- a/securedrop/tests/test_encryption.py +++ b/securedrop/tests/test_encryption.py @@ -17,13 +17,14 @@ def test_get_default(self, config): assert encryption_mgr assert encryption_mgr.get_journalist_public_key() - def test_generate_source_key_pair(self, setup_journalist_key_and_gpg_folder, source_app): + def test_generate_source_key_pair(self, setup_journalist_key_and_gpg_folder, + source_app, app_storage): # Given a source user with source_app.app_context(): source_user = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) # And an encryption manager @@ -59,7 +60,7 @@ def test_generate_source_key_pair(self, setup_journalist_key_and_gpg_folder, sou # And the user's key does not expire assert source_key_details["expires"] == "" - def test_get_source_public_key(self, source_app, test_source): + def test_get_source_public_key(self, test_source): # Given a source user with a key pair in the default encryption manager source_user = test_source["source_user"] encryption_mgr = EncryptionManager.get_default() @@ -225,7 +226,8 @@ def test_encrypt_source_file(self, setup_journalist_key_and_gpg_folder, tmp_path # For GPG 2.1+, a non-null passphrase _must_ be passed to decrypt() assert not encryption_mgr._gpg.decrypt(encrypted_file, passphrase="test 123").ok - def test_encrypt_and_decrypt_journalist_reply(self, source_app, test_source, tmp_path): + def test_encrypt_and_decrypt_journalist_reply(self, source_app, test_source, + tmp_path, app_storage): # Given a source user with a key pair in the default encryption manager source_user1 = test_source["source_user"] encryption_mgr = EncryptionManager.get_default() @@ -235,7 +237,7 @@ def test_encrypt_and_decrypt_journalist_reply(self, source_app, test_source, tmp source_user2 = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) encryption_mgr.generate_source_key_pair(source_user2) diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -11,12 +11,13 @@ import mock from bs4 import BeautifulSoup -from flask import current_app, escape, g, session +from flask import escape, g, session from pyotp import HOTP, TOTP import journalist_app as journalist_app_module from db import db from encryption import EncryptionManager +from store import Storage from source_app.session_manager import SessionManager from . import utils from .test_encryption import import_journalist_private_key @@ -37,7 +38,7 @@ def _login_user(app, user_dict): assert hasattr(g, 'user') # ensure logged in -def test_submit_message(journalist_app, source_app, test_journo): +def test_submit_message(journalist_app, source_app, test_journo, app_storage): """When a source creates an account, test that a new entry appears in the journalist interface""" test_msg = "This is a test message." @@ -134,12 +135,12 @@ def test_submit_message(journalist_app, source_app, test_journo): # needs to wait for the worker to get the job and execute it def assertion(): assert not ( - os.path.exists(current_app.storage.path(filesystem_id, - doc_name))) + os.path.exists(app_storage.path(filesystem_id, + doc_name))) utils.asynchronous.wait_for_assertion(assertion) -def test_submit_file(journalist_app, source_app, test_journo): +def test_submit_file(journalist_app, source_app, test_journo, app_storage): """When a source creates an account, test that a new entry appears in the journalist interface""" test_file_contents = b"This is a test file." @@ -243,8 +244,7 @@ def test_submit_file(journalist_app, source_app, test_journo): # needs to wait for the worker to get the job and execute it def assertion(): assert not ( - os.path.exists(current_app.storage.path(filesystem_id, - doc_name))) + os.path.exists(app_storage.path(filesystem_id, doc_name))) utils.asynchronous.wait_for_assertion(assertion) @@ -380,8 +380,8 @@ def _helper_filenames_delete(journalist_app, soup, i): # Make sure the files were deleted from the filesystem def assertion(): - assert not any([os.path.exists(current_app.storage.path(filesystem_id, - doc_name)) + assert not any([os.path.exists(Storage.get_default().path(filesystem_id, + doc_name)) for doc_name in checkbox_values]) utils.asynchronous.wait_for_assertion(assertion) @@ -481,7 +481,7 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): # Make sure the collection is deleted from the filesystem def assertion(): - assert not os.path.exists(current_app.storage.path(filesystem_id)) + assert not os.path.exists(Storage.get_default().path(filesystem_id)) utils.asynchronous.wait_for_assertion(assertion) @@ -525,7 +525,7 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): # Make sure the collections are deleted from the filesystem def assertion(): assert not ( - any([os.path.exists(current_app.storage.path(filesystem_id)) + any([os.path.exists(Storage.get_default().path(filesystem_id)) for filesystem_id in checkbox_values])) utils.asynchronous.wait_for_assertion(assertion) diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -2261,11 +2261,11 @@ def test_passphrase_migration_on_reset(journalist_app): assert journalist.valid_password(VALID_PASSWORD) -def test_journalist_reply_view(journalist_app, test_source, test_journo): - source, _ = utils.db_helper.init_source() +def test_journalist_reply_view(journalist_app, test_source, test_journo, app_storage): + source, _ = utils.db_helper.init_source(app_storage) journalist, _ = utils.db_helper.init_journalist() - submissions = utils.db_helper.submit(source, 1) - replies = utils.db_helper.reply(journalist, source, 1) + submissions = utils.db_helper.submit(app_storage, source, 1) + replies = utils.db_helper.reply(app_storage, journalist, source, 1) subm_url = url_for('col.download_single_file', filesystem_id=submissions[0].source.filesystem_id, @@ -2426,7 +2426,8 @@ def test_edit_hotp(journalist_app, test_journo): def test_delete_data_deletes_submissions_retaining_source(journalist_app, test_journo, - test_source): + test_source, + app_storage): """Verify that when only a source's data is deleted, the submissions are deleted but the source is not.""" @@ -2434,8 +2435,8 @@ def test_delete_data_deletes_submissions_retaining_source(journalist_app, source = Source.query.get(test_source['id']) journo = Journalist.query.get(test_journo['id']) - utils.db_helper.submit(source, 2) - utils.db_helper.reply(journo, source, 2) + utils.db_helper.submit(app_storage, source, 2) + utils.db_helper.reply(app_storage, journo, source, 2) assert len(source.collection) == 4 @@ -2450,7 +2451,8 @@ def test_delete_data_deletes_submissions_retaining_source(journalist_app, def test_delete_source_deletes_submissions(journalist_app, test_journo, - test_source): + test_source, + app_storage): """Verify that when a source is deleted, the submissions that correspond to them are also deleted.""" @@ -2458,8 +2460,8 @@ def test_delete_source_deletes_submissions(journalist_app, source = Source.query.get(test_source['id']) journo = Journalist.query.get(test_journo['id']) - utils.db_helper.submit(source, 2) - utils.db_helper.reply(journo, source, 2) + utils.db_helper.submit(app_storage, source, 2) + utils.db_helper.reply(app_storage, journo, source, 2) journalist_app_module.utils.delete_collection( test_source['filesystem_id']) @@ -2468,7 +2470,7 @@ def test_delete_source_deletes_submissions(journalist_app, assert res is None -def test_delete_collection_updates_db(journalist_app, test_journo, test_source): +def test_delete_collection_updates_db(journalist_app, test_journo, test_source, app_storage): """ Verify that when a source is deleted, the Source record is deleted and all records associated with the source are deleted. @@ -2477,11 +2479,11 @@ def test_delete_collection_updates_db(journalist_app, test_journo, test_source): with journalist_app.app_context(): source = Source.query.get(test_source["id"]) journo = Journalist.query.get(test_journo["id"]) - files = utils.db_helper.submit(source, 2) + files = utils.db_helper.submit(app_storage, source, 2) mark_seen(files, journo) - messages = utils.db_helper.submit(source, 2) + messages = utils.db_helper.submit(app_storage, source, 2) mark_seen(messages, journo) - replies = utils.db_helper.reply(journo, source, 2) + replies = utils.db_helper.reply(app_storage, journo, source, 2) mark_seen(replies, journo) journalist_app_module.utils.delete_collection(test_source["filesystem_id"]) @@ -2520,7 +2522,8 @@ def test_delete_collection_updates_db(journalist_app, test_journo, test_source): def test_delete_source_deletes_source_key(journalist_app, test_source, - test_journo): + test_journo, + app_storage): """Verify that when a source is deleted, the PGP key that corresponds to them is also deleted.""" @@ -2528,8 +2531,8 @@ def test_delete_source_deletes_source_key(journalist_app, source = Source.query.get(test_source['id']) journo = Journalist.query.get(test_journo['id']) - utils.db_helper.submit(source, 2) - utils.db_helper.reply(journo, source, 2) + utils.db_helper.submit(app_storage, source, 2) + utils.db_helper.reply(app_storage, journo, source, 2) # Source key exists encryption_mgr = EncryptionManager.get_default() @@ -2546,7 +2549,8 @@ def test_delete_source_deletes_source_key(journalist_app, def test_delete_source_deletes_docs_on_disk(journalist_app, test_source, test_journo, - config): + config, + app_storage): """Verify that when a source is deleted, the encrypted documents that exist on disk is also deleted.""" @@ -2554,8 +2558,8 @@ def test_delete_source_deletes_docs_on_disk(journalist_app, source = Source.query.get(test_source['id']) journo = Journalist.query.get(test_journo['id']) - utils.db_helper.submit(source, 2) - utils.db_helper.reply(journo, source, 2) + utils.db_helper.submit(app_storage, source, 2) + utils.db_helper.reply(app_storage, journo, source, 2) dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) assert os.path.exists(dir_source_docs) @@ -2571,7 +2575,8 @@ def assertion(): def test_bulk_delete_deletes_db_entries(journalist_app, test_source, test_journo, - config): + config, + app_storage): """ Verify that when files are deleted, the corresponding db entries are also deleted. @@ -2581,8 +2586,8 @@ def test_bulk_delete_deletes_db_entries(journalist_app, source = Source.query.get(test_source['id']) journo = Journalist.query.get(test_journo['id']) - utils.db_helper.submit(source, 2) - utils.db_helper.reply(journo, source, 2) + utils.db_helper.submit(app_storage, source, 2) + utils.db_helper.reply(app_storage, journo, source, 2) dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) assert os.path.exists(dir_source_docs) @@ -2614,18 +2619,19 @@ def db_assertion(): def test_bulk_delete_works_when_files_absent(journalist_app, test_source, test_journo, - config): + config, + app_storage): """ Verify that when files are deleted but are already missing, - the corresponding db entries are still + the corresponding db entries are still deleted """ with journalist_app.app_context(): source = Source.query.get(test_source['id']) journo = Journalist.query.get(test_journo['id']) - utils.db_helper.submit(source, 2) - utils.db_helper.reply(journo, source, 2) + utils.db_helper.submit(app_storage, source, 2) + utils.db_helper.reply(app_storage, journo, source, 2) dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) assert os.path.exists(dir_source_docs) @@ -2705,12 +2711,12 @@ def test_render_locales(config, journalist_app, test_journo, test_source): def test_download_selected_submissions_and_replies( - journalist_app, test_journo, test_source + journalist_app, test_journo, test_source, app_storage ): journo = Journalist.query.get(test_journo["id"]) source = Source.query.get(test_source["id"]) - submissions = utils.db_helper.submit(source, 4) - replies = utils.db_helper.reply(journo, source, 4) + submissions = utils.db_helper.submit(app_storage, source, 4) + replies = utils.db_helper.reply(app_storage, journo, source, 4) selected_submissions = random.sample(submissions, 2) selected_replies = random.sample(replies, 2) selected = [submission.filename for submission in selected_submissions + selected_replies] @@ -2775,12 +2781,12 @@ def test_download_selected_submissions_and_replies( def test_download_selected_submissions_and_replies_previously_seen( - journalist_app, test_journo, test_source + journalist_app, test_journo, test_source, app_storage ): journo = Journalist.query.get(test_journo["id"]) source = Source.query.get(test_source["id"]) - submissions = utils.db_helper.submit(source, 4) - replies = utils.db_helper.reply(journo, source, 4) + submissions = utils.db_helper.submit(app_storage, source, 4) + replies = utils.db_helper.reply(app_storage, journo, source, 4) selected_submissions = random.sample(submissions, 2) selected_replies = random.sample(replies, 2) selected = [submission.filename for submission in selected_submissions + selected_replies] @@ -2853,12 +2859,12 @@ def test_download_selected_submissions_and_replies_previously_seen( def test_download_selected_submissions_previously_downloaded( - journalist_app, test_journo, test_source + journalist_app, test_journo, test_source, app_storage ): journo = Journalist.query.get(test_journo["id"]) source = Source.query.get(test_source["id"]) - submissions = utils.db_helper.submit(source, 4) - replies = utils.db_helper.reply(journo, source, 4) + submissions = utils.db_helper.submit(app_storage, source, 4) + replies = utils.db_helper.reply(app_storage, journo, source, 4) selected_submissions = random.sample(submissions, 2) selected_replies = random.sample(replies, 2) selected = [submission.filename for submission in selected_submissions + selected_replies] @@ -2915,13 +2921,13 @@ def test_download_selected_submissions_previously_downloaded( @pytest.fixture(scope="function") -def selected_missing_files(journalist_app, test_source): +def selected_missing_files(journalist_app, test_source, app_storage): """Fixture for the download tests with missing files in storage.""" source = Source.query.get(test_source["id"]) - submissions = utils.db_helper.submit(source, 2) + submissions = utils.db_helper.submit(app_storage, source, 2) selected = sorted([s.filename for s in submissions]) - storage_path = Path(journalist_app.storage.storage_path) + storage_path = Path(app_storage.storage_path) msg_files = sorted([p for p in storage_path.rglob("*") if p.is_file()]) assert len(msg_files) == 2 for file in msg_files: @@ -2931,7 +2937,7 @@ def selected_missing_files(journalist_app, test_source): def test_download_selected_submissions_missing_files( - journalist_app, test_journo, test_source, mocker, selected_missing_files + journalist_app, test_journo, test_source, mocker, selected_missing_files, app_storage ): """Tests download of selected submissions with missing files in storage.""" mocked_error_logger = mocker.patch('journalist.app.logger.error') @@ -2958,7 +2964,7 @@ def test_download_selected_submissions_missing_files( expected_calls = [] for file in selected_missing_files: missing_file = ( - Path(journalist_app.storage.storage_path) + Path(app_storage.storage_path) .joinpath(test_source["filesystem_id"]) .joinpath(file) .as_posix() @@ -2969,7 +2975,7 @@ def test_download_selected_submissions_missing_files( def test_download_single_submission_missing_file( - journalist_app, test_journo, test_source, mocker, selected_missing_files + journalist_app, test_journo, test_source, mocker, selected_missing_files, app_storage ): """Tests download of single submissions with missing files in storage.""" mocked_error_logger = mocker.patch('journalist.app.logger.error') @@ -2994,7 +3000,7 @@ def test_download_single_submission_missing_file( assert resp.status_code == 302 missing_file = ( - Path(journalist_app.storage.storage_path) + Path(app_storage.storage_path) .joinpath(test_source["filesystem_id"]) .joinpath(missing_file) .as_posix() @@ -3005,14 +3011,14 @@ def test_download_single_submission_missing_file( ) -def test_download_unread_all_sources(journalist_app, test_journo): +def test_download_unread_all_sources(journalist_app, test_journo, app_storage): """ Test that downloading all unread creates a zip that contains all unread submissions from the selected sources and marks these submissions as seen. """ journo = Journalist.query.get(test_journo["id"]) - bulk = utils.db_helper.bulk_setup_for_seen_only(journo) + bulk = utils.db_helper.bulk_setup_for_seen_only(journo, app_storage) with journalist_app.test_client() as app: _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) @@ -3081,14 +3087,14 @@ def test_download_unread_all_sources(journalist_app, test_journo): assert zipinfo -def test_download_all_selected_sources(journalist_app, test_journo): +def test_download_all_selected_sources(journalist_app, test_journo, app_storage): """ Test that downloading all selected sources creates zip that contains all submissions from the selected sources and marks these submissions as seen. """ journo = Journalist.query.get(test_journo["id"]) - bulk = utils.db_helper.bulk_setup_for_seen_only(journo) + bulk = utils.db_helper.bulk_setup_for_seen_only(journo, app_storage) with journalist_app.test_client() as app: _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) @@ -3263,14 +3269,14 @@ def test_col_process_aborts_with_bad_action(journalist_app, test_journo): def test_col_process_successfully_deletes_multiple_sources(journalist_app, - test_journo): + test_journo, app_storage): # Create two sources with one submission each - source_1, _ = utils.db_helper.init_source() - utils.db_helper.submit(source_1, 1) - source_2, _ = utils.db_helper.init_source() - utils.db_helper.submit(source_2, 1) - source_3, _ = utils.db_helper.init_source() - utils.db_helper.submit(source_3, 1) + source_1, _ = utils.db_helper.init_source(app_storage) + utils.db_helper.submit(app_storage, source_1, 1) + source_2, _ = utils.db_helper.init_source(app_storage) + utils.db_helper.submit(app_storage, source_2, 1) + source_3, _ = utils.db_helper.init_source(app_storage) + utils.db_helper.submit(app_storage, source_3, 1) with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], @@ -3296,8 +3302,9 @@ def test_col_process_successfully_deletes_multiple_sources(journalist_app, def test_col_process_successfully_stars_sources(journalist_app, test_journo, - test_source): - utils.db_helper.submit(test_source['source'], 1) + test_source, + app_storage): + utils.db_helper.submit(app_storage, test_source['source'], 1) with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], @@ -3316,8 +3323,9 @@ def test_col_process_successfully_stars_sources(journalist_app, def test_col_process_successfully_unstars_sources(journalist_app, test_journo, - test_source): - utils.db_helper.submit(test_source['source'], 1) + test_source, + app_storage): + utils.db_helper.submit(app_storage, test_source['source'], 1) with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -718,7 +718,7 @@ def test_unencrypted_replies_get_rejected(journalist_app, journalist_api_token, def test_authorized_user_can_add_reply(journalist_app, journalist_api_token, - test_source, test_journo): + test_source, test_journo, app_storage): with journalist_app.test_client() as app: source_id = test_source['source'].id uuid = test_source['source'].uuid @@ -760,8 +760,7 @@ def test_authorized_user_can_add_reply(journalist_app, journalist_api_token, expected_filename = '{}-{}-reply.gpg'.format( source.interaction_count, source.journalist_filename) - expected_filepath = journalist_app.storage.path( - source.filesystem_id, expected_filename) + expected_filepath = app_storage.path(source.filesystem_id, expected_filename) with open(expected_filepath, 'rb') as fh: saved_content = fh.read() diff --git a/securedrop/tests/test_manage.py b/securedrop/tests/test_manage.py --- a/securedrop/tests/test_manage.py +++ b/securedrop/tests/test_manage.py @@ -215,7 +215,7 @@ def test_clean_tmp_removed(config, caplog): assert 'FILE removed' in caplog.text -def test_were_there_submissions_today(source_app, config): +def test_were_there_submissions_today(source_app, config, app_storage): with source_app.app_context() as context: # We need to override the config to point at the per-test DB data_root = config.SECUREDROP_DATA_ROOT @@ -225,7 +225,7 @@ def test_were_there_submissions_today(source_app, config): source_user = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) source = source_user.get_db_record() source.last_updated = (datetime.datetime.utcnow() - datetime.timedelta(hours=24*2)) diff --git a/securedrop/tests/test_session_manager.py b/securedrop/tests/test_session_manager.py --- a/securedrop/tests/test_session_manager.py +++ b/securedrop/tests/test_session_manager.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from unittest import mock import pytest @@ -15,13 +15,13 @@ class TestSessionManager: - def test_log_user_in(self, source_app): + def test_log_user_in(self, source_app, app_storage): # Given a source user passphrase = PassphraseGenerator.get_default().generate_passphrase() source_user = create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) with source_app.test_request_context(): @@ -33,13 +33,13 @@ def test_log_user_in(self, source_app): logged_in_user = SessionManager.get_logged_in_user(db_session=db.session) assert logged_in_user.db_record_id == source_user.db_record_id - def test_log_user_out(self, source_app): + def test_log_user_out(self, source_app, app_storage): # Given a source user passphrase = PassphraseGenerator.get_default().generate_passphrase() create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) with source_app.test_request_context(): @@ -54,13 +54,13 @@ def test_log_user_out(self, source_app): with pytest.raises(UserNotLoggedIn): SessionManager.get_logged_in_user(db_session=db.session) - def test_get_logged_in_user_but_session_expired(self, source_app): + def test_get_logged_in_user_but_session_expired(self, source_app, app_storage): # Given a source user passphrase = PassphraseGenerator.get_default().generate_passphrase() create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) with source_app.test_request_context(): @@ -69,21 +69,21 @@ def test_get_logged_in_user_but_session_expired(self, source_app): # But we're now 6 hours later hence their session expired with mock.patch("source_app.session_manager.datetime") as mock_datetime: - six_hours_later = datetime.utcnow() + timedelta(hours=6) - mock_datetime.utcnow.return_value = six_hours_later + six_hours_later = datetime.now(timezone.utc) + timedelta(hours=6) + mock_datetime.now.return_value = six_hours_later # When querying the current user from the SessionManager # it fails with the right error with pytest.raises(UserSessionExpired): SessionManager.get_logged_in_user(db_session=db.session) - def test_get_logged_in_user_but_user_deleted(self, source_app): + def test_get_logged_in_user_but_user_deleted(self, source_app, app_storage): # Given a source user passphrase = PassphraseGenerator.get_default().generate_passphrase() source_user = create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) with source_app.test_request_context(): diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -6,7 +6,7 @@ import time import os import shutil -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from io import BytesIO, StringIO from pathlib import Path from unittest import mock @@ -319,17 +319,17 @@ def login_test(app, codename): login_test(app, codename_) -def test_login_with_missing_reply_files(source_app): +def test_login_with_missing_reply_files(source_app, app_storage): """ Test that source can log in when replies are present in database but missing from storage. """ - source, codename = utils.db_helper.init_source() + source, codename = utils.db_helper.init_source(app_storage) journalist, _ = utils.db_helper.init_journalist() - replies = utils.db_helper.reply(journalist, source, 1) + replies = utils.db_helper.reply(app_storage, journalist, source, 1) assert len(replies) > 0 # Delete the reply file - reply_file_path = Path(source_app.storage.path(source.filesystem_id, replies[0].filename)) + reply_file_path = Path(app_storage.path(source.filesystem_id, replies[0].filename)) reply_file_path.unlink() assert not reply_file_path.exists() @@ -445,12 +445,12 @@ def test_submit_both(source_app): assert "Thanks! We received your message and document" in text -def test_delete_all_successfully_deletes_replies(source_app): +def test_delete_all_successfully_deletes_replies(source_app, app_storage): with source_app.app_context(): journalist, _ = utils.db_helper.init_journalist() - source, codename = utils.db_helper.init_source() + source, codename = utils.db_helper.init_source(app_storage) source_id = source.id - utils.db_helper.reply(journalist, source, 1) + utils.db_helper.reply(app_storage, journalist, source, 1) with source_app.test_client() as app: resp = app.post(url_for('main.login'), @@ -469,13 +469,13 @@ def test_delete_all_successfully_deletes_replies(source_app): assert reply.deleted_by_source is True -def test_delete_all_replies_deleted_by_source_but_not_journalist(source_app): +def test_delete_all_replies_deleted_by_source_but_not_journalist(source_app, app_storage): """Replies can be deleted by a source, but not by journalists. As such, replies may still exist in the replies table, but no longer be visible.""" with source_app.app_context(): journalist, _ = utils.db_helper.init_journalist() - source, codename = utils.db_helper.init_source() - utils.db_helper.reply(journalist, source, 1) + source, codename = utils.db_helper.init_source(app_storage) + utils.db_helper.reply(app_storage, journalist, source, 1) replies = Reply.query.filter(Reply.source_id == source.id).all() for reply in replies: reply.deleted_by_source = True @@ -496,10 +496,10 @@ def test_delete_all_replies_deleted_by_source_but_not_journalist(source_app): ) -def test_delete_all_replies_already_deleted_by_journalists(source_app): +def test_delete_all_replies_already_deleted_by_journalists(source_app, app_storage): with source_app.app_context(): journalist, _ = utils.db_helper.init_journalist() - source, codename = utils.db_helper.init_source() + source, codename = utils.db_helper.init_source(app_storage) # Note that we are creating the source and no replies with source_app.test_client() as app: @@ -627,7 +627,7 @@ def test_login_with_overly_long_codename(source_app): .format(PassphraseGenerator.MAX_PASSPHRASE_LENGTH)) in text -def test_normalize_timestamps(source_app): +def test_normalize_timestamps(source_app, app_storage): """ Check function of source_app.utils.normalize_timestamps. @@ -637,14 +637,14 @@ def test_normalize_timestamps(source_app): """ with source_app.test_client() as app: # create a source - source, codename = utils.db_helper.init_source() + source, codename = utils.db_helper.init_source(app_storage) # create one submission - first_submission = submit(source, 1)[0] + first_submission = submit(app_storage, source, 1)[0] # delete the submission's file from the store first_submission_path = Path( - source_app.storage.path(source.filesystem_id, first_submission.filename) + app_storage.path(source.filesystem_id, first_submission.filename) ) first_submission_path.unlink() assert not first_submission_path.exists() @@ -676,7 +676,7 @@ def test_normalize_timestamps(source_app): # only two of the source's three submissions should have files in the store assert 3 == len(source.submissions) submission_paths = [ - Path(source_app.storage.path(source.filesystem_id, s.filename)) + Path(app_storage.path(source.filesystem_id, s.filename)) for s in source.submissions ] extant_paths = [p for p in submission_paths if p.exists()] @@ -766,8 +766,8 @@ def test_source_session_expiration(source_app): # But we're now 6 hours later hence their session expired with mock.patch("source_app.session_manager.datetime") as mock_datetime: - six_hours_later = datetime.utcnow() + timedelta(hours=6) - mock_datetime.utcnow.return_value = six_hours_later + six_hours_later = datetime.now(timezone.utc) + timedelta(hours=6) + mock_datetime.now.return_value = six_hours_later # When they browse to an authenticated page resp = app.get(url_for('main.lookup'), follow_redirects=True) @@ -785,8 +785,8 @@ def test_source_session_expiration_create(source_app): # But we're now 6 hours later hence they did not finish the account creation flow in time with mock.patch("source_app.main.datetime") as mock_datetime: - six_hours_later = datetime.utcnow() + timedelta(hours=6) - mock_datetime.utcnow.return_value = six_hours_later + six_hours_later = datetime.now(timezone.utc) + timedelta(hours=6) + mock_datetime.now.return_value = six_hours_later # When the user tries to complete the create flow resp = app.post(url_for('main.create'), follow_redirects=True) @@ -805,7 +805,7 @@ def test_source_no_session_expiration_message_when_not_logged_in(source_app): # And their session expired with mock.patch("source_app.session_manager.datetime") as mock_datetime: six_hours_later = datetime.utcnow() + timedelta(hours=6) - mock_datetime.utcnow.return_value = six_hours_later + mock_datetime.now.return_value = six_hours_later # When they browse again the index page refreshed_resp = app.get(url_for('main.index'), follow_redirects=True) @@ -827,14 +827,14 @@ def test_csrf_error_page(source_app): assert 'You were logged out due to inactivity' in text -def test_source_can_only_delete_own_replies(source_app): +def test_source_can_only_delete_own_replies(source_app, app_storage): '''This test checks for a bug an authenticated source A could delete replies send to source B by "guessing" the filename. ''' - source0, codename0 = utils.db_helper.init_source() - source1, codename1 = utils.db_helper.init_source() + source0, codename0 = utils.db_helper.init_source(app_storage) + source1, codename1 = utils.db_helper.init_source(app_storage) journalist, _ = utils.db_helper.init_journalist() - replies = utils.db_helper.reply(journalist, source0, 1) + replies = utils.db_helper.reply(app_storage, journalist, source0, 1) filename = replies[0].filename confirmation_msg = 'Reply deleted' diff --git a/securedrop/tests/test_source_user.py b/securedrop/tests/test_source_user.py --- a/securedrop/tests/test_source_user.py +++ b/securedrop/tests/test_source_user.py @@ -19,7 +19,7 @@ class TestSourceUser: - def test_create_source_user(self, source_app): + def test_create_source_user(self, source_app, app_storage): # Given a passphrase passphrase = PassphraseGenerator.get_default().generate_passphrase() @@ -27,18 +27,18 @@ def test_create_source_user(self, source_app): source_user = create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) assert source_user assert source_user.get_db_record() - def test_create_source_user_passphrase_collision(self, source_app): + def test_create_source_user_passphrase_collision(self, source_app, app_storage): # Given a source in the DB passphrase = PassphraseGenerator.get_default().generate_passphrase() create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) # When trying to create another with the same passphrase, it fails @@ -46,15 +46,15 @@ def test_create_source_user_passphrase_collision(self, source_app): create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) - def test_create_source_user_designation_collision(self, source_app): + def test_create_source_user_designation_collision(self, source_app, app_storage): # Given a source in the DB existing_source = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) existing_designation = existing_source.get_db_record().journalist_designation @@ -69,16 +69,16 @@ def test_create_source_user_designation_collision(self, source_app): create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) - def test_authenticate_source_user(self, source_app): + def test_authenticate_source_user(self, source_app, app_storage): # Given a source in the DB passphrase = PassphraseGenerator.get_default().generate_passphrase() source_user = create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) # When they try to authenticate using their passphrase @@ -90,12 +90,12 @@ def test_authenticate_source_user(self, source_app): assert authenticated_user assert authenticated_user.db_record_id == source_user.db_record_id - def test_authenticate_source_user_wrong_passphrase(self, source_app): + def test_authenticate_source_user_wrong_passphrase(self, source_app, app_storage): # Given a source in the DB create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=source_app.storage, + source_app_storage=app_storage, ) # When a user tries to authenticate using a wrong passphrase, it fails diff --git a/securedrop/tests/test_store.py b/securedrop/tests/test_store.py --- a/securedrop/tests/test_store.py +++ b/securedrop/tests/test_store.py @@ -6,6 +6,9 @@ import re import stat import zipfile +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Generator from passphrases import PassphraseGenerator from source_user import create_source_user @@ -19,9 +22,25 @@ from store import Storage, queued_add_checksum_for_file, async_add_checksum_for_file -def create_file_in_source_dir(config, filesystem_id, filename): [email protected](scope="function") +def test_storage( +) -> Generator[Storage, None, None]: + # Setup the filesystem for the storage object + with TemporaryDirectory() as data_dir_name: + data_dir = Path(data_dir_name) + store_dir = data_dir / "store" + store_dir.mkdir() + tmp_dir = data_dir / "tmp" + tmp_dir.mkdir() + + storage = Storage(str(store_dir), str(tmp_dir)) + + yield storage + + +def create_file_in_source_dir(base_dir, filesystem_id, filename): """Helper function for simulating files""" - source_directory = os.path.join(config.STORE_DIR, + source_directory = os.path.join(base_dir, filesystem_id) os.makedirs(source_directory) @@ -32,34 +51,33 @@ def create_file_in_source_dir(config, filesystem_id, filename): return source_directory, file_path -def test_path_returns_filename_of_folder(journalist_app, config): +def test_path_returns_filename_of_folder(test_storage): """`Storage.path` is called in this way in journalist.delete_collection """ filesystem_id = 'example' - generated_absolute_path = journalist_app.storage.path(filesystem_id) + generated_absolute_path = test_storage.path(filesystem_id) - expected_absolute_path = os.path.join(config.STORE_DIR, filesystem_id) + expected_absolute_path = os.path.join(test_storage.storage_path, filesystem_id) assert generated_absolute_path == expected_absolute_path -def test_path_returns_filename_of_items_within_folder(journalist_app, config): - """`Storage.path` is called in this way in journalist.bulk_delete""" +def test_path_returns_filename_of_items_within_folder(test_storage): + """`Storage.path` is called in this way in journalist.bulk_delete""" filesystem_id = 'example' item_filename = '1-quintuple_cant-msg.gpg' - generated_absolute_path = journalist_app.storage.path(filesystem_id, - item_filename) + generated_absolute_path = test_storage.path(filesystem_id, item_filename) - expected_absolute_path = os.path.join(config.STORE_DIR, + expected_absolute_path = os.path.join(test_storage.storage_path, filesystem_id, item_filename) assert generated_absolute_path == expected_absolute_path -def test_path_without_filesystem_id(journalist_app, config): +def test_path_without_filesystem_id(test_storage): filesystem_id = 'example' item_filename = '1-quintuple_cant-msg.gpg' - basedir = os.path.join(config.STORE_DIR, filesystem_id) + basedir = os.path.join(test_storage.storage_path, filesystem_id) os.makedirs(basedir) path_to_file = os.path.join(basedir, item_filename) @@ -67,20 +85,20 @@ def test_path_without_filesystem_id(journalist_app, config): os.utime(path_to_file, None) generated_absolute_path = \ - journalist_app.storage.path_without_filesystem_id(item_filename) + test_storage.path_without_filesystem_id(item_filename) - expected_absolute_path = os.path.join(config.STORE_DIR, + expected_absolute_path = os.path.join(test_storage.storage_path, filesystem_id, item_filename) assert generated_absolute_path == expected_absolute_path -def test_path_without_filesystem_id_duplicate_files(journalist_app, config): +def test_path_without_filesystem_id_duplicate_files(test_storage): filesystem_id = 'example' filesystem_id_duplicate = 'example2' item_filename = '1-quintuple_cant-msg.gpg' - basedir = os.path.join(config.STORE_DIR, filesystem_id) - duplicate_basedir = os.path.join(config.STORE_DIR, filesystem_id_duplicate) + basedir = os.path.join(test_storage.storage_path, filesystem_id) + duplicate_basedir = os.path.join(test_storage.storage_path, filesystem_id_duplicate) for directory in [basedir, duplicate_basedir]: os.makedirs(directory) @@ -89,43 +107,43 @@ def test_path_without_filesystem_id_duplicate_files(journalist_app, config): os.utime(path_to_file, None) with pytest.raises(store.TooManyFilesException): - journalist_app.storage.path_without_filesystem_id(item_filename) + test_storage.path_without_filesystem_id(item_filename) -def test_path_without_filesystem_id_no_file(journalist_app, config): +def test_path_without_filesystem_id_no_file(test_storage): item_filename = 'not there' with pytest.raises(store.NoFileFoundException): - journalist_app.storage.path_without_filesystem_id(item_filename) + test_storage.path_without_filesystem_id(item_filename) -def test_verify_path_not_absolute(journalist_app, config): +def test_verify_path_not_absolute(test_storage): with pytest.raises(store.PathException): - journalist_app.storage.verify( - os.path.join(config.STORE_DIR, '..', 'etc', 'passwd')) + test_storage.verify( + os.path.join(test_storage.storage_path, '..', 'etc', 'passwd')) -def test_verify_in_store_dir(journalist_app, config): +def test_verify_in_store_dir(test_storage): with pytest.raises(store.PathException) as e: - path = config.STORE_DIR + "_backup" - journalist_app.storage.verify(path) + path = test_storage.storage_path + "_backup" + test_storage.verify(path) assert e.message == "Path not valid in store: {}".format(path) -def test_verify_store_path_not_absolute(journalist_app): +def test_verify_store_path_not_absolute(test_storage): with pytest.raises(store.PathException) as e: - journalist_app.storage.verify('..') + test_storage.verify('..') assert e.message == "Path not valid in store: .." -def test_verify_rejects_symlinks(journalist_app): +def test_verify_rejects_symlinks(test_storage): """ Test that verify rejects paths involving links outside the store. """ try: - link = os.path.join(journalist_app.storage.storage_path, "foo") + link = os.path.join(test_storage.storage_path, "foo") os.symlink("/foo", link) with pytest.raises(store.PathException) as e: - journalist_app.storage.verify(link) + test_storage.verify(link) assert e.message == "Path not valid in store: {}".format(link) finally: os.unlink(link) @@ -147,7 +165,7 @@ def test_verify_store_temp_dir_not_absolute(): assert re.compile('temp_dir.*is not absolute').match(msg) -def test_verify_regular_submission_in_sourcedir_returns_true(journalist_app, config): +def test_verify_regular_submission_in_sourcedir_returns_true(test_storage): """ Tests that verify is happy with a regular submission file. @@ -155,48 +173,46 @@ def test_verify_regular_submission_in_sourcedir_returns_true(journalist_app, con naming scheme of submissions. """ source_directory, file_path = create_file_in_source_dir( - config, 'example-filesystem-id', '1-regular-doc.gz.gpg' + test_storage.storage_path, 'example-filesystem-id', '1-regular-doc.gz.gpg' ) - assert journalist_app.storage.verify(file_path) + assert test_storage.verify(file_path) -def test_verify_invalid_file_extension_in_sourcedir_raises_exception( - journalist_app, config): +def test_verify_invalid_file_extension_in_sourcedir_raises_exception(test_storage): source_directory, file_path = create_file_in_source_dir( - config, 'example-filesystem-id', 'not_valid.txt' + test_storage.storage_path, 'example-filesystem-id', 'not_valid.txt' ) with pytest.raises(store.PathException) as e: - journalist_app.storage.verify(file_path) + test_storage.verify(file_path) assert 'Path not valid in store: {}'.format(file_path) in str(e) -def test_verify_invalid_filename_in_sourcedir_raises_exception( - journalist_app, config): +def test_verify_invalid_filename_in_sourcedir_raises_exception(test_storage): source_directory, file_path = create_file_in_source_dir( - config, 'example-filesystem-id', 'NOTVALID.gpg' + test_storage.storage_path, 'example-filesystem-id', 'NOTVALID.gpg' ) with pytest.raises(store.PathException) as e: - journalist_app.storage.verify(file_path) + test_storage.verify(file_path) assert e.message == 'Path not valid in store: {}'.format(file_path) -def test_get_zip(journalist_app, test_source, config): +def test_get_zip(journalist_app, test_source, app_storage, config): with journalist_app.app_context(): submissions = utils.db_helper.submit( - test_source['source'], 2) + app_storage, test_source['source'], 2) filenames = [os.path.join(config.STORE_DIR, test_source['filesystem_id'], submission.filename) for submission in submissions] archive = zipfile.ZipFile( - journalist_app.storage.get_bulk_archive(submissions)) + app_storage.get_bulk_archive(submissions)) archivefile_contents = archive.namelist() for archived_file, actual_file in zip(archivefile_contents, filenames): @@ -207,7 +223,7 @@ def test_get_zip(journalist_app, test_source, config): @pytest.mark.parametrize('db_model', [Submission, Reply]) -def test_add_checksum_for_file(config, db_model): +def test_add_checksum_for_file(config, app_storage, db_model): ''' Check that when we execute the `add_checksum_for_file` function, the database object is correctly updated with the actual hash of the file. @@ -217,15 +233,17 @@ def test_add_checksum_for_file(config, db_model): ''' app = create_app(config) + test_storage = app_storage + with app.app_context(): db.create_all() source_user = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=app.storage, + source_app_storage=test_storage, ) source = source_user.get_db_record() - target_file_path = app.storage.path(source.filesystem_id, '1-foo-msg.gpg') + target_file_path = test_storage.path(source.filesystem_id, '1-foo-msg.gpg') test_message = b'hash me!' expected_hash = 'f1df4a6d8659471333f7f6470d593e0911b4d487856d88c83d2d187afa195927' @@ -233,10 +251,10 @@ def test_add_checksum_for_file(config, db_model): f.write(test_message) if db_model == Submission: - db_obj = Submission(source, target_file_path) + db_obj = Submission(source, target_file_path, app_storage) else: journalist, _ = utils.db_helper.init_journalist() - db_obj = Reply(journalist, source, target_file_path) + db_obj = Reply(journalist, source, target_file_path, app_storage) db.session.add(db_obj) db.session.commit() @@ -254,7 +272,7 @@ def test_add_checksum_for_file(config, db_model): @pytest.mark.parametrize('db_model', [Submission, Reply]) -def test_async_add_checksum_for_file(config, db_model): +def test_async_add_checksum_for_file(config, app_storage, db_model): ''' Check that when we execute the `add_checksum_for_file` function, the database object is correctly updated with the actual hash of the file. @@ -269,10 +287,10 @@ def test_async_add_checksum_for_file(config, db_model): source_user = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=app.storage, + source_app_storage=app_storage, ) source = source_user.get_db_record() - target_file_path = app.storage.path(source.filesystem_id, '1-foo-msg.gpg') + target_file_path = app_storage.path(source.filesystem_id, '1-foo-msg.gpg') test_message = b'hash me!' expected_hash = 'f1df4a6d8659471333f7f6470d593e0911b4d487856d88c83d2d187afa195927' @@ -280,16 +298,16 @@ def test_async_add_checksum_for_file(config, db_model): f.write(test_message) if db_model == Submission: - db_obj = Submission(source, target_file_path) + db_obj = Submission(source, target_file_path, app_storage) else: journalist, _ = utils.db_helper.init_journalist() - db_obj = Reply(journalist, source, target_file_path) + db_obj = Reply(journalist, source, target_file_path, app_storage) db.session.add(db_obj) db.session.commit() db_obj_id = db_obj.id - job = async_add_checksum_for_file(db_obj) + job = async_add_checksum_for_file(db_obj, app_storage) utils.asynchronous.wait_for_redis_worker(job, timeout=5) @@ -299,7 +317,7 @@ def test_async_add_checksum_for_file(config, db_model): assert db_obj.checksum == 'sha256:' + expected_hash -def test_path_configuration_is_immutable(journalist_app): +def test_path_configuration_is_immutable(test_storage): """ Check that the store's paths cannot be changed. @@ -309,62 +327,62 @@ def test_path_configuration_is_immutable(journalist_app): are prevented. """ with pytest.raises(AttributeError): - journalist_app.storage.storage_path = "/foo" + test_storage.storage_path = "/foo" - original_storage_path = journalist_app.storage.storage_path[:] - journalist_app.storage.__storage_path = "/foo" - assert journalist_app.storage.storage_path == original_storage_path + original_storage_path = test_storage.storage_path[:] + test_storage.__storage_path = "/foo" + assert test_storage.storage_path == original_storage_path with pytest.raises(AttributeError): - journalist_app.storage.shredder_path = "/foo" + test_storage.shredder_path = "/foo" - original_shredder_path = journalist_app.storage.shredder_path[:] - journalist_app.storage.__shredder_path = "/foo" - assert journalist_app.storage.shredder_path == original_shredder_path + original_shredder_path = test_storage.shredder_path[:] + test_storage.__shredder_path = "/foo" + assert test_storage.shredder_path == original_shredder_path -def test_shredder_configuration(journalist_app): +def test_shredder_configuration(journalist_app, app_storage): """ Ensure we're creating the shredder directory correctly. We want to ensure that it's a sibling of the store directory, with mode 0700. """ - store_path = journalist_app.storage.storage_path - shredder_path = journalist_app.storage.shredder_path + store_path = app_storage.storage_path + shredder_path = app_storage.shredder_path assert os.path.dirname(shredder_path) == os.path.dirname(store_path) s = os.stat(shredder_path) assert stat.S_ISDIR(s.st_mode) is True assert stat.S_IMODE(s.st_mode) == 0o700 -def test_shredder_deletes_symlinks(journalist_app, caplog): +def test_shredder_deletes_symlinks(journalist_app, app_storage, caplog): """ Confirm that `store.clear_shredder` removes any symlinks in the shredder. """ caplog.set_level(logging.DEBUG) link_target = "/foo" - link = os.path.abspath(os.path.join(journalist_app.storage.shredder_path, "foo")) + link = os.path.abspath(os.path.join(app_storage.shredder_path, "foo")) os.symlink(link_target, link) - journalist_app.storage.clear_shredder() + app_storage.clear_shredder() assert "Deleting link {} to {}".format(link, link_target) in caplog.text assert not os.path.exists(link) -def test_shredder_shreds(journalist_app, caplog): +def test_shredder_shreds(journalist_app, app_storage, caplog): """ Confirm that `store.clear_shredder` removes files. """ caplog.set_level(logging.DEBUG) - testdir = os.path.abspath(os.path.join(journalist_app.storage.shredder_path, "testdir")) + testdir = os.path.abspath(os.path.join(app_storage.shredder_path, "testdir")) os.makedirs(testdir) testfile = os.path.join(testdir, "testfile") with open(testfile, "w") as f: f.write("testdata\n") - journalist_app.storage.clear_shredder() + app_storage.clear_shredder() assert "Securely deleted file 1/1: {}".format(testfile) in caplog.text assert not os.path.isfile(testfile) assert not os.path.isdir(testdir) diff --git a/securedrop/tests/test_submission_cleanup.py b/securedrop/tests/test_submission_cleanup.py --- a/securedrop/tests/test_submission_cleanup.py +++ b/securedrop/tests/test_submission_cleanup.py @@ -8,16 +8,16 @@ from tests import utils -def test_delete_disconnected_db_submissions(journalist_app, config): +def test_delete_disconnected_db_submissions(journalist_app, app_storage, config): """ Test that Submission records without corresponding files are deleted. """ with journalist_app.app_context(): - source, _ = utils.db_helper.init_source() + source, _ = utils.db_helper.init_source(app_storage) source_id = source.id # make two submissions - utils.db_helper.submit(source, 2) + utils.db_helper.submit(app_storage, source, 2) submission_id = source.submissions[0].id # remove one submission's file @@ -39,14 +39,14 @@ def test_delete_disconnected_db_submissions(journalist_app, config): assert db.session.query(Submission).filter(Submission.source_id == source_id).count() == 1 -def test_delete_disconnected_fs_submissions(journalist_app, config): +def test_delete_disconnected_fs_submissions(journalist_app, app_storage, config): """ Test that files in the store without corresponding Submission records are deleted. """ - source, _ = utils.db_helper.init_source() + source, _ = utils.db_helper.init_source(app_storage) # make two submissions - utils.db_helper.submit(source, 2) + utils.db_helper.submit(app_storage, source, 2) source_filesystem_id = source.filesystem_id submission_filename = source.submissions[0].filename disconnect_path = os.path.join(config.STORE_DIR, source_filesystem_id, submission_filename) @@ -54,7 +54,7 @@ def test_delete_disconnected_fs_submissions(journalist_app, config): # make two replies, to make sure that their files are not seen # as disconnects journalist, _ = utils.db_helper.init_journalist("Mary", "Lane") - utils.db_helper.reply(journalist, source, 2) + utils.db_helper.reply(app_storage, journalist, source, 2) # delete the first Submission record db.session.delete(source.submissions[0]) diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -10,7 +10,6 @@ from typing import Dict, List import mock -from flask import current_app from db import db from encryption import EncryptionManager @@ -18,6 +17,7 @@ from models import Journalist, Reply, SeenReply, Submission from passphrases import PassphraseGenerator from source_user import create_source_user +from store import Storage def init_journalist(first_name=None, last_name=None, is_admin=False): @@ -55,7 +55,7 @@ def delete_journalist(journalist): db.session.commit() -def reply(journalist, source, num_replies): +def reply(storage, journalist, source, num_replies): """Generates and submits *num_replies* replies to *source* from *journalist*. Returns reply objects as a list. @@ -78,10 +78,10 @@ def reply(journalist, source, num_replies): EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=source.filesystem_id, reply_in=str(os.urandom(1)), - encrypted_reply_path_out=current_app.storage.path(source.filesystem_id, fname), + encrypted_reply_path_out=storage.path(source.filesystem_id, fname), ) - reply = Reply(journalist, source, fname) + reply = Reply(journalist, source, fname, storage) replies.append(reply) db.session.add(reply) seen_reply = SeenReply(reply=reply, journalist=journalist) @@ -118,7 +118,7 @@ def mark_downloaded(*submissions): # {Source,Submission} -def init_source(): +def init_source(storage): """Initialize a source: create their database record, the filesystem directory that stores their submissions & replies, and their GPG key encrypted with their codename. Return a source @@ -131,17 +131,19 @@ def init_source(): source_user = create_source_user( db_session=db.session, source_passphrase=passphrase, - source_app_storage=current_app.storage, + source_app_storage=storage, ) EncryptionManager.get_default().generate_source_key_pair(source_user) return source_user.get_db_record(), passphrase -def submit(source, num_submissions, submission_type="message"): +def submit(storage, source, num_submissions, submission_type="message"): """Generates and submits *num_submissions* :class:`Submission`s on behalf of a :class:`Source` *source*. + :param Storage storage: the Storage object to use. + :param Source source: The source on who's behalf to make submissions. @@ -158,7 +160,7 @@ def submit(source, num_submissions, submission_type="message"): source.interaction_count += 1 source.pending = False if submission_type == "file": - fpath = current_app.storage.save_file_submission( + fpath = storage.save_file_submission( source.filesystem_id, source.interaction_count, source.journalist_filename, @@ -166,13 +168,13 @@ def submit(source, num_submissions, submission_type="message"): io.BytesIO(b"Ceci n'est pas une pipe.") ) else: - fpath = current_app.storage.save_message_submission( + fpath = storage.save_message_submission( source.filesystem_id, source.interaction_count, source.journalist_filename, str(os.urandom(1)) ) - submission = Submission(source, fpath) + submission = Submission(source, fpath, storage) submissions.append(submission) db.session.add(source) db.session.add(submission) @@ -190,7 +192,7 @@ def new_codename(client, session): return codename -def bulk_setup_for_seen_only(journo: Journalist) -> List[Dict]: +def bulk_setup_for_seen_only(journo: Journalist, storage: Storage) -> List[Dict]: """ Create some sources with some seen submissions that are not marked as 'downloaded' in the database and some seen replies from journo. @@ -201,13 +203,13 @@ def bulk_setup_for_seen_only(journo: Journalist) -> List[Dict]: for i in range(random.randint(2, 4)): collection = {} - source, _ = init_source() + source, _ = init_source(storage) - submissions = submit(source, random.randint(2, 4)) + submissions = submit(storage, source, random.randint(2, 4)) half = math.ceil(len(submissions) / 2) messages = submissions[half:] files = submissions[:half] - replies = reply(journo, source, random.randint(1, 3)) + replies = reply(storage, journo, source, random.randint(1, 3)) seen_files = random.sample(files, math.ceil(len(files) / 2)) seen_messages = random.sample(messages, math.ceil(len(messages) / 2))
Update Flask version to 2.0.*, along with associated requirements ## Description Core requirements (Flask, Werkzeug, Jinja, etc) are lagging behind their most up-to-date available versions by quite a bit. This complicates the process of upgrading other requirements with shared dependencies (e.g. the `click` package). An attempt at updating these requirements to recent versions has been started in https://github.com/freedomofpress/securedrop/tree/add-https-to-dev - this has uncovered some juicy issues: - some application requirements are duplicated in test requirements, and as test requirements are installed *last* in the dev Docker container, application-side updates to those requirements are not reflected in dev (current workaround in branch is to swap the order in which requirements are installed) - `Pylint` now complains with an `E0237: assgning-non-slot` error when attributes are assigned to the flask.g object - see https://github.com/pallets/flask/issues/4020 for more. (The simplest workaround for this is to disable pylint assigning-non-slot warnings, either selectively or globally) - There are some new `mypy` errors of note: - Adding attributes to the Flask object (to make them "global") throws an error like `error: "Flask" has no attribute "instance_config"` - see https://github.com/pallets/flask/issues/4167 for an explanation - stricter type checking is causing errors like [this one](https://app.circleci.com/pipelines/github/freedomofpress/securedrop/3162/workflows/73985030-c78d-4f4e-a125-48303e1405b9/jobs/57561?invite=true&invite=true#step-110-415) A more informed attempt would probably start by cleaning up the existing requirements so that the test requirements are in sync with securedrop-app-code requirements, and then address the mypy globals issue, since that is likely to have the biggest impact on application code. Prerequisite tasks for this dependency update: - [x] #6160 - [ ] Update flask-babel: remove refs to `app.babel_instance` (done in `add-https-to-dev` branch) - [x] #6201 - [x] #6202 - [ ] #6203
A few things I thought of: > Adding attributes to the Flask object (to make them "global") throws an error like `error: "Flask" has no attribute "instance_config"` Dynamically adding attributes to the Flask object (or any object) is a bit of an anti-pattern as it causes various problems, one of them being that the dynamically-added attribute is not type-checked at all. Hence, in the context of type-checking, mypy is "right" to complain about it. I described this problem in more details in https://github.com/freedomofpress/securedrop/issues/5599. I am close to being done with the CryptoUtil refactoring to specifically address that (next PR at https://github.com/freedomofpress/securedrop/pull/6087, and after that one there will probably be one more). I think it would be valuable to remove dynamically-added attributes from the code base. After CryptoUtil, I think there will be a couple more (I remember Storage being one of them). > Pylint now complains with an E0237: assgning-non-slot error when attributes are assigned to the flask.g object. Similarly, using flask.g is a bit of anti-pattern too as it cannot be type-checked either (the content of g is fully dynamic). Even Flask recommends against using it in https://flask.palletsprojects.com/en/1.1.x/design/#micro-with-dependencies and I also talked a little bit about it in https://github.com/freedomofpress/securedrop/pull/5694 . I think the usage of flask.g should be reduced to the minimum. Overall, both patterns (dynamically adding attributes and using flask.g) are "incompatible" with type-checking (and have other problems). I think there's value in moving away from them. Not really what this GItHub issue is about but I thought I'd give my opinion 😅. Thanks @nabla-c0d3 - it may not explicitly be the topic of the issue but it does seem necessary for the version bump and is extremely useful feedback! Getting type checking working against CryptoUtil is probably the most critical part security-wise - thanks for the work you've done already. IIRC `storage` and `instance_config` are also dynamically attached, and can probably be refactored out as globals in much the same way. I'll take a look at #6087 on Monday and maybe also see about the requirements cleanup mentioned above (which isn't related to the code refactoring, but probably still needs doing). One gotcha here is that `flask-babel`'s Babel object attaches itself as the `babel_instance` attribute to the Flask app, so for that one an approach other than the one in the CryptoUtil refactor may be required (or we could suppress that single mypy error).
2022-01-10T16:07:40Z
[]
[]
freedomofpress/securedrop
6,222
freedomofpress__securedrop-6222
[ "6189" ]
bc3ca5851b11607479bc1352064598c862d00baf
diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import os +import binascii from typing import Optional from typing import Union @@ -132,6 +133,17 @@ def add_user() -> Union[str, werkzeug.Response]: 'There was an error with the autogenerated password. ' 'User not created. Please try again.'), 'error') form_valid = False + except (binascii.Error, TypeError) as e: + if "Non-hexadecimal digit found" in str(e): + flash(gettext( + "Invalid HOTP secret format: " + "please only submit letters A-F and numbers 0-9."), + "error") + else: + flash(gettext( + "An unexpected error occurred! " + "Please inform your admin."), "error") + form_valid = False except InvalidUsernameException as e: form_valid = False # Translators: Here, "{message}" explains the problem with the username. diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -19,7 +19,8 @@ from journalist_app import utils from models import (Journalist, Reply, SeenReply, Source, Submission, LoginThrottledException, InvalidUsernameException, - BadTokenException, WrongPasswordException) + BadTokenException, InvalidOTPSecretException, + WrongPasswordException) from sdconfig import SDConfig from store import NotEncrypted @@ -133,7 +134,7 @@ def get_token() -> Tuple[flask.Response, int]: return response, 200 except (LoginThrottledException, InvalidUsernameException, - BadTokenException, WrongPasswordException): + BadTokenException, InvalidOTPSecretException, WrongPasswordException): return abort(403, 'Token authentication failed.') @api.route('/sources', methods=['GET']) diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -6,15 +6,41 @@ from wtforms import Field from wtforms import (TextAreaField, StringField, BooleanField, HiddenField, ValidationError) -from wtforms.validators import InputRequired, Optional +from wtforms.validators import InputRequired, Optional, DataRequired, StopValidation -from models import Journalist, InstanceConfig +from models import Journalist, InstanceConfig, HOTP_SECRET_LENGTH + +from typing import Any + + +class RequiredIf(DataRequired): + + def __init__(self, other_field_name: str, *args: Any, **kwargs: Any) -> None: + self.other_field_name = other_field_name + + def __call__(self, form: FlaskForm, field: Field) -> None: + if self.other_field_name in form: + other_field = form[self.other_field_name] + if bool(other_field.data): + self.message = gettext( + 'The "{name}" field is required when "{other_name}" is set.' + .format(other_name=self.other_field_name, name=field.name)) + super(RequiredIf, self).__call__(form, field) + else: + field.errors[:] = [] + raise StopValidation() + else: + raise ValidationError( + gettext( + 'The "{other_name}" field was not found - it is required by "{name}".' + .format(other_name=self.other_field_name, name=field.name)) + ) def otp_secret_validation(form: FlaskForm, field: Field) -> None: strip_whitespace = field.data.replace(' ', '') input_length = len(strip_whitespace) - if input_length != 40: + if input_length != HOTP_SECRET_LENGTH: raise ValidationError( ngettext( 'HOTP secrets are 40 characters long - you have entered {num}.', @@ -74,8 +100,8 @@ class NewUserForm(FlaskForm): is_admin = BooleanField('is_admin') is_hotp = BooleanField('is_hotp') otp_secret = StringField('otp_secret', validators=[ - otp_secret_validation, - Optional() + RequiredIf("is_hotp"), + otp_secret_validation ]) diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -16,6 +16,7 @@ BadTokenException, FirstOrLastNameError, InvalidPasswordLength, + InvalidOTPSecretException, InvalidUsernameException, Journalist, LoginThrottledException, @@ -30,6 +31,7 @@ Submission, WrongPasswordException, get_one_or_else, + HOTP_SECRET_LENGTH, ) from store import add_checksum_for_file @@ -93,6 +95,7 @@ def validate_user( try: return Journalist.login(username, password, token) except (InvalidUsernameException, + InvalidOTPSecretException, BadTokenException, WrongPasswordException, LoginThrottledException, @@ -111,6 +114,11 @@ def validate_user( "Please wait at least {num} seconds before logging in again.", period ).format(num=period) + elif isinstance(e, InvalidOTPSecretException): + login_flashed_msg += ' ' + login_flashed_msg += gettext( + "Your 2FA details are invalid" + " - please contact an administrator to reset them.") else: try: user = Journalist.query.filter_by( @@ -134,21 +142,26 @@ def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: :param otp_secret: the new HOTP secret :return: True if it validates, False if it does not """ + strip_whitespace = otp_secret.replace(' ', '') + secret_length = len(strip_whitespace) + + if secret_length != HOTP_SECRET_LENGTH: + flash(ngettext( + 'HOTP secrets are 40 characters long - you have entered {num}.', + 'HOTP secrets are 40 characters long - you have entered {num}.', + secret_length + ).format(num=secret_length), "error") + return False + try: user.set_hotp_secret(otp_secret) except (binascii.Error, TypeError) as e: if "Non-hexadecimal digit found" in str(e): flash(gettext( - "Invalid secret format: " + "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9."), "error") return False - elif "Odd-length string" in str(e): - flash(gettext( - "Invalid secret format: " - "odd-length secret. Did you mistype the secret?"), - "error") - return False else: flash(gettext( "An unexpected error occurred! " diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -36,6 +36,13 @@ ARGON2_PARAMS = dict(memory_cost=2**16, rounds=4, parallelism=2) +# Required length for hex-format HOTP secrets as input by users +HOTP_SECRET_LENGTH = 40 # 160 bits == 40 hex digits (== 32 ascii-encoded chars in db) + +# Minimum length for ascii-encoded OTP secrets - by default, secrets are now 160-bit (32 chars) +# but existing Journalist users may still have 80-bit (16-char) secrets +OTP_SECRET_MIN_ASCII_LENGTH = 16 # 80 bits == 40 hex digits (== 16 ascii-encoded chars in db) + def get_one_or_else(query: Query, logger: 'Logger', @@ -364,6 +371,11 @@ class BadTokenException(Exception): """Raised when a user logins in with an incorrect TOTP token""" +class InvalidOTPSecretException(Exception): + + """Raised when a user's OTP secret is invalid - for example, too short""" + + class PasswordError(Exception): """Generic error for passwords that are invalid. @@ -696,6 +708,9 @@ def login(cls, user.uuid in Journalist.INVALID_USERNAMES: raise InvalidUsernameException(gettext("Invalid username")) + if len(user.otp_secret) < OTP_SECRET_MIN_ASCII_LENGTH: + raise InvalidOTPSecretException(gettext("Invalid OTP secret")) + if LOGIN_HARDENING: cls.throttle_login(user)
diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -639,7 +639,7 @@ def test_user_change_password(journalist_app, test_journo): def test_login_after_regenerate_hotp(journalist_app, test_journo): """Test that journalists can login after resetting their HOTP 2fa""" - otp_secret = 'aaaaaa' + otp_secret = '0123456789abcdef0123456789abcdef01234567' b32_otp_secret = b32encode(unhexlify(otp_secret)) # edit hotp diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -52,14 +52,31 @@ VALID_PASSWORD_2 = 'another correct horse battery staple generic passphrase' -def _login_user(app, username, password, otp_secret): +def _login_user(app, username, password, otp_secret, success=True): resp = app.post(url_for('main.login'), data={'username': username, 'password': password, 'token': TOTP(otp_secret).now()}, follow_redirects=True) assert resp.status_code == 200 - assert hasattr(g, 'user') # ensure logged in + assert (success == hasattr(g, 'user')) # check logged-in vs expected + + [email protected]("otp_secret", ['', 'GA','GARBAGE','JHCOGO7VCER3EJ4']) +def test_user_with_invalid_otp_secret_cannot_login(journalist_app, otp_secret): + # Create a user with whitespace at the end of the username + with journalist_app.app_context(): + new_username = 'badotp' + otp_secret + user, password = utils.db_helper.init_journalist(is_admin=False) + user.otp_secret = otp_secret + user.username = new_username + db.session.add(user) + db.session.commit() + + # Verify that user is *not* able to login successfully + with journalist_app.test_client() as app: + _login_user(app, new_username, password, + otp_secret, success=False) def test_user_with_whitespace_in_username_can_login(journalist_app): @@ -1016,9 +1033,10 @@ def test_admin_resets_user_hotp_format_non_hexa( old_secret = journo.otp_secret + non_hexa_secret='0123456789ABCDZZ0123456789ABCDEF01234567' with InstrumentedApp(journalist_app) as ins: app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret='ZZ')) + data=dict(uid=test_journo['id'], otp_secret=non_hexa_secret)) # fetch altered DB object journo = Journalist.query.get(journo.id) @@ -1030,57 +1048,66 @@ def test_admin_resets_user_hotp_format_non_hexa( assert journo.is_totp ins.assert_message_flashed( - "Invalid secret format: please only submit letters A-F and " + "Invalid HOTP secret format: please only submit letters A-F and " "numbers 0-9.", "error") -def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): [email protected]("the_secret", [' ', ' ', '0123456789ABCDEF0123456789ABCDE']) +def test_admin_resets_user_hotp_format_too_short( + journalist_app, test_admin, test_journo, the_secret): + with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) journo = test_journo['journalist'] + # guard to ensure check below tests the correct condition + assert journo.is_totp + old_secret = journo.otp_secret with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], - otp_secret=123456)) + app.post(url_for('admin.reset_two_factor_hotp'), + data=dict(uid=test_journo['id'], otp_secret=the_secret)) # fetch altered DB object journo = Journalist.query.get(journo.id) new_secret = journo.otp_secret - assert old_secret != new_secret - assert not journo.is_totp + assert old_secret == new_secret - # Redirect to admin 2FA view - ins.assert_redirects(resp, url_for('admin.new_user_two_factor', - uid=journo.id)) + # ensure we didn't accidentally enable hotp + assert journo.is_totp + ins.assert_message_flashed( + "HOTP secrets are 40 characters long" + " - you have entered {num}.".format(num=len(the_secret.replace(' ', ''))), "error") -def test_admin_resets_user_hotp_format_odd(journalist_app, - test_admin, - test_journo): - old_secret = test_journo['otp_secret'] +def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + journo = test_journo['journalist'] + old_secret = journo.otp_secret + + valid_secret="DEADBEEF01234567DEADBEEF01234567DEADBEEF" with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret='Z')) + resp = app.post(url_for('admin.reset_two_factor_hotp'), + data=dict(uid=test_journo['id'], + otp_secret=valid_secret)) - ins.assert_message_flashed( - "Invalid secret format: " - "odd-length secret. Did you mistype the secret?", "error") + # fetch altered DB object + journo = Journalist.query.get(journo.id) - # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) - new_secret = user.otp_secret + new_secret = journo.otp_secret + assert old_secret != new_secret + assert not journo.is_totp - assert old_secret == new_secret + # Redirect to admin 2FA view + ins.assert_redirects(resp, url_for('admin.new_user_two_factor', + uid=journo.id)) def test_admin_resets_user_hotp_error(mocker, @@ -1088,7 +1115,7 @@ def test_admin_resets_user_hotp_error(mocker, test_admin, test_journo): - bad_secret = '1234' + bad_secret = '0123456789ABCDZZ0123456789ABCDZZ01234567' error_message = 'SOMETHING WRONG!' mocked_error_logger = mocker.patch('journalist.app.logger.error') old_secret = test_journo['otp_secret'] @@ -1120,7 +1147,7 @@ def test_admin_resets_user_hotp_error(mocker, def test_user_resets_hotp(journalist_app, test_journo): old_secret = test_journo['otp_secret'] - new_secret = 123456 + new_secret = '0123456789ABCDEF0123456789ABCDEF01234567' # Precondition assert new_secret != old_secret @@ -1142,39 +1169,19 @@ def test_user_resets_hotp(journalist_app, test_journo): assert old_secret != new_secret -def test_user_resets_user_hotp_format_odd(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] - - with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) - - with InstrumentedApp(journalist_app) as ins: - app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret='123')) - ins.assert_message_flashed( - "Invalid secret format: " - "odd-length secret. Did you mistype the secret?", "error") - - # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) - new_secret = user.otp_secret - - assert old_secret == new_secret - - def test_user_resets_user_hotp_format_non_hexa(journalist_app, test_journo): old_secret = test_journo['otp_secret'] + non_hexa_secret='0123456789ABCDZZ0123456789ABCDEF01234567' with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], test_journo['otp_secret']) with InstrumentedApp(journalist_app) as ins: app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret='ZZ')) + data=dict(otp_secret=non_hexa_secret)) ins.assert_message_flashed( - "Invalid secret format: " + "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9.", "error") # Re-fetch journalist to get fresh DB instance @@ -1187,7 +1194,7 @@ def test_user_resets_user_hotp_format_non_hexa(journalist_app, test_journo): def test_user_resets_user_hotp_error(mocker, journalist_app, test_journo): - bad_secret = '1234' + bad_secret = '0123456789ABCDZZ0123456789ABCDZZ01234567' old_secret = test_journo['otp_secret'] error_message = 'SOMETHING WRONG!' mocked_error_logger = mocker.patch('journalist.app.logger.error') @@ -1268,7 +1275,7 @@ def test_admin_resets_hotp_with_missing_otp_secret_key(config, journalist_app, t ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Change Secret'] + msgids = ['Change HOTP Secret'] with xfail_untranslated_messages(config, locale, msgids): assert gettext(msgids[0]) in resp.data.decode('utf-8') @@ -1528,6 +1535,40 @@ def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, s in resp.data.decode("utf-8") ) +@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]( + "locale, secret", + ( + (locale, ' ' *i) + for locale in get_test_locales() + for i in range(3) + ) +) +def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, secret): + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + + resp = app.post( + url_for('admin.add_user', l=locale), + data=dict( + username='dellsberg', + first_name='', + last_name='', + password=VALID_PASSWORD, + password_again=VALID_PASSWORD, + is_admin=None, + is_hotp=True, + otp_secret=secret + ), + ) + + assert page_language(resp.data) == language_tag(locale) + msgids = ['The "otp_secret" field is required when "is_hotp" is set.'] + with xfail_untranslated_messages(config, locale, msgids): + # Should redirect to the token verification page + assert gettext(msgids[0]) in resp.data.decode('utf-8') + @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) @@ -2363,6 +2404,7 @@ def test_regenerate_totp(journalist_app, test_journo): def test_edit_hotp(journalist_app, test_journo): old_secret = test_journo['otp_secret'] + valid_secret="DEADBEEF01234567DEADBEEF01234567DADEFEEB" with journalist_app.test_client() as app: _login_user(app, test_journo['username'], test_journo['password'], @@ -2370,7 +2412,7 @@ def test_edit_hotp(journalist_app, test_journo): with InstrumentedApp(journalist_app) as ins: resp = app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret=123456)) + data=dict(otp_secret=valid_secret)) new_secret = Journalist.query.get(test_journo['id']).otp_secret
HOTP secrets are not validated correctly. ## Description HOTP secrets are not set up correctly in all cases: On the JI: - case 1: if an admin adds a user and selects the "is using a Yubikey [HOTP]" checkbox, but does not provide a HOTP secret, an error is not thrown and an account using TOTP is set up instead. - case 2: if an admin adds a user and selects the "is using a Yubikey [HOTP]" checkbox, and provides a HOTP secret containing only spaces, an error is not thrown and an account using HOTP is set up. ## Steps to Reproduce - log in to the JI as an admin user and go to **Admin** - case 1: add a user, enabling HOTP but leaving the HOTP Secret field empty - case 2: add a user, enabling HOTP and setting the HOTP Secret field to contain one or more spaces only ## Expected Behavior Both cases should fail, displaying the add user form again with a message about the length requirement for HOTP secrets ## Actual Behavior - case 1: user add succeeds, admin is redirected to TOTP setup screen - case 2: user add succeeds, admin is redirected to HOTP PIN verification screen. ## Comments Suggestions to fix, any other relevant information.
2022-01-12T16:58:58Z
[]
[]
freedomofpress/securedrop
6,225
freedomofpress__securedrop-6225
[ "6192" ]
a20c843e903649f5ca10436214a9cb450a95a780
diff --git a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py @@ -0,0 +1,158 @@ +"""make journalist_id non-nullable + +Revision ID: 2e24fc7536e8 +Revises: de00920916bf +Create Date: 2022-01-12 19:31:06.186285 + +""" +from passlib.hash import argon2 +import os +import pyotp +import uuid + +from alembic import op +import sqlalchemy as sa + +# raise the errors if we're not in production +raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" + +try: + from models import ARGON2_PARAMS + from passphrases import PassphraseGenerator +except: # noqa + if raise_errors: + raise + + +# revision identifiers, used by Alembic. +revision = '2e24fc7536e8' +down_revision = 'de00920916bf' +branch_labels = None +depends_on = None + + +def generate_passphrase_hash() -> str: + passphrase = PassphraseGenerator.get_default().generate_passphrase() + return argon2.using(**ARGON2_PARAMS).hash(passphrase) + + +def create_deleted() -> int: + """manually insert a "deleted" journalist user. + + We need to do it this way since the model will reflect the current state of + the schema, not what it is at the current migration step + + It should be basically identical to what Journalist.get_deleted() does + """ + op.execute(sa.text( + """\ + INSERT INTO journalists (uuid, username, session_nonce, passphrase_hash, otp_secret) + VALUES (:uuid, "deleted", 0, :passphrase_hash, :otp_secret); + """ + ).bindparams( + uuid=str(uuid.uuid4()), + passphrase_hash=generate_passphrase_hash(), + otp_secret=pyotp.random_base32(), + )) + # Get the autoincrement ID back + conn = op.get_bind() + result = conn.execute('SELECT id FROM journalists WHERE username="deleted";').fetchall() + return result[0][0] + + +def migrate_nulls(): + """migrate existing journalist_id=NULL over to deleted or delete them""" + op.execute("DELETE FROM journalist_login_attempt WHERE journalist_id IS NULL;") + op.execute("DELETE FROM revoked_tokens WHERE journalist_id IS NULL;") + # Look to see if we have data to migrate + tables = ('replies', 'seen_files', 'seen_messages', 'seen_replies') + needs_migration = [] + conn = op.get_bind() + for table in tables: + result = conn.execute(f'SELECT 1 FROM {table} WHERE journalist_id IS NULL;').first() # nosec + if result is not None: + needs_migration.append(table) + + if not needs_migration: + return + + deleted_id = create_deleted() + for table in needs_migration: + # The seen_ tables have UNIQUE(fk_id, journalist_id), so the deleted journalist can only have + # seen each item once. It is possible multiple NULL journalist have seen the same thing so we + # do this update in two passes. + # First we update as many rows to point to the deleted journalist as possible, ignoring any + # unique key violations. + op.execute(sa.text( + f'UPDATE OR IGNORE {table} SET journalist_id=:journalist_id WHERE journalist_id IS NULL;' + ).bindparams(journalist_id=deleted_id)) + # Then we delete any leftovers which had been ignored earlier. + op.execute(f'DELETE FROM {table} WHERE journalist_id IS NULL') # nosec + + +def upgrade(): + migrate_nulls() + + with op.batch_alter_table('journalist_login_attempt', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('replies', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('revoked_tokens', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('seen_files', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('seen_messages', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('seen_replies', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=False) + + +def downgrade(): + # We do not un-migrate the data back to journalist_id=NULL + + with op.batch_alter_table('seen_replies', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=True) + + with op.batch_alter_table('seen_messages', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=True) + + with op.batch_alter_table('seen_files', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=True) + + with op.batch_alter_table('revoked_tokens', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=True) + + with op.batch_alter_table('replies', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=True) + + with op.batch_alter_table('journalist_login_attempt', schema=None) as batch_op: + batch_op.alter_column('journalist_id', + existing_type=sa.INTEGER(), + nullable=True) diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -30,7 +30,7 @@ def make_blueprint(config: SDConfig) -> Blueprint: @view.route('/', methods=('GET', 'POST')) @admin_required def index() -> str: - users = Journalist.query.all() + users = Journalist.query.filter(Journalist.username != "deleted").all() return render_template("admin.html", users=users) @view.route('/config', methods=('GET', 'POST')) @@ -288,16 +288,22 @@ def delete_user(user_id: int) -> werkzeug.Response: current_app.logger.error( "Admin {} tried to delete itself".format(g.user.username)) abort(403) - elif user: - db.session.delete(user) - db.session.commit() - flash(gettext("Deleted user '{user}'.").format( - user=user.username), "notification") - else: + elif not user: current_app.logger.error( "Admin {} tried to delete nonexistent user with pk={}".format( g.user.username, user_id)) abort(404) + elif user.is_deleted_user(): + # Do not flash because the interface does not expose this. + # It can only happen by manually crafting a POST request + current_app.logger.error( + "Admin {} tried to delete \"deleted\" user".format(g.user.username)) + abort(403) + else: + user.delete() + db.session.commit() + flash(gettext("Deleted user '{user}'.").format( + user=user.username), "notification") return redirect(url_for('admin.index')) diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -382,7 +382,7 @@ def load(args: argparse.Namespace) -> None: # delete one journalist _, _, journalist_to_be_deleted = journalists - db.session.delete(journalist_to_be_deleted) + journalist_to_be_deleted.delete() db.session.commit() diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -30,6 +30,7 @@ from pyotp import TOTP, HOTP from encryption import EncryptionManager, GpgKeyNotFoundError +from passphrases import PassphraseGenerator from store import Storage _default_instance_config: Optional["InstanceConfig"] = None @@ -256,7 +257,7 @@ class Reply(db.Model): id = Column(Integer, primary_key=True) uuid = Column(String(36), unique=True, nullable=False) - journalist_id = Column(Integer, ForeignKey('journalists.id')) + journalist_id = Column(Integer, ForeignKey('journalists.id'), nullable=False) journalist = relationship( "Journalist", backref=backref( @@ -296,18 +297,8 @@ def __repr__(self) -> str: return '<Reply %r>' % (self.filename) def to_json(self) -> 'Dict[str, Any]': - journalist_username = "deleted" - journalist_first_name = "" - journalist_last_name = "" - journalist_uuid = "deleted" - if self.journalist: - journalist_username = self.journalist.username - journalist_first_name = self.journalist.first_name - journalist_last_name = self.journalist.last_name - journalist_uuid = self.journalist.uuid seen_by = [ r.journalist.uuid for r in SeenReply.query.filter(SeenReply.reply_id == self.id) - if r.journalist ] json_reply = { 'source_url': url_for('api.single_source', @@ -317,10 +308,10 @@ def to_json(self) -> 'Dict[str, Any]': reply_uuid=self.uuid) if self.source else None, 'filename': self.filename, 'size': self.size, - 'journalist_username': journalist_username, - 'journalist_first_name': journalist_first_name, - 'journalist_last_name': journalist_last_name, - 'journalist_uuid': journalist_uuid, + 'journalist_username': self.journalist.username, + 'journalist_first_name': self.journalist.first_name or '', + 'journalist_last_name': self.journalist.last_name or '', + 'journalist_uuid': self.journalist.uuid, 'uuid': self.uuid, 'is_deleted_by_source': self.deleted_by_source, 'seen_by': seen_by @@ -436,10 +427,17 @@ class Journalist(db.Model): ) # type: Column[Optional[datetime.datetime]] last_access = Column(DateTime) # type: Column[Optional[datetime.datetime]] passphrase_hash = Column(String(256)) # type: Column[Optional[str]] + login_attempts = relationship( "JournalistLoginAttempt", - backref="journalist" + backref="journalist", + cascade="all, delete" ) # type: RelationshipProperty[JournalistLoginAttempt] + revoked_tokens = relationship( + "RevokedToken", + backref="journalist", + cascade="all, delete" + ) # type: RelationshipProperty[RevokedToken] MIN_USERNAME_LEN = 3 MIN_NAME_LEN = 0 @@ -713,8 +711,7 @@ def login(cls, except NoResultFound: raise InvalidUsernameException(gettext("Invalid username")) - if user.username in Journalist.INVALID_USERNAMES and \ - user.uuid in Journalist.INVALID_USERNAMES: + if user.username in Journalist.INVALID_USERNAMES: raise InvalidUsernameException(gettext("Invalid username")) if len(user.otp_secret) < OTP_SECRET_MIN_ASCII_LENGTH: @@ -786,13 +783,84 @@ def to_json(self, all_info: bool = True) -> Dict[str, Any]: return json_user + def is_deleted_user(self) -> bool: + """Is this the special "deleted" user managed by the system?""" + return self.username == "deleted" + + @classmethod + def get_deleted(cls) -> "Journalist": + """Get a system user that represents deleted journalists for referential integrity + + Callers must commit the session themselves + """ + deleted = Journalist.query.filter_by(username='deleted').one_or_none() + if deleted is None: + # Lazily create + deleted = cls( + # Use a placeholder username to bypass validation that would reject + # "deleted" as unusable + username="placeholder", + # We store a randomly generated passphrase for this account that is + # never revealed to anyone. + password=PassphraseGenerator.get_default().generate_passphrase() + ) + deleted.username = "deleted" + db.session.add(deleted) + return deleted + + def delete(self) -> None: + """delete a journalist, migrating some data over to the "deleted" journalist + + Callers must commit the session themselves + """ + deleted = self.get_deleted() + # All replies should be reassociated with the "deleted" journalist + for reply in Reply.query.filter_by(journalist_id=self.id).all(): + reply.journalist_id = deleted.id + db.session.add(reply) + + # For seen indicators, we need to make sure one doesn't already exist + # otherwise it'll hit a unique key conflict + already_seen_files = { + file.file_id for file in + SeenFile.query.filter_by(journalist_id=deleted.id).all()} + for file in SeenFile.query.filter_by(journalist_id=self.id).all(): + if file.file_id in already_seen_files: + db.session.delete(file) + else: + file.journalist_id = deleted.id + db.session.add(file) + + already_seen_messages = { + message.message_id for message in + SeenMessage.query.filter_by(journalist_id=deleted.id).all()} + for message in SeenMessage.query.filter_by(journalist_id=self.id).all(): + if message.message_id in already_seen_messages: + db.session.delete(message) + else: + message.journalist_id = deleted.id + db.session.add(message) + + already_seen_replies = { + reply.reply_id for reply in + SeenReply.query.filter_by(journalist_id=deleted.id).all()} + for reply in SeenReply.query.filter_by(journalist_id=self.id).all(): + if reply.reply_id in already_seen_replies: + db.session.delete(reply) + else: + reply.journalist_id = deleted.id + db.session.add(reply) + + # For the rest of the associated data we rely on cascading deletions + db.session.delete(self) + class SeenFile(db.Model): __tablename__ = "seen_files" __table_args__ = (db.UniqueConstraint("file_id", "journalist_id"),) id = Column(Integer, primary_key=True) file_id = Column(Integer, ForeignKey("submissions.id"), nullable=False) - journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=True) + journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) file = relationship( "Submission", backref=backref("seen_files", lazy="dynamic", cascade="all,delete") ) # type: RelationshipProperty[Submission] @@ -806,7 +874,7 @@ class SeenMessage(db.Model): __table_args__ = (db.UniqueConstraint("message_id", "journalist_id"),) id = Column(Integer, primary_key=True) message_id = Column(Integer, ForeignKey("submissions.id"), nullable=False) - journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=True) + journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) message = relationship( "Submission", backref=backref("seen_messages", lazy="dynamic", cascade="all,delete") ) # type: RelationshipProperty[Submission] @@ -820,7 +888,7 @@ class SeenReply(db.Model): __table_args__ = (db.UniqueConstraint("reply_id", "journalist_id"),) id = Column(Integer, primary_key=True) reply_id = Column(Integer, ForeignKey("replies.id"), nullable=False) - journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=True) + journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) reply = relationship( "Reply", backref=backref("seen_replies", cascade="all,delete") ) # type: RelationshipProperty[Reply] @@ -840,7 +908,7 @@ class JournalistLoginAttempt(db.Model): DateTime, default=datetime.datetime.utcnow ) # type: Column[Optional[datetime.datetime]] - journalist_id = Column(Integer, ForeignKey('journalists.id')) + journalist_id = Column(Integer, ForeignKey('journalists.id'), nullable=False) def __init__(self, journalist: Journalist) -> None: self.journalist = journalist @@ -855,7 +923,7 @@ class RevokedToken(db.Model): __tablename__ = 'revoked_tokens' id = Column(Integer, primary_key=True) - journalist_id = Column(Integer, ForeignKey('journalists.id')) + journalist_id = Column(Integer, ForeignKey('journalists.id'), nullable=False) token = db.Column(db.Text, nullable=False, unique=True)
diff --git a/securedrop/tests/migrations/migration_2e24fc7536e8.py b/securedrop/tests/migrations/migration_2e24fc7536e8.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_2e24fc7536e8.py @@ -0,0 +1,113 @@ +import uuid + +from sqlalchemy import text + +from db import db +from journalist_app import create_app +from .helpers import random_datetime + + +class UpgradeTester: + """Insert a Reply, SeenReply and JournalistLoginAttempt with journalist_id=NULL. + Verify that the first two are reassociated to the "Deleted" user, while the last + is deleted outright. + """ + + def __init__(self, config): + """This function MUST accept an argument named `config`. + You will likely want to save a reference to the config in your + class, so you can access the database later. + """ + self.config = config + self.app = create_app(config) + + def load_data(self): + """This function loads data into the database and filesystem. It is + executed before the upgrade. + """ + with self.app.app_context(): + params = { + 'uuid': str(uuid.uuid4()), + 'journalist_id': None, + 'source_id': 0, + 'filename': 'dummy.txt', + 'size': 1, + 'checksum': '', + 'deleted_by_source': False, + } + sql = """\ + INSERT INTO replies (uuid, journalist_id, source_id, filename, + size, checksum, deleted_by_source) + VALUES (:uuid, :journalist_id, :source_id, :filename, + :size, :checksum, :deleted_by_source);""" + db.engine.execute(text(sql), **params) + # Insert two SeenReplys corresponding to the just-inserted reply, which also + # verifies our handling of duplicate keys. + for _ in range(2): + db.engine.execute(text( + """\ + INSERT INTO seen_replies (reply_id, journalist_id) + VALUES (1, NULL); + """ + )) + # Insert a JournalistLoginAttempt + db.engine.execute(text( + """\ + INSERT INTO journalist_login_attempt (timestamp, journalist_id) + VALUES (:timestamp, NULL) + """ + ), timestamp=random_datetime(nullable=False)) + + def check_upgrade(self): + """This function is run after the upgrade and verifies the state + of the database or filesystem. It MUST raise an exception if the + check fails. + """ + with self.app.app_context(): + deleted = db.engine.execute( + 'SELECT id, passphrase_hash, otp_secret FROM journalists WHERE username="deleted"' + ).first() + # A passphrase_hash is set + assert deleted[1].startswith('$argon2') + # And a TOTP secret is set + assert len(deleted[2]) == 32 + deleted_id = deleted[0] + replies = db.engine.execute( + text('SELECT journalist_id FROM replies')).fetchall() + assert len(replies) == 1 + # And the journalist_id matches our "deleted" one + assert replies[0][0] == deleted_id + seen_replies = db.engine.execute( + text('SELECT journalist_id FROM seen_replies')).fetchall() + assert len(seen_replies) == 1 + # And the journalist_id matches our "deleted" one + assert seen_replies[0][0] == deleted_id + login_attempts = db.engine.execute( + text('SELECT * FROM journalist_login_attempt')).fetchall() + # The NULL login attempt was deleted outright + assert login_attempts == [] + + +class DowngradeTester: + """Downgrading only makes fields nullable again, which is a + non-destructive and safe operation""" + + def __init__(self, config): + """This function MUST accept an argument named `config`. + You will likely want to save a reference to the config in your + class, so you can access the database later. + """ + self.config = config + + def load_data(self): + """This function loads data into the database and filesystem. It is + executed before the downgrade. + """ + pass + + def check_downgrade(self): + """This function is run after the downgrade and verifies the state + of the database or filesystem. It MUST raise an exception if the + check fails. + """ + pass diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -31,6 +31,7 @@ InvalidPasswordLength, InstanceConfig, Journalist, + JournalistLoginAttempt, Reply, SeenFile, SeenMessage, @@ -39,6 +40,7 @@ InvalidUsernameException, Submission ) +from passphrases import PassphraseGenerator from sdconfig import config from .utils.instrument import InstrumentedApp @@ -647,6 +649,19 @@ def test_admin_deletes_invalid_user_404(journalist_app, test_admin): assert resp.status_code == 404 +def test_admin_deletes_deleted_user_403(journalist_app, test_admin): + with journalist_app.app_context(): + deleted = Journalist.get_deleted() + db.session.commit() + deleted_id = deleted.id + + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + resp = app.post(url_for('admin.delete_user', user_id=deleted_id)) + assert resp.status_code == 403 + + @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_edits_user_password_error_response( @@ -1377,17 +1392,12 @@ def test_admin_add_user_with_invalid_username(config, journalist_app, test_admin @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_deleted_user_cannot_login(config, journalist_app, locale): - username = 'deleted' - uuid = 'deleted' - - # Create a user with username and uuid as deleted with journalist_app.app_context(): - user, password = utils.db_helper.init_journalist(is_admin=False) - otp_secret = user.otp_secret - user.username = username - user.uuid = uuid - db.session.add(user) + user = Journalist.get_deleted() + password = PassphraseGenerator.get_default().generate_passphrase() + user.set_password(password) db.session.commit() + otp_secret = user.otp_secret with InstrumentedApp(journalist_app) as ins: # Verify that deleted user is not able to login @@ -1395,9 +1405,9 @@ def test_deleted_user_cannot_login(config, journalist_app, locale): resp = app.post( url_for('main.login', l=locale), data=dict( - username=username, + username="deleted", password=password, - token=otp_secret + token=TOTP(otp_secret).now() ), ) assert page_language(resp.data) == language_tag(locale) @@ -1421,21 +1431,16 @@ def test_deleted_user_cannot_login(config, journalist_app, locale): @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_deleted_user_cannot_login_exception(journalist_app, locale): - username = 'deleted' - uuid = 'deleted' - - # Create a user with username and uuid as deleted with journalist_app.app_context(): - user, password = utils.db_helper.init_journalist(is_admin=False) - otp_secret = user.otp_secret - user.username = username - user.uuid = uuid - db.session.add(user) + user = Journalist.get_deleted() + password = PassphraseGenerator.get_default().generate_passphrase() + user.set_password(password) db.session.commit() + otp_secret = user.otp_secret with journalist_app.test_request_context('/'): with pytest.raises(InvalidUsernameException): - Journalist.login(username, password, TOTP(otp_secret).now()) + Journalist.login("deleted", password, TOTP(otp_secret).now()) @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -3379,3 +3384,46 @@ def test_app_error_handlers_defined(journalist_app): for status_code in [400, 401, 403, 404, 500]: # This will raise KeyError if an app-wide error handler is not defined assert journalist_app.error_handler_spec[None][status_code] + + +def test_lazy_deleted_journalist_creation(journalist_app): + """test lazy creation of "deleted" jousrnalist works""" + not_found = Journalist.query.filter_by(username='deleted').one_or_none() + assert not_found is None, "deleted journalist doesn't exist yet" + deleted = Journalist.get_deleted() + db.session.commit() + # Can be found as a normal Journalist object + found = Journalist.query.filter_by(username='deleted').one() + assert deleted.uuid == found.uuid + assert found.is_deleted_user() is True + # And get_deleted() now returns the same instance + deleted2 = Journalist.get_deleted() + assert deleted.uuid == deleted2.uuid + + +def test_journalist_deletion(journalist_app, app_storage): + """test deleting a journalist and see data reassociated to "deleted" journalist""" + # Create a journalist that's seen two replies and has a login attempt + source, _ = utils.db_helper.init_source(app_storage) + journalist, _ = utils.db_helper.init_journalist() + db.session.add(JournalistLoginAttempt(journalist)) + replies = utils.db_helper.reply(app_storage, journalist, source, 2) + # Create a second journalist that's seen those replies + journalist2, _ = utils.db_helper.init_journalist() + for reply in replies: + db.session.add(SeenReply(reply=reply, journalist=journalist2)) + db.session.commit() + # Only one login attempt in the table + assert len(JournalistLoginAttempt.query.all()) == 1 + # And four SeenReplys + assert len(SeenReply.query.all()) == 4 + # Delete the journalists + journalist.delete() + journalist2.delete() + db.session.commit() + # Verify the "deleted" journalist has 2 associated rows of both types + deleted = Journalist.get_deleted() + assert len(Reply.query.filter_by(journalist_id=deleted.id).all()) == 2 + assert len(SeenReply.query.filter_by(journalist_id=deleted.id).all()) == 2 + # And there are no login attempts + assert JournalistLoginAttempt.query.all() == [] diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -488,9 +488,9 @@ def test_authorized_user_can_get_single_reply(journalist_app, test_files, assert response.json['journalist_uuid'] == \ reply.journalist.uuid assert response.json['journalist_first_name'] == \ - reply.journalist.first_name + (reply.journalist.first_name or '') assert response.json['journalist_last_name'] == \ - reply.journalist.last_name + (reply.journalist.last_name or '') assert response.json['is_deleted_by_source'] is False assert response.json['filename'] == \ test_files['source'].replies[0].filename @@ -508,12 +508,12 @@ def test_reply_of_deleted_journalist(journalist_app, source_uuid=uuid, reply_uuid=reply_uuid), headers=get_api_headers(journalist_api_token)) - + deleted_uuid = Journalist.get_deleted().uuid assert response.status_code == 200 assert response.json['uuid'] == reply_uuid assert response.json['journalist_username'] == "deleted" - assert response.json['journalist_uuid'] == "deleted" + assert response.json['journalist_uuid'] == deleted_uuid assert response.json['journalist_first_name'] == "" assert response.json['journalist_last_name'] == "" assert response.json['is_deleted_by_source'] is False diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -51,7 +51,7 @@ def delete_journalist(journalist): :returns: None """ - db.session.delete(journalist) + journalist.delete() db.session.commit()
Use a special `deleted` journalist user for associations with deleted users As discussed in #5467 and #5503, we currently delete rows for deleted journalist users. After deletion, `journalist_id` will be `NULL` in other tables that reference the deleted user (e.g., `replies` and the `seen` tables; see the [database diagram](https://docs.securedrop.org/en/stable/_images/securedrop-database.png)). The API will return the username `deleted` and the UUID `deleted` wherever these users are referenced. There are a few issues with this: - It creates an avoidable inconsistency between the data's internal representation and its API representation, which makes it harder to reason about where the data returned by the API originates - We cannot rely on the `/users` endpoint of the API to get a complete list of users that an API consumer may need to associate data with - User management in the SecureDrop Client does not map directly to user management on the server In #5467, we considered preserving a record for each user, while removing all data _about_ the user. This may be desirable in the long run (alongside features such as user locking: #3926), but even if we do this, we will need a migration for historical data. The solution we've settled on for now is to create a global `deleted` user. A database migration will need to a) create this user, b) associate records currently associated with `NULL` users with this new user. This puts us in a good position to make other changes like #5467 in future, and unblocks further work on SecureDrop Client features that rely on journalist attribution.
I think there are two approaches, but first here are some notes (recap): ## Notes * The endpoint `/get_all_replies` tells us which replies exist on the server (so that we can add, update, or delete reply records accordingly to match the server), and which journalists have seen each reply (so that we can add seen records accordingly- note that we decided early on that we only delete seen records when the source or conversation are deleted). * The only reason a reply should be updated is because the reply `filename`, `size`, or `journalist_id` has changed. (We can remove the update logic around `journalist_id` if we go with Option B take below.) * The endpoint only sends UUIDs (IDs are partial PII), which is why "deleted" is a [hard-coded string for `journalist_uuid` in the API endpoint](https://github.com/freedomofpress/securedrop/blob/c5d7766d886b6bf3c9fdc297e4bb21b960e58447/securedrop/models.py#L293) * [ISSUE] The endpoint does not hard-code a "deleted" string when returning the [list of journalist UUIDs in the `seen_by` field](https://github.com/freedomofpress/securedrop/blob/c5d7766d886b6bf3c9fdc297e4bb21b960e58447/securedrop/models.py#L299-L302), which means that a `SeenReply` record with a NULL `journalist_id` would exist in the `seen_replies` table (this is also true for `SeenMessage` and `SeenFile`), but the endpoint would never report it. Downstream, the client has to ignore this (usually we we rely on remote data from the API to ensure or confirm that we match the server). Overall, the API is inconsistent with how it treats data associated with deleted users. ## Option A 1. Create a `deleted` user account. 2. When a user account is deleted, reassociate that user's `replies` and `seen*` records to point to the `deleted` user. 3. Do the data migration where `journalist_id` is NULL to point to the new `deleted` user account. 4. This automatically fixes the issue described above and the API will work without change. (It should be cleaned up so that we no longer hard-code the "deleted" string.) ## Option B 1. On the client, rely on the new `/users` endpoint to delete user accounts (we need to do this anyway), which will update the `replies` and `seen*` tables to match the server with NULL `journalist_id`s (this is default behaviour for foreign keys). 2. No longer create user accounts when we see new `journalist_uuid`s for replies (again, we were going to do this anyway). No client data migration is needed because steps 1 and 2 will ensure that we delete the local "deleted" user account, and `journalist_id`s will be updated to NULL by default. 3. Fix the issue above by updating the Journalist API so that it returns the same "deleted" string for `journalist_uuid` in the `seen_by` field. I looked into this a bit, my personal preference would be to have the placeholder "deleted" user (Option A), just so we can rely on journalist_id being type `uuid` rather than `Optional[uuid]` (sidenote, [MediaWiki](https://www.mediawiki.org/wiki/Extension:UserMerge) takes a similar approach, "deleting" users by merging them into one named "Anonymous"). A bit more concrete proposal: Rather than calling `db.session.delete(journalist)`, we could add a `delete(session)` method on `Journalist`, that would scan through whatever tables we want to keep data for, updating the journalist_id to point to the "deleted" user instead. All other models would set cascade="delete" since we want to drop the data on journalist deletion (e.g. journalist_login_attempt, revoked_tokens, etc.). The main downside of this is if someone does use `db.session.delete(journalist)` we're going to have inconsistent state again. The migration step would basically do the same thing, look for NULL journalist_ids, either assigning them to the "deleted" user or deleting them. Another option is to set an event to listen for deletion attempts (https://docs.sqlalchemy.org/en/13/orm/session_events.html), and intercept them to update the seen/reply models to point to "deleted". This seems more much more complex. Also the system was changed in 1.4, so we might have to update/migrate it when upgrading sqlalchemy. Thanks for joining the conversation @legoktm! Option A is part of what I've been advocating for for at least a year to resolve downstream issues (the other part being: https://github.com/freedomofpress/securedrop/issues/5467). The reason I mention Option B is that it allows us to avoid the data migration and to continue relying on the DB to null out the journalist IDs upon account deletion. It is worth considering in case more issues come up with Option A. Either way, Read Receipts is partially unblocked, so I'll head over that way while you work on this Github Issue and iron out even more details with @zenmonkeykstop. I pushed my current WIP to the "delete-journalist" branch, so far it lazily creates a "deleted" journalist and reassigns the seen rows to it upon deletion (or so I think, I'll do more testing tomorrow).
2022-01-14T08:04:06Z
[]
[]
freedomofpress/securedrop
6,256
freedomofpress__securedrop-6256
[ "6255" ]
5de9dc08c940667f3ae3e2654c263c2d863ad327
diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -20,11 +20,10 @@ from models import (Journalist, Reply, SeenReply, Source, Submission, LoginThrottledException, InvalidUsernameException, BadTokenException, InvalidOTPSecretException, - WrongPasswordException) + WrongPasswordException, API_DATETIME_FORMAT) from sdconfig import SDConfig from store import NotEncrypted, Storage - TOKEN_EXPIRATION_MINS = 60 * 8 @@ -121,7 +120,7 @@ def get_token() -> Tuple[flask.Response, int]: response = jsonify({ 'token': journalist.generate_api_token(expiration=TOKEN_EXPIRATION_MINS * 60), - 'expiration': token_expiry.isoformat() + 'Z', + 'expiration': token_expiry.strftime(API_DATETIME_FORMAT), 'journalist_uuid': journalist.uuid, 'journalist_first_name': journalist.first_name, 'journalist_last_name': journalist.last_name, diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -48,6 +48,9 @@ # but existing Journalist users may still have 80-bit (16-char) secrets OTP_SECRET_MIN_ASCII_LENGTH = 16 # 80 bits == 40 hex digits (== 16 ascii-encoded chars in db) +# Timezone-naive datetime format expected by SecureDrop Client +API_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" + def get_one_or_else(query: Query, logger: 'Logger', @@ -138,9 +141,9 @@ def to_json(self) -> 'Dict[str, object]': docs_msg_count = self.documents_messages_count() if self.last_updated: - last_updated = self.last_updated.isoformat() + 'Z' + last_updated = self.last_updated.strftime(API_DATETIME_FORMAT) else: - last_updated = datetime.datetime.utcnow().isoformat() + 'Z' + last_updated = datetime.datetime.utcnow().strftime(API_DATETIME_FORMAT) if self.star and self.star.starred: starred = True @@ -777,7 +780,7 @@ def to_json(self, all_info: bool = True) -> Dict[str, Any]: if all_info is True: json_user['is_admin'] = self.is_admin if self.last_access: - json_user['last_login'] = self.last_access.isoformat() + 'Z' + json_user['last_login'] = self.last_access.strftime(API_DATETIME_FORMAT) else: json_user['last_login'] = None
diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -2,6 +2,7 @@ import json import random +from datetime import datetime from flask import url_for from itsdangerous import TimedJSONWebSignatureSerializer from pyotp import TOTP @@ -20,6 +21,8 @@ from .utils.api_helper import get_api_headers +API_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" + random.seed('◔ ⌣ ◔') @@ -53,6 +56,15 @@ def test_valid_user_can_get_an_api_token(journalist_app, test_journo): assert response.json['journalist_first_name'] == test_journo['first_name'] assert response.json['journalist_last_name'] == test_journo['last_name'] + def _valid_date(date_str, date_format): + try: + if date_str != datetime.strptime(date_str, date_format).strftime(date_format): + raise ValueError + return True + except ValueError: + return False + assert _valid_date(response.json['expiration'], API_DATETIME_FORMAT) + def test_user_cannot_get_an_api_token_with_wrong_password(journalist_app, test_journo):
Journalist API datetime format has changed, breaking client login. ## Description See freedomofpress/securedrop-sdk#171 - the datetime format being returned by the Journalist API includes timezone info as a result of the Flask 2.0 update - previously it dd not, and the SecureDrop Client expects naive datetimes with no timezones. ## Steps to Reproduce Attempt to use the client with a server running 2.2.0-rc1 or latest develop ## Expected Behavior Client works as normal ## Actual Behavior Client crashes with error in linked issue above ## Comments A simple fix would be to force the datetime format to not include timezones in the API. There's a larger issue here of how to handle tz-aware datetimes in the client, but that might be too much to take on during the client process, it seems better to preserve the existing behaviour. Looks like there are two potential areas to consider: the API token expiry datetime (which is probably causing the issue above), and the source last_updated field (which is used in the client). The first is a change in securedrop/journalist_app/api.py, the second is a change in models.py, in Source.to_json(). I don't think there are any other affected areas.
2022-02-08T23:30:55Z
[]
[]
freedomofpress/securedrop
6,299
freedomofpress__securedrop-6299
[ "6292" ]
ecd6b2b2309715ccbedc1b8b75c1daaa71ad1961
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -8,7 +8,7 @@ import werkzeug from flask import (Blueprint, render_template, flash, redirect, url_for, - session, current_app, request, Markup, abort, g) + session, current_app, request, Markup, abort, g, make_response) from flask_babel import gettext import store @@ -322,4 +322,11 @@ def logout() -> Union[str, werkzeug.Response]: else: return redirect(url_for('.index')) + @view.route('/robots.txt') + def robots_txt() -> werkzeug.Response: + """Tell robots we don't want them""" + resp = make_response("User-agent: *\nDisallow: /") + resp.headers["content-type"] = "text/plain" + return resp + return view
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -869,3 +869,13 @@ def test_source_can_only_delete_own_replies(source_app, app_storage): reply = Reply.query.filter_by(filename=filename).one() assert reply.deleted_by_source + + +def test_robots_txt(source_app): + """Test that robots.txt works""" + with source_app.test_client() as app: + # Not using url_for here because we care about the actual URL path + resp = app.get('/robots.txt') + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert 'Disallow: /' in text
add `robots.txt` and a `nofollow` robots meta tag to dissuade legitimate crawlers from crawling tor2webb-ed instances
2022-02-18T22:36:47Z
[]
[]
freedomofpress/securedrop
6,300
freedomofpress__securedrop-6300
[ "6291" ]
f2c958617d6f4184ce747abb7187c09b041efcb6
diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -4,8 +4,7 @@ import os import time import werkzeug -from flask import (Flask, render_template, escape, flash, Markup, request, g, session, - url_for) +from flask import (Flask, render_template, request, g, session, redirect, url_for) from flask_babel import gettext from flask_assets import Environment from flask_wtf.csrf import CSRFProtect, CSRFError @@ -90,28 +89,8 @@ def handle_csrf_error(e: CSRFError) -> werkzeug.Response: for module in [main, info, api]: app.register_blueprint(module.make_blueprint(config)) # type: ignore - @app.before_request - @ignore_static - def check_tor2web() -> None: - # ignore_static here so we only flash a single message warning - # about Tor2Web, corresponding to the initial page load. - if 'X-tor2web' in request.headers: - flash( - Markup( - '<strong>{}</strong>&nbsp;{}&nbsp;<a href="{}">{}</a>'.format( - escape(gettext("WARNING:")), - escape( - gettext( - 'You appear to be using Tor2Web, which does not provide anonymity.' - ) - ), - url_for('info.tor2web_warning'), - escape(gettext('Why is this dangerous?')), - ) - ), - "banner-warning" - ) - + # before_request hooks are executed in order of declaration, so set up g object + # before the potential tor2web 403 response. @app.before_request @ignore_static def setup_g() -> Optional[werkzeug.Response]: @@ -128,6 +107,15 @@ def setup_g() -> Optional[werkzeug.Response]: return None + @app.before_request + @ignore_static + def check_tor2web() -> Optional[werkzeug.Response]: + # TODO: expand header checking logic to catch modern tor2web proxies + if 'X-tor2web' in request.headers: + if request.path != url_for('info.tor2web_warning'): + return redirect(url_for('info.tor2web_warning')) + return None + @app.errorhandler(404) def page_not_found(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: return render_template('notfound.html'), 404 diff --git a/securedrop/source_app/info.py b/securedrop/source_app/info.py --- a/securedrop/source_app/info.py +++ b/securedrop/source_app/info.py @@ -1,20 +1,25 @@ # -*- coding: utf-8 -*- import flask -from flask import Blueprint, render_template, send_file, redirect, url_for +from flask import Blueprint, render_template, send_file, redirect, url_for, flash +from flask_babel import gettext import werkzeug from io import BytesIO # noqa from encryption import EncryptionManager from sdconfig import SDConfig +from source_app.utils import get_sourcev3_url def make_blueprint(config: SDConfig) -> Blueprint: view = Blueprint('info', __name__) @view.route('/tor2web-warning') - def tor2web_warning() -> str: - return render_template("tor2web-warning.html") + def tor2web_warning() -> flask.Response: + flash(gettext("Your connection is not anonymous right now!"), "error") + return flask.Response( + render_template("tor2web-warning.html", source_url=get_sourcev3_url()), + 403) @view.route('/use-tor') def recommend_tor_browser() -> str:
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -537,38 +537,24 @@ def test_submit_sanitizes_filename(source_app): mtime=0) -@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) -def test_tor2web_warning_headers(config, source_app, locale): [email protected]("test_url", ['main.index', 'main.create', 'main.submit']) +def test_redirect_when_tor2web(config, source_app, test_url): with source_app.test_client() as app: - with InstrumentedApp(app) as ins: - resp = app.get(url_for('main.index', l=locale), headers=[('X-tor2web', 'encrypted')]) - assert resp.status_code == 200 - - assert page_language(resp.data) == language_tag(locale) - msgids = [ - "WARNING:", - "You appear to be using Tor2Web, which does not provide anonymity.", - "Why is this dangerous?", - ] - with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed( - '<strong>{}</strong>&nbsp;{}&nbsp;<a href="{}">{}</a>'.format( - escape(gettext(msgids[0])), - escape(gettext(msgids[1])), - url_for('info.tor2web_warning'), - escape(gettext(msgids[2])), - ), - 'banner-warning' - ) - + resp = app.get( + url_for(test_url), + headers=[('X-tor2web', 'encrypted')], + follow_redirects=True) + text = resp.data.decode('utf-8') + assert resp.status_code == 403 + assert "Proxy Service Detected" in text def test_tor2web_warning(source_app): with source_app.test_client() as app: resp = app.get(url_for('info.tor2web_warning')) - assert resp.status_code == 200 + assert resp.status_code == 403 text = resp.data.decode('utf-8') - assert "Why is there a warning about Tor2Web?" in text + assert "Proxy Service Detected" in text + def test_why_use_tor_browser(source_app):
update tor2web detection response, replacing warning flash message with a redirect to a static page.
2022-02-22T18:44:42Z
[]
[]
freedomofpress/securedrop
6,302
freedomofpress__securedrop-6302
[ "6295" ]
f2c958617d6f4184ce747abb7187c09b041efcb6
diff --git a/securedrop/source_app/forms.py b/securedrop/source_app/forms.py --- a/securedrop/source_app/forms.py +++ b/securedrop/source_app/forms.py @@ -1,7 +1,8 @@ import wtforms +from flask import abort from flask_babel import lazy_gettext as gettext from flask_wtf import FlaskForm -from wtforms import FileField, PasswordField, TextAreaField +from wtforms import FileField, PasswordField, StringField, TextAreaField from wtforms.validators import InputRequired, Regexp, Length, ValidationError from models import Submission, InstanceConfig @@ -26,6 +27,7 @@ class SubmissionForm(FlaskForm): msg = TextAreaField("msg", render_kw={"placeholder": gettext("Write a message."), "aria-label": gettext("Write a message.")}) fh = FileField("fh", render_kw={"aria-label": gettext("Select a file to upload.")}) + antispam = StringField(id="text", name="text") def validate_msg(self, field: wtforms.Field) -> None: if len(field.data) > Submission.MAX_MESSAGE_LEN: @@ -38,3 +40,8 @@ def validate_msg(self, field: wtforms.Field) -> None: ) ) raise ValidationError(message) + + def validate_antispam(self, field: wtforms.Field) -> None: + """If the antispam field has any contents, abort with a 403""" + if field.data: + abort(403)
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -445,6 +445,20 @@ def test_submit_both(source_app): assert "Thanks! We received your message and document" in text +def test_submit_antispam(source_app): + """ + Test the antispam check. + """ + with source_app.test_client() as app: + new_codename(app, session) + _dummy_submission(app) + resp = app.post( + url_for('main.submit'), + data=dict(msg="Test", fh=(StringIO(''), ''), text="blah"), + follow_redirects=True) + assert resp.status_code == 403 + + def test_delete_all_successfully_deletes_replies(source_app, app_storage): with source_app.app_context(): journalist, _ = utils.db_helper.init_journalist()
Add honeypot field to SI message form to block automated submissions ## Description The Source Interface has limited protections in place to block bots. One simple bot-blocking measure would be to add a hidden form field on the message submission form, and reject submissions that include a value for the field. ## User Research Evidence Spam reports from instance maintainers. ## User Stories As a journalist, I want to save time by not having to review spam messages.
For reference, MediaWiki does this with https://gerrit.wikimedia.org/g/mediawiki/core/+/4afd0f7c3e017b84adef7938a31bc40a69304e62/includes/EditPage.php#2981 The intention is to block generic form-filling spambots. Anything designed to spam SecureDrops will eventually adapt. >The Source Interface has limited protections in place to block bots. One simple bot-blocking measure would be to add a hidden form field on the message submission form, and reject submissions that include a value for the field. How much effective will this be? I am wondering if someone is targeting SecureDrop instances, that is much targeted than random spambots. @kushaldas I don't think we'll know until we try mitigations like this, 1:1. That said—I do think this one back(ish)-end mitigation, should go in before any others—so that its effectiveness on its own, can be measured against other bot mitigations. While I'm not a fan of the "bounce" remediation prior to other UX measures going in before it, entirely separate from that opinion I would like to see _different_ spam mitigations go out in different releases... as the source of the spam is not known at this time. We'll never know, unless 1:1 they're deployed with methodical research endeavored following each release, to learn more. @kushaldas I don't expect that it will help with much tbh, but dealing with low-hanging fruit first (see the rest of https://github.com/freedomofpress/securedrop/milestone/77). Targeted spam is gonna require more work, probably the best mitigations there would require the use of SecureDrop Workstation. @legoktm in https://github.com/freedomofpress/securedrop/issues/6295#issuecomment-1045303533: > For reference, MediaWiki does this with https://gerrit.wikimedia.org/g/mediawiki/core/+/4afd0f7c3e017b84adef7938a31bc40a69304e62/includes/EditPage.php#2981 > > The intention is to block generic form-filling spambots. Anything designed to spam SecureDrops will eventually adapt. Seconding this example's use of `display: none`, which will [correctly hide the honeypot field both visually and in the accessibility tree (but of course leave it reachable in the DOM)](https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html).
2022-02-22T23:29:35Z
[]
[]
freedomofpress/securedrop
6,304
freedomofpress__securedrop-6304
[ "6293" ]
bcfd17d97f7cb542dc25af830072deeb0206df2d
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -37,8 +37,15 @@ def make_blueprint(config: SDConfig) -> Blueprint: def index() -> str: return render_template('index.html') - @view.route('/generate', methods=('GET',)) + @view.route('/generate', methods=('POST',)) def generate() -> Union[str, werkzeug.Response]: + # Try to detect Tor2Web usage by looking to see if tor2web_check got mangled + tor2web_check = request.form.get('tor2web_check') + if tor2web_check is None: + # Missing form field + abort(403) + elif tor2web_check != 'href="fake.onion"': + return redirect(url_for('info.tor2web_warning')) if SessionManager.is_user_logged_in(db_session=db.session): flash(gettext( "You were redirected because you are already logged in. " @@ -46,7 +53,6 @@ def generate() -> Union[str, werkzeug.Response]: "first."), "notification") return redirect(url_for('.lookup')) - codename = PassphraseGenerator.get_default().generate_passphrase( preferred_language=g.localeinfo.language )
diff --git a/securedrop/tests/functional/source_navigation_steps.py b/securedrop/tests/functional/source_navigation_steps.py --- a/securedrop/tests/functional/source_navigation_steps.py +++ b/securedrop/tests/functional/source_navigation_steps.py @@ -36,18 +36,22 @@ def _source_checks_instance_metadata(self): assert j["sd_version"] == self.source_app.jinja_env.globals["version"] assert j["gpg_fpr"] != "" - def _source_clicks_submit_documents_on_homepage(self): + def _source_clicks_submit_documents_on_homepage(self, assert_success=True): # It's the source's first time visiting this SecureDrop site, so they # choose to "Submit Documents". self.safe_click_by_id("submit-documents-button") - # The source should now be on the page where they are presented with - # a diceware codename they can use for subsequent logins - assert self._is_on_generate_page() + if assert_success: + # The source should now be on the page where they are presented with + # a diceware codename they can use for subsequent logins + assert self._is_on_generate_page() def _source_regenerates_codename(self): - self.driver.refresh() + self._source_visits_source_homepage() + # We do not want to assert success here since it's possible they got + # redirected if already logged in. + self._source_clicks_submit_documents_on_homepage(assert_success=False) def _source_chooses_to_submit_documents(self): self._source_clicks_submit_documents_on_homepage() diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -275,7 +275,7 @@ def test_html_en_lang_correct(journalist_app, config): assert re.compile('<html lang="en-US".*>').search(html), html # check '/generate' too because '/' uses a different template - resp = app.get('/generate', follow_redirects=True) + resp = app.post('/generate', data={'tor2web_check': 'href="fake.onion"'}, follow_redirects=True) html = resp.data.decode('utf-8') assert re.compile('<html lang="en-US".*>').search(html), html @@ -299,7 +299,8 @@ def test_html_fr_lang_correct(journalist_app, config): assert re.compile('<html lang="fr-FR".*>').search(html), html # check '/generate' too because '/' uses a different template - resp = app.get('/generate?l=fr_FR', follow_redirects=True) + resp = app.post('/generate?l=fr_FR', data={'tor2web_check': 'href="fake.onion"'}, + follow_redirects=True) html = resp.data.decode('utf-8') assert re.compile('<html lang="fr-FR".*>').search(html), html @@ -329,9 +330,11 @@ def test_html_attributes(journalist_app, config): assert '<html lang="en-US" dir="ltr">' in html # check '/generate' too because '/' uses a different template - resp = app.get('/generate?l=ar', follow_redirects=True) + resp = app.post('/generate?l=ar', data={'tor2web_check': 'href="fake.onion"'}, + follow_redirects=True) html = resp.data.decode('utf-8') assert '<html lang="ar" dir="rtl">' in html - resp = app.get('/generate?l=en_US', follow_redirects=True) + resp = app.post('/generate?l=en_US', data={'tor2web_check': 'href="fake.onion"'}, + follow_redirects=True) html = resp.data.decode('utf-8') assert '<html lang="en-US" dir="ltr">' in html diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -26,6 +26,7 @@ # Seed the RNG for deterministic testing random.seed('ಠ_ಠ') +GENERATE_DATA = {'tor2web_check': 'href="fake.onion"'} def _login_user(app, user_dict): @@ -44,7 +45,7 @@ def test_submit_message(journalist_app, source_app, test_journo, app_storage): test_msg = "This is a test message." with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) source_user = SessionManager.get_logged_in_user(db_session=db.session) @@ -148,7 +149,7 @@ def test_submit_file(journalist_app, source_app, test_journo, app_storage): test_filename = "test.txt" with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) source_user = SessionManager.get_logged_in_user(db_session=db.session) @@ -255,7 +256,7 @@ def _helper_test_reply(journalist_app, source_app, config, test_journo, test_msg = "This is a test message." with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id, codename = next(iter(session['codenames'].items())) app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) # redirected to submission form @@ -446,7 +447,7 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): # first, add a source with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) app.post('/create', data={'tab_id': tab_id}) resp = app.post('/submit', data=dict( @@ -496,7 +497,7 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): with source_app.test_client() as app: num_sources = 2 for i in range(num_sources): - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) app.post('/create', data={'tab_id': tab_id}) app.post('/submit', data=dict( @@ -553,7 +554,7 @@ def test_filenames(source_app, journalist_app, test_journo): and files""" # add a source and submit stuff with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) app.post('/create', data={'tab_id': tab_id}) _helper_filenames_submit(app) @@ -580,7 +581,7 @@ def test_filenames_delete(journalist_app, source_app, test_journo): """Test pretty, sequential filenames when journalist deletes files""" # add a source and submit stuff with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) app.post('/create', data={'tab_id': tab_id}) _helper_filenames_submit(app) @@ -692,7 +693,7 @@ def test_prevent_document_uploads(source_app, journalist_app, test_admin): # Check that the source interface accepts only messages: with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) resp = app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) assert resp.status_code == 200 @@ -718,7 +719,7 @@ def test_no_prevent_document_uploads(source_app, journalist_app, test_admin): # Check that the source interface accepts both files and messages: with source_app.test_client() as app: - app.get('/generate') + app.post('/generate', data=GENERATE_DATA) tab_id = next(iter(session['codenames'].keys())) resp = app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) assert resp.status_code == 200 diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -31,6 +31,8 @@ from .utils.i18n import get_test_locales, language_tag, page_language, xfail_untranslated_messages from .utils.instrument import InstrumentedApp +GENERATE_DATA = {'tor2web_check': 'href="fake.onion"'} + def test_logo_default_available(config, source_app): # if the custom image is available, this test will fail @@ -108,10 +110,10 @@ def test_generate_already_logged_in(source_app): with source_app.test_client() as app: new_codename(app, session) # Make sure it redirects to /lookup when logged in - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 302 # Make sure it flashes the message on the lookup page - resp = app.get(url_for('main.generate'), follow_redirects=True) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA, follow_redirects=True) # Should redirect to /lookup assert resp.status_code == 200 text = resp.data.decode('utf-8') @@ -120,7 +122,7 @@ def test_generate_already_logged_in(source_app): def test_create_new_source(source_app): with source_app.test_client() as app: - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 tab_id = next(iter(session['codenames'].keys())) resp = app.post(url_for('main.create'), data={'tab_id': tab_id}, follow_redirects=True) @@ -133,7 +135,7 @@ def test_create_new_source(source_app): def test_generate(source_app): with source_app.test_client() as app: - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 session_codename = next(iter(session['codenames'].values())) @@ -149,7 +151,7 @@ def test_generate(source_app): def test_create_duplicate_codename_logged_in_not_in_session(source_app): with patch.object(source_app.logger, 'error') as logger: with source_app.test_client() as app: - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 tab_id, codename = next(iter(session['codenames'].items())) @@ -172,12 +174,12 @@ def test_create_duplicate_codename_logged_in_not_in_session(source_app): def test_create_duplicate_codename_logged_in_in_session(source_app): with source_app.test_client() as app: # Given a user who generated a codename in a browser tab - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 first_tab_id, first_codename = list(session['codenames'].items())[0] # And then they opened a new browser tab to generate a second codename - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 second_tab_id, second_codename = list(session['codenames'].items())[1] assert first_codename != second_codename @@ -780,7 +782,7 @@ def test_source_session_expiration(source_app): def test_source_session_expiration_create(source_app): with source_app.test_client() as app: # Given a source user who is in the middle of the account creation flow - resp = app.get(url_for('main.generate')) + resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 # But we're now 6 hours later hence they did not finish the account creation flow in time diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -186,7 +186,7 @@ def submit(storage, source, num_submissions, submission_type="message"): def new_codename(client, session): """Helper function to go through the "generate codename" flow. """ - client.get('/generate') + client.post('/generate', data={'tor2web_check': 'href="fake.onion"'}) tab_id, codename = next(iter(session['codenames'].items())) client.post('/create', data={'tab_id': tab_id}) return codename
investigate and implement improvements to header-based tor2web detection for current active tor2web proxies
2022-02-23T07:21:53Z
[]
[]
freedomofpress/securedrop
6,306
freedomofpress__securedrop-6306
[ "6298" ]
970aab5780d9592cbc19ed59c9d34bb83d6d8e7c
diff --git a/securedrop/alembic/versions/55f26cd22043_remove_partial_index_on_valid_until_set_.py b/securedrop/alembic/versions/55f26cd22043_remove_partial_index_on_valid_until_set_.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/55f26cd22043_remove_partial_index_on_valid_until_set_.py @@ -0,0 +1,57 @@ +"""remove partial_index on valid_until, set it to nullable=false, add message filter fields + +Revision ID: 55f26cd22043 +Revises: 2e24fc7536e8 +Create Date: 2022-03-03 22:40:36.149638 + +""" +from alembic import op +import sqlalchemy as sa + +from datetime import datetime + +# revision identifiers, used by Alembic. +revision = '55f26cd22043' +down_revision = '2e24fc7536e8' +branch_labels = None +depends_on = None + + +def upgrade(): + # remove the old partial index on valid_until, as alembic can't handle it. + op.execute(sa.text('DROP INDEX IF EXISTS ix_one_active_instance_config')) + + # valid_until will be non-nullable after batch, so set existing nulls to + # the new default unix epoch datetime + op.execute(sa.text( + 'UPDATE OR IGNORE instance_config SET ' + 'valid_until=:epoch WHERE valid_until IS NULL;' + ).bindparams(epoch=datetime.fromtimestamp(0))) + with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.alter_column('valid_until', + existing_type=sa.DATETIME(), + nullable=False) + batch_op.add_column(sa.Column('initial_message_min_len', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('reject_message_with_codename', sa.Boolean(), nullable=True)) + + # remove the old partial index *again* in case the batch op recreated it. + op.execute(sa.text('DROP INDEX IF EXISTS ix_one_active_instance_config')) + + +def downgrade(): + with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.alter_column('valid_until', + existing_type=sa.DATETIME(), + nullable=True) + batch_op.drop_column('reject_message_with_codename') + batch_op.drop_column('initial_message_min_len') + + # valid_until is nullable again, set entries with unix epoch datetime value to NULL + op.execute(sa.text( + 'UPDATE OR IGNORE instance_config SET ' + 'valid_until = NULL WHERE valid_until=:epoch;' + ).bindparams(epoch=datetime.fromtimestamp(0))) + + # manually restore the partial index + op.execute(sa.text('CREATE UNIQUE INDEX IF NOT EXISTS ix_one_active_instance_config ON ' + 'instance_config (valid_until IS NULL) WHERE valid_until IS NULL')) diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -15,7 +15,7 @@ from db import db from html import escape from models import (InstanceConfig, Journalist, InvalidUsernameException, - FirstOrLastNameError, PasswordError) + FirstOrLastNameError, PasswordError, Submission) from journalist_app.decorators import admin_required from journalist_app.utils import (commit_account_changes, set_diceware_password, validate_hotp_secret, revoke_token) @@ -36,9 +36,18 @@ def index() -> str: @view.route('/config', methods=('GET', 'POST')) @admin_required def manage_config() -> Union[str, werkzeug.Response]: - # The UI prompt ("prevent") is the opposite of the setting ("allow"): + if InstanceConfig.get_default().initial_message_min_len > 0: + prevent_short_messages = True + else: + prevent_short_messages = False + + # The UI document upload prompt ("prevent") is the opposite of the setting ("allow") submission_preferences_form = SubmissionPreferencesForm( - prevent_document_uploads=not InstanceConfig.get_default().allow_document_uploads) + prevent_document_uploads=not InstanceConfig.get_default().allow_document_uploads, + prevent_short_messages=prevent_short_messages, + min_message_length=InstanceConfig.get_default().initial_message_min_len, + reject_codename_messages=InstanceConfig.get_default().reject_message_with_codename + ) organization_name_form = OrgNameForm( organization_name=InstanceConfig.get_default().organization_name) logo_form = LogoForm() @@ -67,6 +76,7 @@ def manage_config() -> Union[str, werkzeug.Response]: return render_template("config.html", submission_preferences_form=submission_preferences_form, organization_name_form=organization_name_form, + max_len=Submission.MAX_MESSAGE_LEN, logo_form=logo_form) @view.route('/update-submission-preferences', methods=['POST']) @@ -75,9 +85,17 @@ def update_submission_preferences() -> Optional[werkzeug.Response]: form = SubmissionPreferencesForm() if form.validate_on_submit(): # The UI prompt ("prevent") is the opposite of the setting ("allow"): + allow_uploads = not form.prevent_document_uploads.data + + if form.prevent_short_messages.data: + msg_length = form.min_message_length.data + else: + msg_length = 0 + + reject_codenames = form.reject_codename_messages.data + + InstanceConfig.update_submission_prefs(allow_uploads, msg_length, reject_codenames) flash(gettext("Preferences saved."), "submission-preferences-success") - value = not bool(request.form.get('prevent_document_uploads')) - InstanceConfig.set_allow_document_uploads(value) return redirect(url_for('admin.manage_config') + "#config-preventuploads") else: for field, errors in list(form.errors.items()): diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -4,7 +4,7 @@ from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import Field -from wtforms import (TextAreaField, StringField, BooleanField, HiddenField, +from wtforms import (TextAreaField, StringField, BooleanField, HiddenField, IntegerField, ValidationError) from wtforms.validators import InputRequired, Optional, DataRequired, StopValidation @@ -12,19 +12,32 @@ from typing import Any +import typing + class RequiredIf(DataRequired): - def __init__(self, other_field_name: str, *args: Any, **kwargs: Any) -> None: + def __init__(self, + other_field_name: str, + custom_message: typing.Optional[str] = None, + *args: Any, **kwargs: Any) -> None: + self.other_field_name = other_field_name + if custom_message is not None: + self.custom_message = custom_message + else: + self.custom_message = "" def __call__(self, form: FlaskForm, field: Field) -> None: if self.other_field_name in form: other_field = form[self.other_field_name] if bool(other_field.data): - self.message = gettext( - 'The "{name}" field is required when "{other_name}" is set.' - .format(other_name=self.other_field_name, name=field.name)) + if self.custom_message != "": + self.message = self.custom_message + else: + self.message = gettext( + 'The "{name}" field is required when "{other_name}" is set.' + .format(other_name=self.other_field_name, name=field.name)) super(RequiredIf, self).__call__(form, field) else: field.errors[:] = [] @@ -89,6 +102,12 @@ def check_invalid_usernames(form: FlaskForm, field: Field) -> None: "This username is invalid because it is reserved for internal use by the software.")) +def check_message_length(form: FlaskForm, field: Field) -> None: + msg_len = field.data + if not isinstance(msg_len, int) or msg_len < 0: + raise ValidationError(gettext("Please specify an integer value greater than 0.")) + + class NewUserForm(FlaskForm): username = StringField('username', validators=[ InputRequired(message=gettext('This field is required.')), @@ -121,7 +140,28 @@ class ReplyForm(FlaskForm): class SubmissionPreferencesForm(FlaskForm): - prevent_document_uploads = BooleanField('prevent_document_uploads') + prevent_document_uploads = BooleanField( + 'prevent_document_uploads', + false_values=('false', 'False', '') + ) + prevent_short_messages = BooleanField( + 'prevent_short_messages', + false_values=('false', 'False', '') + ) + min_message_length = IntegerField('min_message_length', + validators=[ + RequiredIf( + 'prevent_short_messages', + gettext("To configure a minimum message length, " + "you must set the required number of " + "characters.")), + check_message_length], + render_kw={ + 'aria-describedby': 'message-length-notes'}) + reject_codename_messages = BooleanField( + 'reject_codename_messages', + false_values=('false', 'False', '') + ) class OrgNameForm(FlaskForm): diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -19,7 +19,7 @@ from passlib.hash import argon2 from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship, backref, Query, RelationshipProperty -from sqlalchemy import Column, Index, Integer, String, Boolean, DateTime, LargeBinary +from sqlalchemy import Column, Integer, String, Boolean, DateTime, LargeBinary from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound @@ -932,7 +932,7 @@ class RevokedToken(db.Model): class InstanceConfig(db.Model): '''Versioned key-value store of settings configurable from the journalist - interface. The current version has valid_until=None. + interface. The current version has valid_until=0 (unix epoch start) ''' # Limits length of org name used in SI and JI titles, image alt texts etc. @@ -940,16 +940,28 @@ class InstanceConfig(db.Model): __tablename__ = 'instance_config' version = Column(Integer, primary_key=True) - valid_until = Column(DateTime, default=None, unique=True) + valid_until = Column(DateTime, default=datetime.datetime.fromtimestamp(0), + nullable=False, unique=True) allow_document_uploads = Column(Boolean, default=True) organization_name = Column(String(255), nullable=True, default="SecureDrop") + initial_message_min_len = Column(Integer, default=0) + reject_message_with_codename = Column(Boolean, default=False) # Columns not listed here will be included by InstanceConfig.copy() when # updating the configuration. metadata_cols = ['version', 'valid_until'] def __repr__(self) -> str: - return "<InstanceConfig(version=%s, valid_until=%s)>" % (self.version, self.valid_until) + return "<InstanceConfig(version=%s, valid_until=%s, " \ + "allow_document_uploads=%s, organization_name=%s, " \ + "initial_message_min_len=%s, reject_message_with_codename=%s)>" % ( + self.version, + self.valid_until, + self.allow_document_uploads, + self.organization_name, + self.initial_message_min_len, + self.reject_message_with_codename + ) def copy(self) -> "InstanceConfig": '''Make a copy of only the configuration columns of the given @@ -981,7 +993,7 @@ def get_current(cls) -> "InstanceConfig": ''' try: - return cls.query.filter(cls.valid_until == None).one() # lgtm [py/test-equals-none] # noqa: E711, E501 + return cls.query.filter(cls.valid_until == datetime.datetime.fromtimestamp(0)).one() except NoResultFound: try: current = cls() @@ -989,7 +1001,7 @@ def get_current(cls) -> "InstanceConfig": db.session.commit() return current except IntegrityError: - return cls.query.filter(cls.valid_until == None).one() # lgtm [py/test-equals-none] # noqa: E711, E501 + return cls.query.filter(cls.valid_until == datetime.datetime.fromtimestamp(0)).one() @classmethod def check_name_acceptable(cls, name: str) -> None: @@ -1017,9 +1029,14 @@ def set_organization_name(cls, name: str) -> None: db.session.commit() @classmethod - def set_allow_document_uploads(cls, value: bool) -> None: + def update_submission_prefs( + cls, + allow_uploads: bool, + min_length: int, + reject_codenames: bool + ) -> None: '''Invalidate the current configuration and append a new one with the - requested change. + updated submission preferences. ''' old = cls.get_current() @@ -1027,15 +1044,9 @@ def set_allow_document_uploads(cls, value: bool) -> None: db.session.add(old) new = old.copy() - new.allow_document_uploads = value + new.allow_document_uploads = allow_uploads + new.initial_message_min_len = min_length + new.reject_message_with_codename = reject_codenames db.session.add(new) db.session.commit() - - -one_active_instance_config_index = Index( - 'ix_one_active_instance_config', - InstanceConfig.valid_until.is_(None), - unique=True, - sqlite_where=(InstanceConfig.valid_until.is_(None)) -) diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -7,7 +7,7 @@ from typing import Union import werkzeug -from flask import (Blueprint, render_template, flash, redirect, url_for, +from flask import (Blueprint, render_template, flash, redirect, url_for, escape, session, current_app, request, Markup, abort, g, make_response) from flask_babel import gettext @@ -24,7 +24,7 @@ from source_app.decorators import login_required from source_app.session_manager import SessionManager from source_app.utils import normalize_timestamps, fit_codenames_into_cookie, \ - clear_session_and_redirect_to_logged_out_page + clear_session_and_redirect_to_logged_out_page, codename_detected from source_app.forms import LoginForm, SubmissionForm from source_user import InvalidPassphraseError, create_source_user, \ SourcePassphraseCollisionError, SourceDesignationCollisionError, SourceUser @@ -119,6 +119,13 @@ def lookup(logged_in_source: SourceUser) -> str: source_id=logged_in_source_in_db.id, deleted_by_source=False ).all() + first_submission = logged_in_source_in_db.interaction_count == 0 + + if first_submission: + min_message_length = InstanceConfig.get_default().initial_message_min_len + else: + min_message_length = 0 + for reply in source_inbox: reply_path = Storage.get_default().path( logged_in_source.filesystem_id, @@ -158,6 +165,7 @@ def lookup(logged_in_source: SourceUser) -> str: is_user_logged_in=True, allow_document_uploads=InstanceConfig.get_default().allow_document_uploads, replies=replies, + min_len=min_message_length, new_user_codename=session.get('new_user_codename', None), form=SubmissionForm(), ) @@ -192,6 +200,23 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: logged_in_source_in_db = logged_in_source.get_db_record() first_submission = logged_in_source_in_db.interaction_count == 0 + if first_submission: + min_len = InstanceConfig.get_default().initial_message_min_len + if (min_len > 0) and (msg and not fh) and (len(msg) < min_len): + flash(gettext( + "Your first message must be at least {} characters long.".format(min_len)), + "error") + return redirect(url_for('main.lookup')) + + codenames_rejected = InstanceConfig.get_default().reject_message_with_codename + if codenames_rejected and codename_detected(msg, session['new_user_codename']): + flash(Markup('{}<br>{}'.format( + escape(gettext("Please do not submit your codename!")), + escape(gettext("Keep your codename secret, and use it to log in later" + " to check for replies.")) + )), "error") + return redirect(url_for('main.lookup')) + if not os.path.exists(Storage.get_default().path(logged_in_source.filesystem_id)): current_app.logger.debug("Store directory not found for source '{}', creating one." .format(logged_in_source_in_db.journalist_designation)) diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -10,6 +10,8 @@ from flask.sessions import SessionMixin from markupsafe import Markup from store import Storage +from hmac import compare_digest +from flask_babel import gettext import typing @@ -21,6 +23,19 @@ from typing import Optional +def codename_detected(message: str, codename: str) -> bool: + """ + Check for codenames in incoming messages. including case where user copy/pasted + from /generate and the visually-hidden codename heading was included + """ + message = message.strip() + localised_label = gettext("Codename") + if message.startswith(localised_label): + message = message[len(localised_label):] + + return compare_digest(message.strip(), codename) + + def clear_session_and_redirect_to_logged_out_page(flask_session: SessionMixin) -> werkzeug.Response: msg = render_template('session_timeout.html')
diff --git a/securedrop/tests/migrations/migration_55f26cd22043.py b/securedrop/tests/migrations/migration_55f26cd22043.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_55f26cd22043.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +from db import db +from journalist_app import create_app +import sqlalchemy +import pytest +import secrets + +from .helpers import random_bool, random_datetime, random_ascii_chars + + +index_definition = ( + "index", + "ix_one_active_instance_config", + "instance_config", + ( + "CREATE UNIQUE INDEX ix_one_active_instance_config " + "ON instance_config (valid_until IS NULL) WHERE valid_until IS NULL" + ), +) + + +def get_schema(app): + with app.app_context(): + result = list( + db.engine.execute(sqlalchemy.text("SELECT type, name, tbl_name, sql FROM sqlite_master")) + ) + + return ((x[0], x[1], x[2], x[3]) for x in result) + + +class UpgradeTester: + def __init__(self, config): + self.config = config + self.app = create_app(config) + + def load_data(self): + with self.app.app_context(): + self.update_config() + db.session.commit() + + @staticmethod + def update_config(): + params = { + "valid_until": random_datetime(nullable=False), + "allow_document_uploads": random_bool(), + "organization_name": random_ascii_chars(secrets.randbelow(75)) + } + sql = """ + INSERT INTO instance_config ( + valid_until, allow_document_uploads, organization_name + ) VALUES ( + :valid_until, :allow_document_uploads, :organization_name + ) + """ + + db.engine.execute(sqlalchemy.text(sql), **params) + + def check_upgrade(self): + schema = get_schema(self.app) + print(schema) + assert index_definition not in schema + + with self.app.app_context(): + for query in [ + "SELECT * FROM instance_config WHERE initial_message_min_len != 0", + "SELECT * FROM instance_config WHERE reject_message_with_codename != 0" + ]: + result = db.engine.execute(sqlalchemy.text(query)).fetchall() + assert len(result) == 0 + + +class DowngradeTester: + + def __init__(self, config): + self.app = create_app(config) + + def load_data(self): + pass + + def check_downgrade(self): + assert index_definition in get_schema(self.app) + + with self.app.app_context(): + for query in [ + "SELECT * FROM instance_config WHERE initial_message_min_len IS NOT NULL", + "SELECT * FROM instance_config WHERE reject_message_with_codename IS NOT NULL" + ]: + with pytest.raises(sqlalchemy.exc.OperationalError): + db.engine.execute(sqlalchemy.text(query)).fetchall() diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -9,10 +9,12 @@ from alembic.script import ScriptDirectory from os import path from sqlalchemy import text +from collections import OrderedDict from db import db from journalist_app import create_app + MIGRATION_PATH = path.join(path.dirname(__file__), '..', 'alembic', 'versions') ALL_MIGRATIONS = [x.split('.')[0].split('_')[0] @@ -79,11 +81,20 @@ def ddl_equal(left, right): column1 TEXT NOT NULL, column2 TEXT NOT NULL + + Also, sometimes CHECK constraints are duplicated by alembic, like: + CHECK (column IN (0, 1)), + CHECK (column IN (0, 1)), + So dedupe alembic's output as well + ''' # ignore the autoindex cases if left is None and right is None: return True + # dedupe alembic's output by line + left = "\n".join(list(OrderedDict.fromkeys(left.split("\n")))) + left = [x for x in WHITESPACE_REGEX.split(left) if x] right = [x for x in WHITESPACE_REGEX.split(right) if x] diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -644,7 +644,8 @@ def test_prevent_document_uploads(source_app, journalist_app, test_admin): with journalist_app.test_client() as app: _login_user(app, test_admin) form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=True) + prevent_document_uploads=True, + min_message_length=0) resp = app.post('/admin/update-submission-preferences', data=form.data, follow_redirects=True) @@ -672,7 +673,11 @@ def test_no_prevent_document_uploads(source_app, journalist_app, test_admin): # Set allow_document_uploads = True: with journalist_app.test_client() as app: _login_user(app, test_admin) + form = journalist_app_module.forms.SubmissionPreferencesForm( + prevent_document_uploads=False, + min_message_length=0) resp = app.post('/admin/update-submission-preferences', + data=form.data, follow_redirects=True) assert resp.status_code == 200 diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -1813,7 +1813,8 @@ def test_prevent_document_uploads(config, journalist_app, test_admin, locale): _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=True) + prevent_document_uploads=True, + min_message_length=0) app.post(url_for('admin.update_submission_preferences'), data=form.data, follow_redirects=True) @@ -1836,12 +1837,16 @@ def test_no_prevent_document_uploads(config, journalist_app, test_admin, locale) with journalist_app.test_client() as app: _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + form = journalist_app_module.forms.SubmissionPreferencesForm( + min_message_length=0) app.post(url_for('admin.update_submission_preferences'), + data=form.data, follow_redirects=True) assert InstanceConfig.get_current().allow_document_uploads is True with InstrumentedApp(journalist_app) as ins: resp = app.post( url_for('admin.update_submission_preferences', l=locale), + data=form.data, follow_redirects=True ) assert InstanceConfig.get_current().allow_document_uploads is True @@ -1856,7 +1861,8 @@ def test_prevent_document_uploads_invalid(journalist_app, test_admin): _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) form_true = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=True) + prevent_document_uploads=True, + min_message_length=0) app.post(url_for('admin.update_submission_preferences'), data=form_true.data, follow_redirects=True) @@ -1872,6 +1878,60 @@ def test_prevent_document_uploads_invalid(journalist_app, test_admin): assert InstanceConfig.get_current().allow_document_uploads is False +def test_message_filtering(config, journalist_app, test_admin): + with journalist_app.test_client() as app: + _login_user(app, test_admin['username'], test_admin['password'], + test_admin['otp_secret']) + # Assert status quo + assert InstanceConfig.get_current().initial_message_min_len == 0 + + # Try to set min length to 10, but don't tick the "prevent short messages" checkbox + form = journalist_app_module.forms.SubmissionPreferencesForm( + prevent_short_messages=False, + min_message_length=10) + app.post(url_for('admin.update_submission_preferences'), + data=form.data, + follow_redirects=True) + # Still 0 + assert InstanceConfig.get_current().initial_message_min_len == 0 + + # Inverse, tick the "prevent short messages" checkbox but leave min length at 0 + form = journalist_app_module.forms.SubmissionPreferencesForm( + prevent_short_messages=True, + min_message_length=0) + resp = app.post(url_for('admin.update_submission_preferences'), + data=form.data, + follow_redirects=True) + # Still 0 + assert InstanceConfig.get_current().initial_message_min_len == 0 + html = resp.data.decode('utf-8') + assert 'To configure a minimum message length, you must set the required' in html + + # Now tick the "prevent short messages" checkbox + form = journalist_app_module.forms.SubmissionPreferencesForm( + prevent_short_messages=True, + min_message_length=10) + app.post(url_for('admin.update_submission_preferences'), + data=form.data, + follow_redirects=True) + assert InstanceConfig.get_current().initial_message_min_len == 10 + + # Submit junk data for min_message_length + resp = app.post(url_for('admin.update_submission_preferences'), + data={**form.data, 'min_message_length': 'abcdef'}, + follow_redirects=True) + html = resp.data.decode('utf-8') + assert 'To configure a minimum message length, you must set the required' in html + # Now rejecting codenames + assert InstanceConfig.get_current().reject_message_with_codename is False + form = journalist_app_module.forms.SubmissionPreferencesForm( + reject_codename_messages=True) + app.post(url_for('admin.update_submission_preferences'), + data=form.data, + follow_redirects=True) + assert InstanceConfig.get_current().reject_message_with_codename is True + + def test_orgname_default_set(journalist_app, test_admin): class dummy_current(): diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -419,6 +419,40 @@ def test_submit_big_message(source_app): assert "Message text too long." in text +def test_submit_initial_short_message(source_app): + """ + Test the message size limit. + """ + with source_app.test_client() as app: + InstanceConfig.get_default().update_submission_prefs( + allow_uploads=True, min_length=10, reject_codenames=False) + new_codename(app, session) + resp = app.post( + url_for('main.submit'), + data=dict(msg="A" * 5, fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Your first message must be at least 10 characters long." in text + # Now retry with a longer message + resp = app.post( + url_for('main.submit'), + data=dict(msg="A" * 25, fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Thank you for sending this information to us." in text + # Now send another short message, that should still be accepted since + # it's no longer the initial one + resp = app.post( + url_for('main.submit'), + data=dict(msg="A", fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Thanks! We received your message." in text + + def test_submit_file(source_app): with source_app.test_client() as app: new_codename(app, session) @@ -461,6 +495,33 @@ def test_submit_antispam(source_app): assert resp.status_code == 403 +def test_submit_codename(source_app): + """ + Test preventions against people submitting their codename. + """ + with source_app.test_client() as app: + InstanceConfig.get_default().update_submission_prefs( + allow_uploads=True, min_length=0, reject_codenames=True) + codename = new_codename(app, session) + resp = app.post( + url_for('main.submit'), + data=dict(msg=codename, fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Please do not submit your codename!" in text + # Do a dummy submission + _dummy_submission(app) + # Now resubmit the codename, should be accepted. + resp = app.post( + url_for('main.submit'), + data=dict(msg=codename, fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Thanks! We received your message" in text + + def test_delete_all_successfully_deletes_replies(source_app, app_storage): with source_app.app_context(): journalist, _ = utils.db_helper.init_journalist() diff --git a/securedrop/tests/test_source_utils.py b/securedrop/tests/test_source_utils.py --- a/securedrop/tests/test_source_utils.py +++ b/securedrop/tests/test_source_utils.py @@ -2,9 +2,10 @@ import json import os +import pytest import werkzeug -from source_app.utils import check_url_file, fit_codenames_into_cookie +from source_app.utils import check_url_file, codename_detected, fit_codenames_into_cookie from .test_journalist import VALID_PASSWORD @@ -61,3 +62,14 @@ def test_fit_codenames_into_cookie(config): assert(len(serialized) > werkzeug.Response.max_cookie_size) serialized = json.dumps(fit_codenames_into_cookie(codenames)).encode() assert(len(serialized) < werkzeug.Response.max_cookie_size) + + [email protected]('message,expected', ( + ('Foo', False), + ('codename', True), + (' codename ', True), + ('Codename codename', True), + ('foocodenamebar', False), +)) +def test_codename_detected(message, expected): + assert codename_detected(message, 'codename') is expected
Add check for codename-only messages in Source Interface ## Description Some production instances have seen an uptick in initial messages from sources containing only a source codename and no actionable content. This may be attributable to bots, or to UX failures, or a combination of both. Planned changes to the source workflow will mitigate both cases, but in the interim a check should be added to reject codename-only initial messages. This change should take account of the following: • the requirement should be applied on initial submissions only. Returning sources will have had to save their codenames and use them to log in, and therefore can reasonably be expected to do the right thing • rejected messages should result in useful feedback to sources, and should not prevent them from submitting a valid message afterwards • the feature should be configurable by admins in the JI instance config panel, and it should be disabled by default. ## User Research Evidence Spam reports by instance admins.
2022-02-25T20:06:57Z
[]
[]
freedomofpress/securedrop
6,340
freedomofpress__securedrop-6340
[ "6339" ]
8daa11cb23aa19bb3034a37cf30a8481fecf9b39
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -208,14 +208,19 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: "error") return redirect(url_for('main.lookup')) + # if the new_user_codename key is not present in the session, this is + # not a first session + new_codename = session.get('new_user_codename', None) + codenames_rejected = InstanceConfig.get_default().reject_message_with_codename - if codenames_rejected and codename_detected(msg, session['new_user_codename']): - flash(Markup('{}<br>{}'.format( - escape(gettext("Please do not submit your codename!")), - escape(gettext("Keep your codename secret, and use it to log in later" - " to check for replies.")) - )), "error") - return redirect(url_for('main.lookup')) + if new_codename is not None: + if codenames_rejected and codename_detected(msg, new_codename): + flash(Markup('{}<br>{}'.format( + escape(gettext("Please do not submit your codename!")), + escape(gettext("Keep your codename secret, and use it to log in later" + " to check for replies.")) + )), "error") + return redirect(url_for('main.lookup')) if not os.path.exists(Storage.get_default().path(logged_in_source.filesystem_id)): current_app.logger.debug("Store directory not found for source '{}', creating one."
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -495,6 +495,43 @@ def test_submit_antispam(source_app): assert resp.status_code == 403 +def test_submit_codename_second_login(source_app): + """ + Test codename submissions *not* prevented on second session + """ + with source_app.test_client() as app: + InstanceConfig.get_default().update_submission_prefs( + allow_uploads=True, min_length=0, reject_codenames=True) + codename = new_codename(app, session) + resp = app.post( + url_for('main.submit'), + data=dict(msg=codename, fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Please do not submit your codename!" in text + + resp = app.get(url_for('main.logout'), + follow_redirects=True) + assert not SessionManager.is_user_logged_in(db_session=db.session) + text = resp.data.decode('utf-8') + assert 'This will clear your Tor Browser activity data' in text + + resp = app.post(url_for('main.login'), + data=dict(codename=codename), + follow_redirects=True) + assert resp.status_code == 200 + assert SessionManager.is_user_logged_in(db_session=db.session) + + resp = app.post( + url_for('main.submit'), + data=dict(msg=codename, fh=(StringIO(''), '')), + follow_redirects=True) + assert resp.status_code == 200 + text = resp.data.decode('utf-8') + assert "Thank you for sending this information" in text + + def test_submit_codename(source_app): """ Test preventions against people submitting their codename.
Codename check triggers KeyError after subsequent login # Steps to reproduce 1. Enable the new "Prevent sources from submitting their codename as an initial message" setting 2. Create a new source and submit message, note down the codename 3. Log out and log back in as that source 4. Submit another message # Expected behavior Message submitted # Actual behavior KeyError: 'new_user_codename'
Makes sense in retrospect, as that value is no longer in the session on the return visit. Fix inbound
2022-03-14T20:15:36Z
[]
[]
freedomofpress/securedrop
6,345
freedomofpress__securedrop-6345
[ "6342" ]
01418f05ac3b6904a449ef91d29ebd2fbbeab6d3
diff --git a/securedrop/alembic/versions/55f26cd22043_remove_partial_index_on_valid_until_set_.py b/securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py similarity index 70% rename from securedrop/alembic/versions/55f26cd22043_remove_partial_index_on_valid_until_set_.py rename to securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py --- a/securedrop/alembic/versions/55f26cd22043_remove_partial_index_on_valid_until_set_.py +++ b/securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py @@ -1,8 +1,8 @@ """remove partial_index on valid_until, set it to nullable=false, add message filter fields -Revision ID: 55f26cd22043 +Revision ID: d9d36b6f4d1e Revises: 2e24fc7536e8 -Create Date: 2022-03-03 22:40:36.149638 +Create Date: 2022-03-16 17:31:28.408112 """ from alembic import op @@ -11,13 +11,14 @@ from datetime import datetime # revision identifiers, used by Alembic. -revision = '55f26cd22043' +revision = 'd9d36b6f4d1e' down_revision = '2e24fc7536e8' branch_labels = None depends_on = None def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### # remove the old partial index on valid_until, as alembic can't handle it. op.execute(sa.text('DROP INDEX IF EXISTS ix_one_active_instance_config')) @@ -27,25 +28,38 @@ def upgrade(): 'UPDATE OR IGNORE instance_config SET ' 'valid_until=:epoch WHERE valid_until IS NULL;' ).bindparams(epoch=datetime.fromtimestamp(0))) + + # add new columns with default values with op.batch_alter_table('instance_config', schema=None) as batch_op: + batch_op.add_column(sa.Column('initial_message_min_len', + sa.Integer(), + nullable=False, + server_default="0")) + batch_op.add_column(sa.Column('reject_message_with_codename', + sa.Boolean(), + nullable=False, + server_default="0")) batch_op.alter_column('valid_until', - existing_type=sa.DATETIME(), - nullable=False) - batch_op.add_column(sa.Column('initial_message_min_len', sa.Integer(), nullable=True)) - batch_op.add_column(sa.Column('reject_message_with_codename', sa.Boolean(), nullable=True)) + existing_type=sa.DATETIME(), + nullable=False) # remove the old partial index *again* in case the batch op recreated it. op.execute(sa.text('DROP INDEX IF EXISTS ix_one_active_instance_config')) + # ### end Alembic commands ### + + def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('instance_config', schema=None) as batch_op: batch_op.alter_column('valid_until', - existing_type=sa.DATETIME(), - nullable=True) + existing_type=sa.DATETIME(), + nullable=True) batch_op.drop_column('reject_message_with_codename') batch_op.drop_column('initial_message_min_len') + # valid_until is nullable again, set entries with unix epoch datetime value to NULL op.execute(sa.text( 'UPDATE OR IGNORE instance_config SET ' @@ -55,3 +69,6 @@ def downgrade(): # manually restore the partial index op.execute(sa.text('CREATE UNIQUE INDEX IF NOT EXISTS ix_one_active_instance_config ON ' 'instance_config (valid_until IS NULL) WHERE valid_until IS NULL')) + + + # ### end Alembic commands ### diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -944,8 +944,9 @@ class InstanceConfig(db.Model): nullable=False, unique=True) allow_document_uploads = Column(Boolean, default=True) organization_name = Column(String(255), nullable=True, default="SecureDrop") - initial_message_min_len = Column(Integer, default=0) - reject_message_with_codename = Column(Boolean, default=False) + initial_message_min_len = Column(Integer, nullable=False, default=0, server_default="0") + reject_message_with_codename = Column(Boolean, nullable=False, + default=False, server_default="0") # Columns not listed here will be included by InstanceConfig.copy() when # updating the configuration.
diff --git a/securedrop/tests/migrations/migration_55f26cd22043.py b/securedrop/tests/migrations/migration_d9d36b6f4d1e.py similarity index 100% rename from securedrop/tests/migrations/migration_55f26cd22043.py rename to securedrop/tests/migrations/migration_d9d36b6f4d1e.py
[2.3.0] `/lookup` fails to render on fresh install due to `min_length` value in template being set to None ## Description On a fresh install, the initial_message_min_len field in instance_config is NULL, causing checks for equality with integers to fail. ## Steps to Reproduce - Install 2.3.0-rc1 packages in production or staging - visit the SI without updating any config settings in the JI ## Expected Behavior - SI renders correctly ## Actual Behavior 500 errors, with errors like "TypeError: '>' not supported between instances of 'NoneType' and 'int'" in the source logs, if enabled. Please provide screenshots where appropriate. ## Comments
2022-03-16T18:47:08Z
[]
[]
freedomofpress/securedrop
6,375
freedomofpress__securedrop-6375
[ "6334" ]
1a0f2d30a3a5238584401fa42e572ea0d2983922
diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '2.3.0~rc1' +__version__ = '2.4.0~rc1' diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="2.3.0~rc1", + version="2.4.0~rc1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-focal/tests/vars.yml b/molecule/builder-focal/tests/vars.yml --- a/molecule/builder-focal/tests/vars.yml +++ b/molecule/builder-focal/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "2.3.0~rc1" +securedrop_version: "2.4.0~rc1" ossec_version: "3.6.0" keyring_version: "0.1.5" config_version: "0.1.4"
Release SecureDrop 2.3.0 This is a tracking issue for the release of SecureDrop 2.3.0 Scheduled as follows: **Feature / string freeze:** 2022-03-10 **Pre-release announcement:** 2022-03-21 **Release date:** 2022-03-28 **Release manager:** @zenmonkeykstop **Deputy release manager:** @legoktm **Communications manager:** @creviera **Deputy CM:** @eloquence **Localization manager:** @cfm **Deputy LM:** @zenmonkeykstop QA team: TBD _SecureDrop maintainers and testers:_ As you QA 2.3.0, please report back your testing results as comments on this ticket. File GitHub issues for any problems found, tag them "QA: Release", and associate them with the [2.3.0 milestone](https://github.com/freedomofpress/securedrop/milestone/77) for tracking (or ask a maintainer to do so). Test debian packages will be posted on https://apt-test.freedom.press signed with [the test key](https://gist.githubusercontent.com/conorsch/ec4008b111bc3142fca522693f3cce7e/raw/2968621e8ad92db4505a31fcc5776422d7d26729/apt-test%2520apt%2520pubkey) # [QA Matrix for 2.3.0](https://docs.google.com/spreadsheets/d/1ZqI_NimYo0iBVmtrcSWxVa_ogWMQduaIGCm0mSOmb74/edit#gid=2135593926) # [Test Plan for 2.3.0](https://github.com/freedomofpress/securedrop/wiki/2.3.0-Test-Plan) ## Localization management High-level summary of these steps can be found here: https://docs.securedrop.org/en/stable/development/i18n.html#two-weeks-before-the-release-string-freeze Duplicating that content as checkboxes below, for visibility: - [x] Update translations on latest develop, following [docs for i18n procedures](https://docs.securedrop.org/en/stable/development/i18n.html#update-strings-to-be-translated) - [x] Update strings served on Weblate, [following docs](https://docs.securedrop.org/en/stable/development/i18n.html#merge-develop-to-weblate) - [x] [Update Weblate screenshots](https://docs.securedrop.org/en/stable/development/i18n.html#update-weblate-screenshots) so translators can see new or modified source strings in context. - [x] Update the [i18n timeline](https://forum.securedrop.org/t/about-the-translations-category/16) in the translation section of the forum. - [x] Add a [Weblate announcement](https://weblate.securedrop.org/admin/trans/announcement) with the translation timeline for the release. Important: make sure the Notify users box is checked, so that translators receive an email alert. - [x] Remind all developers about the string freeze in [Gitter](https://gitter.im/freedomofpress/securedrop). - [x] Remind all translators about the string freeze in the Localization Lab channel in the [IFF Mattermost](https://internetfreedomfestival.org/wiki/index.php/IFF_Mattermost). # Release management ## Prepare release candidate (2.3.0~rc1) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.3.0~rc1 release changelog - [x] Branch release/2.3.0 from develop - [x] Prepare 2.3.0~rc1 - [x] Build debs, preserving build log, and put up `2.3.0~rc1` on test apt server - [x] Commit build log. ## Prepare release candidate (2.3.0~rc2) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.3.0~rc2 release changelog - [x] Prepare 2.3.0~rc2 - [x] Build debs, preserving build log, and put up `2.3.0~rc2` on test apt server - [x] Commit build log. ## Final release - [x] Ensure builder in release branch is updated and/or update builder image - [x] Push signed tag - [x] Pre-Flight: Test updater logic in Tails (apt-qa tracks the `release` branch in the LFS repo) - [x] Build final Debian packages for 2.3.0 (and preserve build log) - [x] Commit package build log to https://github.com/freedomofpress/build-logs - [x] Upload Debian packages, including kernel debs, to apt-qa server - [x] Pre-Flight: Test that install and upgrade from 2.2,1 to 2.3.0 works w/ prod repo debs (apt-qa.freedom.press polls the `release` branch in the LFS repo for the debs) - [x] Flip apt QA server to prod status (merge to `main` in the LFS repo) - [x] Merge Docs branch changes to ``main`` and verify new docs build in securedrop-docs repo - [x] Prepare release messaging ## Post release - [x] Create GitHub release object - [x] Once release object is created, update version in `securedrop-docs` (version information in Wagtail is updated automatically) - [x] Verify new docs show up on https://docs.securedrop.org - [x] Publish announcements - [x] Merge changelog back to `develop` - [x] Update roadmap wiki page: https://github.com/freedomofpress/securedrop/wiki/Development-Roadmap
2022-03-30T14:22:33Z
[]
[]
freedomofpress/securedrop
6,377
freedomofpress__securedrop-6377
[ "6373" ]
ea11fbde5fb49c8b2416ca202009a3dccc463600
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -37,15 +37,17 @@ def make_blueprint(config: SDConfig) -> Blueprint: def index() -> str: return render_template('index.html') - @view.route('/generate', methods=('POST',)) + @view.route('/generate', methods=('POST', 'GET')) def generate() -> Union[str, werkzeug.Response]: - # Try to detect Tor2Web usage by looking to see if tor2web_check got mangled - tor2web_check = request.form.get('tor2web_check') - if tor2web_check is None: - # Missing form field - abort(403) - elif tor2web_check != 'href="fake.onion"': - return redirect(url_for('info.tor2web_warning')) + if request.method == 'POST': + # Try to detect Tor2Web usage by looking to see if tor2web_check got mangled + tor2web_check = request.form.get('tor2web_check') + if tor2web_check is None: + # Missing form field + abort(403) + elif tor2web_check != 'href="fake.onion"': + return redirect(url_for('info.tor2web_warning')) + if SessionManager.is_user_logged_in(db_session=db.session): flash(gettext( "You were redirected because you are already logged in. "
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -133,7 +133,7 @@ def test_create_new_source(source_app): assert 'codenames' not in session -def test_generate(source_app): +def test_generate_as_post(source_app): with source_app.test_client() as app: resp = app.post(url_for('main.generate'), data=GENERATE_DATA) assert resp.status_code == 200 @@ -147,6 +147,21 @@ def test_generate(source_app): # codename displayed to the source assert codename == escape(session_codename) +def test_generate_as_get(source_app): + with source_app.test_client() as app: + resp = app.get(url_for('main.generate')) + assert resp.status_code == 200 + session_codename = next(iter(session['codenames'].values())) + + text = resp.data.decode('utf-8') + assert "functions as both your username and your password" in text + + codename = _find_codename(resp.data.decode('utf-8')) + # codename is also stored in the session - make sure it matches the + # codename displayed to the source + assert codename == escape(session_codename) + + def test_create_duplicate_codename_logged_in_not_in_session(source_app): with patch.object(source_app.logger, 'error') as logger:
Changing language on `/generate` results in "Method Not Allowed" error # Steps to Reproduce (On `develop` / `release/2.3.0` branch as of this writing. Bug is visible in both staging and dev environments.) 1. Visit the `/generate` page in the Source Interface 2. Change the language using the dropdown selector under the logo # Expected behavior `/generate` page is-rendered in the selected language. # Actual behavior HTTP 405 error page: > Method Not Allowed > > The method is not allowed for the requested URL. The language change still takes effect for subsequent page views.
2022-03-30T16:05:28Z
[]
[]
freedomofpress/securedrop
6,403
freedomofpress__securedrop-6403
[ "204" ]
289c516c9409bdf4c11347e79a37c706c4806e17
diff --git a/securedrop/alembic/versions/c5a02eb52f2d_dropped_session_nonce_from_journalist_.py b/securedrop/alembic/versions/c5a02eb52f2d_dropped_session_nonce_from_journalist_.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/c5a02eb52f2d_dropped_session_nonce_from_journalist_.py @@ -0,0 +1,99 @@ +"""dropped session_nonce from journalist table and revoked tokens table due to new session implementation + +Revision ID: c5a02eb52f2d +Revises: b7f98cfd6a70 +Create Date: 2022-04-16 21:25:22.398189 + +""" +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "c5a02eb52f2d" +down_revision = "b7f98cfd6a70" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table("revoked_tokens") + with op.batch_alter_table("journalists", schema=None) as batch_op: + batch_op.drop_column("session_nonce") + + # ### end Alembic commands ### + + +def downgrade() -> None: + """This would have been the easy way, however previous does not have + default value and thus up/down assertion fails""" + # op.add_column('journalists', sa.Column('session_nonce', sa.Integer(), nullable=False, server_default='0')) + + conn = op.get_bind() + conn.execute("PRAGMA legacy_alter_table=ON") + # Save existing journalist table. + op.rename_table("journalists", "journalists_tmp") + + # Add nonce column. + op.add_column("journalists_tmp", sa.Column("session_nonce", sa.Integer())) + + # Populate nonce column. + journalists = conn.execute(sa.text("SELECT * FROM journalists_tmp")).fetchall() + + for journalist in journalists: + conn.execute( + sa.text( + """UPDATE journalists_tmp SET session_nonce=0 WHERE + id=:id""" + ).bindparams(id=journalist.id) + ) + + # Now create new table with null constraint applied. + op.create_table( + "journalists", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("uuid", sa.String(length=36), nullable=False), + sa.Column("username", sa.String(length=255), nullable=False), + sa.Column("first_name", sa.String(length=255), nullable=True), + sa.Column("last_name", sa.String(length=255), nullable=True), + sa.Column("pw_salt", sa.Binary(), nullable=True), + sa.Column("pw_hash", sa.Binary(), nullable=True), + sa.Column("passphrase_hash", sa.String(length=256), nullable=True), + sa.Column("is_admin", sa.Boolean(), nullable=True), + sa.Column("session_nonce", sa.Integer(), nullable=False), + sa.Column("otp_secret", sa.String(length=32), nullable=True), + sa.Column("is_totp", sa.Boolean(), nullable=True), + sa.Column("hotp_counter", sa.Integer(), nullable=True), + sa.Column("last_token", sa.String(length=6), nullable=True), + sa.Column("created_on", sa.DateTime(), nullable=True), + sa.Column("last_access", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("username"), + sa.UniqueConstraint("uuid"), + ) + + conn.execute( + """ + INSERT INTO journalists + SELECT id, uuid, username, first_name, last_name, pw_salt, pw_hash, + passphrase_hash, is_admin, session_nonce, otp_secret, is_totp, + hotp_counter, last_token, created_on, last_access + FROM journalists_tmp + """ + ) + + # Now delete the old table. + op.drop_table("journalists_tmp") + + op.create_table( + "revoked_tokens", + sa.Column("id", sa.INTEGER(), nullable=False), + sa.Column("journalist_id", sa.INTEGER(), nullable=False), + sa.Column("token", sa.TEXT(), nullable=False), + sa.ForeignKeyConstraint( + ["journalist_id"], + ["journalists.id"], + ), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("token"), + ) diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -214,7 +214,7 @@ def get_locale(config: SDConfig) -> str: - config.FALLBACK_LOCALE """ preferences = [] - if session.get("locale"): + if session and session.get("locale"): preferences.append(session.get("locale")) if request.args.get("l"): preferences.insert(0, request.args.get("l")) diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import typing -from datetime import datetime, timedelta, timezone +from datetime import datetime from os import path from pathlib import Path @@ -9,17 +9,13 @@ import template_filters import version from db import db -from flask import Flask, flash, g, json, redirect, render_template, request, session, url_for +from flask import Flask, abort, g, json, redirect, render_template, request, url_for from flask_babel import gettext from flask_wtf.csrf import CSRFError, CSRFProtect from journalist_app import account, admin, api, col, main -from journalist_app.utils import ( - JournalistInterfaceSessionInterface, - cleanup_expired_revoked_tokens, - get_source, - logged_in, -) -from models import InstanceConfig, Journalist +from journalist_app.sessions import Session, session +from journalist_app.utils import get_source +from models import InstanceConfig from werkzeug.exceptions import default_exceptions # https://www.python.org/dev/peps/pep-0484/#runtime-or-type-checking @@ -35,6 +31,7 @@ from werkzeug.exceptions import HTTPException # noqa: F401 _insecure_views = ["main.login", "static"] +_insecure_api_views = ["api.get_token", "api.get_endpoints"] # Timezone-naive datetime format expected by SecureDrop Client API_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" @@ -63,8 +60,8 @@ def create_app(config: "SDConfig") -> Flask: ) app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS) - app.session_interface = JournalistInterfaceSessionInterface() + Session(app) csrf = CSRFProtect(app) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False @@ -86,9 +83,8 @@ def default(self, obj: "Any") -> "Any": @app.errorhandler(CSRFError) # type: ignore def handle_csrf_error(e: CSRFError) -> "Response": app.logger.error("The CSRF token is invalid.") - session.clear() msg = gettext("You have been logged out due to inactivity.") - flash(msg, "error") + session.destroy(("error", msg), session.get("locale")) return redirect(url_for("main.login")) def _handle_http_exception( @@ -118,10 +114,6 @@ def _handle_http_exception( app.jinja_env.filters["html_datetime_format"] = template_filters.html_datetime_format app.jinja_env.add_extension("jinja2.ext.do") - @app.before_first_request - def expire_blacklisted_tokens() -> None: - cleanup_expired_revoked_tokens() - @app.before_request def update_instance_config() -> None: InstanceConfig.get_default(refresh=True) @@ -129,24 +121,6 @@ def update_instance_config() -> None: @app.before_request def setup_g() -> "Optional[Response]": """Store commonly used values in Flask's special g object""" - if "expires" in session and datetime.now(timezone.utc) >= session["expires"]: - session.clear() - flash(gettext("You have been logged out due to inactivity."), "error") - - uid = session.get("uid", None) - if uid: - user = Journalist.query.get(uid) - if user and "nonce" in session and session["nonce"] != user.session_nonce: - session.clear() - flash(gettext("You have been logged out due to password change"), "error") - - session["expires"] = datetime.now(timezone.utc) + timedelta( - minutes=getattr(config, "SESSION_EXPIRATION_MINUTES", 120) - ) - - uid = session.get("uid", None) - if uid: - g.user = Journalist.query.get(uid) # pylint: disable=assigning-non-slot i18n.set_locale(config) @@ -163,9 +137,10 @@ def setup_g() -> "Optional[Response]": app.logger.error("Site logo not found.") if request.path.split("/")[1] == "api": - pass # We use the @token_required decorator for the API endpoints - else: # We are not using the API - if request.endpoint not in _insecure_views and not logged_in(): + if request.endpoint not in _insecure_api_views and not session.logged_in(): + abort(403) + else: + if request.endpoint not in _insecure_views and not session.logged_in(): return redirect(url_for("main.login")) if request.method == "POST": diff --git a/securedrop/journalist_app/account.py b/securedrop/journalist_app/account.py --- a/securedrop/journalist_app/account.py +++ b/securedrop/journalist_app/account.py @@ -3,8 +3,9 @@ import werkzeug from db import db -from flask import Blueprint, flash, g, redirect, render_template, request, session, url_for +from flask import Blueprint, current_app, flash, g, redirect, render_template, request, url_for from flask_babel import gettext +from journalist_app.sessions import session from journalist_app.utils import ( set_diceware_password, set_name, @@ -29,29 +30,28 @@ def edit() -> str: def change_name() -> werkzeug.Response: first_name = request.form.get("first_name") last_name = request.form.get("last_name") - set_name(g.user, first_name, last_name) + set_name(session.get_user(), first_name, last_name) return redirect(url_for("account.edit")) @view.route("/new-password", methods=("POST",)) def new_password() -> werkzeug.Response: - user = g.user + user = session.get_user() current_password = request.form.get("current_password") token = request.form.get("token") error_message = gettext("Incorrect password or two-factor code.") # If the user is validated, change their password if validate_user(user.username, current_password, token, error_message): password = request.form.get("password") - set_diceware_password(user, password) - session.pop("uid", None) - session.pop("expires", None) - return redirect(url_for("main.login")) + if set_diceware_password(user, password): + current_app.session_interface.logout_user(user.id) # type: ignore + return redirect(url_for("main.login")) return redirect(url_for("account.edit")) @view.route("/2fa", methods=("GET", "POST")) def new_two_factor() -> Union[str, werkzeug.Response]: if request.method == "POST": token = request.form["token"] - if g.user.verify_token(token): + if session.get_user().verify_token(token): flash( gettext("Your two-factor credentials have been reset successfully."), "notification", @@ -63,12 +63,12 @@ def new_two_factor() -> Union[str, werkzeug.Response]: "error", ) - return render_template("account_new_two_factor.html", user=g.user) + return render_template("account_new_two_factor.html", user=session.get_user()) @view.route("/reset-2fa-totp", methods=["POST"]) def reset_two_factor_totp() -> werkzeug.Response: - g.user.is_totp = True - g.user.regenerate_totp_shared_secret() + session.get_user().is_totp = True + session.get_user().regenerate_totp_shared_secret() db.session.commit() return redirect(url_for("account.new_two_factor")) @@ -76,9 +76,9 @@ def reset_two_factor_totp() -> werkzeug.Response: def reset_two_factor_hotp() -> Union[str, werkzeug.Response]: otp_secret = request.form.get("otp_secret", None) if otp_secret: - if not validate_hotp_secret(g.user, otp_secret): + if not validate_hotp_secret(session.get_user(), otp_secret): return render_template("account_edit_hotp_secret.html") - g.user.set_hotp_secret(otp_secret) + session.get_user().set_hotp_secret(otp_secret) db.session.commit() return redirect(url_for("account.new_two_factor")) else: diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -20,12 +20,8 @@ from flask_babel import gettext from journalist_app.decorators import admin_required from journalist_app.forms import LogoForm, NewUserForm, OrgNameForm, SubmissionPreferencesForm -from journalist_app.utils import ( - commit_account_changes, - revoke_token, - set_diceware_password, - validate_hotp_secret, -) +from journalist_app.sessions import session +from journalist_app.utils import commit_account_changes, set_diceware_password, validate_hotp_secret from models import ( FirstOrLastNameError, InstanceConfig, @@ -249,28 +245,26 @@ def new_user_two_factor() -> Union[str, werkzeug.Response]: @view.route("/reset-2fa-totp", methods=["POST"]) @admin_required def reset_two_factor_totp() -> werkzeug.Response: - # nosemgrep: python.flask.security.open-redirect.open-redirect uid = request.form["uid"] user = Journalist.query.get(uid) user.is_totp = True user.regenerate_totp_shared_secret() db.session.commit() - return redirect(url_for("admin.new_user_two_factor", uid=uid)) + return redirect(url_for("admin.new_user_two_factor", uid=user.id)) @view.route("/reset-2fa-hotp", methods=["POST"]) @admin_required def reset_two_factor_hotp() -> Union[str, werkzeug.Response]: - # nosemgrep: python.flask.security.open-redirect.open-redirect uid = request.form["uid"] + user = Journalist.query.get(uid) otp_secret = request.form.get("otp_secret", None) if otp_secret: - user = Journalist.query.get(uid) if not validate_hotp_secret(user, otp_secret): - return render_template("admin_edit_hotp_secret.html", uid=uid) + return render_template("admin_edit_hotp_secret.html", uid=user.id) db.session.commit() - return redirect(url_for("admin.new_user_two_factor", uid=uid)) + return redirect(url_for("admin.new_user_two_factor", uid=user.id)) else: - return render_template("admin_edit_hotp_secret.html", uid=uid) + return render_template("admin_edit_hotp_secret.html", uid=user.id) @view.route("/edit/<int:user_id>", methods=("GET", "POST")) @admin_required @@ -284,7 +278,10 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: try: Journalist.check_username_acceptable(new_username) except InvalidUsernameException as e: - flash(gettext("Invalid username: {message}").format(message=e), "error") + flash( + gettext("Invalid username: {message}").format(message=e), + "error", + ) return redirect(url_for("admin.edit_user", user_id=user_id)) if new_username == user.username: @@ -330,15 +327,17 @@ def edit_user(user_id: int) -> Union[str, werkzeug.Response]: @admin_required def delete_user(user_id: int) -> werkzeug.Response: user = Journalist.query.get(user_id) - if user_id == g.user.id: + if user_id == session.get_uid(): # Do not flash because the interface already has safe guards. # It can only happen by manually crafting a POST request - current_app.logger.error("Admin {} tried to delete itself".format(g.user.username)) + current_app.logger.error( + "Admin {} tried to delete itself".format(session.get_user().username) + ) abort(403) elif not user: current_app.logger.error( "Admin {} tried to delete nonexistent user with pk={}".format( - g.user.username, user_id + session.get_user().username, user_id ) ) abort(404) @@ -346,13 +345,17 @@ def delete_user(user_id: int) -> werkzeug.Response: # Do not flash because the interface does not expose this. # It can only happen by manually crafting a POST request current_app.logger.error( - 'Admin {} tried to delete "deleted" user'.format(g.user.username) + 'Admin {} tried to delete "deleted" user'.format(session.get_user().username) ) abort(403) else: user.delete() + current_app.session_interface.logout_user(user.id) # type: ignore db.session.commit() - flash(gettext("Deleted user '{user}'.").format(user=user.username), "notification") + flash( + gettext("Deleted user '{user}'.").format(user=user.username), + "notification", + ) return redirect(url_for("admin.index")) @@ -363,12 +366,9 @@ def new_password(user_id: int) -> werkzeug.Response: user = Journalist.query.get(user_id) except NoResultFound: abort(404) - password = request.form.get("password") - if set_diceware_password(user, password) is not False: - if user.last_token is not None: - revoke_token(user, user.last_token) - user.session_nonce += 1 + if set_diceware_password(user, password, admin=True) is not False: + current_app.session_interface.logout_user(user.id) # type: ignore db.session.commit() return redirect(url_for("admin.edit_user", user_id=user_id)) @@ -376,7 +376,10 @@ def new_password(user_id: int) -> werkzeug.Response: @admin_required def ossec_test() -> werkzeug.Response: current_app.logger.error("This is a test OSSEC alert") - flash(gettext("Test alert sent. Please check your email."), "testalert-notification") + flash( + gettext("Test alert sent. Please check your email."), + "testalert-notification", + ) return redirect(url_for("admin.manage_config") + "#config-testalert") return view diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -1,9 +1,8 @@ import collections.abc import json -from datetime import datetime, timedelta, timezone -from functools import wraps +from datetime import datetime, timezone from os import path -from typing import Any, Callable, Set, Tuple, Union +from typing import Set, Tuple, Union from uuid import UUID import flask @@ -11,6 +10,7 @@ from db import db from flask import Blueprint, abort, jsonify, request from journalist_app import utils +from journalist_app.sessions import session from models import ( BadTokenException, InvalidOTPSecretException, @@ -29,36 +29,6 @@ from store import NotEncrypted, Storage from werkzeug.exceptions import default_exceptions -TOKEN_EXPIRATION_MINS = 60 * 8 - - -def _authenticate_user_from_auth_header(request: flask.Request) -> Journalist: - try: - auth_header = request.headers["Authorization"] - except KeyError: - return abort(403, "API token not found in Authorization header.") - - if auth_header: - split = auth_header.split(" ") - if len(split) != 2 or split[0] != "Token": - abort(403, "Malformed authorization header.") - auth_token = split[1] - else: - auth_token = "" - authenticated_user = Journalist.validate_api_token_and_get_user(auth_token) - if not authenticated_user: - return abort(403, "API token is invalid or expired.") - return authenticated_user - - -def token_required(f: Callable) -> Callable: - @wraps(f) - def decorated_function(*args: Any, **kwargs: Any) -> Any: - _authenticate_user_from_auth_header(request) - return f(*args, **kwargs) - - return decorated_function - def get_or_404(model: db.Model, object_id: str, column: Column) -> db.Model: result = model.query.filter(column == object_id).one_or_none() @@ -123,14 +93,11 @@ def get_token() -> Tuple[flask.Response, int]: try: journalist = Journalist.login(username, passphrase, one_time_code) - token_expiry = datetime.now(timezone.utc) + timedelta( - seconds=TOKEN_EXPIRATION_MINS * 60 - ) response = jsonify( { - "token": journalist.generate_api_token(expiration=TOKEN_EXPIRATION_MINS * 60), - "expiration": token_expiry, + "token": session.get_token(), + "expiration": session.get_lifetime(), "journalist_uuid": journalist.uuid, "journalist_first_name": journalist.first_name, "journalist_last_name": journalist.last_name, @@ -142,6 +109,8 @@ def get_token() -> Tuple[flask.Response, int]: db.session.add(journalist) db.session.commit() + session["uid"] = journalist.id + return response, 200 except ( LoginThrottledException, @@ -153,13 +122,11 @@ def get_token() -> Tuple[flask.Response, int]: return abort(403, "Token authentication failed.") @api.route("/sources", methods=["GET"]) - @token_required def get_all_sources() -> Tuple[flask.Response, int]: sources = Source.query.filter_by(pending=False, deleted_at=None).all() return jsonify({"sources": [source.to_json() for source in sources]}), 200 @api.route("/sources/<source_uuid>", methods=["GET", "DELETE"]) - @token_required def single_source(source_uuid: str) -> Tuple[flask.Response, int]: if request.method == "GET": source = get_or_404(Source, source_uuid, column=Source.uuid) @@ -172,7 +139,6 @@ def single_source(source_uuid: str) -> Tuple[flask.Response, int]: abort(405) @api.route("/sources/<source_uuid>/add_star", methods=["POST"]) - @token_required def add_star(source_uuid: str) -> Tuple[flask.Response, int]: source = get_or_404(Source, source_uuid, column=Source.uuid) utils.make_star_true(source.filesystem_id) @@ -180,7 +146,6 @@ def add_star(source_uuid: str) -> Tuple[flask.Response, int]: return jsonify({"message": "Star added"}), 201 @api.route("/sources/<source_uuid>/remove_star", methods=["DELETE"]) - @token_required def remove_star(source_uuid: str) -> Tuple[flask.Response, int]: source = get_or_404(Source, source_uuid, column=Source.uuid) utils.make_star_false(source.filesystem_id) @@ -188,12 +153,13 @@ def remove_star(source_uuid: str) -> Tuple[flask.Response, int]: return jsonify({"message": "Star removed"}), 200 @api.route("/sources/<source_uuid>/flag", methods=["POST"]) - @token_required def flag(source_uuid: str) -> Tuple[flask.Response, int]: - return jsonify({"message": "Sources no longer need to be flagged for reply"}), 200 + return ( + jsonify({"message": "Sources no longer need to be flagged for reply"}), + 200, + ) @api.route("/sources/<source_uuid>/conversation", methods=["DELETE"]) - @token_required def source_conversation(source_uuid: str) -> Tuple[flask.Response, int]: if request.method == "DELETE": source = get_or_404(Source, source_uuid, column=Source.uuid) @@ -203,7 +169,6 @@ def source_conversation(source_uuid: str) -> Tuple[flask.Response, int]: abort(405) @api.route("/sources/<source_uuid>/submissions", methods=["GET"]) - @token_required def all_source_submissions(source_uuid: str) -> Tuple[flask.Response, int]: source = get_or_404(Source, source_uuid, column=Source.uuid) return ( @@ -212,22 +177,22 @@ def all_source_submissions(source_uuid: str) -> Tuple[flask.Response, int]: ) @api.route("/sources/<source_uuid>/submissions/<submission_uuid>/download", methods=["GET"]) - @token_required def download_submission(source_uuid: str, submission_uuid: str) -> flask.Response: get_or_404(Source, source_uuid, column=Source.uuid) submission = get_or_404(Submission, submission_uuid, column=Submission.uuid) return utils.serve_file_with_etag(submission) @api.route("/sources/<source_uuid>/replies/<reply_uuid>/download", methods=["GET"]) - @token_required def download_reply(source_uuid: str, reply_uuid: str) -> flask.Response: get_or_404(Source, source_uuid, column=Source.uuid) reply = get_or_404(Reply, reply_uuid, column=Reply.uuid) return utils.serve_file_with_etag(reply) - @api.route("/sources/<source_uuid>/submissions/<submission_uuid>", methods=["GET", "DELETE"]) - @token_required + @api.route( + "/sources/<source_uuid>/submissions/<submission_uuid>", + methods=["GET", "DELETE"], + ) def single_submission(source_uuid: str, submission_uuid: str) -> Tuple[flask.Response, int]: if request.method == "GET": get_or_404(Source, source_uuid, column=Source.uuid) @@ -242,11 +207,13 @@ def single_submission(source_uuid: str, submission_uuid: str) -> Tuple[flask.Res abort(405) @api.route("/sources/<source_uuid>/replies", methods=["GET", "POST"]) - @token_required def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: if request.method == "GET": source = get_or_404(Source, source_uuid, column=Source.uuid) - return jsonify({"replies": [reply.to_json() for reply in source.replies]}), 200 + return ( + jsonify({"replies": [reply.to_json() for reply in source.replies]}), + 200, + ) elif request.method == "POST": source = get_or_404(Source, source_uuid, column=Source.uuid) if request.json is None: @@ -255,8 +222,6 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: if "reply" not in request.json: abort(400, "reply not found in request body") - user = _authenticate_user_from_auth_header(request) - data = request.json if not data["reply"]: abort(400, "reply should not be empty") @@ -275,7 +240,7 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: # issue #3918 filename = path.basename(filename) - reply = Reply(user, source, filename, Storage.get_default()) + reply = Reply(session.get_user(), source, filename, Storage.get_default()) reply_uuid = data.get("uuid", None) if reply_uuid is not None: @@ -288,7 +253,7 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: try: db.session.add(reply) - seen_reply = SeenReply(reply=reply, journalist=user) + seen_reply = SeenReply(reply=reply, journalist=session.get_user()) db.session.add(seen_reply) db.session.add(source) db.session.commit() @@ -313,7 +278,6 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: abort(405) @api.route("/sources/<source_uuid>/replies/<reply_uuid>", methods=["GET", "DELETE"]) - @token_required def single_reply(source_uuid: str, reply_uuid: str) -> Tuple[flask.Response, int]: get_or_404(Source, source_uuid, column=Source.uuid) reply = get_or_404(Reply, reply_uuid, column=Reply.uuid) @@ -326,7 +290,6 @@ def single_reply(source_uuid: str, reply_uuid: str) -> Tuple[flask.Response, int abort(405) @api.route("/submissions", methods=["GET"]) - @token_required def get_all_submissions() -> Tuple[flask.Response, int]: submissions = Submission.query.all() return ( @@ -341,18 +304,18 @@ def get_all_submissions() -> Tuple[flask.Response, int]: ) @api.route("/replies", methods=["GET"]) - @token_required def get_all_replies() -> Tuple[flask.Response, int]: replies = Reply.query.all() - return jsonify({"replies": [reply.to_json() for reply in replies if reply.source]}), 200 + return ( + jsonify({"replies": [reply.to_json() for reply in replies if reply.source]}), + 200, + ) @api.route("/seen", methods=["POST"]) - @token_required def seen() -> Tuple[flask.Response, int]: """ Lists or marks the source conversation items that the journalist has seen. """ - user = _authenticate_user_from_auth_header(request) if request.method == "POST": if request.json is None or not isinstance(request.json, collections.abc.Mapping): @@ -383,30 +346,24 @@ def seen() -> Tuple[flask.Response, int]: targets.add(r) # now mark everything seen. - utils.mark_seen(list(targets), user) + utils.mark_seen(list(targets), session.get_user()) return jsonify({"message": "resources marked seen"}), 200 abort(405) @api.route("/user", methods=["GET"]) - @token_required def get_current_user() -> Tuple[flask.Response, int]: - user = _authenticate_user_from_auth_header(request) - return jsonify(user.to_json()), 200 + return jsonify(session.get_user().to_json()), 200 @api.route("/users", methods=["GET"]) - @token_required def get_all_users() -> Tuple[flask.Response, int]: users = Journalist.query.all() return jsonify({"users": [user.to_json(all_info=False) for user in users]}), 200 @api.route("/logout", methods=["POST"]) - @token_required def logout() -> Tuple[flask.Response, int]: - user = _authenticate_user_from_auth_header(request) - auth_token = request.headers["Authorization"].split(" ")[1] - utils.revoke_token(user, auth_token) + session.destroy() return jsonify({"message": "Your token has been revoked."}), 200 def _handle_api_http_exception( diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -12,7 +12,6 @@ current_app, escape, flash, - g, redirect, render_template, request, @@ -21,6 +20,7 @@ ) from flask_babel import gettext from journalist_app.forms import ReplyForm +from journalist_app.sessions import session from journalist_app.utils import ( col_delete, col_delete_data, @@ -151,7 +151,7 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: # mark as seen by the current user try: - journalist = g.get("user") + journalist = session.get_user() if fn.endswith("reply.gpg"): reply = Reply.query.filter(Reply.filename == fn).one() mark_seen([reply], journalist) @@ -165,7 +165,8 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: current_app.logger.error("Could not mark {} as seen: {}".format(fn, e)) return send_file( - Storage.get_default().path(filesystem_id, fn), mimetype="application/pgp-encrypted" + Storage.get_default().path(filesystem_id, fn), + mimetype="application/pgp-encrypted", ) return view diff --git a/securedrop/journalist_app/decorators.py b/securedrop/journalist_app/decorators.py --- a/securedrop/journalist_app/decorators.py +++ b/securedrop/journalist_app/decorators.py @@ -2,15 +2,15 @@ from functools import wraps from typing import Any, Callable -from flask import flash, g, redirect, url_for +from flask import flash, redirect, url_for from flask_babel import gettext -from journalist_app.utils import logged_in +from journalist_app.sessions import session def admin_required(func: Callable) -> Callable: @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: - if logged_in() and g.user.is_admin: + if session.logged_in() and session.get_user().is_admin: return func(*args, **kwargs) flash(gettext("Only admins can access this page."), "notification") return redirect(url_for("main.index")) diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -18,11 +18,11 @@ redirect, render_template, request, - session, url_for, ) from flask_babel import gettext from journalist_app.forms import ReplyForm +from journalist_app.sessions import session from journalist_app.utils import bulk_delete, download, get_source, validate_user from models import Reply, SeenReply, Source, SourceStar, Submission from sdconfig import SDConfig @@ -38,7 +38,9 @@ def make_blueprint(config: SDConfig) -> Blueprint: def login() -> Union[str, werkzeug.Response]: if request.method == "POST": user = validate_user( - request.form["username"], request.form["password"], request.form["token"] + request.form["username"], + request.form["password"], + request.form["token"], ) if user: current_app.logger.info( @@ -53,16 +55,14 @@ def login() -> Union[str, werkzeug.Response]: db.session.commit() session["uid"] = user.id - session["nonce"] = user.session_nonce + session.regenerate() return redirect(url_for("main.index")) return render_template("login.html") @view.route("/logout") def logout() -> werkzeug.Response: - session.pop("uid", None) - session.pop("expires", None) - session.pop("nonce", None) + session.destroy() return redirect(url_for("main.index")) @view.route("/") @@ -152,20 +152,23 @@ def reply() -> werkzeug.Response: ) try: - reply = Reply(g.user, g.source, filename, Storage.get_default()) + reply = Reply(session.get_user(), g.source, filename, Storage.get_default()) db.session.add(reply) - seen_reply = SeenReply(reply=reply, journalist=g.user) + seen_reply = SeenReply(reply=reply, journalist=session.get_user()) db.session.add(seen_reply) db.session.commit() store.async_add_checksum_for_file(reply, Storage.get_default()) except Exception as exc: - flash(gettext("An unexpected error occurred! Please " "inform your admin."), "error") + flash( + gettext("An unexpected error occurred! Please " "inform your admin."), + "error", + ) # We take a cautious approach to logging here because we're dealing # with responses to sources. It's possible the exception message # could contain information we don't want to write to disk. current_app.logger.error( "Reply from '{}' (ID {}) failed: {}!".format( - g.user.username, g.user.id, exc.__class__ + session.get_user().username, session.get_uid(), exc.__class__ ) ) else: @@ -222,7 +225,9 @@ def bulk() -> Union[str, werkzeug.Response]: if action == "download": source = get_source(g.filesystem_id) return download( - source.journalist_filename, selected_docs, on_error_redirect=error_redirect + source.journalist_filename, + selected_docs, + on_error_redirect=error_redirect, ) elif action == "delete": return bulk_delete(g.filesystem_id, selected_docs) diff --git a/securedrop/journalist_app/sessions.py b/securedrop/journalist_app/sessions.py new file mode 100644 --- /dev/null +++ b/securedrop/journalist_app/sessions.py @@ -0,0 +1,273 @@ +import typing +from datetime import datetime, timedelta, timezone +from json.decoder import JSONDecodeError +from secrets import token_urlsafe +from typing import Any, Dict, Optional, Tuple + +from flask import Flask, Request, Response +from flask import current_app as app +from flask.sessions import SessionInterface as FlaskSessionInterface +from flask.sessions import SessionMixin, session_json_serializer +from flask_babel import gettext +from itsdangerous import BadSignature, URLSafeTimedSerializer +from models import Journalist +from redis import Redis +from werkzeug.datastructures import CallbackDict + + +class ServerSideSession(CallbackDict, SessionMixin): + """Baseclass for server-side based sessions.""" + + def __init__(self, sid: str, token: str, lifetime: int = 0, initial: Any = None) -> None: + def on_update(self: ServerSideSession) -> None: + self.modified = True + + if initial and "uid" in initial: + self.set_uid(initial["uid"]) + self.set_user() + else: + self.uid: Optional[int] = None + self.user = None + CallbackDict.__init__(self, initial, on_update) + self.sid = sid + self.token: str = token + self.lifetime = lifetime + self.is_api = False + self.to_destroy = False + self.to_regenerate = False + self.modified = False + self.flash: Optional[Tuple[str, str]] = None + self.locale: Optional[str] = None + + def get_token(self) -> Optional[str]: + return self.token + + def get_lifetime(self) -> datetime: + return datetime.now(timezone.utc) + timedelta(seconds=self.lifetime) + + def set_user(self) -> None: + if self.uid is not None: + self.user = Journalist.query.get(self.uid) + if self.user is None: + # The uid has no match in the database, and this should really not happen + self.uid = None + self.to_destroy = True + + def get_user(self) -> Optional[Journalist]: + return self.user + + def get_uid(self) -> Optional[int]: + return self.uid + + def set_uid(self, uid: int) -> None: + self.user = None + self.uid = uid + + def logged_in(self) -> bool: + if self.uid is not None: + return True + else: + return False + + def destroy( + self, flash: Optional[Tuple[str, str]] = None, locale: Optional[str] = None + ) -> None: + # The parameters are needed to pass the information to the new session + self.locale = locale + self.flash = flash + self.uid = None + self.user = None + self.to_destroy = True + + def regenerate(self) -> None: + self.to_regenerate = True + + +class SessionInterface(FlaskSessionInterface): + def _generate_sid(self) -> str: + return token_urlsafe(32) + + def _get_signer(self, app: Flask) -> URLSafeTimedSerializer: + if not app.secret_key: + raise RuntimeError("No secret key set") + return URLSafeTimedSerializer(app.secret_key, salt=self.salt) + + """Uses the Redis key-value store as a session backend. + + :param redis: A ``redis.Redis`` instance. + :param key_prefix: A prefix that is added to all Redis store keys. + :param salt: Allows to set the signer salt from the calling interface + :param header_name: if use_header, set the header name to parse + """ + + def __init__( + self, + lifetime: int, + renew_count: int, + redis: Redis, + key_prefix: str, + salt: str, + header_name: str, + ) -> None: + self.serializer = session_json_serializer + self.redis = redis + self.lifetime = lifetime + self.renew_count = renew_count + self.key_prefix = key_prefix + self.api_key_prefix = "api_" + key_prefix + self.salt = salt + self.api_salt = "api_" + salt + self.header_name = header_name + self.new = False + self.has_same_site_capability = hasattr(self, "get_cookie_samesite") + + def _new_session(self, is_api: bool = False, initial: Any = None) -> ServerSideSession: + sid = self._generate_sid() + token: str = self._get_signer(app).dumps(sid) # type: ignore + session = ServerSideSession(sid=sid, token=token, lifetime=self.lifetime, initial=initial) + session.new = True + session.is_api = is_api + return session + + def open_session(self, app: Flask, request: Request) -> Optional[ServerSideSession]: + """This function is called by the flask session interface at the + beginning of each request. + """ + is_api = request.path.split("/")[1] == "api" + + if is_api: + self.key_prefix = self.api_key_prefix + self.salt = self.api_salt + auth_header = request.headers.get(self.header_name) + if auth_header: + split = auth_header.split(" ") + if len(split) != 2 or split[0] != "Token": + return self._new_session(is_api) + sid: Optional[str] = split[1] + else: + return self._new_session(is_api) + else: + sid = request.cookies.get(app.session_cookie_name) + if sid: + try: + sid = self._get_signer(app).loads(sid) + except BadSignature: + sid = None + if not sid: + return self._new_session(is_api) + + val = self.redis.get(self.key_prefix + sid) + if val is not None: + try: + data = self.serializer.loads(val.decode("utf-8")) + token: str = self._get_signer(app).dumps(sid) # type: ignore + return ServerSideSession(sid=sid, token=token, initial=data) + except (JSONDecodeError, NotImplementedError): + return self._new_session(is_api) + # signed session_id provided in cookie is valid, but the session is not on the server + # anymore so maybe here is the code path for a meaningful error message + msg = gettext("You have been logged out due to inactivity.") + return self._new_session(is_api, initial={"_flashes": [("error", msg)]}) + + def save_session( # type: ignore[override] # noqa + self, app: Flask, session: ServerSideSession, response: Response + ) -> None: + """This is called at the end of each request, just + before sending the response. + """ + domain = self.get_cookie_domain(app) + path = self.get_cookie_path(app) + if session.to_destroy: + initial: Dict[str, Any] = {"locale": session.locale} + if session.flash: + initial["_flashes"] = [session.flash] + self.redis.delete(self.key_prefix + session.sid) + if not session.is_api: + # Instead of deleting the cookie and send a new sid with the next request + # create the new session already, so we can pass along messages and locale + session = self._new_session(False, initial=initial) + expires = self.redis.ttl(name=self.key_prefix + session.sid) + if session.new: + session["renew_count"] = self.renew_count + expires = self.lifetime + else: + if expires < (30 * 60) and session["renew_count"] > 0: + session["renew_count"] -= 1 + expires += self.lifetime + session.modified = True + conditional_cookie_kwargs = {} + httponly = self.get_cookie_httponly(app) + secure = self.get_cookie_secure(app) + if self.has_same_site_capability: + conditional_cookie_kwargs["samesite"] = self.get_cookie_samesite(app) + val = self.serializer.dumps(dict(session)) + if session.to_regenerate: + self.redis.delete(self.key_prefix + session.sid) + session.sid = self._generate_sid() + session.token = self._get_signer(app).dumps(session.sid) # type: ignore + if session.new or session.to_regenerate: + self.redis.setex(name=self.key_prefix + session.sid, value=val, time=expires) + elif session.modified: + # To prevent race conditions where session is delete by an admin in the middle of a req + # accept to save the session object if and only if alrady exists using the xx flag + self.redis.set(name=self.key_prefix + session.sid, value=val, ex=expires, xx=True) + if not session.is_api and (session.new or session.to_regenerate): + response.headers.add("Vary", "Cookie") + response.set_cookie( + app.session_cookie_name, + session.token, + httponly=httponly, + domain=domain, + path=path, + secure=secure, + **conditional_cookie_kwargs # type: ignore + ) + + def logout_user(self, uid: int) -> None: + for key in self.redis.keys(self.key_prefix + "*") + self.redis.keys( + "api_" + self.key_prefix + "*" + ): + found = self.redis.get(key) + if found: + sess = session_json_serializer.loads(found.decode("utf-8")) + if "uid" in sess and sess["uid"] == uid: + self.redis.delete(key) + + +class Session: + def __init__(self, app: Flask) -> None: + self.app = app + if app is not None: + self.init_app(app) + + def init_app(self, app: Flask) -> "None": + """This is used to set up session for your app object. + :param app: the Flask app object with proper configuration. + """ + app.session_interface = self._get_interface(app) # type: ignore + + def _get_interface(self, app: Flask) -> SessionInterface: + config = app.config.copy() + config.setdefault("SESSION_REDIS", Redis()) + config.setdefault("SESSION_LIFETIME", 2 * 60 * 60) + config.setdefault("SESSION_RENEW_COUNT", 5) + config.setdefault("SESSION_SIGNER_SALT", "session") + config.setdefault("SESSION_KEY_PREFIX", "session:") + config.setdefault("SESSION_HEADER_NAME", "authorization") + + session_interface = SessionInterface( + config["SESSION_LIFETIME"], + config["SESSION_RENEW_COUNT"], + config["SESSION_REDIS"], + config["SESSION_KEY_PREFIX"], + config["SESSION_SIGNER_SALT"], + config["SESSION_HEADER_NAME"], + ) + + return session_interface + + +# Re-export flask.session, but with the correct type information for mypy. +from flask import session # noqa + +session = typing.cast(ServerSideSession, session) diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -2,26 +2,15 @@ import binascii import os from datetime import datetime, timezone -from typing import Any, List, Optional, Union +from typing import List, Optional, Union import flask import werkzeug from db import db from encryption import EncryptionManager -from flask import ( - Markup, - abort, - current_app, - escape, - flash, - g, - redirect, - request, - send_file, - sessions, - url_for, -) +from flask import Markup, abort, current_app, escape, flash, redirect, send_file, url_for from flask_babel import gettext, ngettext +from journalist_app.sessions import session from models import ( HOTP_SECRET_LENGTH, BadTokenException, @@ -33,7 +22,6 @@ LoginThrottledException, PasswordError, Reply, - RevokedToken, SeenFile, SeenMessage, SeenReply, @@ -47,24 +35,16 @@ from store import Storage, add_checksum_for_file -def logged_in() -> bool: - # When a user is logged in, we push their user ID (database primary key) - # into the session. setup_g checks for this value, and if it finds it, - # stores a reference to the user's Journalist object in g. - # - # This check is good for the edge case where a user is deleted but still - # has an active session - we will not authenticate a user if they are not - # in the database. - return bool(g.get("user", None)) - - def commit_account_changes(user: Journalist) -> None: if db.session.is_modified(user): try: db.session.add(user) db.session.commit() except Exception as e: - flash(gettext("An unexpected error occurred! Please " "inform your admin."), "error") + flash( + gettext("An unexpected error occurred! Please " "inform your admin."), + "error", + ) current_app.logger.error("Account changes for '{}' failed: {}".format(user, e)) db.session.rollback() else: @@ -177,7 +157,10 @@ def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: ) return False else: - flash(gettext("An unexpected error occurred! " "Please inform your admin."), "error") + flash( + gettext("An unexpected error occurred! " "Please inform your admin."), + "error", + ) current_app.logger.error( "set_hotp_secret '{}' (id {}) failed: {}".format(otp_secret, user.id, e) ) @@ -247,7 +230,7 @@ def download( zip_basename, datetime.now(timezone.utc).strftime("%Y-%m-%d--%H-%M-%S") ) - mark_seen(submissions, g.user) + mark_seen(submissions, session.get_user()) return send_file( zf.name, @@ -451,12 +434,17 @@ def set_name(user: Journalist, first_name: Optional[str], last_name: Optional[st flash(gettext("Name not updated: {message}").format(message=e), "error") -def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: +def set_diceware_password( + user: Journalist, password: Optional[str], admin: Optional[bool] = False +) -> bool: try: # nosemgrep: python.django.security.audit.unvalidated-password.unvalidated-password user.set_password(password) except PasswordError: - flash(gettext("The password you submitted is invalid. Password not changed."), "error") + flash( + gettext("The password you submitted is invalid. Password not changed."), + "error", + ) return False try: @@ -474,20 +462,39 @@ def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: return False # using Markup so the HTML isn't escaped - flash( - Markup( - "<p>{message} <span><code>{password}</code></span></p>".format( - message=Markup.escape( - gettext( - "Password updated. Don't forget to save it in your KeePassX database. " - "New password:" + if not admin: + session.destroy( + ( + "success", + Markup( + "<p>{message} <span><code>{password}</code></span></p>".format( + message=Markup.escape( + gettext( + "Password updated. Don't forget to save it in your KeePassX database. " # noqa: E501 + "New password:" + ) + ), + password=Markup.escape("" if password is None else password), ) ), - password=Markup.escape("" if password is None else password), - ) - ), - "success", - ) + ), + session.get("locale"), + ) + else: + flash( + Markup( + "<p>{message} <span><code>{password}</code></span></p>".format( + message=Markup.escape( + gettext( + "Password updated. Don't forget to save it in your KeePassX database. " + "New password:" + ) + ), + password=Markup.escape("" if password is None else password), + ) + ), + "success", + ) return True @@ -535,41 +542,3 @@ def serve_file_with_etag(db_obj: Union[Reply, Submission]) -> flask.Response: response.direct_passthrough = False response.headers["Etag"] = db_obj.checksum return response - - -class JournalistInterfaceSessionInterface(sessions.SecureCookieSessionInterface): - """A custom session interface that skips storing sessions for api requests but - otherwise just uses the default behaviour.""" - - def save_session(self, app: flask.Flask, session: Any, response: flask.Response) -> None: - # If this is an api request do not save the session - if request.path.split("/")[1] == "api": - return - else: - super(JournalistInterfaceSessionInterface, self).save_session(app, session, response) - - -def cleanup_expired_revoked_tokens() -> None: - """Remove tokens that have now expired from the revoked token table.""" - - revoked_tokens = db.session.query(RevokedToken).all() - - for revoked_token in revoked_tokens: - if Journalist.validate_token_is_not_expired_or_invalid(revoked_token.token): - pass # The token has not expired, we must keep in the revoked token table. - else: - # The token is no longer valid, remove from the revoked token table. - db.session.delete(revoked_token) - - db.session.commit() - - -def revoke_token(user: Journalist, auth_token: str) -> None: - try: - revoked_token = RevokedToken(token=auth_token, journalist_id=user.id) - db.session.add(revoked_token) - db.session.commit() - except IntegrityError as e: - db.session.rollback() - if "UNIQUE constraint failed: revoked_tokens.token" not in str(e): - raise e diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -17,9 +17,8 @@ from cryptography.hazmat.primitives.kdf import scrypt from db import db from encryption import EncryptionManager, GpgKeyNotFoundError -from flask import current_app, url_for +from flask import url_for from flask_babel import gettext, ngettext -from itsdangerous import BadData, TimedJSONWebSignatureSerializer from markupsafe import Markup from passlib.hash import argon2 from passphrases import PassphraseGenerator @@ -153,7 +152,11 @@ def to_json(self) -> "Dict[str, object]": "is_starred": starred, "last_updated": last_updated, "interaction_count": self.interaction_count, - "key": {"type": "PGP", "public": self.public_key, "fingerprint": self.fingerprint}, + "key": { + "type": "PGP", + "public": self.public_key, + "fingerprint": self.fingerprint, + }, "number_of_documents": docs_msg_count["documents"], "number_of_messages": docs_msg_count["messages"], "submissions_url": url_for("api.all_source_submissions", source_uuid=self.uuid), @@ -218,7 +221,9 @@ def to_json(self) -> "Dict[str, Any]": if self.source else None, "submission_url": url_for( - "api.single_submission", source_uuid=self.source.uuid, submission_uuid=self.uuid + "api.single_submission", + source_uuid=self.source.uuid, + submission_uuid=self.uuid, ) if self.source else None, @@ -229,7 +234,9 @@ def to_json(self) -> "Dict[str, Any]": "is_read": self.seen, "uuid": self.uuid, "download_url": url_for( - "api.download_submission", source_uuid=self.source.uuid, submission_uuid=self.uuid + "api.download_submission", + source_uuid=self.source.uuid, + submission_uuid=self.uuid, ) if self.source else None, @@ -403,7 +410,6 @@ class Journalist(db.Model): pw_salt = Column(LargeBinary(32), nullable=True) pw_hash = Column(LargeBinary(256), nullable=True) is_admin = Column(Boolean) - session_nonce = Column(Integer, nullable=False, default=0) otp_secret = Column(String(32), default=pyotp.random_base32) is_totp = Column(Boolean, default=True) @@ -417,7 +423,6 @@ class Journalist(db.Model): login_attempts = relationship( "JournalistLoginAttempt", backref="journalist", cascade="all, delete" ) - revoked_tokens = relationship("RevokedToken", backref="journalist", cascade="all, delete") MIN_USERNAME_LEN = 3 MIN_NAME_LEN = 0 @@ -710,39 +715,10 @@ def login( return user - def generate_api_token(self, expiration: int) -> str: - s = TimedJSONWebSignatureSerializer(current_app.config["SECRET_KEY"], expires_in=expiration) - return s.dumps({"id": self.id}).decode("ascii") # type:ignore - - @staticmethod - def validate_token_is_not_expired_or_invalid(token: str) -> bool: - s = TimedJSONWebSignatureSerializer(current_app.config["SECRET_KEY"]) - try: - s.loads(token) - except BadData: - return False - - return True - - @staticmethod - def validate_api_token_and_get_user(token: str) -> "Optional[Journalist]": - s = TimedJSONWebSignatureSerializer(current_app.config["SECRET_KEY"]) - try: - data = s.loads(token) - except BadData: - return None - - revoked_token = RevokedToken.query.filter_by(token=token).one_or_none() - if revoked_token is not None: - return None - - return Journalist.query.get(data["id"]) - def to_json(self, all_info: bool = True) -> Dict[str, Any]: """Returns a JSON representation of the journalist user. If all_info is False, potentially sensitive or extraneous fields are excluded. Note that both representations do NOT include credentials.""" - json_user = { "username": self.username, "uuid": self.uuid, @@ -839,7 +815,8 @@ class SeenFile(db.Model): file_id = Column(Integer, ForeignKey("submissions.id"), nullable=False) journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) file = relationship( - "Submission", backref=backref("seen_files", lazy="dynamic", cascade="all,delete") + "Submission", + backref=backref("seen_files", lazy="dynamic", cascade="all,delete"), ) journalist = relationship("Journalist", backref=backref("seen_files")) @@ -851,7 +828,8 @@ class SeenMessage(db.Model): message_id = Column(Integer, ForeignKey("submissions.id"), nullable=False) journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) message = relationship( - "Submission", backref=backref("seen_messages", lazy="dynamic", cascade="all,delete") + "Submission", + backref=backref("seen_messages", lazy="dynamic", cascade="all,delete"), ) journalist = relationship("Journalist", backref=backref("seen_messages")) @@ -881,19 +859,6 @@ def __init__(self, journalist: Journalist) -> None: self.journalist = journalist -class RevokedToken(db.Model): - - """ - API tokens that have been revoked either through a logout or other revocation mechanism. - """ - - __tablename__ = "revoked_tokens" - - id = Column(Integer, primary_key=True) - journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) - token = db.Column(db.Text, nullable=False, unique=True) - - class InstanceConfig(db.Model): """Versioned key-value store of settings configurable from the journalist interface. The current version has valid_until=0 (unix epoch start) @@ -905,7 +870,10 @@ class InstanceConfig(db.Model): __tablename__ = "instance_config" version = Column(Integer, primary_key=True) valid_until = Column( - DateTime, default=datetime.datetime.fromtimestamp(0), nullable=False, unique=True + DateTime, + default=datetime.datetime.fromtimestamp(0), + nullable=False, + unique=True, ) allow_document_uploads = Column(Boolean, default=True) organization_name = Column(String(255), nullable=True, default="SecureDrop") diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -6,17 +6,28 @@ FALLBACK_LOCALE = "en_US" +# Adding a subclass here allows for adding attributes without modifying config.py +class JournalistInterfaceConfig(_config.JournalistInterfaceFlaskConfig): + SESSION_COOKIE_NAME = "js" + SESSION_SIGNER_SALT = "js_session" + SESSION_KEY_PREFIX = "js_session:" + SESSION_LIFETIME = 2 * 60 * 60 + SESSION_RENEW_COUNT = 5 + + +class SourceInterfaceConfig(_config.SourceInterfaceFlaskConfig): + SESSION_COOKIE_NAME = "ss" + + class SDConfig: def __init__(self) -> None: try: - self.JOURNALIST_APP_FLASK_CONFIG_CLS = ( - _config.JournalistInterfaceFlaskConfig - ) # type: Type + self.JOURNALIST_APP_FLASK_CONFIG_CLS = JournalistInterfaceConfig # type: Type except AttributeError: pass try: - self.SOURCE_APP_FLASK_CONFIG_CLS = _config.SourceInterfaceFlaskConfig # type: Type + self.SOURCE_APP_FLASK_CONFIG_CLS = SourceInterfaceConfig # type: Type except AttributeError: pass
diff --git a/securedrop/tests/functional/sd_config_v2.py b/securedrop/tests/functional/sd_config_v2.py --- a/securedrop/tests/functional/sd_config_v2.py +++ b/securedrop/tests/functional/sd_config_v2.py @@ -19,6 +19,12 @@ class FlaskAppConfig: # This is recommended for performance, and also resolves #369 USE_X_SENDFILE: bool = True + # additional config for JI Redis sessions + SESSION_SIGNER_SALT: str = "js_session" + SESSION_KEY_PREFIX: str = "js_session:" + SESSION_LIFETIME: int = 2 * 60 * 60 + SESSION_RENEW_COUNT: int = 5 + DEFAULT_SECUREDROP_ROOT = Path(__file__).absolute().parent.parent.parent diff --git a/securedrop/tests/migrations/migration_c5a02eb52f2d.py b/securedrop/tests/migrations/migration_c5a02eb52f2d.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_c5a02eb52f2d.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +import random +import uuid + +from db import db +from journalist_app import create_app +from sqlalchemy import text +from sqlalchemy.exc import OperationalError + +from .helpers import random_chars + + +class Helper: + def __init__(self): + self.journalist_id = None + + +class UpgradeTester(Helper): + def __init__(self, config): + Helper.__init__(self) + self.config = config + self.app = create_app(config) + + def create_journalist(self): + params = { + "uuid": str(uuid.uuid4()), + "username": random_chars(50), + "nonce": random.randint(20, 100), + } + sql = """INSERT INTO journalists (uuid, username, session_nonce) + VALUES (:uuid, :username, :nonce)""" + return db.engine.execute(text(sql), **params).lastrowid + + def add_revoked_token(self): + params = { + "journalist_id": self.journalist_id, + "token": "abc123", + } + sql = """INSERT INTO revoked_tokens (journalist_id, token) + VALUES (:journalist_id, :token) + """ + db.engine.execute(text(sql), **params) + + def load_data(self): + with self.app.app_context(): + self.journalist_id = self.create_journalist() + self.add_revoked_token() + + def check_upgrade(self): + with self.app.app_context(): + sql = "SELECT session_nonce FROM journalists WHERE id = :id" + params = {"id": self.journalist_id} + try: + db.engine.execute(text(sql), **params).fetchall() + except OperationalError: + pass + sql = "SELECT * FROM revoked_tokens WHERE id = :id" + try: + db.engine.execute(text(sql), **params).fetchall() + except OperationalError: + pass + + +class DowngradeTester(Helper): + def __init__(self, config): + Helper.__init__(self) + self.config = config + self.app = create_app(config) + + def create_journalist(self): + params = {"uuid": str(uuid.uuid4()), "username": random_chars(50)} + sql = """INSERT INTO journalists (uuid, username) + VALUES (:uuid, :username)""" + return db.engine.execute(text(sql), **params).lastrowid + + def load_data(self): + with self.app.app_context(): + self.journalist_id = self.create_journalist() + + def check_downgrade(self): + with self.app.app_context(): + sql = "SELECT session_nonce FROM journalists WHERE id = :id" + params = {"id": self.journalist_id} + res = db.engine.execute(text(sql), **params).fetchone() + assert isinstance(res["session_nonce"], int) + sql = """INSERT INTO revoked_tokens (journalist_id, token) + VALUES (:journalist_id, :token)""" + params = {"journalist_id": self.journalist_id, "token": "abc789"} + res = db.engine.execute(text(sql), **params).lastrowid + assert isinstance(res, int) diff --git a/securedrop/tests/test_2fa.py b/securedrop/tests/test_2fa.py --- a/securedrop/tests/test_2fa.py +++ b/securedrop/tests/test_2fa.py @@ -62,7 +62,9 @@ def test_totp_reuse_protections(journalist_app, test_journo, hardening): resp = app.post( url_for("main.login"), data=dict( - username=test_journo["username"], password=test_journo["password"], token=token + username=test_journo["username"], + password=test_journo["password"], + token=token, ), ) @@ -136,19 +138,8 @@ def test_bad_token_fails_to_verify_on_admin_new_user_two_factor_page( assert resp.status_code == 200 ins.assert_message_flashed( - "There was a problem verifying the two-factor code. Please try again.", "error" - ) - - with journalist_app.test_client() as app: - login_user(app, test_admin) - # Submit the same invalid token again - with InstrumentedApp(journalist_app) as ins: - resp = app.post( - url_for("admin.new_user_two_factor", uid=test_admin["id"]), - data=dict(token=invalid_token), - ) - ins.assert_message_flashed( - "There was a problem verifying the two-factor code. Please try again.", "error" + "There was a problem verifying the two-factor code. Please try again.", + "error", ) @@ -169,15 +160,6 @@ def test_bad_token_fails_to_verify_on_new_user_two_factor_page( assert resp.status_code == 200 ins.assert_message_flashed( - "There was a problem verifying the two-factor code. Please try again.", "error" - ) - - with journalist_app.test_client() as app: - login_user(app, test_journo) - - # Submit the same invalid token again - with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for("account.new_two_factor"), data=dict(token=invalid_token)) - ins.assert_message_flashed( - "There was a problem verifying the two-factor code. Please try again.", "error" + "There was a problem verifying the two-factor code. Please try again.", + "error", ) diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -14,7 +14,8 @@ from bs4 import BeautifulSoup from db import db from encryption import EncryptionManager -from flask import escape, g, session +from flask import escape +from journalist_app.sessions import session from pyotp import HOTP, TOTP from source_app.session_manager import SessionManager from store import Storage @@ -39,7 +40,7 @@ def _login_user(app, user_dict): follow_redirects=True, ) assert resp.status_code == 200 - assert hasattr(g, "user") # ensure logged in + assert session.get_user() is not None def test_submit_message(journalist_app, source_app, test_journo, app_storage): @@ -306,7 +307,9 @@ def _helper_test_reply( resp = app.post( "/bulk", data=dict( - filesystem_id=filesystem_id, action="download", doc_names_selected=checkbox_values + filesystem_id=filesystem_id, + action="download", + doc_names_selected=checkbox_values, ), follow_redirects=True, ) @@ -355,7 +358,11 @@ def _helper_filenames_delete(journalist_app, soup, i): # delete resp = journalist_app.post( "/bulk", - data=dict(filesystem_id=filesystem_id, action="delete", doc_names_selected=checkbox_values), + data=dict( + filesystem_id=filesystem_id, + action="delete", + doc_names_selected=checkbox_values, + ), follow_redirects=True, ) assert resp.status_code == 200 @@ -400,7 +407,12 @@ def test_reply_normal(journalist_app, source_app, test_journo, config): encryption_mgr = EncryptionManager.get_default() with mock.patch.object(encryption_mgr._gpg, "_encoding", "ansi_x3.4_1968"): _helper_test_reply( - journalist_app, source_app, config, test_journo, "This is a test reply.", True + journalist_app, + source_app, + config, + test_journo, + "This is a test reply.", + True, ) @@ -416,7 +428,12 @@ def test_unicode_reply_with_ansi_env(journalist_app, source_app, test_journo, co encryption_mgr = EncryptionManager.get_default() with mock.patch.object(encryption_mgr._gpg, "_encoding", "ansi_x3.4_1968"): _helper_test_reply( - journalist_app, source_app, config, test_journo, "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ", True + journalist_app, + source_app, + config, + test_journo, + "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ", + True, ) @@ -707,7 +724,9 @@ def test_prevent_document_uploads(source_app, journalist_app, test_admin): prevent_document_uploads=True, min_message_length=0 ) resp = app.post( - "/admin/update-submission-preferences", data=form.data, follow_redirects=True + "/admin/update-submission-preferences", + data=form.data, + follow_redirects=True, ) assert resp.status_code == 200 @@ -737,7 +756,9 @@ def test_no_prevent_document_uploads(source_app, journalist_app, test_admin): prevent_document_uploads=False, min_message_length=0 ) resp = app.post( - "/admin/update-submission-preferences", data=form.data, follow_redirects=True + "/admin/update-submission-preferences", + data=form.data, + follow_redirects=True, ) assert resp.status_code == 200 diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -5,6 +5,7 @@ import io import os import random +import time import zipfile from base64 import b64decode from io import BytesIO @@ -16,8 +17,9 @@ from db import db from encryption import EncryptionManager, GpgKeyNotFoundError from flaky import flaky -from flask import current_app, escape, g, session, url_for +from flask import current_app, escape, g, url_for from flask_babel import gettext, ngettext +from journalist_app.sessions import session from journalist_app.utils import mark_seen from mock import call, patch from models import ( @@ -60,11 +62,15 @@ def _login_user(app, username, password, otp_secret, success=True): resp = app.post( url_for("main.login"), - data={"username": username, "password": password, "token": TOTP(otp_secret).now()}, + data={ + "username": username, + "password": password, + "token": TOTP(otp_secret).now(), + }, follow_redirects=True, ) assert resp.status_code == 200 - assert success == hasattr(g, "user") # check logged-in vs expected + assert (session.get_user() is not None) == success @pytest.mark.parametrize("otp_secret", ["", "GA", "GARBAGE", "JHCOGO7VCER3EJ4"]) @@ -104,13 +110,19 @@ def test_reply_error_logging(journalist_app, test_journo, test_source): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with patch.object(journalist_app.logger, "error") as mocked_error_logger: with patch.object(db.session, "commit", side_effect=exception_class(exception_msg)): resp = app.post( url_for("main.reply"), - data={"filesystem_id": test_source["filesystem_id"], "message": "_"}, + data={ + "filesystem_id": test_source["filesystem_id"], + "message": "_", + }, follow_redirects=True, ) assert resp.status_code == 200 @@ -131,14 +143,20 @@ def test_reply_error_flashed_message(config, journalist_app, test_journo, test_s with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(app) as ins: with patch.object(db.session, "commit", side_effect=exception_class()): resp = app.post( url_for("main.reply", l=locale), - data={"filesystem_id": test_source["filesystem_id"], "message": "_"}, + data={ + "filesystem_id": test_source["filesystem_id"], + "message": "_", + }, follow_redirects=True, ) @@ -153,7 +171,10 @@ def test_reply_error_flashed_message(config, journalist_app, test_journo, test_s def test_empty_replies_are_rejected(config, journalist_app, test_journo, test_source, locale): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) resp = app.post( url_for("main.reply", l=locale), @@ -172,7 +193,10 @@ def test_empty_replies_are_rejected(config, journalist_app, test_journo, test_so def test_nonempty_replies_are_accepted(config, journalist_app, test_journo, test_source, locale): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) resp = app.post( url_for("main.reply", l=locale), @@ -232,7 +256,9 @@ def test_login_throttle(config, journalist_app, test_journo, locale): resp = app.post( url_for("main.login"), data=dict( - username=test_journo["username"], password="invalid", token="invalid" + username=test_journo["username"], + password="invalid", + token="invalid", ), ) assert resp.status_code == 200 @@ -242,7 +268,9 @@ def test_login_throttle(config, journalist_app, test_journo, locale): resp = app.post( url_for("main.login", l=locale), data=dict( - username=test_journo["username"], password="invalid", token="invalid" + username=test_journo["username"], + password="invalid", + token="invalid", ), ) assert page_language(resp.data) == language_tag(locale) @@ -283,7 +311,9 @@ def test_login_throttle_is_not_global(config, journalist_app, test_journo, test_ resp = app.post( url_for("main.login", l=locale), data=dict( - username=test_journo["username"], password="invalid", token="invalid" + username=test_journo["username"], + password="invalid", + token="invalid", ), ) assert page_language(resp.data) == language_tag(locale) @@ -294,7 +324,9 @@ def test_login_throttle_is_not_global(config, journalist_app, test_journo, test_ resp = app.post( url_for("main.login", l=locale), data=dict( - username=test_journo["username"], password="invalid", token="invalid" + username=test_journo["username"], + password="invalid", + token="invalid", ), ) assert page_language(resp.data) == language_tag(locale) @@ -475,7 +507,10 @@ def test_admin_logout_redirects_to_index(journalist_app, test_admin): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: _login_user( - app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) resp = app.get(url_for("main.logout")) ins.assert_redirects(resp, url_for("main.index")) @@ -485,7 +520,10 @@ def test_user_logout_redirects_to_index(journalist_app, test_journo): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) resp = app.get(url_for("main.logout")) ins.assert_redirects(resp, url_for("main.index")) @@ -495,7 +533,12 @@ def test_user_logout_redirects_to_index(journalist_app, test_journo): @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_index(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.get(url_for("admin.index", l=locale)) assert page_language(resp.data) == language_tag(locale) msgids = ["Admin Interface"] @@ -511,7 +554,12 @@ def test_admin_delete_user(config, journalist_app, test_admin, test_journo, loca assert Journalist.query.get(test_journo["id"]) is not None with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( url_for("admin.delete_user", user_id=test_journo["id"], l=locale), @@ -522,7 +570,8 @@ def test_admin_delete_user(config, journalist_app, test_admin, test_journo, loca msgids = ["Deleted user '{user}'."] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(user=test_journo["username"]), "notification" + gettext(msgids[0]).format(user=test_journo["username"]), + "notification", ) # Verify journalist is no longer in the database @@ -538,9 +587,15 @@ def test_admin_cannot_delete_self(config, journalist_app, test_admin, test_journ assert Journalist.query.get(test_journo["id"]) is not None with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( - url_for("admin.delete_user", user_id=test_admin["id"], l=locale), follow_redirects=True + url_for("admin.delete_user", user_id=test_admin["id"], l=locale), + follow_redirects=True, ) # Assert correct interface behavior @@ -580,7 +635,12 @@ def test_admin_edits_user_password_success_response( config, journalist_app, test_admin, test_journo, locale ): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.new_password", user_id=test_journo["id"], l=locale), @@ -606,13 +666,19 @@ def test_admin_edits_user_password_session_invalidate( # Start the journalist session. with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) # Change the journalist password via an admin session. with journalist_app.test_client() as admin_app: _login_user( - admin_app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + admin_app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) resp = admin_app.post( @@ -630,27 +696,18 @@ def test_admin_edits_user_password_session_invalidate( assert escape(gettext(msgids[0])) in resp_text assert VALID_PASSWORD_2 in resp_text - # Now verify the password change error is flashed. - with InstrumentedApp(journalist_app) as ins: - resp = app.get(url_for("main.index", l=locale), follow_redirects=True) - msgids = ["You have been logged out due to password change"] - assert page_language(resp.data) == language_tag(locale) - with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), "error") - - # Also ensure that session is now invalid. - session.pop("expires", None) - session.pop("csrf_token", None) - session.pop("locale", None) - assert not session, session - def test_admin_deletes_invalid_user_404(journalist_app, test_admin): with journalist_app.app_context(): invalid_id = db.session.query(func.max(Journalist.id)).scalar() + 1 with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post(url_for("admin.delete_user", user_id=invalid_id)) assert resp.status_code == 404 @@ -662,7 +719,12 @@ def test_admin_deletes_deleted_user_403(journalist_app, test_admin): deleted_id = deleted.id with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post(url_for("admin.delete_user", user_id=deleted_id)) assert resp.status_code == 403 @@ -673,7 +735,12 @@ def test_admin_edits_user_password_error_response( config, journalist_app, test_admin, test_journo, locale ): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with patch("sqlalchemy.orm.scoping.scoped_session.commit", side_effect=Exception()): with InstrumentedApp(journalist_app) as ins: @@ -704,18 +771,22 @@ def test_user_edits_password_success_response(config, journalist_app, test_journ with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) token = TOTP(test_journo["otp_secret"]).now() resp = app.post( url_for("account.new_password", l=locale), data=dict( - current_password=test_journo["password"], token=token, password=VALID_PASSWORD_2 + current_password=test_journo["password"], + token=token, + password=VALID_PASSWORD_2, ), follow_redirects=True, ) - assert page_language(resp.data) == language_tag(locale) msgids = [ "Password updated. Don't forget to save it in your KeePassX database. New password:" ] @@ -736,7 +807,10 @@ def test_user_edits_password_expires_session(journalist_app, test_journo): models.LOGIN_HARDENING = False with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) assert "uid" in session @@ -754,7 +828,7 @@ def test_user_edits_password_expires_session(journalist_app, test_journo): ins.assert_redirects(resp, url_for("main.login")) # verify the session was expired after the password was changed - assert "uid" not in session + assert session.uid is None and session.user is None finally: models.LOGIN_HARDENING = original_hardening @@ -771,7 +845,10 @@ def test_user_edits_password_error_response(config, journalist_app, test_journo, with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) # patch token verification because there are multiple commits @@ -808,7 +885,10 @@ def test_user_edits_password_error_response(config, journalist_app, test_journo, def test_admin_add_user_when_username_already_taken(config, journalist_app, test_admin, locale): with journalist_app.test_client() as client: _login_user( - client, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + client, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: resp = client.post( @@ -878,7 +958,12 @@ def test_admin_edits_user_password_too_long_warning(journalist_app, test_admin, ) with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: app.post( url_for("admin.new_password", user_id=test_journo["id"]), @@ -893,7 +978,8 @@ def test_admin_edits_user_password_too_long_warning(journalist_app, test_admin, ) ins.assert_message_flashed( - "The password you submitted is invalid. " "Password not changed.", "error" + "The password you submitted is invalid. " "Password not changed.", + "error", ) @@ -904,7 +990,10 @@ def test_user_edits_password_too_long_warning(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: @@ -923,7 +1012,8 @@ def test_user_edits_password_too_long_warning(journalist_app, test_journo): ) ins.assert_message_flashed( - "The password you submitted is invalid. " "Password not changed.", "error" + "The password you submitted is invalid. " "Password not changed.", + "error", ) @@ -934,7 +1024,12 @@ def test_admin_add_user_password_too_long_warning(config, journalist_app, test_a Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1 ) with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( @@ -963,7 +1058,12 @@ def test_admin_add_user_password_too_long_warning(config, journalist_app, test_a def test_admin_add_user_first_name_too_long_warning(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -991,7 +1091,12 @@ def test_admin_add_user_first_name_too_long_warning(config, journalist_app, test def test_admin_add_user_last_name_too_long_warning(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1023,7 +1128,12 @@ def test_admin_edits_user_invalid_username_deleted( username to deleted""" new_username = "deleted" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( @@ -1046,7 +1156,12 @@ def test_admin_edits_user_invalid_username_deleted( def test_admin_resets_user_hotp_format_non_hexa(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) journo = test_journo["journalist"] # guard to ensure check below tests the correct condition @@ -1082,7 +1197,12 @@ def test_admin_resets_user_hotp_format_too_short( ): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) journo = test_journo["journalist"] # guard to ensure check below tests the correct condition @@ -1114,7 +1234,12 @@ def test_admin_resets_user_hotp_format_too_short( def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) journo = test_journo["journalist"] old_secret = journo.otp_secret @@ -1145,9 +1270,17 @@ def test_admin_resets_user_hotp_error(mocker, journalist_app, test_admin, test_j old_secret = test_journo["otp_secret"] with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) - mocker.patch("models.Journalist.set_hotp_secret", side_effect=binascii.Error(error_message)) + mocker.patch( + "models.Journalist.set_hotp_secret", + side_effect=binascii.Error(error_message), + ) with InstrumentedApp(journalist_app) as ins: app.post( @@ -1180,12 +1313,16 @@ def test_user_resets_hotp(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=new_secret) + url_for("account.reset_two_factor_hotp"), + data=dict(otp_secret=new_secret), ) # should redirect to verification page ins.assert_redirects(resp, url_for("account.new_two_factor")) @@ -1203,12 +1340,16 @@ def test_user_resets_user_hotp_format_non_hexa(journalist_app, test_journo): non_hexa_secret = "0123456789ABCDZZ0123456789ABCDEF01234567" with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: app.post( - url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=non_hexa_secret) + url_for("account.reset_two_factor_hotp"), + data=dict(otp_secret=non_hexa_secret), ) ins.assert_message_flashed( "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9.", @@ -1230,13 +1371,22 @@ def test_user_resets_user_hotp_error(mocker, journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) - mocker.patch("models.Journalist.set_hotp_secret", side_effect=binascii.Error(error_message)) + mocker.patch( + "models.Journalist.set_hotp_secret", + side_effect=binascii.Error(error_message), + ) with InstrumentedApp(journalist_app) as ins: - app.post(url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=bad_secret)) + app.post( + url_for("account.reset_two_factor_hotp"), + data=dict(otp_secret=bad_secret), + ) ins.assert_message_flashed( "An unexpected error occurred! Please inform your " "admin.", "error" ) @@ -1257,7 +1407,12 @@ def test_admin_resets_user_totp(journalist_app, test_admin, test_journo): old_secret = test_journo["otp_secret"] with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( @@ -1277,7 +1432,10 @@ def test_user_resets_totp(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: @@ -1296,7 +1454,12 @@ def test_user_resets_totp(journalist_app, test_journo): @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_resets_hotp_with_missing_otp_secret_key(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.reset_two_factor_hotp", l=locale), data=dict(uid=test_admin["id"]), @@ -1310,7 +1473,12 @@ def test_admin_resets_hotp_with_missing_otp_secret_key(config, journalist_app, t def test_admin_new_user_2fa_redirect(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( url_for("admin.new_user_two_factor", uid=test_journo["id"]), @@ -1325,7 +1493,12 @@ def test_http_get_on_admin_new_user_two_factor_page( config, journalist_app, test_admin, test_journo, locale ): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.get( url_for("admin.new_user_two_factor", uid=test_journo["id"], l=locale), ) @@ -1340,7 +1513,12 @@ def test_http_get_on_admin_new_user_two_factor_page( @pytest.mark.parametrize("locale", get_test_locales()) def test_http_get_on_admin_add_user_page(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.get(url_for("admin.add_user", l=locale)) assert page_language(resp.data) == language_tag(locale) msgids = ["ADD USER"] @@ -1352,7 +1530,12 @@ def test_admin_add_user(journalist_app, test_admin): username = "dellsberg" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( @@ -1377,7 +1560,12 @@ def test_admin_add_user_with_invalid_username(config, journalist_app, test_admin username = "deleted" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1452,7 +1640,12 @@ def test_deleted_user_cannot_login_exception(journalist_app, locale): @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_without_username(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1478,7 +1671,12 @@ def test_admin_add_user_too_short_username(config, journalist_app, test_admin, l username = "a" * (Journalist.MIN_USERNAME_LEN - 1) with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1514,7 +1712,12 @@ def test_admin_add_user_too_short_username(config, journalist_app, test_admin, l ) def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1542,11 +1745,17 @@ def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, s @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize( - "locale, secret", ((locale, " " * i) for locale in get_test_locales() for i in range(3)) + "locale, secret", + ((locale, " " * i) for locale in get_test_locales() for i in range(3)), ) def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1575,7 +1784,12 @@ def test_admin_add_user_yubikey_valid_length(journalist_app, test_admin, locale) otp = "1234567890123456789012345678901234567890" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1604,7 +1818,12 @@ def test_admin_add_user_yubikey_correct_length_with_whitespace(journalist_app, t otp = "12 34 56 78 90 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user", l=locale), @@ -1631,7 +1850,12 @@ def test_admin_sets_user_to_admin(journalist_app, test_admin): new_user = "admin-set-user-to-admin-test" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user"), @@ -1664,7 +1888,12 @@ def test_admin_renames_user(journalist_app, test_admin): new_user = "admin-renames-user-test" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user"), @@ -1696,7 +1925,12 @@ def test_admin_adds_first_name_last_name_to_user(journalist_app, test_admin): new_user = "admin-first-name-last-name-user-test" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) resp = app.post( url_for("admin.add_user"), @@ -1730,7 +1964,10 @@ def test_admin_adds_invalid_first_last_name_to_user(config, journalist_app, test new_user = "admin-invalid-first-name-last-name-user-test" _login_user( - client, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + client, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) resp = client.post( @@ -1752,7 +1989,11 @@ def test_admin_adds_invalid_first_last_name_to_user(config, journalist_app, test with InstrumentedApp(journalist_app) as ins: resp = client.post( url_for("admin.edit_user", user_id=journo.id, l=locale), - data=dict(username=new_user, first_name=overly_long_name, last_name="test name"), + data=dict( + username=new_user, + first_name=overly_long_name, + last_name="test name", + ), follow_redirects=True, ) assert resp.status_code == 200 @@ -1775,7 +2016,12 @@ def test_admin_add_user_integrity_error(config, journalist_app, test_admin, mock ) with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( @@ -1807,12 +2053,19 @@ def test_admin_add_user_integrity_error(config, journalist_app, test_admin, mock @pytest.mark.parametrize("locale", get_test_locales()) def test_prevent_document_uploads(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.SubmissionPreferencesForm( prevent_document_uploads=True, min_message_length=0 ) app.post( - url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + url_for("admin.update_submission_preferences"), + data=form.data, + follow_redirects=True, ) assert InstanceConfig.get_current().allow_document_uploads is False with InstrumentedApp(journalist_app) as ins: @@ -1831,10 +2084,17 @@ def test_prevent_document_uploads(config, journalist_app, test_admin, locale): @pytest.mark.parametrize("locale", get_test_locales()) def test_no_prevent_document_uploads(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.SubmissionPreferencesForm(min_message_length=0) app.post( - url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + url_for("admin.update_submission_preferences"), + data=form.data, + follow_redirects=True, ) assert InstanceConfig.get_current().allow_document_uploads is True with InstrumentedApp(journalist_app) as ins: @@ -1852,7 +2112,12 @@ def test_no_prevent_document_uploads(config, journalist_app, test_admin, locale) def test_prevent_document_uploads_invalid(journalist_app, test_admin): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form_true = journalist_app_module.forms.SubmissionPreferencesForm( prevent_document_uploads=True, min_message_length=0 ) @@ -1878,7 +2143,12 @@ def test_prevent_document_uploads_invalid(journalist_app, test_admin): def test_message_filtering(config, journalist_app, test_admin): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) # Assert status quo assert InstanceConfig.get_current().initial_message_min_len == 0 @@ -1887,7 +2157,9 @@ def test_message_filtering(config, journalist_app, test_admin): prevent_short_messages=False, min_message_length=10 ) app.post( - url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + url_for("admin.update_submission_preferences"), + data=form.data, + follow_redirects=True, ) # Still 0 assert InstanceConfig.get_current().initial_message_min_len == 0 @@ -1897,7 +2169,9 @@ def test_message_filtering(config, journalist_app, test_admin): prevent_short_messages=True, min_message_length=0 ) resp = app.post( - url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + url_for("admin.update_submission_preferences"), + data=form.data, + follow_redirects=True, ) # Still 0 assert InstanceConfig.get_current().initial_message_min_len == 0 @@ -1909,7 +2183,9 @@ def test_message_filtering(config, journalist_app, test_admin): prevent_short_messages=True, min_message_length=10 ) app.post( - url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + url_for("admin.update_submission_preferences"), + data=form.data, + follow_redirects=True, ) assert InstanceConfig.get_current().initial_message_min_len == 10 @@ -1925,7 +2201,9 @@ def test_message_filtering(config, journalist_app, test_admin): assert InstanceConfig.get_current().reject_message_with_codename is False form = journalist_app_module.forms.SubmissionPreferencesForm(reject_codename_messages=True) app.post( - url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + url_for("admin.update_submission_preferences"), + data=form.data, + follow_redirects=True, ) assert InstanceConfig.get_current().reject_message_with_codename is True @@ -1938,7 +2216,10 @@ class dummy_current: with journalist_app.test_client() as app: iMock.return_value = dummy_current() _login_user( - app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) assert g.organization_name == "SecureDrop" @@ -1948,12 +2229,19 @@ class dummy_current: def test_orgname_valid_succeeds(config, journalist_app, test_admin, locale): test_name = "Walden Inquirer" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.OrgNameForm(organization_name=test_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True + url_for("admin.update_org_name", l=locale), + data=form.data, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = ["Preferences saved."] @@ -1966,12 +2254,19 @@ def test_orgname_valid_succeeds(config, journalist_app, test_admin, locale): @pytest.mark.parametrize("locale", get_test_locales()) def test_orgname_null_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.OrgNameForm(organization_name=None) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True + url_for("admin.update_org_name", l=locale), + data=form.data, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = ["This field is required."] @@ -1985,11 +2280,18 @@ def test_orgname_null_fails(config, journalist_app, test_admin, locale): def test_orgname_oversized_fails(config, journalist_app, test_admin, locale): test_name = "1234567812345678123456781234567812345678123456781234567812345678a" with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.OrgNameForm(organization_name=test_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" resp = app.post( - url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True + url_for("admin.update_org_name", l=locale), + data=form.data, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = ["Cannot be longer than {num} character."] @@ -2031,13 +2333,20 @@ def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admi with journalist_app.test_client() as app: _login_user( - app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) # Create 1px * 1px 'white' PNG file from its base64 string form = journalist_app_module.forms.LogoForm(logo=(BytesIO(logo_bytes), "test.png")) + # Create 1px * 1px 'white' PNG file from its base64 string + form = journalist_app_module.forms.LogoForm(logo=(BytesIO(logo_bytes), "test.png")) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("admin.manage_config", l=locale), data=form.data, follow_redirects=True + url_for("admin.manage_config", l=locale), + data=form.data, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = ["Image updated."] @@ -2060,12 +2369,19 @@ def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admi @pytest.mark.parametrize("locale", get_test_locales()) def test_logo_upload_with_invalid_filetype_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.LogoForm(logo=(BytesIO(b"filedata"), "bad.exe")) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("admin.manage_config", l=locale), data=form.data, follow_redirects=True + url_for("admin.manage_config", l=locale), + data=form.data, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) @@ -2085,7 +2401,10 @@ def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): try: with journalist_app.test_client() as app: _login_user( - app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], ) # Create 1px * 1px 'white' PNG file from its base64 string form = journalist_app_module.forms.LogoForm( @@ -2121,7 +2440,12 @@ def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): def test_creation_of_ossec_test_log_event(journalist_app, test_admin, mocker): mocked_error_logger = mocker.patch("journalist.app.logger.error") with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) app.post(url_for("admin.ossec_test")) mocked_error_logger.assert_called_once_with("This is a test OSSEC alert") @@ -2131,13 +2455,20 @@ def test_creation_of_ossec_test_log_event(journalist_app, test_admin, mocker): @pytest.mark.parametrize("locale", get_test_locales()) def test_logo_upload_with_empty_input_field_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + _login_user( + app, + test_admin["username"], + test_admin["password"], + test_admin["otp_secret"], + ) form = journalist_app_module.forms.LogoForm(logo=(BytesIO(b""), "")) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("admin.manage_config", l=locale), data=form.data, follow_redirects=True + url_for("admin.manage_config", l=locale), + data=form.data, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) @@ -2155,7 +2486,10 @@ def test_admin_page_restriction_http_gets(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) for admin_url in admin_urls: resp = app.get(admin_url) @@ -2175,7 +2509,10 @@ def test_admin_page_restriction_http_posts(journalist_app, test_journo): ] with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) for admin_url in admin_urls: resp = app.post(admin_url) @@ -2220,7 +2557,10 @@ def test_user_authorization_for_posts(journalist_app): def test_incorrect_current_password_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: resp = app.post( @@ -2317,7 +2657,10 @@ def test_too_long_user_password_change(config, journalist_app, test_journo, loca with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: @@ -2342,7 +2685,10 @@ def test_too_long_user_password_change(config, journalist_app, test_journo, loca def test_valid_user_password_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) resp = app.post( @@ -2368,7 +2714,10 @@ def test_valid_user_password_change(config, journalist_app, test_journo, locale) def test_valid_user_first_last_name_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: @@ -2392,7 +2741,10 @@ def test_valid_user_invalid_first_last_name_change(journalist_app, test_journo, with journalist_app.test_client() as app: overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: @@ -2414,7 +2766,10 @@ def test_regenerate_totp(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: @@ -2435,12 +2790,16 @@ def test_edit_hotp(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=valid_secret) + url_for("account.reset_two_factor_hotp"), + data=dict(otp_secret=valid_secret), ) new_secret = Journalist.query.get(test_journo["id"]).otp_secret @@ -2684,7 +3043,9 @@ def test_login_with_invalid_password_doesnt_call_argon2(mocker, test_journo): def test_valid_login_calls_argon2(mocker, test_journo): mock_argon2 = mocker.patch("models.argon2.verify") Journalist.login( - test_journo["username"], test_journo["password"], TOTP(test_journo["otp_secret"]).now() + test_journo["username"], + test_journo["password"], + TOTP(test_journo["otp_secret"]).now(), ) assert mock_argon2.called @@ -2709,7 +3070,10 @@ def test_render_locales(config, journalist_app, test_journo, test_source): with app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) resp = app.get(url + "?l=fr_FR") @@ -2936,7 +3300,12 @@ def selected_missing_files(journalist_app, test_source, app_storage): def test_download_selected_submissions_missing_files( - journalist_app, test_journo, test_source, mocker, selected_missing_files, app_storage + journalist_app, + test_journo, + test_source, + mocker, + selected_missing_files, + app_storage, ): """Tests download of selected submissions with missing files in storage.""" mocked_error_logger = mocker.patch("journalist.app.logger.error") @@ -2969,7 +3338,12 @@ def test_download_selected_submissions_missing_files( def test_download_single_submission_missing_file( - journalist_app, test_journo, test_source, mocker, selected_missing_files, app_storage + journalist_app, + test_journo, + test_source, + mocker, + selected_missing_files, + app_storage, ): """Tests download of single submissions with missing files in storage.""" mocked_error_logger = mocker.patch("journalist.app.logger.error") @@ -3152,7 +3526,10 @@ def test_download_all_selected_sources(journalist_app, test_journo, app_storage) def test_single_source_is_successfully_starred(journalist_app, test_journo, test_source): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) with InstrumentedApp(journalist_app) as ins: resp = app.post(url_for("col.add_star", filesystem_id=test_source["filesystem_id"])) @@ -3166,7 +3543,10 @@ def test_single_source_is_successfully_starred(journalist_app, test_journo, test def test_single_source_is_successfully_unstarred(journalist_app, test_journo, test_source): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) # First star the source app.post(url_for("col.add_star", filesystem_id=test_source["filesystem_id"])) @@ -3184,8 +3564,8 @@ def test_single_source_is_successfully_unstarred(journalist_app, test_journo, te @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_journalist_session_expiration(config, journalist_app, test_journo, locale): - # set the expiration to ensure we trigger an expiration - config.SESSION_EXPIRATION_MINUTES = -1 + # set the expiration to be very short + journalist_app.session_interface.lifetime = 1 with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: login_data = { @@ -3197,17 +3577,20 @@ def test_journalist_session_expiration(config, journalist_app, test_journo, loca ins.assert_redirects(resp, url_for("main.index")) assert "uid" in session - resp = app.get(url_for("account.edit", l=locale), follow_redirects=True) + # Wait 2s for the redis key to expire + time.sleep(2) + resp = app.get(url_for("account.edit"), follow_redirects=True) # because the session is being cleared when it expires, the # response should always be in English. assert page_language(resp.data) == "en-US" - assert "You have been logged out due to inactivity." in resp.data.decode("utf-8") + assert "Login to access the journalist interface" in resp.data.decode("utf-8") # check that the session was cleared (apart from 'expires' # which is always present and 'csrf_token' which leaks no info) session.pop("expires", None) session.pop("csrf_token", None) session.pop("locale", None) + session.pop("renew_count", None) assert not session, session @@ -3240,10 +3623,16 @@ def test_col_process_aborts_with_bad_action(journalist_app, test_journo): """If the action is not a valid choice, a 500 should occur""" with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) - form_data = {"cols_selected": "does not matter", "action": "this action does not exist"} + form_data = { + "cols_selected": "does not matter", + "action": "this action does not exist", + } resp = app.post(url_for("col.process"), data=form_data) assert resp.status_code == 500 @@ -3262,7 +3651,10 @@ def test_col_process_successfully_deletes_multiple_sources( with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) form_data = { @@ -3290,7 +3682,10 @@ def test_col_process_successfully_stars_sources( with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) form_data = {"cols_selected": [test_source["filesystem_id"]], "action": "star"} @@ -3309,7 +3704,10 @@ def test_col_process_successfully_unstars_sources( with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) # First star the source @@ -3317,7 +3715,10 @@ def test_col_process_successfully_unstars_sources( app.post(url_for("col.process"), data=form_data, follow_redirects=True) # Now unstar the source - form_data = {"cols_selected": [test_source["filesystem_id"]], "action": "un-star"} + form_data = { + "cols_selected": [test_source["filesystem_id"]], + "action": "un-star", + } resp = app.post(url_for("col.process"), data=form_data, follow_redirects=True) assert resp.status_code == 200 @@ -3336,7 +3737,10 @@ def test_source_with_null_last_updated(journalist_app, test_journo, test_files): with journalist_app.test_client() as app: _login_user( - app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + app, + test_journo["username"], + test_journo["password"], + test_journo["otp_secret"], ) resp = app.get(url_for("main.index")) assert resp.status_code == 200 diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -7,8 +7,7 @@ from db import db from encryption import EncryptionManager from flask import url_for -from itsdangerous import TimedJSONWebSignatureSerializer -from models import Journalist, Reply, RevokedToken, Source, SourceStar, Submission +from models import Journalist, Reply, Source, SourceStar, Submission from pyotp import TOTP from .utils.api_helper import get_api_headers @@ -57,18 +56,19 @@ def test_valid_user_can_get_an_api_token(journalist_app, test_journo): ) assert response.json["journalist_uuid"] == test_journo["uuid"] - assert ( - isinstance( - Journalist.validate_api_token_and_get_user(response.json["token"]), Journalist - ) - is True - ) assert response.status_code == 200 assert response.json["journalist_first_name"] == test_journo["first_name"] assert response.json["journalist_last_name"] == test_journo["last_name"] assert_valid_timestamp(response.json["expiration"]) + response = app.get( + url_for("api.get_current_user"), + headers=get_api_headers(response.json["token"]), + ) + assert response.status_code == 200 + assert response.json["uuid"] == test_journo["uuid"] + def test_user_cannot_get_an_api_token_with_wrong_password(journalist_app, test_journo): with journalist_app.test_client() as app: @@ -140,7 +140,10 @@ def test_user_cannot_get_an_api_token_with_no_otp_field(journalist_app, test_jou response = app.post( url_for("api.get_token"), data=json.dumps( - {"username": test_journo["username"], "passphrase": test_journo["password"]} + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + } ), headers=get_api_headers(), ) @@ -153,7 +156,8 @@ def test_user_cannot_get_an_api_token_with_no_otp_field(journalist_app, test_jou def test_authorized_user_gets_all_sources(journalist_app, test_submissions, journalist_api_token): with journalist_app.test_client() as app: response = app.get( - url_for("api.get_all_sources"), headers=get_api_headers(journalist_api_token) + url_for("api.get_all_sources"), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -186,7 +190,11 @@ def test_user_without_token_cannot_get_protected_endpoints(journalist_app, test_ ), url_for("api.get_all_submissions"), url_for("api.get_all_replies"), - url_for("api.single_reply", source_uuid=uuid, reply_uuid=test_files["replies"][0].uuid), + url_for( + "api.single_reply", + source_uuid=uuid, + reply_uuid=test_files["replies"][0].uuid, + ), url_for("api.all_source_replies", source_uuid=uuid), url_for("api.get_current_user"), url_for("api.get_all_users"), @@ -220,19 +228,6 @@ def test_user_without_token_cannot_del_protected_endpoints(journalist_app, test_ assert response.status_code == 403 -def test_attacker_cannot_create_valid_token_with_none_alg(journalist_app, test_source, test_journo): - with journalist_app.test_client() as app: - uuid = test_source["source"].uuid - s = TimedJSONWebSignatureSerializer("not the secret key", algorithm_name="none") - attacker_token = s.dumps({"id": test_journo["id"]}).decode("ascii") - - response = app.delete( - url_for("api.single_source", source_uuid=uuid), headers=get_api_headers(attacker_token) - ) - - assert response.status_code == 403 - - def test_attacker_cannot_use_token_after_admin_deletes( journalist_app, test_source, journalist_api_token ): @@ -243,7 +238,12 @@ def test_attacker_cannot_use_token_after_admin_deletes( # In a scenario where an attacker compromises a journalist workstation # the admin should be able to delete the user and their token should # no longer be valid. - attacker = Journalist.validate_api_token_and_get_user(journalist_api_token) + attacker = app.get( + url_for("api.get_current_user"), + headers=get_api_headers(journalist_api_token), + ).json + + attacker = Journalist.query.filter_by(uuid=attacker["uuid"]).first() db.session.delete(attacker) db.session.commit() @@ -269,7 +269,9 @@ def test_user_without_token_cannot_post_protected_endpoints(journalist_app, test with journalist_app.test_client() as app: for protected_route in protected_routes: response = app.post( - protected_route, headers=get_api_headers(""), data=json.dumps({"some": "stuff"}) + protected_route, + headers=get_api_headers(""), + data=json.dumps({"some": "stuff"}), ) assert response.status_code == 403 @@ -333,7 +335,8 @@ def test_authorized_user_can_star_a_source(journalist_app, test_source, journali uuid = test_source["source"].uuid source_id = test_source["source"].id response = app.post( - url_for("api.add_star", source_uuid=uuid), headers=get_api_headers(journalist_api_token) + url_for("api.add_star", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 201 @@ -354,7 +357,8 @@ def test_authorized_user_can_unstar_a_source(journalist_app, test_source, journa uuid = test_source["source"].uuid source_id = test_source["source"].id response = app.post( - url_for("api.add_star", source_uuid=uuid), headers=get_api_headers(journalist_api_token) + url_for("api.add_star", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 201 @@ -379,7 +383,8 @@ def test_disallowed_methods_produces_405(journalist_app, test_source, journalist with journalist_app.test_client() as app: uuid = test_source["source"].uuid response = app.delete( - url_for("api.add_star", source_uuid=uuid), headers=get_api_headers(journalist_api_token) + url_for("api.add_star", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 405 @@ -391,7 +396,8 @@ def test_authorized_user_can_get_all_submissions( ): with journalist_app.test_client() as app: response = app.get( - url_for("api.get_all_submissions"), headers=get_api_headers(journalist_api_token) + url_for("api.get_all_submissions"), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -411,7 +417,8 @@ def test_authorized_user_get_all_submissions_with_disconnected_submissions( "DELETE FROM sources WHERE id = :id", {"id": test_submissions["source"].id} ) response = app.get( - url_for("api.get_all_submissions"), headers=get_api_headers(journalist_api_token) + url_for("api.get_all_submissions"), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -445,7 +452,11 @@ def test_authorized_user_can_get_single_submission( submission_uuid = test_submissions["source"].submissions[0].uuid uuid = test_submissions["source"].uuid response = app.get( - url_for("api.single_submission", source_uuid=uuid, submission_uuid=submission_uuid), + url_for( + "api.single_submission", + source_uuid=uuid, + submission_uuid=submission_uuid, + ), headers=get_api_headers(journalist_api_token), ) @@ -463,7 +474,8 @@ def test_authorized_user_can_get_all_replies_with_disconnected_replies( with journalist_app.test_client() as app: db.session.execute("DELETE FROM sources WHERE id = :id", {"id": test_files["source"].id}) response = app.get( - url_for("api.get_all_replies"), headers=get_api_headers(journalist_api_token) + url_for("api.get_all_replies"), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -472,7 +484,8 @@ def test_authorized_user_can_get_all_replies_with_disconnected_replies( def test_authorized_user_can_get_all_replies(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app: response = app.get( - url_for("api.get_all_replies"), headers=get_api_headers(journalist_api_token) + url_for("api.get_all_replies"), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -552,7 +565,11 @@ def test_authorized_user_can_delete_single_submission( submission_uuid = test_submissions["source"].submissions[0].uuid uuid = test_submissions["source"].uuid response = app.delete( - url_for("api.single_submission", source_uuid=uuid, submission_uuid=submission_uuid), + url_for( + "api.single_submission", + source_uuid=uuid, + submission_uuid=submission_uuid, + ), headers=get_api_headers(journalist_api_token), ) @@ -681,7 +698,8 @@ def test_authorized_user_can_get_current_user_endpoint( ): with journalist_app.test_client() as app: response = app.get( - url_for("api.get_current_user"), headers=get_api_headers(journalist_api_token) + url_for("api.get_current_user"), + headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -1064,7 +1082,11 @@ def test_reply_download_generates_checksum( with journalist_app.test_client() as app: response = app.get( - url_for("api.download_reply", source_uuid=test_source["uuid"], reply_uuid=reply.uuid), + url_for( + "api.download_reply", + source_uuid=test_source["uuid"], + reply_uuid=reply.uuid, + ), headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -1077,7 +1099,11 @@ def test_reply_download_generates_checksum( mock_add_checksum = mocker.patch("journalist_app.utils.add_checksum_for_file") with journalist_app.test_client() as app: response = app.get( - url_for("api.download_reply", source_uuid=test_source["uuid"], reply_uuid=reply.uuid), + url_for( + "api.download_reply", + source_uuid=test_source["uuid"], + reply_uuid=reply.uuid, + ), headers=get_api_headers(journalist_api_token), ) assert response.status_code == 200 @@ -1089,24 +1115,6 @@ def test_reply_download_generates_checksum( assert not mock_add_checksum.called -def test_revoke_token(journalist_app, test_journo, journalist_api_token): - with journalist_app.test_client() as app: - # without token 403's - resp = app.post(url_for("api.logout")) - assert resp.status_code == 403 - - resp = app.post(url_for("api.logout"), headers=get_api_headers(journalist_api_token)) - assert resp.status_code == 200 - - revoked_token = RevokedToken.query.filter_by(token=journalist_api_token).one() - assert revoked_token.journalist_id == test_journo["id"] - - resp = app.get( - url_for("api.get_all_sources"), headers=get_api_headers(journalist_api_token) - ) - assert resp.status_code == 403 - - def test_seen(journalist_app, journalist_api_token, test_files, test_journo, test_submissions): """ Happy path for seen: marking things seen works. diff --git a/securedrop/tests/test_journalist_session.py b/securedrop/tests/test_journalist_session.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_journalist_session.py @@ -0,0 +1,472 @@ +# -*- coding: utf-8 -*- +import json +import re +from datetime import datetime, timedelta, timezone +from urllib.parse import urlparse + +from flask import Response, url_for +from flask.sessions import session_json_serializer +from itsdangerous import URLSafeTimedSerializer +from pyotp import TOTP +from redis import Redis + +from .utils.api_helper import get_api_headers + +redis = Redis() + +NEW_PASSWORD = "another correct horse battery staple generic passphrase" + + +# Helper function to check if session cookie are properly signed +# Returns just the session id without signature +def _check_sig(session_cookie, journalist_app, api=False): + if api: + salt = "api_" + journalist_app.config["SESSION_SIGNER_SALT"] + else: + salt = journalist_app.config["SESSION_SIGNER_SALT"] + + signer = URLSafeTimedSerializer(journalist_app.secret_key, salt) + return signer.loads(session_cookie) + + +# Helper function to get a session payload from redis +# Returns the unserialized session payload +def _get_session(sid, journalist_app, api=False): + if api: + key = "api_" + journalist_app.config["SESSION_KEY_PREFIX"] + sid + else: + key = journalist_app.config["SESSION_KEY_PREFIX"] + sid + + return session_json_serializer.loads(redis.get(key)) + + +# Helper function to login and return the response +# Returns the raw response object +def _login_user(app, journo): + resp = app.post( + url_for("main.login"), + data={ + "username": journo["username"], + "password": journo["password"], + "token": TOTP(journo["otp_secret"]).now(), + }, + follow_redirects=False, + ) + + assert resp.status_code == 302 + assert urlparse(resp.headers["Location"]).path == url_for("main.index") + + return resp + + +# Helper function to extract a the session cookie from the cookiejar when testing as client +# Returns the session cookie value +def _session_from_cookiejar(cookie_jar, journalist_app): + return next( + ( + cookie + for cookie in cookie_jar + if cookie.name == journalist_app.config["SESSION_COOKIE_NAME"] + ), + None, + ) + + +# Test a standard login sequence +def test_session_login(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a correct login request + resp = _login_user(app, test_journo) + # Then a set-cookie header and a cookie: vary header are returned + assert "Set-Cookie" in list(resp.headers.keys()) + assert "Cookie" in resp.headers["Vary"] + + # When checking the local session cookie jar + session_cookie = _session_from_cookiejar(app.cookie_jar, journalist_app) + # Then there is a session cookie in it + assert session_cookie is not None + + # Then such cookie is properly signed + sid = _check_sig(session_cookie.value, journalist_app) + # Then such session cookie has a corresponding payload in redis + redis_session = _get_session(sid, journalist_app) + ttl = redis.ttl(journalist_app.config["SESSION_KEY_PREFIX"] + sid) + + # Then the TTL of such key in redis conforms to the lifetime configuration + assert ( + (journalist_app.config["SESSION_LIFETIME"] - 10) + < ttl + <= journalist_app.config["SESSION_LIFETIME"] + ) + + # Then the user id of the user who logged in is the same as the user id in session + assert redis_session["uid"] == test_journo["id"] + + # Finally load the main page + resp = app.get(url_for("main.index")) + # And expect a successfull status code + assert resp.status_code == 200 + + +# Test a standard session renewal sequence +def test_session_renew(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a correct login request + resp = _login_user(app, test_journo) + # Then check session existance, signature, and redis payload + session_cookie = _session_from_cookiejar(app.cookie_jar, journalist_app) + assert session_cookie is not None + + sid = _check_sig(session_cookie.value, journalist_app) + redis_session = _get_session(sid, journalist_app) + # The `renew_count` must exists in the session payload and must be equal to the app config + assert redis_session["renew_count"] == journalist_app.config["SESSION_RENEW_COUNT"] + + # When forcing the session TTL in redis to be below the threshold + # Threshold for auto renew is less than 60*30 + redis.setex( + name=journalist_app.config["SESSION_KEY_PREFIX"] + sid, + value=session_json_serializer.dumps(redis_session), + time=15 * 60, + ) + # When doing a generic request to trigger the auto-renew + resp = app.get(url_for("main.index")) + # Then the session must still be valid + assert resp.status_code == 200 + + # Then the corresponding renew_count in redis must have been decreased + redis_session = _get_session(sid, journalist_app) + assert redis_session["renew_count"] == (journalist_app.config["SESSION_RENEW_COUNT"] - 1) + + # Then the ttl must have been updated and the new lifetime must be > of app confing lifetime + # (Bigger because there is also a variable amount of time in the threshold that is kept) + ttl = redis.ttl(journalist_app.config["SESSION_KEY_PREFIX"] + sid) + assert ttl > journalist_app.config["SESSION_LIFETIME"] + + +# Test a standard login then logout sequence +def test_session_logout(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a correct login request + resp = _login_user(app, test_journo) + # Then check session as in the previous tests + session_cookie = _session_from_cookiejar(app.cookie_jar, journalist_app) + assert session_cookie is not None + + sid = _check_sig(session_cookie.value, journalist_app) + assert (redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is not None + + # When sending a logout request from a logged in journalist + resp = app.get(url_for("main.logout"), follow_redirects=False) + # Then it redirects to login + assert resp.status_code == 302 + # Then the session no longer exists in redis + assert (redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is None + + # Then a request to the index redirects back to login + resp = app.get(url_for("main.index"), follow_redirects=False) + assert resp.status_code == 302 + + +# Test the user forced logout when an admin changes the user password +def test_session_admin_change_password_logout(journalist_app, test_journo, test_admin): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a correct login request + resp = _login_user(app, test_journo) + session_cookie = _session_from_cookiejar(app.cookie_jar, journalist_app) + assert session_cookie is not None + # Then save the cookie for later + cookie_val = re.search(r"js=(.*?);", resp.headers["set-cookie"]).group(1) + # Then also save the session id for later + sid = _check_sig(session_cookie.value, journalist_app) + assert (redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is not None + + # Given a another test client and a valid admin user + with journalist_app.test_client() as admin_app: + # When sending a valid login request as the admin user + _login_user(admin_app, test_admin) + # When changing password of the journalist (non-admin) user + resp = admin_app.post( + url_for("admin.new_password", user_id=test_journo["id"]), + data=dict(password=NEW_PASSWORD), + follow_redirects=False, + ) + # Then the password change has been successful + assert resp.status_code == 302 + # Then the journalis (non-admin) user session does no longer exist in redis + assert (redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is None + + with journalist_app.test_client() as app: + # Add our original cookie back in to the session, and try to re-use it + app.set_cookie( + "localhost.localdomain", + "js", + cookie_val, + domain=".localhost.localdomain", + httponly=True, + path="/", + ) + resp = app.get(url_for("main.index"), follow_redirects=False) + # Then trying to reuse the same journalist user cookie fails and redirects + assert resp.status_code == 302 + + +# Test the forced logout when the user changes its password +def test_session_change_password_logout(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a correct login request + resp = _login_user(app, test_journo) + # Then check session as the previous tests + session_cookie = _session_from_cookiejar(app.cookie_jar, journalist_app) + assert session_cookie is not None + + sid = _check_sig(session_cookie.value, journalist_app) + assert (redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is not None + + # When sending a self change password request + resp = app.post( + url_for("account.new_password"), + data=dict( + current_password=test_journo["password"], + token=TOTP(test_journo["otp_secret"]).now(), + password=NEW_PASSWORD, + ), + ) + # Then the session is no longer valid + assert resp.status_code == 302 + # Then the session no longer exists in redis + assert (redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is None + + # Then a request for the index redirects back to login + resp = app.get(url_for("main.index"), follow_redirects=False) + assert resp.status_code == 302 + + +# Test that the session id is regenerated after a valid login +def test_session_login_regenerate_sid(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending an anonymous get request + resp = app.get(url_for("main.login")) + # Then check the response code is correct + assert resp.status_code == 200 + + # Given a valid unauthenticated session id from the previous request + session_cookie_pre_login = _session_from_cookiejar(app.cookie_jar, journalist_app) + assert session_cookie_pre_login is not None + + # When sending a valid login request using the same client (same cookiejar) + resp = _login_user(app, test_journo) + session_cookie_post_login = _session_from_cookiejar(app.cookie_jar, journalist_app) + # Then the two session ids are different as the session id gets regenerated post login + assert session_cookie_post_login != session_cookie_pre_login + + +# Test a standard `get_token` API login +def test_session_api_login(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a `get_token` request to the API with valid creds + resp = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + "one_time_code": TOTP(test_journo["otp_secret"]).now(), + } + ), + headers=get_api_headers(), + ) + + # Then the API token is issued and returned with the correct journalist id + assert resp.json["journalist_uuid"] == test_journo["uuid"] + assert resp.status_code == 200 + + # Then such token is properly signed + sid = _check_sig(resp.json["token"], journalist_app, api=True) + redis_session = _get_session(sid, journalist_app, api=True) + # Then the session id in redis match that of the credentials + assert redis_session["uid"] == test_journo["id"] + + # Then the ttl of the session in redis is lower than the lifetime configured in the app + ttl = redis.ttl("api_" + journalist_app.config["SESSION_KEY_PREFIX"] + sid) + assert ( + (journalist_app.config["SESSION_LIFETIME"] - 10) + < ttl + <= journalist_app.config["SESSION_LIFETIME"] + ) + + # Then the expiration date returned in `get_token` response also conforms to the same rules + assert ( + datetime.now(timezone.utc) + < datetime.strptime(resp.json["expiration"], "%Y-%m-%dT%H:%M:%S.%f%z") + < ( + datetime.now(timezone.utc) + + timedelta(seconds=journalist_app.config["SESSION_LIFETIME"]) + ) + ) + + # When querying the endpoint that return the corrent user with the token + response = app.get( + url_for("api.get_current_user"), headers=get_api_headers(resp.json["token"]) + ) + # Then the reuqest is successful and the correct journalist id is returned + assert response.status_code == 200 + assert response.json["uuid"] == test_journo["uuid"] + + +# test a standard login then logout from API +def test_session_api_logout(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a valid login request and asking an API token + resp = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + "one_time_code": TOTP(test_journo["otp_secret"]).now(), + } + ), + headers=get_api_headers(), + ) + + # Then the token is issued successfully with the correct attributed + assert resp.json["journalist_uuid"] == test_journo["uuid"] + assert resp.status_code == 200 + token = resp.json["token"] + sid = _check_sig(token, journalist_app, api=True) + + # When querying the endpoint for the current user information + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(token)) + # Then the request is successful and the returned id matches the creds journalist id + assert resp.status_code == 200 + assert resp.json["uuid"] == test_journo["uuid"] + + # When sending a logout request using the API token + resp = app.post(url_for("api.logout"), headers=get_api_headers(token)) + # Then it is successful + assert resp.status_code == 200 + # Then the token and the corresponding payload no longer exist in redis + assert (redis.get("api_" + journalist_app.config["SESSION_KEY_PREFIX"] + sid)) is None + + # When sending an authenticated request with the deleted token + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(token)) + # Then the request is unsuccessful + assert resp.status_code == 403 + + +# Test a few cases of valid session token with bad signatures +def test_session_bad_signature(journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_client() as app: + # When sending a valid login request and asking an API token + resp = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + "one_time_code": TOTP(test_journo["otp_secret"]).now(), + } + ), + headers=get_api_headers(), + ) + + # Then the request is successful and the uid matched the creds one + assert resp.json["journalist_uuid"] == test_journo["uuid"] + assert resp.status_code == 200 + + # Given the valid token in the response + token = resp.json["token"] + # When checking the signature and sreipping it + sid = _check_sig(token, journalist_app, api=True) + + # When requesting an authenticated endpoint with a valid unsigned token + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(sid)) + # Then the request is refused + assert resp.status_code == 403 + + # When requesting an authenticated endpoint with a valid unsigned token with a trailing dot + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(sid + ".")) + # Then the request is refused + assert resp.status_code == 403 + + # Given the correct app secret key and a wrong salt + signer = URLSafeTimedSerializer(journalist_app.secret_key, "wrong_salt") + # Given a valid token signed with the correct secret key and the wrong salt + token_wrong_salt = signer.dumps(sid) + + # When requesting an authenticated endpoint with a valid token signed with the wrong salt + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(token_wrong_salt)) + # Then the request is refused + assert resp.status_code == 403 + + # Given the correct app secret and the Journalist Interface salt + signer = URLSafeTimedSerializer( + journalist_app.secret_key, journalist_app.config["SESSION_SIGNER_SALT"] + ) + # Given a valid token signed with the corrects secret key and tje Journalist Interface salt + token_not_api_salt = signer.dumps(sid) + + # When requesting an authenticated endpoint with such token + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(token_not_api_salt)) + # Then the request is refused since the JI salt is not valid for the API + assert resp.status_code == 403 + + # When sending again an authenticated request with the original, valid, signed token + resp = app.get(url_for("api.get_current_user"), headers=get_api_headers(token)) + # Then the request is successful + assert resp.status_code == 200 + assert resp.json["uuid"] == test_journo["uuid"] + + +# Context: there are many cases in which as users may logout or be forcibly logged out. +# For the latter case, a user session is destroyed by an admin when a password change is +# enforced or when the user is deleted. When that happens, the session gets deleted from redis. +# What could happen is that if a user session is deleted between open_session() and save_session(), +# then the session might be restored and the admin deletion might fail. +# To avoid this, save_session() uses a setxx call, which writes in redis only if the key exists. +# This does not apply when the session is new or is being regenerated. +# Test that a deleted session cannot be rewritten by a race condition +def test_session_race_condition(mocker, journalist_app, test_journo): + # Given a test client and a valid journalist user + with journalist_app.test_request_context() as app: + # When manually creating a session in the context + session = journalist_app.session_interface.open_session(journalist_app, app.request) + assert session.sid is not None + # When manually setting the journalist uid in session + session["uid"] = test_journo["id"] + + # When manually builfing a Flask repsonse object + app.response = Response() + # When manually calling save_session() to write the session in redis + journalist_app.session_interface.save_session(journalist_app, session, app.response) + # Then the session gets written in redis + assert redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + session.sid) is not None + + # When manually adding the created session token in the request cookies + app.request.cookies = {journalist_app.config["SESSION_COOKIE_NAME"]: session.token} + # When getting the session object by supplying a request context to open_session() + session2 = journalist_app.session_interface.open_session(journalist_app, app.request) + # Then the properties of the two sessions are the same + # (They are indeed the same session) + assert session2.sid == session.sid + assert session2["uid"] == test_journo["id"] + # When setting the modified properties to issue a write in redis + # (To force entering the redis set xx case) + session.modified = True + session.new = False + session.to_regenerate = False + # When deleting the original session token and object from redis + redis.delete(journalist_app.config["SESSION_KEY_PREFIX"] + session.sid) + # Then the session_save() fails since the original object no longer exists + journalist_app.session_interface.save_session(journalist_app, session, app.response) + assert redis.get(journalist_app.config["SESSION_KEY_PREFIX"] + session.sid) is None diff --git a/securedrop/tests/test_journalist_utils.py b/securedrop/tests/test_journalist_utils.py deleted file mode 100644 --- a/securedrop/tests/test_journalist_utils.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -import random - -import pytest -from flask import url_for -from journalist_app.utils import cleanup_expired_revoked_tokens -from models import RevokedToken -from sqlalchemy.orm.exc import NoResultFound - -from .utils.api_helper import get_api_headers - -random.seed("◔ ⌣ ◔") - - -def test_revoke_token_cleanup_does_not_delete_tokens_if_not_expired( - journalist_app, test_journo, journalist_api_token -): - with journalist_app.test_client() as app: - resp = app.post(url_for("api.logout"), headers=get_api_headers(journalist_api_token)) - assert resp.status_code == 200 - - cleanup_expired_revoked_tokens() - - revoked_token = RevokedToken.query.filter_by(token=journalist_api_token).one() - assert revoked_token.journalist_id == test_journo["id"] - - -def test_revoke_token_cleanup_does_deletes_tokens_that_are_expired( - journalist_app, test_journo, journalist_api_token, mocker -): - with journalist_app.test_client() as app: - resp = app.post(url_for("api.logout"), headers=get_api_headers(journalist_api_token)) - assert resp.status_code == 200 - - # Mock response from expired token method when token is expired - mocker.patch( - "journalist_app.admin.Journalist.validate_token_is_not_expired_or_invalid", - return_value=None, - ) - cleanup_expired_revoked_tokens() - - with pytest.raises(NoResultFound): - RevokedToken.query.filter_by(token=journalist_api_token).one() diff --git a/securedrop/tests/utils/__init__.py b/securedrop/tests/utils/__init__.py --- a/securedrop/tests/utils/__init__.py +++ b/securedrop/tests/utils/__init__.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- -from flask import g from pyotp import TOTP from . import asynchronous # noqa @@ -30,4 +29,4 @@ def login_user(app, test_user): follow_redirects=True, ) assert resp.status_code == 200 - assert hasattr(g, "user") # ensure logged in + assert test_user["username"] in resp.data.decode("utf-8")
Flask cookies leak (server-side) session values The configured secret key, which is needed to use the flask session feature, is not used to encrypt the session values in the cookie, but only to sign them. This means that the cookie can be decoded to show the values in plain text. PoC: ``` >>> cookie_str = "eJw9zMsOQ0AYQOFXaf61BVobSRcuGbVApC6Z2TSYMYohUYo23r3VRZcnOfneUPSUdZlgoL_hkIMORF0qYpkVVYmSW2aTpZrsOtqTpDMvHCTTS8OxSCb6e9BKrsYSRHiGTYLiMZS3sW9Y9-f8V6j5dVLhFInADlesxsfACU9-jYQvkMBRrBHbUILUVbwIL57NFRKezztXthnnjIJeZu2DSdD2e97uX30cJrZ9AOFDPgE" >>> zlib.decompress(base64.urlsafe_b64decode(cookie_str+b"="*(-len(cookie_str) % 4))) ``` ``` {"codename": {"b":"Z2xhZCBhd2Z1bCBkaW50IG5vZWwgcGF0dHkgYmVudCBhd2FyZSAxOTYw"}, "csrf_token":{" b":"NzQ5NjVhYWFmODQyY2U3OGQ4NjFmNmFmYTU5ZDA1OWI1MTYxMDg1ZQ=="}, "flagged":false, "logged_in":true} ``` ``` >>> base64.b64decode('Z2xhZCBhd2Z1bCBkaW50IG5vZWwgcGF0dHkgYmVudCBhd2FyZSAxOTYw') 'glad awful dint noel patty bent aware 1960' ``` There are two ways to mitigate this leak: One is to implement an own session interface that uses encryption for the (un)serialization and pass it to the app via the app.session_interface config. The second method is, to only store a session id in the cookie and create a server-side session store with files or a database. Reported by crew53: SD-01-012 Flask cookies leak (server-side) session values
This is a problem if an attacker steals the session cookie, but that seems unlikely since they're session-based and HTTPOnly. In all of the cases I can think of where an attacker has access to the cookie, they also have access to the page's HTML, which contains the codename in plaintext anyway. Could be wrong though. I agree on the codename in HTML, yet think that cookies should never expose more than is actually needed. The HTML is only shown in the browser, unlikely to be cached anywhere. The cookies reside on the hard-disk and will be transferred via HTTP headers - this significantly extends the window of exposure. Additionally, I don't see any reason for example to transport the CSRF token in the HTTP header. @x00mario thanks for the clarification. In that case, the problem isn't that the cookies leak server-side session values, but rather that we use the persistent codename as a session authorization token instead of an actual session value that expires at the end of the session. > In that case, the problem isn't that the cookies leak server-side session values, but rather that we use the persistent codename as a session authorization token instead of an actual session value that expires at the end of the session. @diracdeltas That's exactly right. Given the current design for encrypting replies, I don't see how we can avoid storing the codename in the session cookie (otherwise, the user will need to re-enter it whenever they get a new reply, which would be confusing). We could potentially avoid this issue by making the cookies expire after a short interval (like banks do). Or we can detect if a user is logged in and has received a new reply, and ask them to log in again. I don't think this significantly improves security, and significantly decreases usability. > Additionally, I don't see any reason for example to transport the CSRF token in the HTTP header. @x00mario The goal of CSRF is for an attacker to leverage an existing user's authenticated status to perform unintended actions on their behalf. The point of the token is that an attacker cannot guess it. It is stored in the cookie because otherwise we would have to store state on the server to keep tracking of sessions and their current CSRF tokens, which is unnecessarily complex. Note that storing CSRF tokens in (signed) cookies this way is quite common, and is safe if the connection is end-to-end encrypted (it is because the source site is required to be a Tor Hidden Service). An XSS attack could also be leveraged to steal the token, but 1. we set HttpOnly on our cookies, so it doesn't matter that it's in the cookie because the attacker can't access it 2. they would just extract it from the DOM anyway > The cookies reside on the hard-disk @x00mario Session cookies are not saved to disk by definition, and that is one of the reasons we use them. See [Firefox's implementation](http://dxr.mozilla.org/mozilla-central/source/netwerk/cookie/nsCookieService.cpp#4260). Of course this is not a guarantee. It is implementation-dependent, and the cookie could be saved to disk by other mechanisms such as OS swap (although the codename could be swapped in other circumstances too, so I'm not sure if we guarantee to avoid that). Given this, however, as well as the difficulty described above in decrypting replies given the current design (which requires the codename to decrypt the private key), I think it's worth it not to change this for now. It could be worth encrypting cookies in the future to reduce potential leakage of the codename on the source's computer, but to do so would not be meaningful without also removing the plaintext codename from the reminder message in the DOM, and I'm afraid that could disproportionately impact usability. Since the security risk here is very low (for the reasons discussed above), I'm bumping this to 0.3. Another option is to use randomly-generated session tokens instead of the codename for authentication in the cookie. We would have to have some server state that maps session tokens to source ID. IMO this is better than encrypting the codename and putting it in cookies because session tokens are ephemeral. Also, there could be some security benefits to having the codename displayed on the page. Ex: an active MITM overwrites the source's cookies [1] with his/her own cookies, so the source is suddenly logged into an account that they don't control. That would be extremely dangerous. [1] Not sure if the Tor Hidden Services implementation prevents cookie-overwriting attacks. > Another option is to use randomly-generated session tokens instead of the codename for authentication in the cookie. We would have to have some server state that maps session tokens to source ID. In terms of avoiding leakage that is the best solution, but we still have to contend with the fact that we need to store the user's "reply key" passphrase somewhere. Currently the plaintext codename is stored in the cookie, and the passphrase is re-derived from that as needed. If we want to stop storing the codename on the cookie, we have two options: 1. Store it server-side. We could use memcached or something similar. I don't like this because it increases the time this token is accessible to an attacker who has access to the server. In a sense, storing it in the session cookie minimizes this because the cookie is only kept in memory for the span of time it takes to process the request. 2. Don't store it anywhere. This would require a UX change, but I think I might prefer it. When a source logs in, we decrypt any replies to them at that point. We use a random session token to identify them, and don't store the reply key passphrase or codename. If the authenticated user requests the page and they have received more replies, they will be prompted to enter their codename again to decrypt them. Option 2 is IMO marginally better than what we do now, but I also think there are more important vectors to consider. > Also, there could be some security benefits to having the codename displayed on the page I'm not sure if I understand your example. An active MITM attacker could change cookies but maintain the displayed codename, so showing the codename would not help a user detect such an attacker. Also, such an active MITM attack would only be possible through a catastrophic vulnerability in Tor (at which point, there are probably easier avenues of attack). > An active MITM attacker could change cookies but maintain the displayed codename, so showing the codename would not help a user detect such an attacker. That's not necessarily true; an active MITM needs both read and write access to the connection in order to modify the DOM, whereas an active MITM only needs write access in order to overwrite cookies (without seeing them) and do a session fixation attack [1]. :( But I agree that this would require an exploit in TBB so it's not worth worrying about for us. [1] Attack scenario would go something like this: 1. Alice goes to https://bank.com. 2. Mallory intercepts an unrelated request from Alice's computer to http://notify.dropbox.com and injects a 302 redirect to http://bank.com. 3. Assuming bank.com hasn't set STS headers, Alice's computer then makes the HTTP request to bank.com, which Mallory intercepts and injects a set-cookie header that sets Alice's bank.com login cookie to a value that Mallory knows. (Unfortunately, set-cookie over HTTP works even if the cookie was flagged secure.) Moving this to 0.4. While I still think the exploitability of this is very low, it would be worthwhile to either encrypt the cookie or use ephemeral session ids as a defense in depth countermeasure. I'm working on EtM scheme for client-side session based on AES-CTR-128 and HMAC-SHA-224, since IMO that's the best option provided by our current crypto toolkit, PyCrypto. I'd love to at some point switch our crypto over to libsodium, but that's another story. _Each boot_ ([currently every 24 hours](https://github.com/freedomofpress/securedrop/pull/805)), a _new_ encryption and authentication key for both the journalist and source app is generated and _stored in memory_. This provides a mechanism to invalidate client-side session, without the need to add additional attack surface to the application server via an in-memory key/val store (we already have Redis server installed because we use Redis workers, but [we plan to deprecate our Redis dependency](https://github.com/freedomofpress/securedrop/issues/1469)). Granted, the client-side session, if it somehow persists after clicking the logout button or quitting TB, is not really invalidated until the server reboots, this is still better than an infinite lifetime. This also has the effect that if a cookie is obtained from a source's machine (e.g., it somehow persisted in memory, or was swapped out to disk by the OS) after the next server reboot, not only is it invalid for login, but it is also impossible to tie the cookie to any encrypted submissions if the app server is later compromised (or unencrypted submissions if the SVS key is somehow also compromised). It is plausibly deniable the source even visited SD. Before getting too excited about any of that though, we should recognize two things: 1. As @diracdeltas points out, in a scenario where the cookie might be obtained from memory or swap, it's also likely the codename itself, which appears in the HTML, may be obtained. To address this issue, I'm actually proposing that after #1448 is merged--which [forces sources to retype their codename to login](https://github.com/freedomofpress/securedrop/pull/1448/files#diff-c61fcfb187dc9b29a103e57cb3f1a8c3R41), with a warning that it's important they remember it, and [without the ability to copy and paste it](https://github.com/freedomofpress/securedrop/pull/1448/files#diff-2c95cf028a2b1a9492121233b607065aR420) to (hopefully) drive in that message--we remove codenames from the HTML besides on the 'generate' view. 2. The other thing to keep in mind about plausible deniability is a favorite quote by Matthew Green: > “Dammit, they used a deniable key exchange protocol” said no Federal prosecutor ever. > --- https://blog.cryptographyengineering.com/2014/07/26/noodling-about-im-protocols/ The implementation will work the standard way: override `flask.app.session_interface` with a custom subclass of `flask.sessions.SessionInterface`. @justintroutman asked: why SHA-224? The answer is that (i) SHA-224 is considered totally safe, and (ii) it gives us more wiggle room than SHA-256 in terms of a potential non-deterministic website fingerprinting defense that might pad client session. 4B room might not turn out to be significant in terms of expanding the number of sites SecureDrop can be morphed* to (and really this is true if you consider Tor cells are padded to 512B), however, we have not yet shown this and my intuition is to go this way because it's costing us nothing in terms of crypto security. This is also why CTR mode was chosen over CBC, which requires padding. \* Read the [ALPaCA paper](https://3tmaadslguc72xc2.onion/) to understand the term _morphing_ here--essentially it's a method of disguising a web page as another web page, or, more accurately speaking, a probabilistically very average appearing (from the view of the passive observer) site. Read this [circuit fingerprinting paper](https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-kwon.pdf) to see why we're so concerned of the potential impact of website fingerprinting attacks on Hidden Services. And, checkout [the work we're doing](https://github.com/freedomofpress/fingerprint-securedrop) to help evaluate and tackle this problem. So it's come to our attention that we need to replace pycrypto, the progress of which is pretty much stalled (e.g., [this year-old vulnerability](https://github.com/dlitz/pycrypto/issues/173) has still not been fixed in a release, even though it's patched in master--note this one does not effect SD). I wrote most of the code that would resolve this issue as I explained in my last comments (you can check it out at https://github.com/freedomofpress/securedrop/blob/safer-sessions/securedrop/session.py), the only major thing I hadn't figured out yet was how best to share counter objects between Flask threads. Anyway, since this issue is not high-priority, I figure I might postpone finishing up that branch until after we've replaced our crypto library. Ideally, we'd use https://github.com/pyca/pynacl, which bundles `libsodium`, as a replacement, which would allow me to avoid resolving the synchronization problem as I would definitely use CHACHA20/Poly1305 instead of AES-CTR. So I'm moving this one to "blocked" in our recently made Kanban-style project board for the 0.4 milestone. Check it out if you haven't: https://github.com/freedomofpress/securedrop/projects/1. Noting that this is still an issue: 1. Grab `ss` cookie 2. `zlib.decompress(base64.urlsafe_b64decode(cookie_str+"="*(-len(cookie_str) % 4)))` -> result contains codename. Likely low priority given that cookies are cleared out after a SecureDrop session (we even strongly recommend "New Identity" after the session), but still worth addressing.
2022-04-18T08:34:20Z
[]
[]
freedomofpress/securedrop
6,406
freedomofpress__securedrop-6406
[ "6366" ]
56d26e1dde2b540e48f2e64023d059a4a3f537e1
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -17,7 +17,7 @@ # import collections -from typing import Dict, List +from typing import List, Set from babel.core import ( Locale, @@ -29,7 +29,7 @@ from flask import Flask, g, request, session from flask_babel import Babel -from sdconfig import SDConfig +from sdconfig import SDConfig, FALLBACK_LOCALE class RequestLocaleInfo: @@ -126,32 +126,46 @@ def configure_babel(config: SDConfig, app: Flask) -> Babel: return babel +def parse_locale_set(codes: List[str]) -> Set[Locale]: + return {Locale.parse(code) for code in codes} + + def validate_locale_configuration(config: SDConfig, babel: Babel) -> None: """ - Ensure that the configured locales are valid and translated. + Check that configured locales are available in the filesystem and therefore usable by + Babel. Warn about configured locales that are not usable, unless we're left with + no usable default or fallback locale, in which case raise an exception. """ - if config.DEFAULT_LOCALE not in config.SUPPORTED_LOCALES: - raise ValueError( - 'The default locale "{}" is not included in the set of supported locales "{}"'.format( - config.DEFAULT_LOCALE, config.SUPPORTED_LOCALES - ) + # These locales are available and loadable from the filesystem. + available = set(babel.list_translations()) + available.add(Locale.parse(FALLBACK_LOCALE)) + + # These locales were configured via "securedrop-admin sdconfig", meaning + # they were present on the Admin Workstation at "securedrop-admin" runtime. + configured = parse_locale_set(config.SUPPORTED_LOCALES) + + # The intersection of these sets is the set of locales usable by Babel. + usable = available & configured + + missing = configured - usable + if missing: + babel.app.logger.error( + f'Configured locales {missing} are not in the set of usable locales {usable}' ) - translations = babel.list_translations() - for locale in config.SUPPORTED_LOCALES: - if locale == "en_US": - continue + defaults = parse_locale_set([config.DEFAULT_LOCALE, FALLBACK_LOCALE]) + if not defaults & usable: + raise ValueError( + f'None of the default locales {defaults} are in the set of usable locales {usable}' + ) - parsed = Locale.parse(locale) - if parsed not in translations: - raise ValueError( - 'Configured locale "{}" is not in the set of translated locales "{}"'.format( - parsed, translations - ) - ) + global USABLE_LOCALES + USABLE_LOCALES = usable +# TODO(#6420): avoid relying on and manipulating on this global state LOCALES = collections.OrderedDict() # type: collections.OrderedDict[str, RequestLocaleInfo] +USABLE_LOCALES = set() # type: Set[Locale] def map_locale_display_names(config: SDConfig) -> None: @@ -163,16 +177,19 @@ def map_locale_display_names(config: SDConfig) -> None: to distinguish them. For languages with more than one translation, like Chinese, we do need the additional detail. """ - language_locale_counts = collections.defaultdict(int) # type: Dict[str, int] - for l in sorted(config.SUPPORTED_LOCALES): - locale = RequestLocaleInfo(l) - language_locale_counts[locale.language] += 1 - + seen: Set[str] = set() locale_map = collections.OrderedDict() for l in sorted(config.SUPPORTED_LOCALES): + if Locale.parse(l) not in USABLE_LOCALES: + continue + locale = RequestLocaleInfo(l) - if language_locale_counts[locale.language] > 1: + if locale.language in seen: + # Disambiguate translations for this language. locale.use_display_name = True + else: + seen.add(locale.language) + locale_map[str(locale)] = locale global LOCALES @@ -193,23 +210,24 @@ def get_locale(config: SDConfig) -> str: - l request argument or session['locale'] - browser suggested locale, from the Accept-Languages header - config.DEFAULT_LOCALE + - config.FALLBACK_LOCALE """ - # Default to any locale set in the session. - locale = session.get("locale") - - # A valid locale specified in request.args takes precedence. + preferences = [] + if session.get("locale"): + preferences.append(session.get("locale")) if request.args.get("l"): - negotiated = negotiate_locale([request.args["l"]], LOCALES.keys()) - if negotiated: - locale = negotiated + preferences.insert(0, request.args.get("l")) + if not preferences: + preferences.extend(get_accepted_languages()) + preferences.append(config.DEFAULT_LOCALE) + preferences.append(FALLBACK_LOCALE) + + negotiated = negotiate_locale(preferences, LOCALES.keys()) - # If the locale is not in the session or request.args, negotiate - # the best supported option from the browser's accepted languages. - if not locale: - locale = negotiate_locale(get_accepted_languages(), LOCALES.keys()) + if not negotiated: + raise ValueError("No usable locale") - # Finally, fall back to the default locale if necessary. - return locale or config.DEFAULT_LOCALE + return negotiated def get_accepted_languages() -> List[str]: diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -8,6 +8,9 @@ from typing import Set +FALLBACK_LOCALE = "en_US" + + class SDConfig: def __init__(self) -> None: try: @@ -120,7 +123,7 @@ def __init__(self) -> None: # Config entries used by i18n.py # Use en_US as the default locale if the key is not defined in _config self.DEFAULT_LOCALE = getattr( - _config, "DEFAULT_LOCALE", "en_US" + _config, "DEFAULT_LOCALE", FALLBACK_LOCALE, ) # type: str supported_locales = set(getattr( _config, "SUPPORTED_LOCALES", [self.DEFAULT_LOCALE]
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -32,13 +32,17 @@ from flask import request from flask import session from flask_babel import gettext -from sdconfig import SDConfig +from i18n import parse_locale_set +from sdconfig import FALLBACK_LOCALE, SDConfig from sh import pybabel from sh import sed from .utils.env import TESTS_DIR from werkzeug.datastructures import Headers +NEVER_LOCALE = 'eo' # Esperanto + + def verify_i18n(app): not_translated = 'code hello i18n' translated_fr = 'code bonjour' @@ -225,32 +229,77 @@ def test_i18n(journalist_app, config): verify_i18n(app) -def test_supported_locales(config): - fake_config = SDConfig() +def test_parse_locale_set(): + assert parse_locale_set([FALLBACK_LOCALE]) == set([Locale.parse(FALLBACK_LOCALE)]) + - # Check that an invalid locale raises an error during app - # configuration. - fake_config.SUPPORTED_LOCALES = ['en_US', 'yy_ZZ'] +def test_no_usable_fallback_locale(journalist_app, config): + """ + The apps fail if neither the default nor the fallback locale is usable. + """ + fake_config = SDConfig() + fake_config.DEFAULT_LOCALE = NEVER_LOCALE + fake_config.SUPPORTED_LOCALES = [NEVER_LOCALE] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) - with pytest.raises(UnknownLocaleError): + i18n.USABLE_LOCALES = set() + + with pytest.raises(ValueError, match='in the set of usable locales'): journalist_app_module.create_app(fake_config) - with pytest.raises(UnknownLocaleError): + with pytest.raises(ValueError, match='in the set of usable locales'): source_app.create_app(fake_config) - # Check that a valid but unsupported locale raises an error during - # app configuration. - fake_config.SUPPORTED_LOCALES = ['en_US', 'wae_CH'] + +def test_unusable_default_but_usable_fallback_locale(config, caplog): + """ + The apps start even if the default locale is unusable, as along as the fallback locale is + usable, but log an error for OSSEC to pick up. + """ + fake_config = SDConfig() + fake_config.DEFAULT_LOCALE = NEVER_LOCALE + fake_config.SUPPORTED_LOCALES = [NEVER_LOCALE, FALLBACK_LOCALE] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) - with pytest.raises(ValueError, match="not in the set of translated locales"): + for app in (journalist_app_module.create_app(fake_config), + source_app.create_app(fake_config)): + with app.app_context(): + assert NEVER_LOCALE in caplog.text + assert 'not in the set of usable locales' in caplog.text + + +def test_invalid_locales(config): + """ + An invalid locale raises an error during app configuration. + """ + fake_config = SDConfig() + fake_config.SUPPORTED_LOCALES = [FALLBACK_LOCALE, 'yy_ZZ'] + fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) + + with pytest.raises(UnknownLocaleError): journalist_app_module.create_app(fake_config) - with pytest.raises(ValueError, match="not in the set of translated locales"): + with pytest.raises(UnknownLocaleError): source_app.create_app(fake_config) +def test_valid_but_unusable_locales(config, caplog): + """ + The apps start with one or more unusable, but still valid, locales, but log an error for + OSSEC to pick up. + """ + fake_config = SDConfig() + + fake_config.SUPPORTED_LOCALES = [FALLBACK_LOCALE, 'wae_CH'] + fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) + + for app in (journalist_app_module.create_app(fake_config), + source_app.create_app(fake_config)): + with app.app_context(): + assert 'wae' in caplog.text + assert 'not in the set of usable locales' in caplog.text + + def test_language_tags(): assert i18n.RequestLocaleInfo(Locale.parse('en')).language_tag == 'en' assert i18n.RequestLocaleInfo(Locale.parse('en-US', sep="-")).language_tag == 'en-US'
Fail gracefully if language no longer supported In the course of development, a language may fall below an acceptable level of translation coverage, in which case we may want to remove it from the list of supported languages. Currently, the app will fail (Source Interface will display an Internal Server Error) if an unsupported language is specified in `SUPPORTED_LOCALES`. This means that removing support for a language could break running instances. Safer behavior could be to ignore such locales (and fall back to English when specified as the default locale). An error could be displayed in `securedrop-admin` to the user next time they step through `sdconfig`, and an OSSEC email generated if an unsupported locale is detected in the configuration.
2022-04-19T00:53:14Z
[]
[]
freedomofpress/securedrop
6,425
freedomofpress__securedrop-6425
[ "6415" ]
b6483a895410181364aa61e47f2a5a5c4070433b
diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -5,7 +5,6 @@ from flask import (Flask, session, redirect, url_for, flash, g, request, render_template, json) -from flask_assets import Environment from flask_babel import gettext from flask_wtf.csrf import CSRFProtect, CSRFError from os import path @@ -64,7 +63,6 @@ def create_app(config: 'SDConfig') -> Flask: app.session_interface = JournalistInterfaceSessionInterface() csrf = CSRFProtect(app) - Environment(app) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -6,7 +6,6 @@ import werkzeug from flask import (Flask, render_template, request, g, session, redirect, url_for) from flask_babel import gettext -from flask_assets import Environment from flask_wtf.csrf import CSRFProtect, CSRFError from os import path from typing import Tuple @@ -70,9 +69,6 @@ def setup_i18n() -> None: def handle_csrf_error(e: CSRFError) -> werkzeug.Response: return clear_session_and_redirect_to_logged_out_page(flask_session=session) - assets = Environment(app) - app.config['assets'] = assets - app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals['version'] = version.__version__
diff --git a/molecule/builder-focal/tests/test_securedrop_deb_package.py b/molecule/builder-focal/tests/test_securedrop_deb_package.py --- a/molecule/builder-focal/tests/test_securedrop_deb_package.py +++ b/molecule/builder-focal/tests/test_securedrop_deb_package.py @@ -266,37 +266,25 @@ def test_securedrop_app_code_contains_mo_files( def test_deb_package_contains_no_generated_assets(securedrop_app_code_contents: str): """ Ensures the `securedrop-app-code` package does not ship minified - static assets, which are built automatically via Flask-Assets, and - may be present in the source directory used to build from. + static assets previously built at runtime via Flask-Assets under /gen, and + which may be present in the source directory used to build from. """ - # static/gen/ directory should exist - assert re.search( - r"^.*\./var/www/securedrop" "/static/gen/$", securedrop_app_code_contents, re.M - ) - # static/gen/ directory should be empty + # static/gen/ directory not should exist assert not re.search( - r"^.*\./var/www/securedrop" "/static/gen/.+$", - securedrop_app_code_contents, - re.M, + r"^.*\./var/www/securedrop" "/static/gen/$", securedrop_app_code_contents, re.M ) - # static/.webassets-cache/ directory should exist - assert re.search( - r"^.*\./var/www/securedrop" "/static/.webassets-cache/$", - securedrop_app_code_contents, - re.M, - ) - # static/.webassets-cache/ directory should be empty + # static/.webassets-cache/ directory should not exist assert not re.search( - r"^.*\./var/www/securedrop" "/static/.webassets-cache/.+$", + r"^.*\./var/www/securedrop" "/static/.webassets-cache/$", securedrop_app_code_contents, re.M, ) - # no SASS files should exist; only the generated CSS files. + # no SASS files should exist. assert not re.search("^.*sass$", securedrop_app_code_contents, re.M) - # no .map files should exist; only the generated CSS files. + # no .map files should exist. assert not re.search("^.*css.map$", securedrop_app_code_contents, re.M)
Remove JS minification from the web applications. ## Description In order to improve performance of the web applications, support for minification for JS and CSS files was added in https://github.com/freedomofpress/securedrop/commit/e74b39075fa4d407bf929ab8bc5ab24abad79f70, using `flask-assets`, `cssmin`, and `jsmin`. Since then the application has started using SASS for CSS minification (see #2808), meaning only JS is being minified. Only 2 files are currently being minified, `static/js/{source,journalist}.js`, with savings of <1k and <2k respectively. To reduce code complexity at the cost of 1-2k in page size, it would make sense to drop JS minification as well. Alternatively, the files could be minified during the build process (tho IMO it's overkill given the minimal gains). One other disadvantage of server-side minification is that the Apache user needs to be able to write the minified files somewhere on the webroot. Removing it would allow for tightening up the relevant apparmor profile, removing the related write perms ## User Research Evidence n/a ## User Stories n/a
Once you factor in gzip, the benefit of minification becomes pretty negligible. For source.js on 2.3.1: ``` $ du -b securedrop/static/js/source*.js* | sort 1167 securedrop/static/js/source.min.js.gz 1578 securedrop/static/js/source.js.gz 3271 securedrop/static/js/source.min.js 4501 securedrop/static/js/source.js ``` So +1 to getting rid of this extra complexity. The jsmin package is also unmaintained (c.f. https://github.com/tikitu/jsmin/issues/33#issuecomment-914040205) and problematic because the version we're on uses a now-removed setuptools option, which I had to workaround in https://github.com/freedomofpress/securedrop/issues/6358#issuecomment-1076844034.
2022-05-03T22:17:36Z
[]
[]
freedomofpress/securedrop
6,469
freedomofpress__securedrop-6469
[ "6440" ]
cb73282f4066588df972586d7533be17f8c96da5
diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '2.4.0~rc1' +__version__ = '2.5.0~rc1' diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="2.4.0~rc1", + version="2.5.0~rc1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-focal/tests/vars.yml b/molecule/builder-focal/tests/vars.yml --- a/molecule/builder-focal/tests/vars.yml +++ b/molecule/builder-focal/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "2.4.0~rc1" +securedrop_version: "2.5.0~rc1" ossec_version: "3.6.0" keyring_version: "0.1.6" config_version: "0.1.4"
Release SecureDrop 2.4.0 This is a tracking issue for the release of SecureDrop 2.4.0 Scheduled as follows: **Feature / string freeze:** 2022-05-05 **Pre-release announcement:** 2022-05-12 **Release date:** ~~2022-05-19~~ 2022-05-24 **Release manager:** @zenmonkeykstop **Deputy release manager:** @eaon **Communications manager:** @legoktm **Deputy CM:** @eloquence **Localization manager:** @cfm **Deputy LM:** @zenmonkeykstop QA team: TBD _SecureDrop maintainers and testers:_ As you QA 2.4.0, please report back your testing results as comments on this ticket. File GitHub issues for any problems found, tag them "QA: Release", and associate them with the [2.4.0 milestone](https://github.com/freedomofpress/securedrop/milestone/78) for tracking (or ask a maintainer to do so). Test debian packages will be posted on https://apt-test.freedom.press signed with [the test key](https://gist.githubusercontent.com/conorsch/ec4008b111bc3142fca522693f3cce7e/raw/2968621e8ad92db4505a31fcc5776422d7d26729/apt-test%2520apt%2520pubkey) # [QA Matrix for 2.4.0](https://docs.google.com/spreadsheets/d/1autPlQ6RTNguCFLBM919Gy81C9WEphdj2DKl08JFHCY/edit#gid=2135593926) # [Test Plan for 2.4.0](https://github.com/freedomofpress/securedrop/wiki/2.4.0-Test-Plan) ## Localization management High-level summary of these steps can be found here: https://docs.securedrop.org/en/stable/development/i18n.html#two-weeks-before-the-release-string-freeze Duplicating that content as checkboxes below, for visibility: - [x] Update translations on latest develop, following [docs for i18n procedures](https://docs.securedrop.org/en/stable/development/i18n.html#update-strings-to-be-translated) - [x] Update strings served on Weblate, [following docs](https://docs.securedrop.org/en/stable/development/i18n.html#merge-develop-to-weblate) - [x] [Update Weblate screenshots](https://docs.securedrop.org/en/stable/development/i18n.html#update-weblate-screenshots) so translators can see new or modified source strings in context. - [x] Update the [i18n timeline](https://forum.securedrop.org/t/about-the-translations-category/16) in the translation section of the forum. - [x] Add a [Weblate announcement](https://weblate.securedrop.org/admin/trans/announcement) with the translation timeline for the release. Important: make sure the Notify users box is checked, so that translators receive an email alert. - [x] Remind all developers about the string freeze in [Gitter](https://gitter.im/freedomofpress/securedrop). - [x] Remind all translators about the string freeze in the Localization Lab channel in the [IFF Mattermost](https://internetfreedomfestival.org/wiki/index.php/IFF_Mattermost). # Release management ## Prepare release candidate (2.4.0~rc1) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.4.0~rc1 release changelog - [x] Branch release/2.4.0 from develop - [x] Prepare 2.4.0~rc1 - [x] Build debs, preserving build log, and put up `2.4.0~rc1` on test apt server - [x] Commit build log. # Release management ## Prepare release candidate (2.4.0~rc2) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.4.0~rc2 release changelog - [x] Branch release/2.4.0 from develop - [x] Prepare 2.4.0~rc2 - [x] Build debs, preserving build log, and put up `2.4.0~rc2` on test apt server - [x] Commit build log. ## Final release - [x] Ensure builder in release branch is updated and/or update builder image - [x] Push signed tag - [x] Pre-Flight: Test updater logic in Tails (apt-qa tracks the `release` branch in the LFS repo) - [x] Build final Debian packages for 2.4.0 (and preserve build log) - [x] Commit package build log to https://github.com/freedomofpress/build-logs - [x] Upload Debian packages to apt-qa server via PR from `release` branch in LFS repo - [x] Pre-Flight: Test that install and upgrade from 2.3.2 to 2.4.0 works w/ prod repo debs (apt-qa.freedom.press polls the `release` branch in the LFS repo for the debs) - [x] Flip apt QA server to prod status (merge to `main` in the LFS repo) - [x] Merge Docs branch changes to ``main`` and verify new docs build in securedrop-docs repo - [x] Prepare release messaging ## Post release - [x] Create GitHub release object - [x] Once release object is created, update version in `securedrop-docs` (version information in Wagtail is updated automatically) - [x] Verify new docs show up on https://docs.securedrop.org - [x] Publish announcements - [ ] Merge changelog back to `develop` - [x] Update roadmap wiki page: https://github.com/freedomofpress/securedrop/wiki/Development-Roadmap
2022-05-25T15:46:03Z
[]
[]
freedomofpress/securedrop
6,480
freedomofpress__securedrop-6480
[ "5551" ]
f43dc02f246a40e750428c37523dc4f8f7a48a1d
diff --git a/admin/bootstrap.py b/admin/bootstrap.py --- a/admin/bootstrap.py +++ b/admin/bootstrap.py @@ -23,9 +23,7 @@ import shutil import subprocess import sys -from typing import Iterator - -from typing import List +from typing import Iterator, List sdlog = logging.getLogger(__name__) @@ -34,13 +32,13 @@ def setup_logger(verbose: bool = False) -> None: - """ Configure logging handler """ + """Configure logging handler""" # Set default level on parent sdlog.setLevel(logging.DEBUG) level = logging.DEBUG if verbose else logging.INFO stdout = logging.StreamHandler(sys.stdout) - stdout.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) + stdout.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) stdout.setLevel(level) sdlog.addHandler(stdout) @@ -53,9 +51,7 @@ def run_command(command: List[str]) -> Iterator[bytes]: Yields a list of the stdout from the `command`, and raises a CalledProcessError if `command` returns non-zero. """ - popen = subprocess.Popen(command, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) + popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if popen.stdout is None: raise EnvironmentError("Could not run command: None stdout") for stdout_line in iter(popen.stdout.readline, b""): @@ -68,17 +64,16 @@ def run_command(command: List[str]) -> Iterator[bytes]: def is_tails() -> bool: try: - id = subprocess.check_output('lsb_release --id --short', - shell=True).decode('utf-8').strip() + id = subprocess.check_output("lsb_release --id --short", shell=True).decode("utf-8").strip() except subprocess.CalledProcessError: return False # dirty hack to unreliably detect Tails 4.0~beta2 - if id == 'Debian': - if os.uname()[1] == 'amnesia': - id = 'Tails' + if id == "Debian": + if os.uname()[1] == "amnesia": + id = "Tails" - return id == 'Tails' + return id == "Tails" def clean_up_old_tails_venv(virtualenv_dir: str = VENV_DIR) -> None: @@ -90,13 +85,12 @@ def clean_up_old_tails_venv(virtualenv_dir: str = VENV_DIR) -> None: """ if is_tails(): try: - dist = subprocess.check_output('lsb_release --codename --short', - shell=True).strip() + dist = subprocess.check_output("lsb_release --codename --short", shell=True).strip() except subprocess.CalledProcessError: return None # Tails 5 is based on bullseye / Python 3.9 - if dist == b'bullseye': + if dist == b"bullseye": python_lib_path = os.path.join(virtualenv_dir, "lib/python3.7") if os.path.exists(python_lib_path): sdlog.info("Tails 4 virtualenv detected. Removing it.") @@ -113,7 +107,7 @@ def checkenv(args: argparse.Namespace) -> None: def maybe_torify() -> List[str]: if is_tails(): - return ['torify'] + return ["torify"] else: return [] @@ -124,11 +118,18 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: a virtualenv, first there are a number of Python prerequisites. """ sdlog.info("Installing SecureDrop Admin dependencies") - sdlog.info(("You'll be prompted for the temporary Tails admin password," - " which was set on Tails login screen")) + sdlog.info( + ( + "You'll be prompted for the temporary Tails admin password," + " which was set on Tails login screen" + ) + ) - apt_command = ['sudo', 'su', '-c', - "apt-get update && \ + apt_command = [ + "sudo", + "su", + "-c", + "apt-get update && \ apt-get -q -o=Dpkg::Use-Pty=0 install -y \ python3-virtualenv \ python3-yaml \ @@ -137,19 +138,20 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: libffi-dev \ libssl-dev \ libpython3-dev", - ] + ] try: # Print command results in real-time, to keep Admin apprised # of progress during long-running command. for output_line in run_command(apt_command): - print(output_line.decode('utf-8').rstrip()) + print(output_line.decode("utf-8").rstrip()) except subprocess.CalledProcessError: # Tails supports apt persistence, which was used by SecureDrop # under Tails 2.x. If updates are being applied, don't try to pile # on with more apt requests. - sdlog.error(("Failed to install apt dependencies. Check network" - " connection and try again.")) + sdlog.error( + ("Failed to install apt dependencies. Check network" " connection and try again.") + ) raise @@ -179,16 +181,15 @@ def envsetup(args: argparse.Namespace, virtualenv_dir: str = VENV_DIR) -> None: # the effort here. sdlog.info("Setting up virtualenv") try: - sdlog.debug(subprocess.check_output( - maybe_torify() + ['virtualenv', - '--python=python3', - virtualenv_dir - ], - stderr=subprocess.STDOUT)) + sdlog.debug( + subprocess.check_output( + maybe_torify() + ["virtualenv", "--python=python3", virtualenv_dir], + stderr=subprocess.STDOUT, + ) + ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) - sdlog.error(("Unable to create virtualenv. Check network settings" - " and try again.")) + sdlog.error(("Unable to create virtualenv. Check network settings" " and try again.")) sdlog.debug("Cleaning up virtualenv") if os.path.exists(virtualenv_dir): shutil.rmtree(virtualenv_dir) @@ -199,26 +200,22 @@ def envsetup(args: argparse.Namespace, virtualenv_dir: str = VENV_DIR) -> None: if args.t: install_pip_dependencies( args, - requirements_file='requirements-testinfra.txt', - desc="dependencies with verification support" + requirements_file="requirements-testinfra.txt", + desc="dependencies with verification support", ) else: install_pip_dependencies(args) - if os.path.exists(os.path.join(DIR, 'setup.py')): + if os.path.exists(os.path.join(DIR, "setup.py")): install_pip_self(args) sdlog.info("Finished installing SecureDrop dependencies") def install_pip_self(args: argparse.Namespace) -> None: - pip_install_cmd = [ - os.path.join(VENV_DIR, 'bin', 'pip3'), - 'install', '-e', DIR - ] + pip_install_cmd = [os.path.join(VENV_DIR, "bin", "pip3"), "install", "-e", DIR] try: - subprocess.check_output(maybe_torify() + pip_install_cmd, - stderr=subprocess.STDOUT) + subprocess.check_output(maybe_torify() + pip_install_cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: sdlog.debug(e.output) sdlog.error("Unable to install self, run with -v for more information") @@ -234,22 +231,27 @@ def install_pip_dependencies( Install Python dependencies via pip into virtualenv. """ pip_install_cmd = [ - os.path.join(VENV_DIR, 'bin', 'pip3'), - 'install', - '--no-deps', - '-r', os.path.join(DIR, requirements_file), - '--require-hashes', - '-U', '--upgrade-strategy', 'only-if-needed', + os.path.join(VENV_DIR, "bin", "pip3"), + "install", + "--no-deps", + "-r", + os.path.join(DIR, requirements_file), + "--require-hashes", + "-U", + "--upgrade-strategy", + "only-if-needed", ] sdlog.info("Checking {} for securedrop-admin".format(desc)) try: - pip_output = subprocess.check_output(maybe_torify() + pip_install_cmd, - stderr=subprocess.STDOUT) + pip_output = subprocess.check_output( + maybe_torify() + pip_install_cmd, stderr=subprocess.STDOUT + ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) - sdlog.error(("Failed to install {}. Check network" - " connection and try again.".format(desc))) + sdlog.error( + ("Failed to install {}. Check network" " connection and try again.".format(desc)) + ) raise sdlog.debug(pip_output) @@ -261,23 +263,21 @@ def install_pip_dependencies( def parse_argv(argv: List[str]) -> argparse.Namespace: parser = argparse.ArgumentParser() - parser.add_argument('-v', action='store_true', default=False, - help="Increase verbosity on output") - parser.add_argument('-t', action='store_true', default=False, - help="Install additional test dependencies") + parser.add_argument( + "-v", action="store_true", default=False, help="Increase verbosity on output" + ) + parser.add_argument( + "-t", action="store_true", default=False, help="Install additional test dependencies" + ) parser.set_defaults(func=envsetup) subparsers = parser.add_subparsers() - envsetup_parser = subparsers.add_parser( - 'envsetup', - help='Set up the admin virtualenv.' - ) + envsetup_parser = subparsers.add_parser("envsetup", help="Set up the admin virtualenv.") envsetup_parser.set_defaults(func=envsetup) checkenv_parser = subparsers.add_parser( - 'checkenv', - help='Check that the admin virtualenv is properly set up.' + "checkenv", help="Check that the admin virtualenv is properly set up." ) checkenv_parser.set_defaults(func=checkenv) diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -24,42 +24,25 @@ """ import argparse +import base64 import functools +import io import ipaddress +import json import logging import os -import io import re import subprocess import sys -import json -import base64 -from typing import Any -from typing import Optional -from typing import TypeVar -from typing import Union +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union, cast import prompt_toolkit -from prompt_toolkit.document import Document -from prompt_toolkit.validation import Validator, ValidationError import yaml -from pkg_resources import parse_version from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import x25519 - -from typing import cast - -from typing import List - -from typing import Set - -from typing import Dict - -from typing import Tuple - -from typing import Callable - -from typing import Type +from pkg_resources import parse_version +from prompt_toolkit.document import Document +from prompt_toolkit.validation import ValidationError, Validator sdlog = logging.getLogger(__name__) @@ -67,12 +50,12 @@ # to provide a transition window during key rotation. On or around v2.0.0, # we can remove the older of the two keys and only trust the newer going forward. RELEASE_KEYS = [ - '22245C81E3BAEB4138B36061310F561200F4AD77', - '2359E6538C0613E652955E6C188EDD3B7B22E6A3', + "22245C81E3BAEB4138B36061310F561200F4AD77", + "2359E6538C0613E652955E6C188EDD3B7B22E6A3", ] -DEFAULT_KEYSERVER = 'hkps://keys.openpgp.org' -SUPPORT_ONION_URL = 'http://sup6h5iyiyenvjkfxbgrjynm5wsgijjoatvnvdgyyi7je3xqm4kh6uqd.onion' -SUPPORT_URL = 'https://support.freedom.press' +DEFAULT_KEYSERVER = "hkps://keys.openpgp.org" +SUPPORT_ONION_URL = "http://sup6h5iyiyenvjkfxbgrjynm5wsgijjoatvnvdgyyi7je3xqm4kh6uqd.onion" +SUPPORT_URL = "https://support.freedom.press" EXIT_SUCCESS = 0 EXIT_SUBPROCESS_ERROR = 1 EXIT_INTERRUPT = 2 @@ -90,11 +73,11 @@ class JournalistAlertEmailException(Exception): # The type of each entry within SiteConfig.desc -_T = TypeVar('_T', bound=Union[int, str, bool]) +_T = TypeVar("_T", bound=Union[int, str, bool]) # The function type used for the @update_check_required decorator; see # https://mypy.readthedocs.io/en/stable/generics.html#declaring-decorators -_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) +_FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) # Configuration description tuples drive the CLI user experience and the # validation logic of the securedrop-admin tool. A tuple is in the following @@ -117,28 +100,24 @@ class JournalistAlertEmailException(Exception): class SiteConfig: - class ValidateNotEmpty(Validator): def validate(self, document: Document) -> bool: - if document.text != '': + if document.text != "": return True - raise ValidationError( - message="Must not be an empty string") + raise ValidationError(message="Must not be an empty string") class ValidateTime(Validator): def validate(self, document: Document) -> bool: if document.text.isdigit() and int(document.text) in range(0, 24): return True - raise ValidationError( - message="Must be an integer between 0 and 23") + raise ValidationError(message="Must be an integer between 0 and 23") class ValidateUser(Validator): def validate(self, document: Document) -> bool: text = document.text - if text != '' and text != 'root' and text != 'amnesia': + if text != "" and text != "root" and text != "amnesia": return True - raise ValidationError( - message="Must not be root, amnesia or an empty string") + raise ValidationError(message="Must not be root, amnesia or an empty string") class ValidateIP(Validator): def validate(self, document: Document) -> bool: @@ -177,65 +156,57 @@ def __init__(self, basedir: str) -> None: super(SiteConfig.ValidatePath, self).__init__() def validate(self, document: Document) -> bool: - if document.text == '': - raise ValidationError( - message='an existing file name is required') + if document.text == "": + raise ValidationError(message="an existing file name is required") path = os.path.join(self.basedir, document.text) if os.path.exists(path): return True - raise ValidationError( - message=path + ' file does not exist') + raise ValidationError(message=path + " file does not exist") class ValidateOptionalPath(ValidatePath): def validate(self, document: Document) -> bool: - if document.text == '': + if document.text == "": return True - return super(SiteConfig.ValidateOptionalPath, self).validate( - document) + return super(SiteConfig.ValidateOptionalPath, self).validate(document) class ValidateYesNo(Validator): def validate(self, document: Document) -> bool: text = document.text.lower() - if text == 'yes' or text == 'no': + if text == "yes" or text == "no": return True raise ValidationError(message="Must be either yes or no") class ValidateFingerprint(Validator): def validate(self, document: Document) -> bool: - text = document.text.replace(' ', '') - if text == '65A1B5FF195B56353CC63DFFCC40EF1228271441': - raise ValidationError( - message='This is the TEST journalist fingerprint') - if text == '600BC6D5142C68F35DDBCEA87B597104EDDDC102': - raise ValidationError( - message='This is the TEST admin fingerprint') - if not re.match('[a-fA-F0-9]{40}$', text): - raise ValidationError( - message='fingerprints must be 40 hexadecimal characters') + text = document.text.replace(" ", "") + if text == "65A1B5FF195B56353CC63DFFCC40EF1228271441": + raise ValidationError(message="This is the TEST journalist fingerprint") + if text == "600BC6D5142C68F35DDBCEA87B597104EDDDC102": + raise ValidationError(message="This is the TEST admin fingerprint") + if not re.match("[a-fA-F0-9]{40}$", text): + raise ValidationError(message="fingerprints must be 40 hexadecimal characters") return True class ValidateOptionalFingerprint(ValidateFingerprint): def validate(self, document: Document) -> bool: - if document.text == '': + if document.text == "": return True - return super(SiteConfig.ValidateOptionalFingerprint, - self).validate(document) + return super(SiteConfig.ValidateOptionalFingerprint, self).validate(document) class ValidateInt(Validator): def validate(self, document: Document) -> bool: - if re.match(r'\d+$', document.text): + if re.match(r"\d+$", document.text): return True raise ValidationError(message="Must be an integer") class Locales(object): def __init__(self, appdir: str) -> None: - self.translation_dir = os.path.realpath( - os.path.join(appdir, 'translations')) + self.translation_dir = os.path.realpath(os.path.join(appdir, "translations")) def get_translations(self) -> Set[str]: - translations = set(['en_US']) + translations = set(["en_US"]) for dirname in os.listdir(self.translation_dir): - if dirname != 'messages.pot': + if dirname != "messages.pot": translations.add(dirname) return translations @@ -250,53 +221,46 @@ def validate(self, document: Document) -> bool: missing = set(desired) - set(existing) if not missing: return True - raise ValidationError( - message="The following locales do not exist " + " ".join( - missing)) + raise ValidationError(message="The following locales do not exist " + " ".join(missing)) class ValidateOSSECUsername(Validator): def validate(self, document: Document) -> bool: text = document.text - if text and '@' not in text and 'test' != text: + if text and "@" not in text and "test" != text: return True - raise ValidationError( - message="The SASL username should not include the domain name") + raise ValidationError(message="The SASL username should not include the domain name") class ValidateOSSECPassword(Validator): def validate(self, document: Document) -> bool: text = document.text - if len(text) >= 8 and 'password123' != text: + if len(text) >= 8 and "password123" != text: return True - raise ValidationError( - message="Password for OSSEC email account must be strong") + raise ValidationError(message="Password for OSSEC email account must be strong") class ValidateEmail(Validator): def validate(self, document: Document) -> bool: text = document.text - if text == '': - raise ValidationError( - message=("Must not be empty")) - if '@' not in text: - raise ValidationError( - message=("Must contain a @")) + if text == "": + raise ValidationError(message=("Must not be empty")) + if "@" not in text: + raise ValidationError(message=("Must contain a @")) return True class ValidateOSSECEmail(ValidateEmail): def validate(self, document: Document) -> bool: super(SiteConfig.ValidateOSSECEmail, self).validate(document) text = document.text - if '[email protected]' != text: + if "[email protected]" != text: return True raise ValidationError( - message=("Must be set to something other than " - "[email protected]")) + message=("Must be set to something other than " "[email protected]") + ) class ValidateOptionalEmail(ValidateEmail): def validate(self, document: Document) -> bool: - if document.text == '': + if document.text == "": return True - return super(SiteConfig.ValidateOptionalEmail, self).validate( - document) + return super(SiteConfig.ValidateOptionalEmail, self).validate(document) def __init__(self, args: argparse.Namespace) -> None: self.args = args @@ -304,149 +268,246 @@ def __init__(self, args: argparse.Namespace) -> None: # Hold runtime configuration before save, to support # referencing other responses during validation self._config_in_progress = {} # type: Dict - translations = SiteConfig.Locales( - self.args.app_path).get_translations() + translations = SiteConfig.Locales(self.args.app_path).get_translations() translations_as_str = " ".join(translations) self.desc = [ - ('ssh_users', 'sd', str, - 'Username for SSH access to the servers', - SiteConfig.ValidateUser(), - None, - lambda config: True), - ('daily_reboot_time', 4, int, - 'Daily reboot time of the server (24-hour clock)', - SiteConfig.ValidateTime(), - int, - lambda config: True), - ('app_ip', '10.20.2.2', str, - 'Local IPv4 address for the Application Server', - SiteConfig.ValidateIP(), - None, - lambda config: True), - ('monitor_ip', '10.20.3.2', str, - 'Local IPv4 address for the Monitor Server', - SiteConfig.ValidateIP(), - None, - lambda config: True), - ('app_hostname', 'app', str, - 'Hostname for Application Server', - SiteConfig.ValidateNotEmpty(), - None, - lambda config: True), - ('monitor_hostname', 'mon', str, - 'Hostname for Monitor Server', - SiteConfig.ValidateNotEmpty(), - None, - lambda config: True), - ('dns_server', ['8.8.8.8', '8.8.4.4'], list, - 'DNS server(s)', - SiteConfig.ValidateNameservers(), - SiteConfig.split_list, - lambda config: True), - ('securedrop_app_gpg_public_key', 'SecureDrop.asc', str, - 'Local filepath to public key for ' + - 'SecureDrop Application GPG public key', - SiteConfig.ValidatePath(self.args.ansible_path), - None, - lambda config: True), - ('securedrop_app_https_on_source_interface', False, bool, - 'Whether HTTPS should be enabled on ' + - 'Source Interface (requires EV cert)', - SiteConfig.ValidateYesNo(), - lambda x: x.lower() == 'yes', - lambda config: True), - ('securedrop_app_https_certificate_cert_src', '', str, - 'Local filepath to HTTPS certificate', - SiteConfig.ValidateOptionalPath(self.args.ansible_path), - None, - lambda config: config.get( - 'securedrop_app_https_on_source_interface')), - ('securedrop_app_https_certificate_key_src', '', str, - 'Local filepath to HTTPS certificate key', - SiteConfig.ValidateOptionalPath(self.args.ansible_path), - None, - lambda config: config.get( - 'securedrop_app_https_on_source_interface')), - ('securedrop_app_https_certificate_chain_src', '', str, - 'Local filepath to HTTPS certificate chain file', - SiteConfig.ValidateOptionalPath(self.args.ansible_path), - None, - lambda config: config.get( - 'securedrop_app_https_on_source_interface')), - ('securedrop_app_gpg_fingerprint', '', str, - 'Full fingerprint for the SecureDrop Application GPG Key', - SiteConfig.ValidateFingerprint(), - self.sanitize_fingerprint, - lambda config: True), - ('ossec_alert_gpg_public_key', 'ossec.pub', str, - 'Local filepath to OSSEC alerts GPG public key', - SiteConfig.ValidatePath(self.args.ansible_path), - None, - lambda config: True), - ('ossec_gpg_fpr', '', str, - 'Full fingerprint for the OSSEC alerts GPG public key', - SiteConfig.ValidateFingerprint(), - self.sanitize_fingerprint, - lambda config: True), - ('ossec_alert_email', '', str, - 'Admin email address for receiving OSSEC alerts', - SiteConfig.ValidateOSSECEmail(), - None, - lambda config: True), - ('journalist_alert_gpg_public_key', '', str, - 'Local filepath to journalist alerts GPG public key (optional)', - SiteConfig.ValidateOptionalPath(self.args.ansible_path), - None, - lambda config: True), - ('journalist_gpg_fpr', '', str, - 'Full fingerprint for the journalist alerts ' + - 'GPG public key (optional)', - SiteConfig.ValidateOptionalFingerprint(), - self.sanitize_fingerprint, - lambda config: config.get('journalist_alert_gpg_public_key')), - ('journalist_alert_email', '', str, - 'Email address for receiving journalist alerts (optional)', - SiteConfig.ValidateOptionalEmail(), - None, - lambda config: config.get('journalist_alert_gpg_public_key')), - ('smtp_relay', "smtp.gmail.com", str, - 'SMTP relay for sending OSSEC alerts', - SiteConfig.ValidateNotEmpty(), - None, - lambda config: True), - ('smtp_relay_port', 587, int, - 'SMTP port for sending OSSEC alerts', - SiteConfig.ValidateInt(), - int, - lambda config: True), - ('sasl_domain', "gmail.com", str, - 'SASL domain for sending OSSEC alerts', - None, - None, - lambda config: True), - ('sasl_username', '', str, - 'SASL username for sending OSSEC alerts', - SiteConfig.ValidateOSSECUsername(), - None, - lambda config: True), - ('sasl_password', '', str, - 'SASL password for sending OSSEC alerts', - SiteConfig.ValidateOSSECPassword(), - None, - lambda config: True), - ('enable_ssh_over_tor', True, bool, - 'Enable SSH over Tor (recommended, disables SSH over LAN). ' + - 'If you respond no, SSH will be available over LAN only', - SiteConfig.ValidateYesNo(), - lambda x: x.lower() == 'yes', - lambda config: True), - ('securedrop_supported_locales', [], list, - 'Space separated list of additional locales to support ' - '(' + translations_as_str + ')', - SiteConfig.ValidateLocales(self.args.app_path), - str.split, - lambda config: True), + ( + "ssh_users", + "sd", + str, + "Username for SSH access to the servers", + SiteConfig.ValidateUser(), + None, + lambda config: True, + ), + ( + "daily_reboot_time", + 4, + int, + "Daily reboot time of the server (24-hour clock)", + SiteConfig.ValidateTime(), + int, + lambda config: True, + ), + ( + "app_ip", + "10.20.2.2", + str, + "Local IPv4 address for the Application Server", + SiteConfig.ValidateIP(), + None, + lambda config: True, + ), + ( + "monitor_ip", + "10.20.3.2", + str, + "Local IPv4 address for the Monitor Server", + SiteConfig.ValidateIP(), + None, + lambda config: True, + ), + ( + "app_hostname", + "app", + str, + "Hostname for Application Server", + SiteConfig.ValidateNotEmpty(), + None, + lambda config: True, + ), + ( + "monitor_hostname", + "mon", + str, + "Hostname for Monitor Server", + SiteConfig.ValidateNotEmpty(), + None, + lambda config: True, + ), + ( + "dns_server", + ["8.8.8.8", "8.8.4.4"], + list, + "DNS server(s)", + SiteConfig.ValidateNameservers(), + SiteConfig.split_list, + lambda config: True, + ), + ( + "securedrop_app_gpg_public_key", + "SecureDrop.asc", + str, + "Local filepath to public key for " + "SecureDrop Application GPG public key", + SiteConfig.ValidatePath(self.args.ansible_path), + None, + lambda config: True, + ), + ( + "securedrop_app_https_on_source_interface", + False, + bool, + "Whether HTTPS should be enabled on " + "Source Interface (requires EV cert)", + SiteConfig.ValidateYesNo(), + lambda x: x.lower() == "yes", + lambda config: True, + ), + ( + "securedrop_app_https_certificate_cert_src", + "", + str, + "Local filepath to HTTPS certificate", + SiteConfig.ValidateOptionalPath(self.args.ansible_path), + None, + lambda config: config.get("securedrop_app_https_on_source_interface"), + ), + ( + "securedrop_app_https_certificate_key_src", + "", + str, + "Local filepath to HTTPS certificate key", + SiteConfig.ValidateOptionalPath(self.args.ansible_path), + None, + lambda config: config.get("securedrop_app_https_on_source_interface"), + ), + ( + "securedrop_app_https_certificate_chain_src", + "", + str, + "Local filepath to HTTPS certificate chain file", + SiteConfig.ValidateOptionalPath(self.args.ansible_path), + None, + lambda config: config.get("securedrop_app_https_on_source_interface"), + ), + ( + "securedrop_app_gpg_fingerprint", + "", + str, + "Full fingerprint for the SecureDrop Application GPG Key", + SiteConfig.ValidateFingerprint(), + self.sanitize_fingerprint, + lambda config: True, + ), + ( + "ossec_alert_gpg_public_key", + "ossec.pub", + str, + "Local filepath to OSSEC alerts GPG public key", + SiteConfig.ValidatePath(self.args.ansible_path), + None, + lambda config: True, + ), + ( + "ossec_gpg_fpr", + "", + str, + "Full fingerprint for the OSSEC alerts GPG public key", + SiteConfig.ValidateFingerprint(), + self.sanitize_fingerprint, + lambda config: True, + ), + ( + "ossec_alert_email", + "", + str, + "Admin email address for receiving OSSEC alerts", + SiteConfig.ValidateOSSECEmail(), + None, + lambda config: True, + ), + ( + "journalist_alert_gpg_public_key", + "", + str, + "Local filepath to journalist alerts GPG public key (optional)", + SiteConfig.ValidateOptionalPath(self.args.ansible_path), + None, + lambda config: True, + ), + ( + "journalist_gpg_fpr", + "", + str, + "Full fingerprint for the journalist alerts " + "GPG public key (optional)", + SiteConfig.ValidateOptionalFingerprint(), + self.sanitize_fingerprint, + lambda config: config.get("journalist_alert_gpg_public_key"), + ), + ( + "journalist_alert_email", + "", + str, + "Email address for receiving journalist alerts (optional)", + SiteConfig.ValidateOptionalEmail(), + None, + lambda config: config.get("journalist_alert_gpg_public_key"), + ), + ( + "smtp_relay", + "smtp.gmail.com", + str, + "SMTP relay for sending OSSEC alerts", + SiteConfig.ValidateNotEmpty(), + None, + lambda config: True, + ), + ( + "smtp_relay_port", + 587, + int, + "SMTP port for sending OSSEC alerts", + SiteConfig.ValidateInt(), + int, + lambda config: True, + ), + ( + "sasl_domain", + "gmail.com", + str, + "SASL domain for sending OSSEC alerts", + None, + None, + lambda config: True, + ), + ( + "sasl_username", + "", + str, + "SASL username for sending OSSEC alerts", + SiteConfig.ValidateOSSECUsername(), + None, + lambda config: True, + ), + ( + "sasl_password", + "", + str, + "SASL password for sending OSSEC alerts", + SiteConfig.ValidateOSSECPassword(), + None, + lambda config: True, + ), + ( + "enable_ssh_over_tor", + True, + bool, + "Enable SSH over Tor (recommended, disables SSH over LAN). " + + "If you respond no, SSH will be available over LAN only", + SiteConfig.ValidateYesNo(), + lambda x: x.lower() == "yes", + lambda config: True, + ), + ( + "securedrop_supported_locales", + [], + list, + "Space separated list of additional locales to support " + "(" + translations_as_str + ")", + SiteConfig.ValidateLocales(self.args.app_path), + str.split, + lambda config: True, + ), ] # type: List[_DescEntryType] def load_and_update_config(self, validate: bool = True, prompt: bool = True) -> bool: @@ -469,22 +530,20 @@ def update_config(self, prompt: bool = True) -> bool: def user_prompt_config(self) -> Dict[str, Any]: self._config_in_progress = {} for desc in self.desc: - (var, default, type, prompt, validator, transform, - condition) = desc + (var, default, type, prompt, validator, transform, condition) = desc if not condition(self._config_in_progress): - self._config_in_progress[var] = '' + self._config_in_progress[var] = "" continue - self._config_in_progress[var] = self.user_prompt_config_one(desc, - self.config.get(var)) # noqa: E501 + self._config_in_progress[var] = self.user_prompt_config_one( + desc, self.config.get(var) + ) # noqa: E501 return self._config_in_progress - def user_prompt_config_one( - self, desc: _DescEntryType, from_config: Optional[Any] - ) -> Any: + def user_prompt_config_one(self, desc: _DescEntryType, from_config: Optional[Any]) -> Any: (var, default, type, prompt, validator, transform, condition) = desc if from_config is not None: default = from_config - prompt += ': ' + prompt += ": " # The following is for the dynamic check of the user input # for the previous question, as we are calling the default value @@ -498,58 +557,54 @@ def validated_input( self, prompt: str, default: Any, validator: Validator, transform: Optional[Callable] ) -> Any: if type(default) is bool: - default = default and 'yes' or 'no' + default = default and "yes" or "no" if type(default) is int: default = str(default) if isinstance(default, list): default = " ".join(default) if type(default) is not str: default = str(default) - value = prompt_toolkit.prompt(prompt, - default=default, - validator=validator) + value = prompt_toolkit.prompt(prompt, default=default, validator=validator) if transform: return transform(value) else: return value def sanitize_fingerprint(self, value: str) -> str: - return value.upper().replace(' ', '') + return value.upper().replace(" ", "") def validate_gpg_keys(self) -> bool: - keys = (('securedrop_app_gpg_public_key', - 'securedrop_app_gpg_fingerprint'), - - ('ossec_alert_gpg_public_key', - 'ossec_gpg_fpr'), - - ('journalist_alert_gpg_public_key', - 'journalist_gpg_fpr')) - validate = os.path.join( - os.path.dirname(__file__), '..', 'bin', - 'validate-gpg-key.sh') + keys = ( + ("securedrop_app_gpg_public_key", "securedrop_app_gpg_fingerprint"), + ("ossec_alert_gpg_public_key", "ossec_gpg_fpr"), + ("journalist_alert_gpg_public_key", "journalist_gpg_fpr"), + ) + validate = os.path.join(os.path.dirname(__file__), "..", "bin", "validate-gpg-key.sh") for (public_key, fingerprint) in keys: - if (self.config[public_key] == '' and - self.config[fingerprint] == ''): + if self.config[public_key] == "" and self.config[fingerprint] == "": continue - public_key = os.path.join(self.args.ansible_path, - self.config[public_key]) + public_key = os.path.join(self.args.ansible_path, self.config[public_key]) fingerprint = self.config[fingerprint] try: - sdlog.debug(subprocess.check_output( - [validate, public_key, fingerprint], - stderr=subprocess.STDOUT)) + sdlog.debug( + subprocess.check_output( + [validate, public_key, fingerprint], stderr=subprocess.STDOUT + ) + ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) raise FingerprintException( - "fingerprint {} ".format(fingerprint) + - "does not match " + - "the public key {}".format(public_key)) + "fingerprint {} ".format(fingerprint) + + "does not match " + + "the public key {}".format(public_key) + ) return True def validate_journalist_alert_email(self) -> bool: - if (self.config['journalist_alert_gpg_public_key'] == '' and - self.config['journalist_gpg_fpr'] == ''): + if ( + self.config["journalist_alert_gpg_public_key"] == "" + and self.config["journalist_gpg_fpr"] == "" + ): return True class Document: @@ -557,21 +612,17 @@ def __init__(self, text: str) -> None: self.text = text try: - SiteConfig.ValidateEmail().validate(Document( - self.config['journalist_alert_email'])) + SiteConfig.ValidateEmail().validate(Document(self.config["journalist_alert_email"])) except ValidationError as e: - raise JournalistAlertEmailException( - "journalist alerts email: " + e.message) + raise JournalistAlertEmailException("journalist alerts email: " + e.message) return True def exists(self) -> bool: return os.path.exists(self.args.site_config) def save(self) -> None: - with io.open(self.args.site_config, 'w') as site_config_file: - yaml.safe_dump(self.config, - site_config_file, - default_flow_style=False) + with io.open(self.args.site_config, "w") as site_config_file: + yaml.safe_dump(self.config, site_config_file, default_flow_style=False) def clean_config(self, config: Dict) -> Dict: """ @@ -604,7 +655,7 @@ def clean_config(self, config: Dict) -> Dict: except ValidationError as e: sdlog.error(e) sdlog.error( - 'Error loading configuration. ' + "Error loading configuration. " 'Please run "securedrop-admin sdconfig" again.' ) raise @@ -629,19 +680,18 @@ def load(self, validate: bool = True) -> Dict: sdlog.error("Config file missing, re-run with sdconfig") raise except yaml.YAMLError: - sdlog.error("There was an issue processing {}".format( - self.args.site_config)) + sdlog.error("There was an issue processing {}".format(self.args.site_config)) raise def setup_logger(verbose: bool = False) -> None: - """ Configure logging handler """ + """Configure logging handler""" # Set default level on parent sdlog.setLevel(logging.DEBUG) level = logging.DEBUG if verbose else logging.INFO stdout = logging.StreamHandler(sys.stdout) - stdout.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) + stdout.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) stdout.setLevel(level) sdlog.addHandler(stdout) @@ -657,6 +707,7 @@ def update_check_required(cmd_name: str) -> Callable[[_FuncT], _FuncT]: The user can override this check by specifying the --force argument before any subcommand. """ + def decorator_update_check(func: _FuncT) -> _FuncT: @functools.wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: @@ -671,8 +722,10 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: # Useful for troubleshooting branch_status = get_git_branch(cli_args) - sdlog.error("You are not running the most recent signed SecureDrop release " - "on this workstation.") + sdlog.error( + "You are not running the most recent signed SecureDrop release " + "on this workstation." + ) sdlog.error("Latest available version: {}".format(latest_tag)) if branch_status is not None: @@ -680,19 +733,27 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: else: sdlog.error("Problem determining current branch status.") - sdlog.error("Running outdated or mismatched code can cause significant " - "technical issues.") - sdlog.error("To display more information about your repository state, run:\n\n\t" - "git status\n") - sdlog.error("If you are certain you want to proceed, run:\n\n\t" - "./securedrop-admin --force {}\n".format(cmd_name)) - sdlog.error("To apply the latest updates, run:\n\n\t" - "./securedrop-admin update\n") - sdlog.error("If this fails, see the latest upgrade guide on " - "https://docs.securedrop.org/ for instructions.") + sdlog.error( + "Running outdated or mismatched code can cause significant " "technical issues." + ) + sdlog.error( + "To display more information about your repository state, run:\n\n\t" + "git status\n" + ) + sdlog.error( + "If you are certain you want to proceed, run:\n\n\t" + "./securedrop-admin --force {}\n".format(cmd_name) + ) + sdlog.error("To apply the latest updates, run:\n\n\t" "./securedrop-admin update\n") + sdlog.error( + "If this fails, see the latest upgrade guide on " + "https://docs.securedrop.org/ for instructions." + ) sys.exit(1) return func(*args, **kwargs) + return cast(_FuncT, wrapper) + return decorator_update_check @@ -712,17 +773,18 @@ def generate_new_v3_keys() -> Tuple[str, str]: private_key = x25519.X25519PrivateKey.generate() private_bytes = private_key.private_bytes( - encoding=serialization.Encoding.Raw , + encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, - encryption_algorithm=serialization.NoEncryption()) + encryption_algorithm=serialization.NoEncryption(), + ) public_key = private_key.public_key() public_bytes = public_key.public_bytes( - encoding=serialization.Encoding.Raw, - format=serialization.PublicFormat.Raw) + encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw + ) # Base32 encode and remove base32 padding characters (`=`) - public = base64.b32encode(public_bytes).replace(b'=', b'').decode("utf-8") - private = base64.b32encode(private_bytes).replace(b'=', b'').decode("utf-8") + public = base64.b32encode(public_bytes).replace(b"=", b"").decode("utf-8") + private = base64.b32encode(private_bytes).replace(b"=", b"").decode("utf-8") return public, private @@ -731,31 +793,27 @@ def find_or_generate_new_torv3_keys(args: argparse.Namespace) -> int: This method will either read v3 Tor onion service keys if found or generate a new public/private keypair. """ - secret_key_path = os.path.join(args.ansible_path, - "tor_v3_keys.json") + secret_key_path = os.path.join(args.ansible_path, "tor_v3_keys.json") if os.path.exists(secret_key_path): - print('Tor v3 onion service keys already exist in: {}'.format( - secret_key_path)) + print("Tor v3 onion service keys already exist in: {}".format(secret_key_path)) return 0 # No old keys, generate and store them first - app_journalist_public_key, \ - app_journalist_private_key = generate_new_v3_keys() + app_journalist_public_key, app_journalist_private_key = generate_new_v3_keys() # For app SSH service app_ssh_public_key, app_ssh_private_key = generate_new_v3_keys() # For mon SSH service mon_ssh_public_key, mon_ssh_private_key = generate_new_v3_keys() tor_v3_service_info = { - "app_journalist_public_key": app_journalist_public_key, - "app_journalist_private_key": app_journalist_private_key, - "app_ssh_public_key": app_ssh_public_key, - "app_ssh_private_key": app_ssh_private_key, - "mon_ssh_public_key": mon_ssh_public_key, - "mon_ssh_private_key": mon_ssh_private_key, + "app_journalist_public_key": app_journalist_public_key, + "app_journalist_private_key": app_journalist_private_key, + "app_ssh_public_key": app_ssh_public_key, + "app_ssh_private_key": app_ssh_private_key, + "mon_ssh_public_key": mon_ssh_public_key, + "mon_ssh_private_key": mon_ssh_private_key, } - with open(secret_key_path, 'w') as fobj: + with open(secret_key_path, "w") as fobj: json.dump(tor_v3_service_info, fobj, indent=4) - print('Tor v3 onion service keys generated and stored in: {}'.format( - secret_key_path)) + print("Tor v3 onion service keys generated and stored in: {}".format(secret_key_path)) return 0 @@ -766,13 +824,11 @@ def install_securedrop(args: argparse.Namespace) -> int: SiteConfig(args).load_and_update_config(prompt=False) sdlog.info("Now installing SecureDrop on remote servers.") - sdlog.info("You will be prompted for the sudo password on the " - "servers.") - sdlog.info("The sudo password is only necessary during initial " - "installation.") + sdlog.info("You will be prompted for the sudo password on the " "servers.") + sdlog.info("The sudo password is only necessary during initial " "installation.") return subprocess.check_call( - [os.path.join(args.ansible_path, 'securedrop-prod.yml'), '--ask-become-pass'], - cwd=args.ansible_path + [os.path.join(args.ansible_path, "securedrop-prod.yml"), "--ask-become-pass"], + cwd=args.ansible_path, ) @@ -781,8 +837,7 @@ def verify_install(args: argparse.Namespace) -> int: sdlog.info("Running configuration tests: ") testinfra_cmd = ["./devops/scripts/run_prod_testinfra"] - return subprocess.check_call(testinfra_cmd, - cwd=os.getcwd()) + return subprocess.check_call(testinfra_cmd, cwd=os.getcwd()) @update_check_required("backup") @@ -793,8 +848,8 @@ def backup_securedrop(args: argparse.Namespace) -> int: with the backup tarball.""" sdlog.info("Backing up the SecureDrop Application Server") ansible_cmd = [ - 'ansible-playbook', - os.path.join(args.ansible_path, 'securedrop-backup.yml'), + "ansible-playbook", + os.path.join(args.ansible_path, "securedrop-backup.yml"), ] return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) @@ -815,9 +870,9 @@ def restore_securedrop(args: argparse.Namespace) -> int: os.environ["ANSIBLE_STDOUT_CALLBACK"] = "debug" ansible_cmd = [ - 'ansible-playbook', - os.path.join(args.ansible_path, 'securedrop-restore.yml'), - '-e', + "ansible-playbook", + os.path.join(args.ansible_path, "securedrop-restore.yml"), + "-e", ] ansible_cmd_extras = [ @@ -830,7 +885,7 @@ def restore_securedrop(args: argparse.Namespace) -> int: if args.restore_manual_transfer: ansible_cmd_extras.append("restore_manual_transfer='True'") - ansible_cmd.append(' '.join(ansible_cmd_extras)) + ansible_cmd.append(" ".join(ansible_cmd_extras)) return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) @@ -838,17 +893,21 @@ def restore_securedrop(args: argparse.Namespace) -> int: def run_tails_config(args: argparse.Namespace) -> int: """Configure Tails environment post SD install""" sdlog.info("Configuring Tails workstation environment") - sdlog.info(("You'll be prompted for the temporary Tails admin password," - " which was set on Tails login screen")) + sdlog.info( + ( + "You'll be prompted for the temporary Tails admin password," + " which was set on Tails login screen" + ) + ) ansible_cmd = [ - os.path.join(args.ansible_path, 'securedrop-tails.yml'), + os.path.join(args.ansible_path, "securedrop-tails.yml"), "--ask-become-pass", # Passing an empty inventory file to override the automatic dynamic # inventory script, which fails if no site vars are configured. - '-i', '/dev/null', + "-i", + "/dev/null", ] - return subprocess.check_call(ansible_cmd, - cwd=args.ansible_path) + return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) def check_for_updates_wrapper(args: argparse.Namespace) -> int: @@ -865,20 +924,25 @@ def check_for_updates(args: argparse.Namespace) -> Tuple[bool, str]: # may produce very surprising results, because it will locate the most recent # _reachable_ tag. However, in our current branching model, it can be # relied on to determine if we're on the latest tag or not. - current_tag = subprocess.check_output(['git', 'describe'], - cwd=args.root).decode('utf-8').rstrip('\n') # noqa: E501 + current_tag = ( + subprocess.check_output(["git", "describe"], cwd=args.root).decode("utf-8").rstrip("\n") + ) # noqa: E501 # Fetch all branches - git_fetch_cmd = ['git', 'fetch', '--all'] + git_fetch_cmd = ["git", "fetch", "--all"] subprocess.check_call(git_fetch_cmd, cwd=args.root) # Get latest tag git_all_tags = ["git", "tag"] - all_tags = subprocess.check_output(git_all_tags, - cwd=args.root).decode('utf-8').rstrip('\n').split('\n') # noqa: E501 + all_tags = ( + subprocess.check_output(git_all_tags, cwd=args.root) + .decode("utf-8") + .rstrip("\n") + .split("\n") + ) # noqa: E501 # Do not check out any release candidate tags - all_prod_tags = [x for x in all_tags if 'rc' not in x] + all_prod_tags = [x for x in all_tags if "rc" not in x] # We want the tags to be sorted based on semver all_prod_tags.sort(key=parse_version) @@ -896,8 +960,7 @@ def get_git_branch(args: argparse.Namespace) -> Optional[str]: """ Returns the starred line of `git branch` output. """ - git_branch_raw = subprocess.check_output(['git', 'branch'], - cwd=args.root).decode('utf-8') + git_branch_raw = subprocess.check_output(["git", "branch"], cwd=args.root).decode("utf-8") match = re.search(r"\* (.*)\n", git_branch_raw) if match is not None and len(match.groups()) > 0: return match.group(1) @@ -908,12 +971,11 @@ def get_git_branch(args: argparse.Namespace) -> Optional[str]: def get_release_key_from_keyserver( args: argparse.Namespace, keyserver: Optional[str] = None, timeout: int = 45 ) -> None: - gpg_recv = ['timeout', str(timeout), 'gpg', '--batch', '--no-tty', - '--recv-key'] + gpg_recv = ["timeout", str(timeout), "gpg", "--batch", "--no-tty", "--recv-key"] for release_key in RELEASE_KEYS: # We construct the gpg --recv-key command based on optional keyserver arg. if keyserver: - get_key_cmd = gpg_recv + ['--keyserver', keyserver] + [release_key] + get_key_cmd = gpg_recv + ["--keyserver", keyserver] + [release_key] else: get_key_cmd = gpg_recv + [release_key] @@ -933,48 +995,47 @@ def update(args: argparse.Namespace) -> int: sdlog.info("Verifying signature on latest update...") # Retrieve key from openpgp.org keyserver - get_release_key_from_keyserver(args, - keyserver=DEFAULT_KEYSERVER) + get_release_key_from_keyserver(args, keyserver=DEFAULT_KEYSERVER) - git_verify_tag_cmd = ['git', 'tag', '-v', latest_tag] + git_verify_tag_cmd = ["git", "tag", "-v", latest_tag] try: - sig_result = subprocess.check_output(git_verify_tag_cmd, - stderr=subprocess.STDOUT, - cwd=args.root).decode('utf-8') - - good_sig_text = ['Good signature from "SecureDrop Release Signing ' + - 'Key"', - 'Good signature from "SecureDrop Release Signing ' + - 'Key <[email protected]>"', - 'Good signature from "SecureDrop Release Signing ' + - 'Key <[email protected]>"'] - bad_sig_text = 'BAD signature' - gpg_lines = sig_result.split('\n') + sig_result = subprocess.check_output( + git_verify_tag_cmd, stderr=subprocess.STDOUT, cwd=args.root + ).decode("utf-8") + + good_sig_text = [ + 'Good signature from "SecureDrop Release Signing ' + 'Key"', + 'Good signature from "SecureDrop Release Signing ' + + 'Key <[email protected]>"', + 'Good signature from "SecureDrop Release Signing ' + + 'Key <[email protected]>"', + ] + bad_sig_text = "BAD signature" + gpg_lines = sig_result.split("\n") # Check if any strings in good_sig_text match against gpg_lines[] - good_sig_matches = [s for s in gpg_lines if - any(xs in s for xs in good_sig_text)] + good_sig_matches = [s for s in gpg_lines if any(xs in s for xs in good_sig_text)] # To ensure that an adversary cannot name a malicious key good_sig_text # we check that bad_sig_text does not appear, that the release key # appears on the second line of the output, and that there is a single # match from good_sig_text[] - if (RELEASE_KEYS[0] in gpg_lines[1] or RELEASE_KEYS[1] in gpg_lines[1]) and \ - len(good_sig_matches) == 1 and \ - bad_sig_text not in sig_result: + if ( + (RELEASE_KEYS[0] in gpg_lines[1] or RELEASE_KEYS[1] in gpg_lines[1]) + and len(good_sig_matches) == 1 + and bad_sig_text not in sig_result + ): # Finally, we check that there is no branch of the same name # prior to reporting success. - cmd = ['git', 'show-ref', '--heads', '--verify', - 'refs/heads/{}'.format(latest_tag)] + cmd = ["git", "show-ref", "--heads", "--verify", "refs/heads/{}".format(latest_tag)] try: # We expect this to produce a non-zero exit code, which # will produce a subprocess.CalledProcessError - subprocess.check_output(cmd, stderr=subprocess.STDOUT, - cwd=args.root) + subprocess.check_output(cmd, stderr=subprocess.STDOUT, cwd=args.root) sdlog.info("Signature verification failed.") return 1 except subprocess.CalledProcessError as e: - if 'not a valid ref' in e.output.decode('utf-8'): + if "not a valid ref" in e.output.decode("utf-8"): # Then there is no duplicate branch. sdlog.info("Signature verification successful.") else: # If any other exception occurs, we bail. @@ -992,7 +1053,7 @@ def update(args: argparse.Namespace) -> int: return 1 # Only if the proper signature verifies do we check out the latest - git_checkout_cmd = ['git', 'checkout', latest_tag] + git_checkout_cmd = ["git", "checkout", latest_tag] subprocess.check_call(git_checkout_cmd, cwd=args.root) sdlog.info("Updated to SecureDrop {}.".format(latest_tag)) @@ -1004,12 +1065,14 @@ def get_logs(args: argparse.Namespace) -> int: """Get logs for forensics and debugging purposes""" sdlog.info("Gathering logs for forensics and debugging") ansible_cmd = [ - 'ansible-playbook', - os.path.join(args.ansible_path, 'securedrop-logs.yml'), + "ansible-playbook", + os.path.join(args.ansible_path, "securedrop-logs.yml"), ] subprocess.check_call(ansible_cmd, cwd=args.ansible_path) - sdlog.info("Please send the encrypted logs to [email protected] or " - "upload them to the SecureDrop support portal: " + SUPPORT_URL) + sdlog.info( + "Please send the encrypted logs to [email protected] or " + "upload them to the SecureDrop support portal: " + SUPPORT_URL + ) return 0 @@ -1032,92 +1095,98 @@ def reset_admin_access(args: argparse.Namespace) -> int: this Admin Workstation.""" sdlog.info("Resetting SSH access to the SecureDrop servers") ansible_cmd = [ - 'ansible-playbook', - os.path.join(args.ansible_path, 'securedrop-reset-ssh-key.yml'), + "ansible-playbook", + os.path.join(args.ansible_path, "securedrop-reset-ssh-key.yml"), ] return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) def parse_argv(argv: List[str]) -> argparse.Namespace: - class ArgParseFormatterCombo(argparse.ArgumentDefaultsHelpFormatter, - argparse.RawTextHelpFormatter): + class ArgParseFormatterCombo( + argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter + ): """Needed to combine formatting classes for help output""" + pass - parser = argparse.ArgumentParser(description=__doc__, - formatter_class=ArgParseFormatterCombo) - parser.add_argument('-v', action='store_true', default=False, - help="Increase verbosity on output") - parser.add_argument('-d', action='store_true', default=False, - help="Developer mode. Not to be used in production.") - parser.add_argument('--force', action='store_true', required=False, - help="force command execution without update check") - parser.add_argument('--root', required=True, - help="path to the root of the SecureDrop repository") - parser.add_argument('--site-config', - help="path to the YAML site configuration file") - parser.add_argument('--ansible-path', - help="path to the Ansible root") - parser.add_argument('--app-path', - help="path to the SecureDrop application root") + parser = argparse.ArgumentParser(description=__doc__, formatter_class=ArgParseFormatterCombo) + parser.add_argument( + "-v", action="store_true", default=False, help="Increase verbosity on output" + ) + parser.add_argument( + "-d", + action="store_true", + default=False, + help="Developer mode. Not to be used in production.", + ) + parser.add_argument( + "--force", + action="store_true", + required=False, + help="force command execution without update check", + ) + parser.add_argument( + "--root", required=True, help="path to the root of the SecureDrop repository" + ) + parser.add_argument("--site-config", help="path to the YAML site configuration file") + parser.add_argument("--ansible-path", help="path to the Ansible root") + parser.add_argument("--app-path", help="path to the SecureDrop application root") subparsers = parser.add_subparsers() - parse_sdconfig = subparsers.add_parser('sdconfig', help=sdconfig.__doc__) + parse_sdconfig = subparsers.add_parser("sdconfig", help=sdconfig.__doc__) parse_sdconfig.set_defaults(func=sdconfig) - parse_install = subparsers.add_parser('install', - help=install_securedrop.__doc__) + parse_install = subparsers.add_parser("install", help=install_securedrop.__doc__) parse_install.set_defaults(func=install_securedrop) - parse_tailsconfig = subparsers.add_parser('tailsconfig', - help=run_tails_config.__doc__) + parse_tailsconfig = subparsers.add_parser("tailsconfig", help=run_tails_config.__doc__) parse_tailsconfig.set_defaults(func=run_tails_config) parse_generate_tor_keys = subparsers.add_parser( - 'generate_v3_keys', - help=find_or_generate_new_torv3_keys.__doc__) + "generate_v3_keys", help=find_or_generate_new_torv3_keys.__doc__ + ) parse_generate_tor_keys.set_defaults(func=find_or_generate_new_torv3_keys) - parse_backup = subparsers.add_parser('backup', - help=backup_securedrop.__doc__) + parse_backup = subparsers.add_parser("backup", help=backup_securedrop.__doc__) parse_backup.set_defaults(func=backup_securedrop) - parse_restore = subparsers.add_parser('restore', - help=restore_securedrop.__doc__) + parse_restore = subparsers.add_parser("restore", help=restore_securedrop.__doc__) parse_restore.set_defaults(func=restore_securedrop) parse_restore.add_argument("restore_file") - parse_restore.add_argument("--preserve-tor-config", default=False, - action='store_true', - dest='restore_skip_tor', - help="Preserve the server's current Tor config") + parse_restore.add_argument( + "--preserve-tor-config", + default=False, + action="store_true", + dest="restore_skip_tor", + help="Preserve the server's current Tor config", + ) - parse_restore.add_argument("--no-transfer", default=False, - action='store_true', - dest='restore_manual_transfer', - help="Restore using a backup file already present on the server") + parse_restore.add_argument( + "--no-transfer", + default=False, + action="store_true", + dest="restore_manual_transfer", + help="Restore using a backup file already present on the server", + ) - parse_update = subparsers.add_parser('update', help=update.__doc__) + parse_update = subparsers.add_parser("update", help=update.__doc__) parse_update.set_defaults(func=update) - parse_check_updates = subparsers.add_parser('check_for_updates', - help=check_for_updates.__doc__) + parse_check_updates = subparsers.add_parser("check_for_updates", help=check_for_updates.__doc__) parse_check_updates.set_defaults(func=check_for_updates_wrapper) - parse_logs = subparsers.add_parser('logs', - help=get_logs.__doc__) + parse_logs = subparsers.add_parser("logs", help=get_logs.__doc__) parse_logs.set_defaults(func=get_logs) - parse_reset_ssh = subparsers.add_parser('reset_admin_access', - help=reset_admin_access.__doc__) + parse_reset_ssh = subparsers.add_parser("reset_admin_access", help=reset_admin_access.__doc__) parse_reset_ssh.set_defaults(func=reset_admin_access) - parse_verify = subparsers.add_parser('verify', - help=verify_install.__doc__) + parse_verify = subparsers.add_parser("verify", help=verify_install.__doc__) parse_verify.set_defaults(func=verify_install) args = parser.parse_args(argv) - if getattr(args, 'func', None) is None: - print('Please specify an operation.\n') + if getattr(args, "func", None) is None: + print("Please specify an operation.\n") parser.print_help() sys.exit(1) return set_default_paths(args) @@ -1134,15 +1203,13 @@ def main(argv: List[str]) -> None: try: return_code = args.func(args) except KeyboardInterrupt: - print('Process was interrupted.') + print("Process was interrupted.") sys.exit(EXIT_INTERRUPT) except subprocess.CalledProcessError as e: - print('ERROR (run with -v for more): {msg}'.format(msg=e), - file=sys.stderr) + print("ERROR (run with -v for more): {msg}".format(msg=e), file=sys.stderr) sys.exit(EXIT_SUBPROCESS_ERROR) except Exception as e: - raise SystemExit( - 'ERROR (run with -v for more): {msg}'.format(msg=e)) + raise SystemExit("ERROR (run with -v for more): {msg}".format(msg=e)) if return_code == 0: sys.exit(EXIT_SUCCESS) else: diff --git a/admin/setup.py b/admin/setup.py --- a/admin/setup.py +++ b/admin/setup.py @@ -17,6 +17,4 @@ # import setuptools -setuptools.setup( - setup_requires=['d2to1', 'pbr'], - d2to1=True) +setuptools.setup(setup_requires=["d2to1", "pbr"], d2to1=True) diff --git a/install_files/ansible-base/callback_plugins/ansible_version_check.py b/install_files/ansible-base/callback_plugins/ansible_version_check.py --- a/install_files/ansible-base/callback_plugins/ansible_version_check.py +++ b/install_files/ansible-base/callback_plugins/ansible_version_check.py @@ -1,6 +1,5 @@ # -*- encoding:utf-8 -*- -from __future__ import absolute_import, division, print_function, \ - unicode_literals +from __future__ import absolute_import, division, print_function, unicode_literals import sys @@ -14,7 +13,7 @@ def print_red_bold(text): - print('\x1b[31;1m' + text + '\x1b[0m') + print("\x1b[31;1m" + text + "\x1b[0m") class CallbackModule(CallbackBase): @@ -23,14 +22,13 @@ def __init__(self): # requirements files. viable_start = [2, 9, 7] viable_end = [2, 10, 0] - ansible_version = [int(v) for v in ansible.__version__.split('.')] + ansible_version = [int(v) for v in ansible.__version__.split(".")] if not (viable_start <= ansible_version < viable_end): print_red_bold( "SecureDrop restriction: Ansible version must be at least {viable_start} " - "and less than {viable_end}." - .format( - viable_start='.'.join(str(v) for v in viable_start), - viable_end='.'.join(str(v) for v in viable_end), + "and less than {viable_end}.".format( + viable_start=".".join(str(v) for v in viable_start), + viable_end=".".join(str(v) for v in viable_end), ) ) sys.exit(1) diff --git a/install_files/ansible-base/roles/backup/files/backup.py b/install_files/ansible-base/roles/backup/files/backup.py --- a/install_files/ansible-base/roles/backup/files/backup.py +++ b/install_files/ansible-base/roles/backup/files/backup.py @@ -8,26 +8,25 @@ information and limitations, see https://docs.securedrop.org/en/stable/backup_and_restore.html """ -from datetime import datetime import os import tarfile +from datetime import datetime def main(): - backup_filename = 'sd-backup-{}.tar.gz'.format( - datetime.utcnow().strftime("%Y-%m-%d--%H-%M-%S")) + backup_filename = "sd-backup-{}.tar.gz".format(datetime.utcnow().strftime("%Y-%m-%d--%H-%M-%S")) # This code assumes everything is in the default locations. - sd_data = '/var/lib/securedrop' + sd_data = "/var/lib/securedrop" - sd_code = '/var/www/securedrop' + sd_code = "/var/www/securedrop" sd_config = os.path.join(sd_code, "config.py") sd_custom_logo = os.path.join(sd_code, "static/i/custom_logo.png") tor_hidden_services = "/var/lib/tor/services" torrc = "/etc/tor/torrc" - with tarfile.open(backup_filename, 'w:gz') as backup: + with tarfile.open(backup_filename, "w:gz") as backup: backup.add(sd_config) # If no custom logo has been configured, the file will not exist diff --git a/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py b/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py --- a/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py +++ b/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: ossec_urls short_description: Gather facts for OSSEC download URLs @@ -20,11 +20,11 @@ - The OSSEC version to download is hardcoded to avoid surprises. If you want a newer version than the current default, you should pass the version in via I(ossec_version). -''' -EXAMPLES = ''' +""" +EXAMPLES = """ - ossec_urls: ossec_version: "3.6.0" -''' +""" HAS_REQUESTS = True @@ -34,8 +34,7 @@ HAS_REQUESTS = False -class OSSECURLs(): - +class OSSECURLs: def __init__(self, ossec_version): self.REPO_URL = "https://github.com/ossec/ossec-hids" self.ossec_version = ossec_version @@ -45,7 +44,7 @@ def __init__(self, ossec_version): ossec_tarball_url=self.ossec_tarball_url, ossec_signature_filename=self.ossec_signature_filename, ossec_signature_url=self.ossec_signature_url, - ) + ) @property def ossec_tarball_filename(self): @@ -58,7 +57,8 @@ def ossec_tarball_url(self): @property def ossec_signature_url(self): return self.REPO_URL + "/releases/download/{}/{}".format( - self.ossec_version, self.ossec_signature_filename) + self.ossec_version, self.ossec_signature_filename + ) @property def ossec_signature_filename(self): @@ -70,19 +70,21 @@ def main(): argument_spec=dict( ossec_version=dict(default="3.6.0"), ), - supports_check_mode=False + supports_check_mode=False, ) if not HAS_REQUESTS: - module.fail_json(msg='requests required for this module') + module.fail_json(msg="requests required for this module") - ossec_version = module.params['ossec_version'] + ossec_version = module.params["ossec_version"] try: ossec_config = OSSECURLs(ossec_version=ossec_version) except Exception: - msg = ("Failed to find checksum information for OSSEC v{}." - "Ensure you have the proper release specified, " - "and check the download page to confirm: " - "http://www.ossec.net/?page_id=19".format(ossec_version)) + msg = ( + "Failed to find checksum information for OSSEC v{}." + "Ensure you have the proper release specified, " + "and check the download page to confirm: " + "http://www.ossec.net/?page_id=19".format(ossec_version) + ) module.fail_json(msg=msg) results = ossec_config.ansible_facts @@ -94,5 +96,6 @@ def main(): module.fail_json(msg=msg) -from ansible.module_utils.basic import * # noqa E402,F403 +from ansible.module_utils.basic import * # noqa E402,F403 + main() diff --git a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py --- a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py +++ b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py @@ -1,50 +1,52 @@ #!/usr/bin/python3 import grp -import os import io +import os import pwd -import sys import subprocess - +import sys import tempfile from shutil import copyfile, copyfileobj - # check for root if os.geteuid() != 0: - sys.exit('You need to run this as root') + sys.exit("You need to run this as root") # paths -path_torrc_additions = '/home/amnesia/Persistent/.securedrop/torrc_additions' -path_torrc_backup = '/etc/tor/torrc.bak' -path_torrc = '/etc/tor/torrc' -path_desktop = '/home/amnesia/Desktop/' -path_persistent_desktop = '/lib/live/mount/persistence/TailsData_unlocked/dotfiles/Desktop/' # noqa: E501 -path_securedrop_root = '/home/amnesia/Persistent/securedrop' -path_securedrop_admin_venv = os.path.join(path_securedrop_root, - 'admin/.venv3/bin/python') -path_securedrop_admin_init = os.path.join(path_securedrop_root, - 'admin/securedrop_admin/__init__.py') -path_gui_updater = os.path.join(path_securedrop_root, - 'journalist_gui/SecureDropUpdater') +path_torrc_additions = "/home/amnesia/Persistent/.securedrop/torrc_additions" +path_torrc_backup = "/etc/tor/torrc.bak" +path_torrc = "/etc/tor/torrc" +path_desktop = "/home/amnesia/Desktop/" +path_persistent_desktop = ( + "/lib/live/mount/persistence/TailsData_unlocked/dotfiles/Desktop/" # noqa: E501 +) +path_securedrop_root = "/home/amnesia/Persistent/securedrop" +path_securedrop_admin_venv = os.path.join(path_securedrop_root, "admin/.venv3/bin/python") +path_securedrop_admin_init = os.path.join( + path_securedrop_root, "admin/securedrop_admin/__init__.py" +) +path_gui_updater = os.path.join(path_securedrop_root, "journalist_gui/SecureDropUpdater") paths_v3_authfiles = { - "app-journalist": os.path.join(path_securedrop_root, - 'install_files/ansible-base/app-journalist.auth_private'), - "app-ssh": os.path.join(path_securedrop_root, - 'install_files/ansible-base/app-ssh.auth_private'), - "mon-ssh": os.path.join(path_securedrop_root, - 'install_files/ansible-base/mon-ssh.auth_private') + "app-journalist": os.path.join( + path_securedrop_root, "install_files/ansible-base/app-journalist.auth_private" + ), + "app-ssh": os.path.join( + path_securedrop_root, "install_files/ansible-base/app-ssh.auth_private" + ), + "mon-ssh": os.path.join( + path_securedrop_root, "install_files/ansible-base/mon-ssh.auth_private" + ), } -path_onion_auth_dir = '/var/lib/tor/onion_auth' +path_onion_auth_dir = "/var/lib/tor/onion_auth" # load torrc_additions if os.path.isfile(path_torrc_additions): with io.open(path_torrc_additions) as f: torrc_additions = f.read() else: - sys.exit('Error opening {0} for reading'.format(path_torrc_additions)) + sys.exit("Error opening {0} for reading".format(path_torrc_additions)) # load torrc if os.path.isfile(path_torrc_backup): @@ -55,14 +57,14 @@ with io.open(path_torrc) as f: torrc = f.read() else: - sys.exit('Error opening {0} for reading'.format(path_torrc)) + sys.exit("Error opening {0} for reading".format(path_torrc)) # save a backup - with io.open(path_torrc_backup, 'w') as f: + with io.open(path_torrc_backup, "w") as f: f.write(torrc) # append the additions -with io.open(path_torrc, 'w') as f: +with io.open(path_torrc, "w") as f: f.write(torrc + torrc_additions) # check for v3 aths files @@ -91,64 +93,67 @@ # restart tor try: - subprocess.check_call(['systemctl', 'restart', '[email protected]']) + subprocess.check_call(["systemctl", "restart", "[email protected]"]) except subprocess.CalledProcessError: - sys.exit('Error restarting Tor') + sys.exit("Error restarting Tor") # Set journalist.desktop and source.desktop links as trusted with Nautilus (see # https://github.com/freedomofpress/securedrop/issues/2586) # set euid and env variables to amnesia user -amnesia_gid = grp.getgrnam('amnesia').gr_gid -amnesia_uid = pwd.getpwnam('amnesia').pw_uid +amnesia_gid = grp.getgrnam("amnesia").gr_gid +amnesia_uid = pwd.getpwnam("amnesia").pw_uid os.setresgid(amnesia_gid, amnesia_gid, -1) os.setresuid(amnesia_uid, amnesia_uid, -1) env = os.environ.copy() -env['XDG_CURRENT_DESKTOP'] = 'GNOME' -env['DESKTOP_SESSION'] = 'default' -env['DISPLAY'] = ':1' -env['XDG_RUNTIME_DIR'] = '/run/user/{}'.format(amnesia_uid) -env['XDG_DATA_DIR'] = '/usr/share/gnome:/usr/local/share/:/usr/share/' -env['HOME'] = '/home/amnesia' -env['LOGNAME'] = 'amnesia' -env['DBUS_SESSION_BUS_ADDRESS'] = 'unix:path=/run/user/{}/bus'.format( - amnesia_uid) +env["XDG_CURRENT_DESKTOP"] = "GNOME" +env["DESKTOP_SESSION"] = "default" +env["DISPLAY"] = ":1" +env["XDG_RUNTIME_DIR"] = "/run/user/{}".format(amnesia_uid) +env["XDG_DATA_DIR"] = "/usr/share/gnome:/usr/local/share/:/usr/share/" +env["HOME"] = "/home/amnesia" +env["LOGNAME"] = "amnesia" +env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/run/user/{}/bus".format(amnesia_uid) # remove existing shortcut, recreate symlink and change metadata attribute # to trust .desktop -for shortcut in ['source.desktop', 'journalist.desktop']: - subprocess.call(['rm', path_desktop + shortcut], env=env) - subprocess.call(['ln', '-s', path_persistent_desktop + shortcut, - path_desktop + shortcut], env=env) - subprocess.call(['gio', 'set', path_desktop + shortcut, - 'metadata::trusted', 'true'], env=env) +for shortcut in ["source.desktop", "journalist.desktop"]: + subprocess.call(["rm", path_desktop + shortcut], env=env) + subprocess.call( + ["ln", "-s", path_persistent_desktop + shortcut, path_desktop + shortcut], env=env + ) + subprocess.call(["gio", "set", path_desktop + shortcut, "metadata::trusted", "true"], env=env) # in Tails 4, reload gnome-shell desktop icons extension to update with changes above cmd = ["lsb_release", "--id", "--short"] p = subprocess.check_output(cmd) distro_id = p.rstrip() -if distro_id == 'Debian' and os.uname()[1] == 'amnesia': - subprocess.call(['gnome-shell-extension-tool', '-r', 'desktop-icons@csoriano'], env=env) +if distro_id == "Debian" and os.uname()[1] == "amnesia": + subprocess.call(["gnome-shell-extension-tool", "-r", "desktop-icons@csoriano"], env=env) # reacquire uid0 and notify the user os.setresuid(0, 0, -1) os.setresgid(0, 0, -1) -success_message = 'You can now access the Journalist Interface.\nIf you are an admin, you can now SSH to the servers.' # noqa: E501 -subprocess.call(['tails-notify-user', - 'SecureDrop successfully auto-configured!', - success_message]) +success_message = "You can now access the Journalist Interface.\nIf you are an admin, you can now SSH to the servers." # noqa: E501 +subprocess.call(["tails-notify-user", "SecureDrop successfully auto-configured!", success_message]) # As the amnesia user, check for SecureDrop workstation updates. os.setresgid(amnesia_gid, amnesia_gid, -1) os.setresuid(amnesia_uid, amnesia_uid, -1) -output = subprocess.check_output([path_securedrop_admin_venv, - path_securedrop_admin_init, - '--root', path_securedrop_root, - 'check_for_updates'], env=env) +output = subprocess.check_output( + [ + path_securedrop_admin_venv, + path_securedrop_admin_init, + "--root", + path_securedrop_root, + "check_for_updates", + ], + env=env, +) flag_location = "/home/amnesia/Persistent/.securedrop/securedrop_update.flag" -if b'Update needed' in output or os.path.exists(flag_location): +if b"Update needed" in output or os.path.exists(flag_location): # Start the SecureDrop updater GUI. - subprocess.Popen(['python3', path_gui_updater], env=env) + subprocess.Popen(["python3", path_gui_updater], env=env) # Check for Tails < 4.19 and apply a fix to the auto-updater. # See https://tails.boum.org/news/version_4.18/ @@ -157,59 +162,70 @@ needs_update = False tails_current_version = None -with open('/etc/os-release') as file: +with open("/etc/os-release") as file: for line in file: try: k, v = line.strip().split("=") if k == "TAILS_VERSION_ID": - tails_current_version = v.strip("\"").split(".") + tails_current_version = v.strip('"').split(".") except ValueError: continue if tails_current_version: try: - needs_update = (len(tails_current_version) >= 2 and - int(tails_current_version[1]) < tails_4_min_version) + needs_update = ( + len(tails_current_version) >= 2 and int(tails_current_version[1]) < tails_4_min_version + ) except (TypeError, ValueError): sys.exit(0) # Don't break tailsconfig trying to fix this if needs_update: - cert_name = 'isrg-root-x1-cross-signed.pem' + cert_name = "isrg-root-x1-cross-signed.pem" pem_file = tempfile.NamedTemporaryFile(delete=True) try: - subprocess.call(['torsocks', 'curl', '--silent', - 'https://tails.boum.org/' + cert_name], - stdout=pem_file, env=env) + subprocess.call( + ["torsocks", "curl", "--silent", "https://tails.boum.org/" + cert_name], + stdout=pem_file, + env=env, + ) # Verify against /etc/ssl/certs/DST_Root_CA_X3.pem, which cross-signs # the new LetsEncrypt cert but is expiring - verify_proc = subprocess.check_output(['openssl', 'verify', - '-no_check_time', '-no-CApath', - '-CAfile', - '/etc/ssl/certs/DST_Root_CA_X3.pem', - pem_file.name], - universal_newlines=True, env=env) - - if 'OK' in verify_proc: + verify_proc = subprocess.check_output( + [ + "openssl", + "verify", + "-no_check_time", + "-no-CApath", + "-CAfile", + "/etc/ssl/certs/DST_Root_CA_X3.pem", + pem_file.name, + ], + universal_newlines=True, + env=env, + ) + + if "OK" in verify_proc: # Updating the cert chain requires sudo privileges os.setresgid(0, 0, -1) os.setresuid(0, 0, -1) - with open('/usr/local/etc/ssl/certs/tails.boum.org-CA.pem', 'a') as chain: + with open("/usr/local/etc/ssl/certs/tails.boum.org-CA.pem", "a") as chain: pem_file.seek(0) copyfileobj(pem_file, chain) # As amnesia user, start updater GUI os.setresgid(amnesia_gid, amnesia_gid, -1) os.setresuid(amnesia_uid, amnesia_uid, -1) - restart_proc = subprocess.call(['systemctl', '--user', 'restart', - 'tails-upgrade-frontend'], env=env) + restart_proc = subprocess.call( + ["systemctl", "--user", "restart", "tails-upgrade-frontend"], env=env + ) except subprocess.CalledProcessError: - sys.exit(0) # Don't break tailsconfig trying to fix this + sys.exit(0) # Don't break tailsconfig trying to fix this except IOError: sys.exit(0) diff --git a/install_files/securedrop-ossec-agent/var/ossec/checksdconfig.py b/install_files/securedrop-ossec-agent/var/ossec/checksdconfig.py --- a/install_files/securedrop-ossec-agent/var/ossec/checksdconfig.py +++ b/install_files/securedrop-ossec-agent/var/ossec/checksdconfig.py @@ -5,10 +5,7 @@ import subprocess import sys - -IPTABLES_RULES_UNCONFIGURED = { - "all": ["-P INPUT ACCEPT", "-P FORWARD ACCEPT", "-P OUTPUT ACCEPT"] -} +IPTABLES_RULES_UNCONFIGURED = {"all": ["-P INPUT ACCEPT", "-P FORWARD ACCEPT", "-P OUTPUT ACCEPT"]} IPTABLES_RULES_DEFAULT_DROP = { @@ -31,14 +28,12 @@ "-A LOGNDROP -p udp -m limit --limit 5/min -j LOG --log-ip-options --log-uid", "-A LOGNDROP -p icmp -m limit --limit 5/min -j LOG --log-ip-options --log-uid", "-A LOGNDROP -j DROP", - ] + ], } def list_iptables_rules(): - result = subprocess.run( - ["iptables", "-S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) + result = subprocess.run(["iptables", "-S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rules = result.stdout.decode("utf-8").splitlines() policies = [r for r in rules if r.startswith("-P")] input_rules = [r for r in rules if r.startswith("-A INPUT")] @@ -84,7 +79,7 @@ def check_system_configuration(args): print("System configuration checks were successful.") -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='SecureDrop server configuration check') +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="SecureDrop server configuration check") args = parser.parse_args() check_system_configuration(args) diff --git a/install_files/securedrop-ossec-server/var/ossec/checksdconfig.py b/install_files/securedrop-ossec-server/var/ossec/checksdconfig.py --- a/install_files/securedrop-ossec-server/var/ossec/checksdconfig.py +++ b/install_files/securedrop-ossec-server/var/ossec/checksdconfig.py @@ -5,10 +5,7 @@ import subprocess import sys - -IPTABLES_RULES_UNCONFIGURED = { - "all": ["-P INPUT ACCEPT", "-P FORWARD ACCEPT", "-P OUTPUT ACCEPT"] -} +IPTABLES_RULES_UNCONFIGURED = {"all": ["-P INPUT ACCEPT", "-P FORWARD ACCEPT", "-P OUTPUT ACCEPT"]} IPTABLES_RULES_DEFAULT_DROP = { @@ -31,14 +28,12 @@ "-A LOGNDROP -p udp -m limit --limit 5/min -j LOG --log-ip-options --log-uid", "-A LOGNDROP -p icmp -m limit --limit 5/min -j LOG --log-ip-options --log-uid", "-A LOGNDROP -j DROP", - ] + ], } def list_iptables_rules(): - result = subprocess.run( - ["iptables", "-S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) + result = subprocess.run(["iptables", "-S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rules = result.stdout.decode("utf-8").splitlines() policies = [r for r in rules if r.startswith("-P")] input_rules = [r for r in rules if r.startswith("-A INPUT")] @@ -84,7 +79,7 @@ def check_system_configuration(args): print("System configuration checks were successful.") -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='SecureDrop server configuration check') +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="SecureDrop server configuration check") args = parser.parse_args() check_system_configuration(args) diff --git a/journalist_gui/journalist_gui/SecureDropUpdater.py b/journalist_gui/journalist_gui/SecureDropUpdater.py --- a/journalist_gui/journalist_gui/SecureDropUpdater.py +++ b/journalist_gui/journalist_gui/SecureDropUpdater.py @@ -1,26 +1,26 @@ #!/usr/bin/python -from PyQt5 import QtGui, QtWidgets -from PyQt5.QtCore import QThread, pyqtSignal -import subprocess import os import re -import pexpect import socket +import subprocess import sys import syslog as log -from journalist_gui import updaterUI, strings, resources_rc # noqa +import pexpect +from PyQt5 import QtGui, QtWidgets +from PyQt5.QtCore import QThread, pyqtSignal +from journalist_gui import resources_rc, strings, updaterUI # noqa FLAG_LOCATION = "/home/amnesia/Persistent/.securedrop/securedrop_update.flag" # noqa -ESCAPE_POD = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') +ESCAPE_POD = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]") def password_is_set(): - pwd_flag = subprocess.check_output(['passwd', '--status']).decode('utf-8').split()[1] + pwd_flag = subprocess.check_output(["passwd", "--status"]).decode("utf-8").split()[1] - if pwd_flag == 'NP': + if pwd_flag == "NP": return False return True @@ -28,7 +28,7 @@ def password_is_set(): def prevent_second_instance(app: QtWidgets.QApplication, name: str) -> None: # noqa # Null byte triggers abstract namespace - IDENTIFIER = '\0' + name + IDENTIFIER = "\0" + name ALREADY_BOUND_ERRNO = 98 app.instance_binding = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) @@ -43,7 +43,7 @@ def prevent_second_instance(app: QtWidgets.QApplication, name: str) -> None: # class SetupThread(QThread): - signal = pyqtSignal('PyQt_PyObject') + signal = pyqtSignal("PyQt_PyObject") def __init__(self): QThread.__init__(self) @@ -52,36 +52,38 @@ def __init__(self): self.failure_reason = "" def run(self): - sdadmin_path = '/home/amnesia/Persistent/securedrop/securedrop-admin' - update_command = [sdadmin_path, 'setup'] + sdadmin_path = "/home/amnesia/Persistent/securedrop/securedrop-admin" + update_command = [sdadmin_path, "setup"] # Create flag file to indicate we should resume failed updates on # reboot. Don't create the flag if it already exists. if not os.path.exists(FLAG_LOCATION): - open(FLAG_LOCATION, 'a').close() + open(FLAG_LOCATION, "a").close() try: - self.output = subprocess.check_output( - update_command, - stderr=subprocess.STDOUT).decode('utf-8') - if 'Failed to install' in self.output: + self.output = subprocess.check_output(update_command, stderr=subprocess.STDOUT).decode( + "utf-8" + ) + if "Failed to install" in self.output: self.update_success = False self.failure_reason = strings.update_failed_generic_reason else: self.update_success = True except subprocess.CalledProcessError as e: - self.output += e.output.decode('utf-8') + self.output += e.output.decode("utf-8") self.update_success = False self.failure_reason = strings.update_failed_generic_reason - result = {'status': self.update_success, - 'output': self.output, - 'failure_reason': self.failure_reason} + result = { + "status": self.update_success, + "output": self.output, + "failure_reason": self.failure_reason, + } self.signal.emit(result) # This thread will handle the ./securedrop-admin update command class UpdateThread(QThread): - signal = pyqtSignal('PyQt_PyObject') + signal = pyqtSignal("PyQt_PyObject") def __init__(self): QThread.__init__(self) @@ -90,32 +92,34 @@ def __init__(self): self.failure_reason = "" def run(self): - sdadmin_path = '/home/amnesia/Persistent/securedrop/securedrop-admin' - update_command = [sdadmin_path, 'update'] + sdadmin_path = "/home/amnesia/Persistent/securedrop/securedrop-admin" + update_command = [sdadmin_path, "update"] try: - self.output = subprocess.check_output( - update_command, - stderr=subprocess.STDOUT).decode('utf-8') + self.output = subprocess.check_output(update_command, stderr=subprocess.STDOUT).decode( + "utf-8" + ) if "Signature verification successful" in self.output: self.update_success = True else: self.failure_reason = strings.update_failed_generic_reason except subprocess.CalledProcessError as e: self.update_success = False - self.output += e.output.decode('utf-8') - if 'Signature verification failed' in self.output: + self.output += e.output.decode("utf-8") + if "Signature verification failed" in self.output: self.failure_reason = strings.update_failed_sig_failure else: self.failure_reason = strings.update_failed_generic_reason - result = {'status': self.update_success, - 'output': self.output, - 'failure_reason': self.failure_reason} + result = { + "status": self.update_success, + "output": self.output, + "failure_reason": self.failure_reason, + } self.signal.emit(result) # This thread will handle the ./securedrop-admin tailsconfig command class TailsconfigThread(QThread): - signal = pyqtSignal('PyQt_PyObject') + signal = pyqtSignal("PyQt_PyObject") def __init__(self): QThread.__init__(self) @@ -125,17 +129,17 @@ def __init__(self): self.sudo_password = "" def run(self): - tailsconfig_command = ("/home/amnesia/Persistent/" - "securedrop/securedrop-admin " - "tailsconfig") + tailsconfig_command = ( + "/home/amnesia/Persistent/" "securedrop/securedrop-admin " "tailsconfig" + ) self.failure_reason = "" try: child = pexpect.spawn(tailsconfig_command) - child.expect('SUDO password:') - self.output += child.before.decode('utf-8') + child.expect("SUDO password:") + self.output += child.before.decode("utf-8") child.sendline(self.sudo_password) child.expect(pexpect.EOF, timeout=120) - self.output += child.before.decode('utf-8') + self.output += child.before.decode("utf-8") child.close() # For Tailsconfig to be considered a success, we expect no @@ -154,14 +158,15 @@ def run(self): except subprocess.CalledProcessError: self.update_success = False self.failure_reason = strings.tailsconfig_failed_generic_reason - result = {'status': self.update_success, - 'output': ESCAPE_POD.sub('', self.output), - 'failure_reason': self.failure_reason} + result = { + "status": self.update_success, + "output": ESCAPE_POD.sub("", self.output), + "failure_reason": self.failure_reason, + } self.signal.emit(result) class UpdaterApp(QtWidgets.QMainWindow, updaterUI.Ui_MainWindow): - def __init__(self, parent=None): super(UpdaterApp, self).__init__(parent) self.setupUi(self) @@ -176,24 +181,26 @@ def __init__(self, parent=None): self.progressBar.setProperty("value", 0) self.setWindowTitle(strings.window_title) - self.setWindowIcon(QtGui.QIcon(':/images/static/securedrop_icon.png')) + self.setWindowIcon(QtGui.QIcon(":/images/static/securedrop_icon.png")) self.label.setText(strings.update_in_progress) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), - strings.main_tab) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), - strings.output_tab) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), strings.main_tab) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), strings.output_tab) # Connect buttons to their functions. self.pushButton.setText(strings.install_later_button) - self.pushButton.setStyleSheet("""background-color: lightgrey; + self.pushButton.setStyleSheet( + """background-color: lightgrey; min-height: 2em; - border-radius: 10px""") + border-radius: 10px""" + ) self.pushButton.clicked.connect(self.close) self.pushButton_2.setText(strings.install_update_button) - self.pushButton_2.setStyleSheet("""background-color: #E6FFEB; + self.pushButton_2.setStyleSheet( + """background-color: #E6FFEB; min-height: 2em; - border-radius: 10px;""") + border-radius: 10px;""" + ) self.pushButton_2.clicked.connect(self.update_securedrop) self.update_thread = UpdateThread() self.update_thread.signal.connect(self.update_status) @@ -206,9 +213,9 @@ def __init__(self, parent=None): # A new slot will handle tailsconfig output def setup_status(self, result): "This is the slot for setup thread" - self.output += result['output'] - self.update_success = result['status'] - self.failure_reason = result['failure_reason'] + self.output += result["output"] + self.update_success = result["status"] + self.failure_reason = result["failure_reason"] self.progressBar.setProperty("value", 60) self.plainTextEdit.setPlainText(self.output) self.plainTextEdit.setReadOnly = True @@ -225,9 +232,9 @@ def setup_status(self, result): # This will update the output text after the git commands. def update_status(self, result): "This is the slot for update thread" - self.output += result['output'] - self.update_success = result['status'] - self.failure_reason = result['failure_reason'] + self.output += result["output"] + self.update_success = result["status"] + self.failure_reason = result["failure_reason"] self.progressBar.setProperty("value", 40) self.plainTextEdit.setPlainText(self.output) self.plainTextEdit.setReadOnly = True @@ -246,7 +253,7 @@ def update_status_bar_and_output(self, status_message): """This method updates the status bar and the output window with the status_message.""" self.statusbar.showMessage(status_message) - self.output += status_message + '\n' + self.output += status_message + "\n" self.plainTextEdit.setPlainText(self.output) def call_tailsconfig(self): @@ -260,7 +267,7 @@ def call_tailsconfig(self): self.failure_reason = strings.missing_sudo_password self.on_failure() return - self.tails_thread.sudo_password = sudo_password + '\n' + self.tails_thread.sudo_password = sudo_password + "\n" self.update_status_bar_and_output(strings.updating_tails_env) self.tails_thread.start() else: @@ -268,9 +275,9 @@ def call_tailsconfig(self): def tails_status(self, result): "This is the slot for Tailsconfig thread" - self.output += result['output'] - self.update_success = result['status'] - self.failure_reason = result['failure_reason'] + self.output += result["output"] + self.update_success = result["status"] + self.failure_reason = result["failure_reason"] self.plainTextEdit.setPlainText(self.output) self.progressBar.setProperty("value", 80) if self.update_success: @@ -319,8 +326,12 @@ def alert_failure(self, failure_reason): def get_sudo_password(self): sudo_password, ok_is_pressed = QtWidgets.QInputDialog.getText( - self, "Tails Administrator password", strings.sudo_password_text, - QtWidgets.QLineEdit.Password, "") + self, + "Tails Administrator password", + strings.sudo_password_text, + QtWidgets.QLineEdit.Password, + "", + ) if ok_is_pressed and sudo_password: return sudo_password else: diff --git a/journalist_gui/journalist_gui/resources_rc.py b/journalist_gui/journalist_gui/resources_rc.py --- a/journalist_gui/journalist_gui/resources_rc.py +++ b/journalist_gui/journalist_gui/resources_rc.py @@ -1013,18 +1013,25 @@ \x00\x00\x01\x6d\x2b\x7b\x43\xf7\ " -qt_version = QtCore.qVersion().split('.') -if qt_version < ['5', '8', '0']: +qt_version = QtCore.qVersion().split(".") +if qt_version < ["5", "8", "0"]: rcc_version = 1 qt_resource_struct = qt_resource_struct_v1 else: rcc_version = 2 qt_resource_struct = qt_resource_struct_v2 + def qInitResources(): - QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + QtCore.qRegisterResourceData( + rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data + ) + def qCleanupResources(): - QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + QtCore.qUnregisterResourceData( + rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data + ) + qInitResources() diff --git a/journalist_gui/journalist_gui/strings.py b/journalist_gui/journalist_gui/strings.py --- a/journalist_gui/journalist_gui/strings.py +++ b/journalist_gui/journalist_gui/strings.py @@ -1,51 +1,59 @@ -window_title = 'SecureDrop Workstation Updater' -update_in_progress = ("SecureDrop workstation updates are available! " - "It is recommended to install them now. \n\n" - "If you don\'t want to install them now, " - "you can install them the next time you reboot.\n\n" - "You will need to have set a Tails Administration " - "password in " - "the Tails Greeter on boot to complete the update.\n\n" - "When you start your workstation, this window will " - "automatically appear if you have not " - "completed any required updates.\n") -fetching_update = ('Fetching and verifying latest update...' - ' (5 mins remaining)') -updating_tails_env = ('Configuring local Tails environment...' - ' (1 min remaining)') -finished = 'Update successfully completed!' -finished_dialog_message = 'Updates completed successfully. ' -finished_dialog_title = 'SecureDrop Workstation is up to date!' -missing_sudo_password = 'Missing Tails Administrator password' -update_failed_dialog_title = 'Error Updating SecureDrop Workstation' -update_failed_generic_reason = ("Update failed. " - "Please contact your SecureDrop " - "administrator.") -update_failed_sig_failure = ("WARNING: Signature verification failed. " - "Contact your SecureDrop administrator " - "or [email protected] immediately.") -tailsconfig_failed_sudo_password = ('Administrator password incorrect. ' - 'Click Update Now to try again.') -tailsconfig_failed_generic_reason = ("Tails workstation configuration failed. " - "Contact your administrator. " - "If you are an administrator, contact " - "[email protected].") -tailsconfig_failed_timeout = ("Tails workstation configuration took too long. " - "Contact your administrator. " - "If you are an administrator, contact " - "[email protected].") -install_update_button = 'Update Now' -install_later_button = 'Update Later' -sudo_password_text = ("Enter the Tails Administrator password you " - "entered in the Tails Greeter.\n If you did not " - "set an Administrator password, click Cancel " - "and reboot. ") -main_tab = 'Updates Available' -output_tab = 'Detailed Update Progress' -initial_text_box = ("When the update begins, this area will populate with " - "output.\n") +window_title = "SecureDrop Workstation Updater" +update_in_progress = ( + "SecureDrop workstation updates are available! " + "It is recommended to install them now. \n\n" + "If you don't want to install them now, " + "you can install them the next time you reboot.\n\n" + "You will need to have set a Tails Administration " + "password in " + "the Tails Greeter on boot to complete the update.\n\n" + "When you start your workstation, this window will " + "automatically appear if you have not " + "completed any required updates.\n" +) +fetching_update = "Fetching and verifying latest update..." " (5 mins remaining)" +updating_tails_env = "Configuring local Tails environment..." " (1 min remaining)" +finished = "Update successfully completed!" +finished_dialog_message = "Updates completed successfully. " +finished_dialog_title = "SecureDrop Workstation is up to date!" +missing_sudo_password = "Missing Tails Administrator password" +update_failed_dialog_title = "Error Updating SecureDrop Workstation" +update_failed_generic_reason = "Update failed. " "Please contact your SecureDrop " "administrator." +update_failed_sig_failure = ( + "WARNING: Signature verification failed. " + "Contact your SecureDrop administrator " + "or [email protected] immediately." +) +tailsconfig_failed_sudo_password = ( + "Administrator password incorrect. " "Click Update Now to try again." +) +tailsconfig_failed_generic_reason = ( + "Tails workstation configuration failed. " + "Contact your administrator. " + "If you are an administrator, contact " + "[email protected]." +) +tailsconfig_failed_timeout = ( + "Tails workstation configuration took too long. " + "Contact your administrator. " + "If you are an administrator, contact " + "[email protected]." +) +install_update_button = "Update Now" +install_later_button = "Update Later" +sudo_password_text = ( + "Enter the Tails Administrator password you " + "entered in the Tails Greeter.\n If you did not " + "set an Administrator password, click Cancel " + "and reboot. " +) +main_tab = "Updates Available" +output_tab = "Detailed Update Progress" +initial_text_box = "When the update begins, this area will populate with " "output.\n" doing_setup = "Checking dependencies are up to date... (2 mins remaining)" -no_password_set_message = ("The Tails Administration Password was not set.\n\n" - "Please reboot and set a password before updating " - "SecureDrop.") +no_password_set_message = ( + "The Tails Administration Password was not set.\n\n" + "Please reboot and set a password before updating " + "SecureDrop." +) app_is_already_running = " is already running." diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -8,14 +8,13 @@ import io import os -import yaml from typing import Any, Dict import testutils - +import yaml # The config tests target staging by default. -target_host = os.environ.get('SECUREDROP_TESTINFRA_TARGET_HOST', 'staging') +target_host = os.environ.get("SECUREDROP_TESTINFRA_TARGET_HOST", "staging") def securedrop_import_testinfra_vars(hostname, with_header=False): @@ -26,43 +25,48 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): Vars must be stored in `testinfra/vars/<hostname>.yml`. """ - filepath = os.path.join(os.path.dirname(__file__), "vars", hostname+".yml") - with io.open(filepath, 'r') as f: + filepath = os.path.join(os.path.dirname(__file__), "vars", hostname + ".yml") + with io.open(filepath, "r") as f: hostvars = yaml.safe_load(f) - hostvars['securedrop_venv_site_packages'] = hostvars["securedrop_venv_site_packages"].format("3.8") # noqa: E501 - hostvars['python_version'] = "3.8" - hostvars['apparmor_enforce_actual'] = hostvars['apparmor_enforce']['focal'] + hostvars["securedrop_venv_site_packages"] = hostvars["securedrop_venv_site_packages"].format( + "3.8" + ) # noqa: E501 + hostvars["python_version"] = "3.8" + hostvars["apparmor_enforce_actual"] = hostvars["apparmor_enforce"]["focal"] # If the tests are run against a production environment, check local config # and override as necessary. - prod_filepath = os.path.join(os.path.dirname(__file__), - "../../install_files/ansible-base/group_vars/all/site-specific") + prod_filepath = os.path.join( + os.path.dirname(__file__), "../../install_files/ansible-base/group_vars/all/site-specific" + ) if os.path.isfile(prod_filepath): - with io.open(prod_filepath, 'r') as f: + with io.open(prod_filepath, "r") as f: prodvars = yaml.safe_load(f) def _prod_override(vars_key, prod_key): if prod_key in prodvars: hostvars[vars_key] = prodvars[prod_key] - _prod_override('app_ip', 'app_ip') - _prod_override('app_hostname', 'app_hostname') - _prod_override('mon_ip', 'monitor_ip') - _prod_override('monitor_hostname', 'monitor_hostname') - _prod_override('sasl_domain', 'sasl_domain') - _prod_override('sasl_username', 'sasl_username') - _prod_override('sasl_password', 'sasl_password') - _prod_override('daily_reboot_time', 'daily_reboot_time') + _prod_override("app_ip", "app_ip") + _prod_override("app_hostname", "app_hostname") + _prod_override("mon_ip", "monitor_ip") + _prod_override("monitor_hostname", "monitor_hostname") + _prod_override("sasl_domain", "sasl_domain") + _prod_override("sasl_username", "sasl_username") + _prod_override("sasl_password", "sasl_password") + _prod_override("daily_reboot_time", "daily_reboot_time") # Check repo targeting, and update vars - repo_filepath = os.path.join(os.path.dirname(__file__), - "../../install_files/ansible-base/roles/install-fpf-repo/defaults/main.yml") # noqa: E501 + repo_filepath = os.path.join( + os.path.dirname(__file__), + "../../install_files/ansible-base/roles/install-fpf-repo/defaults/main.yml", + ) # noqa: E501 if os.path.isfile(repo_filepath): - with io.open(repo_filepath, 'r') as f: + with io.open(repo_filepath, "r") as f: repovars = yaml.safe_load(f) - if 'apt_repo_url' in repovars: - hostvars['fpf_apt_repo_url'] = repovars['apt_repo_url'] + if "apt_repo_url" in repovars: + hostvars["fpf_apt_repo_url"] = repovars["apt_repo_url"] if with_header: hostvars = dict(securedrop_test_vars=hostvars) diff --git a/securedrop/alembic/env.py b/securedrop/alembic/env.py --- a/securedrop/alembic/env.py +++ b/securedrop/alembic/env.py @@ -2,18 +2,18 @@ import os import sys +from logging.config import fileConfig +from os import path from alembic import context from sqlalchemy import engine_from_config, pool -from logging.config import fileConfig -from os import path config = context.config fileConfig(config.config_file_name) # needed to import local modules -sys.path.insert(0, path.realpath(path.join(path.dirname(__file__), '..'))) +sys.path.insert(0, path.realpath(path.join(path.dirname(__file__), ".."))) from db import db # noqa try: @@ -26,7 +26,7 @@ create_app(sdconfig).app_context().push() except Exception: # Only reraise the exception in 'dev' where a developer actually cares - if os.environ.get('SECUREDROP_ENV') == 'dev': + if os.environ.get("SECUREDROP_ENV") == "dev": raise @@ -47,7 +47,8 @@ def run_migrations_offline() -> None: """ url = config.get_main_option("sqlalchemy.url") context.configure( - url=url, target_metadata=target_metadata, compare_type=True, literal_binds=True) + url=url, target_metadata=target_metadata, compare_type=True, literal_binds=True + ) with context.begin_transaction(): context.run_migrations() @@ -61,16 +62,15 @@ def run_migrations_online() -> None: """ connectable = engine_from_config( - config.get_section(config.config_ini_section), - prefix='sqlalchemy.', - poolclass=pool.NullPool) + config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool + ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, compare_type=True, - render_as_batch=True + render_as_batch=True, ) with context.begin_transaction(): diff --git a/securedrop/alembic/versions/15ac9509fc68_init.py b/securedrop/alembic/versions/15ac9509fc68_init.py --- a/securedrop/alembic/versions/15ac9509fc68_init.py +++ b/securedrop/alembic/versions/15ac9509fc68_init.py @@ -5,9 +5,8 @@ Create Date: 2018-03-30 21:20:58.280753 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. revision = "15ac9509fc68" diff --git a/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py b/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py --- a/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py +++ b/securedrop/alembic/versions/1ddb81fb88c2_unique_index_for_instanceconfig_valid_.py @@ -5,28 +5,32 @@ Create Date: 2021-06-04 17:28:25.725563 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = '1ddb81fb88c2' -down_revision = 'b060f38c0c31' +revision = "1ddb81fb88c2" +down_revision = "b060f38c0c31" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('instance_config', schema=None) as batch_op: - batch_op.create_index('ix_one_active_instance_config', [sa.text('valid_until IS NULL')], unique=True, sqlite_where=sa.text('valid_until IS NULL')) + with op.batch_alter_table("instance_config", schema=None) as batch_op: + batch_op.create_index( + "ix_one_active_instance_config", + [sa.text("valid_until IS NULL")], + unique=True, + sqlite_where=sa.text("valid_until IS NULL"), + ) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('instance_config', schema=None) as batch_op: - batch_op.drop_index('ix_one_active_instance_config') + with op.batch_alter_table("instance_config", schema=None) as batch_op: + batch_op.drop_index("ix_one_active_instance_config") # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/2d0ce3ee5bdc_added_passphrase_hash_column_to_.py b/securedrop/alembic/versions/2d0ce3ee5bdc_added_passphrase_hash_column_to_.py --- a/securedrop/alembic/versions/2d0ce3ee5bdc_added_passphrase_hash_column_to_.py +++ b/securedrop/alembic/versions/2d0ce3ee5bdc_added_passphrase_hash_column_to_.py @@ -5,9 +5,8 @@ Create Date: 2018-06-08 15:08:37.718268 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. revision = "2d0ce3ee5bdc" diff --git a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py --- a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py +++ b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py @@ -5,13 +5,13 @@ Create Date: 2022-01-12 19:31:06.186285 """ -from passlib.hash import argon2 import os -import pyotp import uuid -from alembic import op +import pyotp import sqlalchemy as sa +from alembic import op +from passlib.hash import argon2 # raise the errors if we're not in production raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" @@ -25,8 +25,8 @@ # revision identifiers, used by Alembic. -revision = '2e24fc7536e8' -down_revision = 'de00920916bf' +revision = "2e24fc7536e8" +down_revision = "de00920916bf" branch_labels = None depends_on = None @@ -44,16 +44,18 @@ def create_deleted() -> int: It should be basically identical to what Journalist.get_deleted() does """ - op.execute(sa.text( - """\ + op.execute( + sa.text( + """\ INSERT INTO journalists (uuid, username, session_nonce, passphrase_hash, otp_secret) VALUES (:uuid, "deleted", 0, :passphrase_hash, :otp_secret); """ - ).bindparams( - uuid=str(uuid.uuid4()), - passphrase_hash=generate_passphrase_hash(), - otp_secret=pyotp.random_base32(), - )) + ).bindparams( + uuid=str(uuid.uuid4()), + passphrase_hash=generate_passphrase_hash(), + otp_secret=pyotp.random_base32(), + ) + ) # Get the autoincrement ID back conn = op.get_bind() result = conn.execute('SELECT id FROM journalists WHERE username="deleted";').fetchall() @@ -65,11 +67,13 @@ def migrate_nulls() -> None: op.execute("DELETE FROM journalist_login_attempt WHERE journalist_id IS NULL;") op.execute("DELETE FROM revoked_tokens WHERE journalist_id IS NULL;") # Look to see if we have data to migrate - tables = ('replies', 'seen_files', 'seen_messages', 'seen_replies') + tables = ("replies", "seen_files", "seen_messages", "seen_replies") needs_migration = [] conn = op.get_bind() for table in tables: - result = conn.execute(f'SELECT 1 FROM {table} WHERE journalist_id IS NULL;').first() # nosec + result = conn.execute( # nosec + f"SELECT 1 FROM {table} WHERE journalist_id IS NULL;" + ).first() if result is not None: needs_migration.append(table) @@ -83,76 +87,54 @@ def migrate_nulls() -> None: # do this update in two passes. # First we update as many rows to point to the deleted journalist as possible, ignoring any # unique key violations. - op.execute(sa.text( - f'UPDATE OR IGNORE {table} SET journalist_id=:journalist_id WHERE journalist_id IS NULL;' - ).bindparams(journalist_id=deleted_id)) + op.execute( + sa.text( + f"UPDATE OR IGNORE {table} SET journalist_id=:journalist_id WHERE journalist_id IS NULL;" + ).bindparams(journalist_id=deleted_id) + ) # Then we delete any leftovers which had been ignored earlier. - op.execute(f'DELETE FROM {table} WHERE journalist_id IS NULL') # nosec + op.execute(f"DELETE FROM {table} WHERE journalist_id IS NULL") # nosec def upgrade() -> None: migrate_nulls() - with op.batch_alter_table('journalist_login_attempt', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=False) + with op.batch_alter_table("journalist_login_attempt", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=False) - with op.batch_alter_table('replies', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=False) + with op.batch_alter_table("replies", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=False) - with op.batch_alter_table('revoked_tokens', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=False) + with op.batch_alter_table("revoked_tokens", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=False) - with op.batch_alter_table('seen_files', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=False) + with op.batch_alter_table("seen_files", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=False) - with op.batch_alter_table('seen_messages', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=False) + with op.batch_alter_table("seen_messages", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=False) - with op.batch_alter_table('seen_replies', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=False) + with op.batch_alter_table("seen_replies", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=False) def downgrade() -> None: # We do not un-migrate the data back to journalist_id=NULL - with op.batch_alter_table('seen_replies', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=True) - - with op.batch_alter_table('seen_messages', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=True) - - with op.batch_alter_table('seen_files', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=True) - - with op.batch_alter_table('revoked_tokens', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=True) - - with op.batch_alter_table('replies', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=True) - - with op.batch_alter_table('journalist_login_attempt', schema=None) as batch_op: - batch_op.alter_column('journalist_id', - existing_type=sa.INTEGER(), - nullable=True) + with op.batch_alter_table("seen_replies", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=True) + + with op.batch_alter_table("seen_messages", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=True) + + with op.batch_alter_table("seen_files", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=True) + + with op.batch_alter_table("revoked_tokens", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=True) + + with op.batch_alter_table("replies", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=True) + + with op.batch_alter_table("journalist_login_attempt", schema=None) as batch_op: + batch_op.alter_column("journalist_id", existing_type=sa.INTEGER(), nullable=True) diff --git a/securedrop/alembic/versions/35513370ba0d_add_source_deleted_at.py b/securedrop/alembic/versions/35513370ba0d_add_source_deleted_at.py --- a/securedrop/alembic/versions/35513370ba0d_add_source_deleted_at.py +++ b/securedrop/alembic/versions/35513370ba0d_add_source_deleted_at.py @@ -5,28 +5,27 @@ Create Date: 2020-05-06 22:28:01.214359 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = '35513370ba0d' -down_revision = '523fff3f969c' +revision = "35513370ba0d" +down_revision = "523fff3f969c" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('sources', schema=None) as batch_op: - batch_op.add_column(sa.Column('deleted_at', sa.DateTime(), nullable=True)) + with op.batch_alter_table("sources", schema=None) as batch_op: + batch_op.add_column(sa.Column("deleted_at", sa.DateTime(), nullable=True)) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('sources', schema=None) as batch_op: - batch_op.drop_column('deleted_at') + with op.batch_alter_table("sources", schema=None) as batch_op: + batch_op.drop_column("deleted_at") # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/3d91d6948753_create_source_uuid_column.py b/securedrop/alembic/versions/3d91d6948753_create_source_uuid_column.py --- a/securedrop/alembic/versions/3d91d6948753_create_source_uuid_column.py +++ b/securedrop/alembic/versions/3d91d6948753_create_source_uuid_column.py @@ -5,10 +5,11 @@ Create Date: 2018-07-09 22:39:05.088008 """ -from alembic import op -import sqlalchemy as sa import uuid +import sqlalchemy as sa +from alembic import op + # revision identifiers, used by Alembic. revision = "3d91d6948753" down_revision = "faac8092c123" diff --git a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py --- a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py +++ b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py @@ -8,8 +8,9 @@ """ import os -from alembic import op + import sqlalchemy as sa +from alembic import op # raise the errors if we're not in production raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" @@ -17,15 +18,15 @@ try: from journalist_app import create_app from sdconfig import config - from store import NoFileFoundException, TooManyFilesException, Storage + from store import NoFileFoundException, Storage, TooManyFilesException except ImportError: # This is a fresh install, and config.py has not been created yet. if raise_errors: raise # revision identifiers, used by Alembic. -revision = '3da3fcab826a' -down_revision = '60f41bb14d98' +revision = "3da3fcab826a" +down_revision = "60f41bb14d98" branch_labels = None depends_on = None @@ -33,21 +34,19 @@ def raw_sql_grab_orphaned_objects(table_name: str) -> str: """Objects that have a source ID that doesn't exist in the sources table OR a NULL source ID should be deleted.""" - return ('SELECT id, filename, source_id FROM {table} ' # nosec - 'WHERE source_id NOT IN (SELECT id FROM sources) ' - 'UNION SELECT id, filename, source_id FROM {table} ' # nosec - 'WHERE source_id IS NULL').format(table=table_name) + return ( + "SELECT id, filename, source_id FROM {table} " # nosec + "WHERE source_id NOT IN (SELECT id FROM sources) " + "UNION SELECT id, filename, source_id FROM {table} " # nosec + "WHERE source_id IS NULL" + ).format(table=table_name) def upgrade() -> None: conn = op.get_bind() - submissions = conn.execute( - sa.text(raw_sql_grab_orphaned_objects('submissions')) - ).fetchall() + submissions = conn.execute(sa.text(raw_sql_grab_orphaned_objects("submissions"))).fetchall() - replies = conn.execute( - sa.text(raw_sql_grab_orphaned_objects('replies')) - ).fetchall() + replies = conn.execute(sa.text(raw_sql_grab_orphaned_objects("replies"))).fetchall() try: app = create_app(config) @@ -55,10 +54,12 @@ def upgrade() -> None: for submission in submissions: try: conn.execute( - sa.text(""" + sa.text( + """ DELETE FROM submissions WHERE id=:id - """).bindparams(id=submission.id) + """ + ).bindparams(id=submission.id) ) path = Storage.get_default().path_without_filesystem_id(submission.filename) @@ -66,10 +67,12 @@ def upgrade() -> None: except NoFileFoundException: # The file must have been deleted by the admin, remove the row conn.execute( - sa.text(""" + sa.text( + """ DELETE FROM submissions WHERE id=:id - """).bindparams(id=submission.id) + """ + ).bindparams(id=submission.id) ) except TooManyFilesException: pass @@ -77,10 +80,12 @@ def upgrade() -> None: for reply in replies: try: conn.execute( - sa.text(""" + sa.text( + """ DELETE FROM replies WHERE id=:id - """).bindparams(id=reply.id) + """ + ).bindparams(id=reply.id) ) path = Storage.get_default().path_without_filesystem_id(reply.filename) @@ -88,10 +93,12 @@ def upgrade() -> None: except NoFileFoundException: # The file must have been deleted by the admin, remove the row conn.execute( - sa.text(""" + sa.text( + """ DELETE FROM replies WHERE id=:id - """).bindparams(id=reply.id) + """ + ).bindparams(id=reply.id) ) except TooManyFilesException: pass diff --git a/securedrop/alembic/versions/48a75abc0121_add_seen_tables.py b/securedrop/alembic/versions/48a75abc0121_add_seen_tables.py --- a/securedrop/alembic/versions/48a75abc0121_add_seen_tables.py +++ b/securedrop/alembic/versions/48a75abc0121_add_seen_tables.py @@ -5,9 +5,8 @@ Create Date: 2020-09-15 22:34:50.116403 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. revision = "48a75abc0121" diff --git a/securedrop/alembic/versions/523fff3f969c_add_versioned_instance_config.py b/securedrop/alembic/versions/523fff3f969c_add_versioned_instance_config.py --- a/securedrop/alembic/versions/523fff3f969c_add_versioned_instance_config.py +++ b/securedrop/alembic/versions/523fff3f969c_add_versioned_instance_config.py @@ -5,26 +5,25 @@ Create Date: 2019-11-02 23:06:12.161868 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = '523fff3f969c' -down_revision = '3da3fcab826a' +revision = "523fff3f969c" +down_revision = "3da3fcab826a" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.create_table('instance_config', - sa.Column('version', sa.Integer(), nullable=False), - sa.Column('valid_until', sa.DateTime(), nullable=True), - sa.Column('allow_document_uploads', sa.Boolean(), nullable=True), - - sa.PrimaryKeyConstraint('version'), - sa.UniqueConstraint('valid_until'), + op.create_table( + "instance_config", + sa.Column("version", sa.Integer(), nullable=False), + sa.Column("valid_until", sa.DateTime(), nullable=True), + sa.Column("allow_document_uploads", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("version"), + sa.UniqueConstraint("valid_until"), ) # ### end Alembic commands ### @@ -37,5 +36,5 @@ def upgrade() -> None: def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('instance_config') + op.drop_table("instance_config") # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/60f41bb14d98_add_session_nonce_to_journalist.py b/securedrop/alembic/versions/60f41bb14d98_add_session_nonce_to_journalist.py --- a/securedrop/alembic/versions/60f41bb14d98_add_session_nonce_to_journalist.py +++ b/securedrop/alembic/versions/60f41bb14d98_add_session_nonce_to_journalist.py @@ -5,13 +5,12 @@ Create Date: 2019-08-19 04:20:59.489516 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = '60f41bb14d98' -down_revision = 'a9fe328b053a' +revision = "60f41bb14d98" +down_revision = "a9fe328b053a" branch_labels = None depends_on = None @@ -20,59 +19,63 @@ def upgrade() -> None: conn = op.get_bind() conn.execute("PRAGMA legacy_alter_table=ON") # Save existing journalist table. - op.rename_table('journalists', 'journalists_tmp') + op.rename_table("journalists", "journalists_tmp") # Add nonce column. - op.add_column('journalists_tmp', sa.Column('session_nonce', sa.Integer())) + op.add_column("journalists_tmp", sa.Column("session_nonce", sa.Integer())) # Populate nonce column. - journalists = conn.execute( - sa.text("SELECT * FROM journalists_tmp")).fetchall() + journalists = conn.execute(sa.text("SELECT * FROM journalists_tmp")).fetchall() for journalist in journalists: conn.execute( - sa.text("""UPDATE journalists_tmp SET session_nonce=0 WHERE - id=:id""").bindparams(id=journalist.id) - ) + sa.text( + """UPDATE journalists_tmp SET session_nonce=0 WHERE + id=:id""" + ).bindparams(id=journalist.id) + ) # Now create new table with null constraint applied. - op.create_table('journalists', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('uuid', sa.String(length=36), nullable=False), - sa.Column('username', sa.String(length=255), nullable=False), - sa.Column('first_name', sa.String(length=255), nullable=True), - sa.Column('last_name', sa.String(length=255), nullable=True), - sa.Column('pw_salt', sa.Binary(), nullable=True), - sa.Column('pw_hash', sa.Binary(), nullable=True), - sa.Column('passphrase_hash', sa.String(length=256), nullable=True), - sa.Column('is_admin', sa.Boolean(), nullable=True), - sa.Column('session_nonce', sa.Integer(), nullable=False), - sa.Column('otp_secret', sa.String(length=16), nullable=True), - sa.Column('is_totp', sa.Boolean(), nullable=True), - sa.Column('hotp_counter', sa.Integer(), nullable=True), - sa.Column('last_token', sa.String(length=6), nullable=True), - sa.Column('created_on', sa.DateTime(), nullable=True), - sa.Column('last_access', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id'), - sa.UniqueConstraint('username'), - sa.UniqueConstraint('uuid') + op.create_table( + "journalists", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("uuid", sa.String(length=36), nullable=False), + sa.Column("username", sa.String(length=255), nullable=False), + sa.Column("first_name", sa.String(length=255), nullable=True), + sa.Column("last_name", sa.String(length=255), nullable=True), + sa.Column("pw_salt", sa.Binary(), nullable=True), + sa.Column("pw_hash", sa.Binary(), nullable=True), + sa.Column("passphrase_hash", sa.String(length=256), nullable=True), + sa.Column("is_admin", sa.Boolean(), nullable=True), + sa.Column("session_nonce", sa.Integer(), nullable=False), + sa.Column("otp_secret", sa.String(length=16), nullable=True), + sa.Column("is_totp", sa.Boolean(), nullable=True), + sa.Column("hotp_counter", sa.Integer(), nullable=True), + sa.Column("last_token", sa.String(length=6), nullable=True), + sa.Column("created_on", sa.DateTime(), nullable=True), + sa.Column("last_access", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("username"), + sa.UniqueConstraint("uuid"), ) - conn.execute(''' + conn.execute( + """ INSERT INTO journalists SELECT id, uuid, username, first_name, last_name, pw_salt, pw_hash, passphrase_hash, is_admin, session_nonce, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access FROM journalists_tmp - ''') + """ + ) # Now delete the old table. - op.drop_table('journalists_tmp') + op.drop_table("journalists_tmp") def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('journalists', schema=None) as batch_op: - batch_op.drop_column('session_nonce') + with op.batch_alter_table("journalists", schema=None) as batch_op: + batch_op.drop_column("session_nonce") # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/6db892e17271_add_reply_uuid.py b/securedrop/alembic/versions/6db892e17271_add_reply_uuid.py --- a/securedrop/alembic/versions/6db892e17271_add_reply_uuid.py +++ b/securedrop/alembic/versions/6db892e17271_add_reply_uuid.py @@ -5,11 +5,11 @@ Create Date: 2018-08-06 20:31:50.035066 """ -from alembic import op -import sqlalchemy as sa - import uuid +import sqlalchemy as sa +from alembic import op + # revision identifiers, used by Alembic. revision = "6db892e17271" down_revision = "e0a525cbab83" diff --git a/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py b/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py --- a/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py +++ b/securedrop/alembic/versions/92fba0be98e9_added_organization_name_field_in_.py @@ -5,28 +5,27 @@ Create Date: 2020-11-15 19:36:20.351993 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = '92fba0be98e9' -down_revision = '48a75abc0121' +revision = "92fba0be98e9" +down_revision = "48a75abc0121" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('instance_config', schema=None) as batch_op: - batch_op.add_column(sa.Column('organization_name', sa.String(length=255), nullable=True)) + with op.batch_alter_table("instance_config", schema=None) as batch_op: + batch_op.add_column(sa.Column("organization_name", sa.String(length=255), nullable=True)) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('instance_config', schema=None) as batch_op: - batch_op.drop_column('organization_name') + with op.batch_alter_table("instance_config", schema=None) as batch_op: + batch_op.drop_column("organization_name") # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/a9fe328b053a_migrations_for_0_14_0.py b/securedrop/alembic/versions/a9fe328b053a_migrations_for_0_14_0.py --- a/securedrop/alembic/versions/a9fe328b053a_migrations_for_0_14_0.py +++ b/securedrop/alembic/versions/a9fe328b053a_migrations_for_0_14_0.py @@ -5,24 +5,23 @@ Create Date: 2019-05-21 20:23:30.005632 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = 'a9fe328b053a' -down_revision = 'b58139cfdc8c' +revision = "a9fe328b053a" +down_revision = "b58139cfdc8c" branch_labels = None depends_on = None def upgrade() -> None: - with op.batch_alter_table('journalists', schema=None) as batch_op: - batch_op.add_column(sa.Column('first_name', sa.String(length=255), nullable=True)) - batch_op.add_column(sa.Column('last_name', sa.String(length=255), nullable=True)) + with op.batch_alter_table("journalists", schema=None) as batch_op: + batch_op.add_column(sa.Column("first_name", sa.String(length=255), nullable=True)) + batch_op.add_column(sa.Column("last_name", sa.String(length=255), nullable=True)) def downgrade() -> None: - with op.batch_alter_table('journalists', schema=None) as batch_op: - batch_op.drop_column('last_name') - batch_op.drop_column('first_name') + with op.batch_alter_table("journalists", schema=None) as batch_op: + batch_op.drop_column("last_name") + batch_op.drop_column("first_name") diff --git a/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py b/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py --- a/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py +++ b/securedrop/alembic/versions/b060f38c0c31_drop_source_flagged.py @@ -5,9 +5,8 @@ Create Date: 2021-05-10 18:15:56.071880 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. revision = "b060f38c0c31" diff --git a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py --- a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py +++ b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py @@ -4,17 +4,18 @@ Create Date: 2019-04-02 10:45:05.178481 """ import os -from alembic import op + import sqlalchemy as sa +from alembic import op # raise the errors if we're not in production raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" try: from journalist_app import create_app - from models import Submission, Reply + from models import Reply, Submission from sdconfig import config - from store import queued_add_checksum_for_file, Storage + from store import Storage, queued_add_checksum_for_file from worker import create_queue except: # noqa if raise_errors: diff --git a/securedrop/alembic/versions/b7f98cfd6a70_make_filesystem_id_non_nullable.py b/securedrop/alembic/versions/b7f98cfd6a70_make_filesystem_id_non_nullable.py --- a/securedrop/alembic/versions/b7f98cfd6a70_make_filesystem_id_non_nullable.py +++ b/securedrop/alembic/versions/b7f98cfd6a70_make_filesystem_id_non_nullable.py @@ -5,13 +5,12 @@ Create Date: 2022-03-18 18:10:27.842201 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = 'b7f98cfd6a70' -down_revision = 'd9d36b6f4d1e' +revision = "b7f98cfd6a70" +down_revision = "d9d36b6f4d1e" branch_labels = None depends_on = None @@ -22,37 +21,36 @@ def upgrade() -> None: # Because we can't rely on SQLAlchemy's cascade deletion, we have to do it manually. # First we delete out of replies/seen_files/seen_messages (things that refer to things that refer # to sources) - op.execute("DELETE FROM seen_replies WHERE reply_id IN (" - "SELECT replies.id FROM replies " - "JOIN sources ON sources.id=replies.source_id " - "WHERE filesystem_id IS NULL)") - op.execute("DELETE FROM seen_files WHERE file_id IN (" - "SELECT submissions.id FROM submissions " - "JOIN sources ON sources.id=submissions.source_id " - "WHERE filesystem_id IS NULL)") - op.execute("DELETE FROM seen_messages WHERE message_id IN (" - "SELECT submissions.id FROM submissions " - "JOIN sources ON sources.id=submissions.source_id " - "WHERE filesystem_id IS NULL)") + op.execute( + "DELETE FROM seen_replies WHERE reply_id IN (" + "SELECT replies.id FROM replies " + "JOIN sources ON sources.id=replies.source_id " + "WHERE filesystem_id IS NULL)" + ) + op.execute( + "DELETE FROM seen_files WHERE file_id IN (" + "SELECT submissions.id FROM submissions " + "JOIN sources ON sources.id=submissions.source_id " + "WHERE filesystem_id IS NULL)" + ) + op.execute( + "DELETE FROM seen_messages WHERE message_id IN (" + "SELECT submissions.id FROM submissions " + "JOIN sources ON sources.id=submissions.source_id " + "WHERE filesystem_id IS NULL)" + ) # Now things that directly refer to sources for table in ("source_stars", "submissions", "replies"): op.execute( f"DELETE FROM {table} WHERE source_id IN " # nosec - f"(SELECT id FROM sources WHERE filesystem_id IS NULL)") # nosec + f"(SELECT id FROM sources WHERE filesystem_id IS NULL)" + ) # nosec # And now the sources op.execute("DELETE FROM sources WHERE filesystem_id IS NULL") - with op.batch_alter_table('sources', schema=None) as batch_op: - batch_op.alter_column( - 'filesystem_id', - existing_type=sa.VARCHAR(length=96), - nullable=False - ) + with op.batch_alter_table("sources", schema=None) as batch_op: + batch_op.alter_column("filesystem_id", existing_type=sa.VARCHAR(length=96), nullable=False) def downgrade() -> None: - with op.batch_alter_table('sources', schema=None) as batch_op: - batch_op.alter_column( - 'filesystem_id', - existing_type=sa.VARCHAR(length=96), - nullable=True - ) + with op.batch_alter_table("sources", schema=None) as batch_op: + batch_op.alter_column("filesystem_id", existing_type=sa.VARCHAR(length=96), nullable=True) diff --git a/securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py b/securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py --- a/securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py +++ b/securedrop/alembic/versions/d9d36b6f4d1e_remove_partial_index_on_valid_until_set_.py @@ -5,14 +5,14 @@ Create Date: 2022-03-16 17:31:28.408112 """ -from alembic import op -import sqlalchemy as sa - from datetime import datetime +import sqlalchemy as sa +from alembic import op + # revision identifiers, used by Alembic. -revision = 'd9d36b6f4d1e' -down_revision = '2e24fc7536e8' +revision = "d9d36b6f4d1e" +down_revision = "2e24fc7536e8" branch_labels = None depends_on = None @@ -20,55 +20,54 @@ def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### # remove the old partial index on valid_until, as alembic can't handle it. - op.execute(sa.text('DROP INDEX IF EXISTS ix_one_active_instance_config')) + op.execute(sa.text("DROP INDEX IF EXISTS ix_one_active_instance_config")) # valid_until will be non-nullable after batch, so set existing nulls to # the new default unix epoch datetime - op.execute(sa.text( - 'UPDATE OR IGNORE instance_config SET ' - 'valid_until=:epoch WHERE valid_until IS NULL;' - ).bindparams(epoch=datetime.fromtimestamp(0))) + op.execute( + sa.text( + "UPDATE OR IGNORE instance_config SET " "valid_until=:epoch WHERE valid_until IS NULL;" + ).bindparams(epoch=datetime.fromtimestamp(0)) + ) # add new columns with default values - with op.batch_alter_table('instance_config', schema=None) as batch_op: - batch_op.add_column(sa.Column('initial_message_min_len', - sa.Integer(), - nullable=False, - server_default="0")) - batch_op.add_column(sa.Column('reject_message_with_codename', - sa.Boolean(), - nullable=False, - server_default="0")) - batch_op.alter_column('valid_until', - existing_type=sa.DATETIME(), - nullable=False) + with op.batch_alter_table("instance_config", schema=None) as batch_op: + batch_op.add_column( + sa.Column("initial_message_min_len", sa.Integer(), nullable=False, server_default="0") + ) + batch_op.add_column( + sa.Column( + "reject_message_with_codename", sa.Boolean(), nullable=False, server_default="0" + ) + ) + batch_op.alter_column("valid_until", existing_type=sa.DATETIME(), nullable=False) # remove the old partial index *again* in case the batch op recreated it. - op.execute(sa.text('DROP INDEX IF EXISTS ix_one_active_instance_config')) - + op.execute(sa.text("DROP INDEX IF EXISTS ix_one_active_instance_config")) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('instance_config', schema=None) as batch_op: - batch_op.alter_column('valid_until', - existing_type=sa.DATETIME(), - nullable=True) - batch_op.drop_column('reject_message_with_codename') - batch_op.drop_column('initial_message_min_len') - + with op.batch_alter_table("instance_config", schema=None) as batch_op: + batch_op.alter_column("valid_until", existing_type=sa.DATETIME(), nullable=True) + batch_op.drop_column("reject_message_with_codename") + batch_op.drop_column("initial_message_min_len") # valid_until is nullable again, set entries with unix epoch datetime value to NULL - op.execute(sa.text( - 'UPDATE OR IGNORE instance_config SET ' - 'valid_until = NULL WHERE valid_until=:epoch;' - ).bindparams(epoch=datetime.fromtimestamp(0))) + op.execute( + sa.text( + "UPDATE OR IGNORE instance_config SET " "valid_until = NULL WHERE valid_until=:epoch;" + ).bindparams(epoch=datetime.fromtimestamp(0)) + ) # manually restore the partial index - op.execute(sa.text('CREATE UNIQUE INDEX IF NOT EXISTS ix_one_active_instance_config ON ' - 'instance_config (valid_until IS NULL) WHERE valid_until IS NULL')) - + op.execute( + sa.text( + "CREATE UNIQUE INDEX IF NOT EXISTS ix_one_active_instance_config ON " + "instance_config (valid_until IS NULL) WHERE valid_until IS NULL" + ) + ) # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py b/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py --- a/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py +++ b/securedrop/alembic/versions/de00920916bf_updates_journalists_otp_secret_length_.py @@ -5,34 +5,37 @@ Create Date: 2021-05-21 15:51:39.202368 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = 'de00920916bf' -down_revision = '1ddb81fb88c2' +revision = "de00920916bf" +down_revision = "1ddb81fb88c2" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('journalists', schema=None) as batch_op: - batch_op.alter_column('otp_secret', - existing_type=sa.VARCHAR(length=16), - type_=sa.String(length=32), - existing_nullable=True) + with op.batch_alter_table("journalists", schema=None) as batch_op: + batch_op.alter_column( + "otp_secret", + existing_type=sa.VARCHAR(length=16), + type_=sa.String(length=32), + existing_nullable=True, + ) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('journalists', schema=None) as batch_op: - batch_op.alter_column('otp_secret', - existing_type=sa.String(length=32), - type_=sa.VARCHAR(length=16), - existing_nullable=True) + with op.batch_alter_table("journalists", schema=None) as batch_op: + batch_op.alter_column( + "otp_secret", + existing_type=sa.String(length=32), + type_=sa.VARCHAR(length=16), + existing_nullable=True, + ) # ### end Alembic commands ### diff --git a/securedrop/alembic/versions/e0a525cbab83_add_column_to_track_source_deletion_of_.py b/securedrop/alembic/versions/e0a525cbab83_add_column_to_track_source_deletion_of_.py --- a/securedrop/alembic/versions/e0a525cbab83_add_column_to_track_source_deletion_of_.py +++ b/securedrop/alembic/versions/e0a525cbab83_add_column_to_track_source_deletion_of_.py @@ -5,9 +5,8 @@ Create Date: 2018-08-02 00:07:59.242510 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. revision = "e0a525cbab83" diff --git a/securedrop/alembic/versions/f2833ac34bb6_add_uuid_column_for_users_table.py b/securedrop/alembic/versions/f2833ac34bb6_add_uuid_column_for_users_table.py --- a/securedrop/alembic/versions/f2833ac34bb6_add_uuid_column_for_users_table.py +++ b/securedrop/alembic/versions/f2833ac34bb6_add_uuid_column_for_users_table.py @@ -5,10 +5,10 @@ Create Date: 2018-08-13 18:10:19.914274 """ -from alembic import op -import sqlalchemy as sa import uuid +import sqlalchemy as sa +from alembic import op # revision identifiers, used by Alembic. revision = "f2833ac34bb6" diff --git a/securedrop/alembic/versions/faac8092c123_enable_security_pragmas.py b/securedrop/alembic/versions/faac8092c123_enable_security_pragmas.py --- a/securedrop/alembic/versions/faac8092c123_enable_security_pragmas.py +++ b/securedrop/alembic/versions/faac8092c123_enable_security_pragmas.py @@ -5,21 +5,20 @@ Create Date: 2018-03-31 10:44:26.533395 """ -from alembic import op import sqlalchemy as sa - +from alembic import op # revision identifiers, used by Alembic. -revision = 'faac8092c123' -down_revision = '15ac9509fc68' +revision = "faac8092c123" +down_revision = "15ac9509fc68" branch_labels = None depends_on = None def upgrade() -> None: conn = op.get_bind() - conn.execute(sa.text('PRAGMA secure_delete = ON')) - conn.execute(sa.text('PRAGMA auto_vacuum = FULL')) + conn.execute(sa.text("PRAGMA secure_delete = ON")) + conn.execute(sa.text("PRAGMA auto_vacuum = FULL")) def downgrade() -> None: diff --git a/securedrop/alembic/versions/fccf57ceef02_create_submission_uuid_column.py b/securedrop/alembic/versions/fccf57ceef02_create_submission_uuid_column.py --- a/securedrop/alembic/versions/fccf57ceef02_create_submission_uuid_column.py +++ b/securedrop/alembic/versions/fccf57ceef02_create_submission_uuid_column.py @@ -5,11 +5,11 @@ Create Date: 2018-07-12 00:06:20.891213 """ -from alembic import op -import sqlalchemy as sa - import uuid +import sqlalchemy as sa +from alembic import op + # revision identifiers, used by Alembic. revision = "fccf57ceef02" down_revision = "3d91d6948753" diff --git a/securedrop/encryption.py b/securedrop/encryption.py --- a/securedrop/encryption.py +++ b/securedrop/encryption.py @@ -1,17 +1,15 @@ +import os +import re import typing +from datetime import date from distutils.version import StrictVersion -from io import StringIO, BytesIO +from io import BytesIO, StringIO from pathlib import Path -from typing import Optional, Dict, List +from typing import Dict, List, Optional import pretty_bad_protocol as gnupg -import os -import re - -from datetime import date from redis import Redis - if typing.TYPE_CHECKING: from source_user import SourceUser @@ -94,16 +92,14 @@ def __init__(self, gpg_key_dir: Path, journalist_key_fingerprint: str) -> None: # Instantiate the "main" GPG binary gpg = gnupg.GPG( - binary="gpg2", - homedir=str(self._gpg_key_dir), - options=["--trust-model direct"] + binary="gpg2", homedir=str(self._gpg_key_dir), options=["--trust-model direct"] ) if StrictVersion(gpg.binary_version) >= StrictVersion("2.1"): # --pinentry-mode, required for SecureDrop on GPG 2.1.x+, was added in GPG 2.1. self._gpg = gnupg.GPG( binary="gpg2", homedir=str(gpg_key_dir), - options=["--pinentry-mode loopback", "--trust-model direct"] + options=["--pinentry-mode loopback", "--trust-model direct"], ) else: self._gpg = gpg @@ -112,9 +108,7 @@ def __init__(self, gpg_key_dir: Path, journalist_key_fingerprint: str) -> None: # invoking pinentry-mode=loopback # see: https://lists.gnupg.org/pipermail/gnupg-users/2016-May/055965.html self._gpg_for_key_deletion = gnupg.GPG( - binary="gpg2", - homedir=str(self._gpg_key_dir), - options=["--yes", "--trust-model direct"] + binary="gpg2", homedir=str(self._gpg_key_dir), options=["--yes", "--trust-model direct"] ) # Ensure that the journalist public key has been previously imported in GPG diff --git a/securedrop/execution.py b/securedrop/execution.py --- a/securedrop/execution.py +++ b/securedrop/execution.py @@ -1,11 +1,13 @@ from threading import Thread -def asynchronous(f): # type: ignore +def asynchronous(f): # type: ignore """ Wraps a """ + def wrapper(*args, **kwargs): # type: ignore thread = Thread(target=f, args=args, kwargs=kwargs) thread.start() + return wrapper diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -16,7 +16,6 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import collections - from typing import List, Set from babel.core import ( @@ -28,8 +27,7 @@ ) from flask import Flask, g, request, session from flask_babel import Babel - -from sdconfig import SDConfig, FALLBACK_LOCALE +from sdconfig import FALLBACK_LOCALE, SDConfig class RequestLocaleInfo: @@ -150,13 +148,13 @@ def validate_locale_configuration(config: SDConfig, babel: Babel) -> None: missing = configured - usable if missing: babel.app.logger.error( - f'Configured locales {missing} are not in the set of usable locales {usable}' + f"Configured locales {missing} are not in the set of usable locales {usable}" ) defaults = parse_locale_set([config.DEFAULT_LOCALE, FALLBACK_LOCALE]) if not defaults & usable: raise ValueError( - f'None of the default locales {defaults} are in the set of usable locales {usable}' + f"None of the default locales {defaults} are in the set of usable locales {usable}" ) global USABLE_LOCALES @@ -250,9 +248,7 @@ def get_accepted_languages() -> List[str]: # at least be more legible at first contact than the # probable default locale of English. if parsed.language == "zh" and parsed.script: - accept_languages.append( - str(Locale(language=parsed.language, script=parsed.script)) - ) + accept_languages.append(str(Locale(language=parsed.language, script=parsed.script))) except (ValueError, UnknownLocaleError): pass return accept_languages diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -2,27 +2,23 @@ # -*- coding: utf-8 -*- import argparse +import glob import io import logging import os -import glob import re import signal import subprocess import sys import textwrap from argparse import _SubParsersAction -from typing import Optional -from typing import Set -from typing import List - -import version - from os.path import abspath, dirname, join, realpath +from typing import List, Optional, Set -from sh import git, pybabel, sed, msgmerge, xgettext, msgfmt +import version +from sh import git, msgfmt, msgmerge, pybabel, sed, xgettext -logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s') +logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger(__name__) @@ -38,131 +34,196 @@ class I18NTool: # desktop: The language code used for dekstop icons. # supported_languages = { - 'ar': {'name': 'Arabic', 'desktop': 'ar', }, - 'ca': {'name': 'Catalan', 'desktop': 'ca', }, - 'cs': {'name': 'Czech', 'desktop': 'cs', }, - 'de_DE': {'name': 'German', 'desktop': 'de_DE', }, - 'el': {'name': 'Greek', 'desktop': 'el', }, - 'es_ES': {'name': 'Spanish', 'desktop': 'es_ES', }, - 'fr_FR': {'name': 'French', 'desktop': 'fr', }, - 'hi': {'name': 'Hindi', 'desktop': 'hi', }, - 'is': {'name': 'Icelandic', 'desktop': 'is', }, - 'it_IT': {'name': 'Italian', 'desktop': 'it', }, - 'nb_NO': {'name': 'Norwegian', 'desktop': 'nb_NO', }, - 'nl': {'name': 'Dutch', 'desktop': 'nl', }, - 'pt_BR': {'name': 'Portuguese, Brasil', 'desktop': 'pt_BR', }, - 'pt_PT': {'name': 'Portuguese, Portugal', 'desktop': 'pt_PT', }, - 'ro': {'name': 'Romanian', 'desktop': 'ro', }, - 'ru': {'name': 'Russian', 'desktop': 'ru', }, - 'sk': {'name': 'Slovak', 'desktop': 'sk', }, - 'sv': {'name': 'Swedish', 'desktop': 'sv', }, - 'tr': {'name': 'Turkish', 'desktop': 'tr', }, - 'zh_Hans': {'name': 'Chinese, Simplified', 'desktop': 'zh_Hans', }, - 'zh_Hant': {'name': 'Chinese, Traditional', 'desktop': 'zh_Hant', }, + "ar": { + "name": "Arabic", + "desktop": "ar", + }, + "ca": { + "name": "Catalan", + "desktop": "ca", + }, + "cs": { + "name": "Czech", + "desktop": "cs", + }, + "de_DE": { + "name": "German", + "desktop": "de_DE", + }, + "el": { + "name": "Greek", + "desktop": "el", + }, + "es_ES": { + "name": "Spanish", + "desktop": "es_ES", + }, + "fr_FR": { + "name": "French", + "desktop": "fr", + }, + "hi": { + "name": "Hindi", + "desktop": "hi", + }, + "is": { + "name": "Icelandic", + "desktop": "is", + }, + "it_IT": { + "name": "Italian", + "desktop": "it", + }, + "nb_NO": { + "name": "Norwegian", + "desktop": "nb_NO", + }, + "nl": { + "name": "Dutch", + "desktop": "nl", + }, + "pt_BR": { + "name": "Portuguese, Brasil", + "desktop": "pt_BR", + }, + "pt_PT": { + "name": "Portuguese, Portugal", + "desktop": "pt_PT", + }, + "ro": { + "name": "Romanian", + "desktop": "ro", + }, + "ru": { + "name": "Russian", + "desktop": "ru", + }, + "sk": { + "name": "Slovak", + "desktop": "sk", + }, + "sv": { + "name": "Swedish", + "desktop": "sv", + }, + "tr": { + "name": "Turkish", + "desktop": "tr", + }, + "zh_Hans": { + "name": "Chinese, Simplified", + "desktop": "zh_Hans", + }, + "zh_Hant": { + "name": "Chinese, Traditional", + "desktop": "zh_Hant", + }, } release_tag_re = re.compile(r"^\d+\.\d+\.\d+$") - translated_commit_re = re.compile('Translated using Weblate') - updated_commit_re = re.compile(r'(?:updated from| (?:revision|commit):) (\w+)') + translated_commit_re = re.compile("Translated using Weblate") + updated_commit_re = re.compile(r"(?:updated from| (?:revision|commit):) (\w+)") def file_is_modified(self, path: str) -> bool: - return bool(subprocess.call(['git', '-C', dirname(path), 'diff', '--quiet', path])) + return bool(subprocess.call(["git", "-C", dirname(path), "diff", "--quiet", path])) def ensure_i18n_remote(self, args: argparse.Namespace) -> None: """ Make sure we have a git remote for the i18n repo. """ - k = {'_cwd': args.root} - if b'i18n' not in git.remote(**k).stdout: - git.remote.add('i18n', args.url, **k) - git.fetch('i18n', **k) + k = {"_cwd": args.root} + if b"i18n" not in git.remote(**k).stdout: + git.remote.add("i18n", args.url, **k) + git.fetch("i18n", **k) def translate_messages(self, args: argparse.Namespace) -> None: - messages_file = os.path.join(args.translations_dir, 'messages.pot') + messages_file = os.path.join(args.translations_dir, "messages.pot") if args.extract_update: if not os.path.exists(args.translations_dir): os.makedirs(args.translations_dir) - sources = args.sources.split(',') + sources = args.sources.split(",") pybabel.extract( - '--charset=utf-8', - '--mapping', args.mapping, - '--output', messages_file, - '--project=SecureDrop', - '--version', args.version, + "--charset=utf-8", + "--mapping", + args.mapping, + "--output", + messages_file, + "--project=SecureDrop", + "--version", + args.version, "[email protected]", "--copyright-holder=Freedom of the Press Foundation", "--add-comments=Translators:", "--strip-comments", "--add-location=never", "--no-wrap", - *sources) + *sources + ) - sed('-i', '-e', '/^"POT-Creation-Date/d', messages_file) + sed("-i", "-e", '/^"POT-Creation-Date/d', messages_file) - if (self.file_is_modified(messages_file) and - len(os.listdir(args.translations_dir)) > 1): - tglob = '{}/*/LC_MESSAGES/*.po'.format(args.translations_dir) + if self.file_is_modified(messages_file) and len(os.listdir(args.translations_dir)) > 1: + tglob = "{}/*/LC_MESSAGES/*.po".format(args.translations_dir) for translation in glob.iglob(tglob): - msgmerge( - '--previous', - '--update', - '--no-wrap', - translation, - messages_file - ) - log.warning("messages translations updated in {}".format( - messages_file)) + msgmerge("--previous", "--update", "--no-wrap", translation, messages_file) + log.warning("messages translations updated in {}".format(messages_file)) else: log.warning("messages translations are already up to date") if args.compile and len(os.listdir(args.translations_dir)) > 1: - pybabel.compile('--directory', args.translations_dir) + pybabel.compile("--directory", args.translations_dir) def translate_desktop(self, args: argparse.Namespace) -> None: - messages_file = os.path.join(args.translations_dir, 'desktop.pot') + messages_file = os.path.join(args.translations_dir, "desktop.pot") if args.extract_update: - sources = args.sources.split(',') - k = {'_cwd': args.translations_dir} + sources = args.sources.split(",") + k = {"_cwd": args.translations_dir} xgettext( "--output=desktop.pot", "--language=Desktop", "--keyword", "--keyword=Name", - "--package-version", args.version, + "--package-version", + args.version, "[email protected]", "--copyright-holder=Freedom of the Press Foundation", *sources, - **k) - sed('-i', '-e', '/^"POT-Creation-Date/d', messages_file, **k) + **k + ) + sed("-i", "-e", '/^"POT-Creation-Date/d', messages_file, **k) if self.file_is_modified(messages_file): for f in os.listdir(args.translations_dir): - if not f.endswith('.po'): + if not f.endswith(".po"): continue po_file = os.path.join(args.translations_dir, f) - msgmerge('--update', po_file, messages_file) - log.warning("messages translations updated in " + - messages_file) + msgmerge("--update", po_file, messages_file) + log.warning("messages translations updated in " + messages_file) else: log.warning("desktop translations are already up to date") if args.compile: - pos = [f for f in os.listdir(args.translations_dir) if f.endswith('.po')] + pos = [f for f in os.listdir(args.translations_dir) if f.endswith(".po")] linguas = [l[:-3] for l in pos] content = "\n".join(linguas) + "\n" - linguas_file = join(args.translations_dir, 'LINGUAS') + linguas_file = join(args.translations_dir, "LINGUAS") try: - open(linguas_file, 'w').write(content) - - for source in args.sources.split(','): - target = source.rstrip('.in') - msgfmt('--desktop', - '--template', source, - '-o', target, - '-d', '.', - _cwd=args.translations_dir) + open(linguas_file, "w").write(content) + + for source in args.sources.split(","): + target = source.rstrip(".in") + msgfmt( + "--desktop", + "--template", + source, + "-o", + target, + "-d", + ".", + _cwd=args.translations_dir, + ) self.sort_desktop_template(join(args.translations_dir, target)) finally: if os.path.exists(linguas_file): @@ -181,89 +242,91 @@ def sort_desktop_template(self, template: str) -> None: for line in names: new_template.write(line) - def set_translate_parser(self, - parser: argparse.ArgumentParser, - translations_dir: str, - sources: str) -> None: + def set_translate_parser( + self, parser: argparse.ArgumentParser, translations_dir: str, sources: str + ) -> None: parser.add_argument( - '--extract-update', - action='store_true', - help=('extract strings to translate and ' - 'update existing translations')) - parser.add_argument( - '--compile', - action='store_true', - help='compile translations') + "--extract-update", + action="store_true", + help=("extract strings to translate and " "update existing translations"), + ) + parser.add_argument("--compile", action="store_true", help="compile translations") parser.add_argument( - '--translations-dir', + "--translations-dir", default=translations_dir, - help='Base directory for translation files (default {})'.format( - translations_dir)) + help="Base directory for translation files (default {})".format(translations_dir), + ) parser.add_argument( - '--version', + "--version", default=version.__version__, - help=('SecureDrop version ' - 'to store in pot files (default {})'.format( - version.__version__))) + help=( + "SecureDrop version " + "to store in pot files (default {})".format(version.__version__) + ), + ) parser.add_argument( - '--sources', + "--sources", default=sources, - help='Source files and directories to extract (default {})'.format( - sources)) + help="Source files and directories to extract (default {})".format(sources), + ) def set_translate_messages_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser('translate-messages', - help=('Update and compile ' - 'source and template translations')) - translations_dir = join(dirname(realpath(__file__)), 'translations') - sources = '.,source_templates,journalist_templates' + parser = subps.add_parser( + "translate-messages", help=("Update and compile " "source and template translations") + ) + translations_dir = join(dirname(realpath(__file__)), "translations") + sources = ".,source_templates,journalist_templates" self.set_translate_parser(parser, translations_dir, sources) - mapping = 'babel.cfg' + mapping = "babel.cfg" parser.add_argument( - '--mapping', + "--mapping", default=mapping, - help='Mapping of files to consider (default {})'.format( - mapping)) + help="Mapping of files to consider (default {})".format(mapping), + ) parser.set_defaults(func=self.translate_messages) def set_translate_desktop_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser('translate-desktop', - help=('Update and compile ' - 'desktop icons translations')) + parser = subps.add_parser( + "translate-desktop", help=("Update and compile " "desktop icons translations") + ) translations_dir = join( dirname(realpath(__file__)), - '../install_files/ansible-base/roles/tails-config/templates') - sources = 'desktop-journalist-icon.j2.in,desktop-source-icon.j2.in' + "../install_files/ansible-base/roles/tails-config/templates", + ) + sources = "desktop-journalist-icon.j2.in,desktop-source-icon.j2.in" self.set_translate_parser(parser, translations_dir, sources) parser.set_defaults(func=self.translate_desktop) @staticmethod def require_git_email_name(git_dir: str) -> bool: - cmd = ('git -C {d} config --get user.name > /dev/null && ' - 'git -C {d} config --get user.email > /dev/null'.format( - d=git_dir)) + cmd = ( + "git -C {d} config --get user.name > /dev/null && " + "git -C {d} config --get user.email > /dev/null".format(d=git_dir) + ) # nosemgrep: python.lang.security.audit.subprocess-shell-true.subprocess-shell-true if subprocess.call(cmd, shell=True): # nosec - if u'docker' in io.open('/proc/1/cgroup').read(): - log.error("remember ~/.gitconfig does not exist " - "in the dev-shell Docker container, " - "only .git/config does") - raise Exception(cmd + ' returned false, please set name and email') + if "docker" in io.open("/proc/1/cgroup").read(): + log.error( + "remember ~/.gitconfig does not exist " + "in the dev-shell Docker container, " + "only .git/config does" + ) + raise Exception(cmd + " returned false, please set name and email") return True def update_docs(self, args: argparse.Namespace) -> None: - l10n_content = u'.. GENERATED BY i18n_tool.py DO NOT EDIT:\n\n' + l10n_content = ".. GENERATED BY i18n_tool.py DO NOT EDIT:\n\n" for (code, info) in sorted(self.supported_languages.items()): - l10n_content += '* ' + info['name'] + ' (``' + code + '``)\n' - includes = abspath(join(args.docs_repo_dir, 'docs/includes')) - l10n_txt = join(includes, 'l10n.txt') - io.open(l10n_txt, mode='w').write(l10n_content) + l10n_content += "* " + info["name"] + " (``" + code + "``)\n" + includes = abspath(join(args.docs_repo_dir, "docs/includes")) + l10n_txt = join(includes, "l10n.txt") + io.open(l10n_txt, mode="w").write(l10n_content) self.require_git_email_name(includes) if self.file_is_modified(l10n_txt): - k = {'_cwd': includes} - git.add('l10n.txt', **k) - msg = 'docs: update the list of supported languages' - git.commit('-m', msg, 'l10n.txt', **k) + k = {"_cwd": includes} + git.add("l10n.txt", **k) + msg = "docs: update the list of supported languages" + git.commit("-m", msg, "l10n.txt", **k) log.warning(l10n_txt + " updated") git_show_out = git.show(**k) log.warning(git_show_out) @@ -271,12 +334,12 @@ def update_docs(self, args: argparse.Namespace) -> None: log.warning(l10n_txt + " already up to date") def set_update_docs_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser('update-docs', - help=('Update the documentation')) + parser = subps.add_parser("update-docs", help=("Update the documentation")) parser.add_argument( - '--docs-repo-dir', + "--docs-repo-dir", required=True, - help=('root directory of the SecureDrop documentation repository')) + help=("root directory of the SecureDrop documentation repository"), + ) parser.set_defaults(func=self.update_docs) def update_from_weblate(self, args: argparse.Namespace) -> None: @@ -286,7 +349,7 @@ def update_from_weblate(self, args: argparse.Namespace) -> None: self.ensure_i18n_remote(args) codes = list(self.supported_languages.keys()) if args.supported_languages: - codes = args.supported_languages.split(',') + codes = args.supported_languages.split(",") for code in sorted(codes): info = self.supported_languages[code] @@ -296,9 +359,9 @@ def need_update(path: str) -> bool: """ exists = os.path.exists(join(args.root, path)) - k = {'_cwd': args.root} - git.checkout(args.target, '--', path, **k) - git.reset('HEAD', '--', path, **k) + k = {"_cwd": args.root} + git.checkout(args.target, "--", path, **k) + git.reset("HEAD", "--", path, **k) if not exists: return True @@ -308,24 +371,26 @@ def add(path: str) -> None: """ Add the file to the git index. """ - git('-C', args.root, 'add', path) + git("-C", args.root, "add", path) updated = False # # Add changes to web .po files # path = "securedrop/translations/{l}/LC_MESSAGES/messages.po".format( - l=code) # noqa: E741 + l=code # noqa: E741 + ) if need_update(path): add(path) updated = True # # Add changes to desktop .po files # - desktop_code = info['desktop'] - path = join("install_files/ansible-base/roles", - "tails-config/templates/{l}.po".format( - l=desktop_code)) # noqa: E741 + desktop_code = info["desktop"] + path = join( + "install_files/ansible-base/roles", + "tails-config/templates/{l}.po".format(l=desktop_code), # noqa: E741 + ) if need_update(path): add(path) updated = True @@ -351,14 +416,14 @@ def translators( since = self.get_commit_timestamp(args.root, since_commit) log_command.extend(["--since", since]) - log_command.extend([args.target, '--', path]) + log_command.extend([args.target, "--", path]) log_lines = subprocess.check_output(log_command).decode("utf-8").strip().split("\n") - path_changes = [c.split('\x1e') for c in log_lines] + path_changes = [c.split("\x1e") for c in log_lines] path_changes = [ - c for c in path_changes if len(c) > 1 - and c[2] != since_commit - and self.translated_commit_re.match(c[1]) + c + for c in path_changes + if len(c) > 1 and c[2] != since_commit and self.translated_commit_re.match(c[1]) ] log.debug("Path changes for %s: %s", path, path_changes) translators = set([c[0] for c in path_changes]) @@ -370,25 +435,25 @@ def get_path_commits(self, root: str, path: str) -> List[str]: Returns the list of commit hashes involving the path, most recent first. """ return git( - "--no-pager", "-C", root, "log", "--format=%H", path, _encoding='utf-8' + "--no-pager", "-C", root, "log", "--format=%H", path, _encoding="utf-8" ).splitlines() def commit_changes(self, args: argparse.Namespace, code: str) -> None: self.require_git_email_name(args.root) authors = set() # type: Set[str] - diffs = u"{}".format(git('--no-pager', '-C', args.root, 'diff', '--name-only', '--cached')) + diffs = "{}".format(git("--no-pager", "-C", args.root, "diff", "--name-only", "--cached")) # for each modified file, find the last commit made by this # function, then collect all the contributors since that # commit, so they can be credited in this one. if no commit # with the right message is found, just use the most recent # commit that touched the file. - for path in sorted(diffs.strip().split('\n')): + for path in sorted(diffs.strip().split("\n")): path_commits = self.get_path_commits(args.root, path) since_commit = None for path_commit in path_commits: commit_message = "{}".format( - git('--no-pager', '-C', args.root, 'show', path_commit, _encoding='utf-8') + git("--no-pager", "-C", args.root, "show", path_commit, _encoding="utf-8") ) m = self.updated_commit_re.search(commit_message) if m: @@ -397,11 +462,12 @@ def commit_changes(self, args: argparse.Namespace, code: str) -> None: log.debug("Crediting translators of %s since %s", path, since_commit) authors |= self.translators(args, path, since_commit) - authors_as_str = u"\n ".join(sorted(authors)) + authors_as_str = "\n ".join(sorted(authors)) - current = git('-C', args.root, 'rev-parse', args.target) + current = git("-C", args.root, "rev-parse", args.target) info = self.supported_languages[code] - message = textwrap.dedent(u""" + message = textwrap.dedent( + """ l10n: updated {name} ({code}) contributors: @@ -410,103 +476,90 @@ def commit_changes(self, args: argparse.Namespace, code: str) -> None: updated from: repo: {remote} commit: {current} - """).format( - remote=args.url, - name=info['name'], - authors=authors_as_str, - code=code, - current=current + """ + ).format( + remote=args.url, name=info["name"], authors=authors_as_str, code=code, current=current ) - git('-C', args.root, 'commit', '-m', message) + git("-C", args.root, "commit", "-m", message) def set_update_from_weblate_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser('update-from-weblate', - help=('Import translations from weblate')) - root = join(dirname(realpath(__file__)), '..') + parser = subps.add_parser("update-from-weblate", help=("Import translations from weblate")) + root = join(dirname(realpath(__file__)), "..") parser.add_argument( - '--root', + "--root", default=root, - help=('root of the SecureDrop git repository' - ' (default {})'.format(root))) - url = 'https://github.com/freedomofpress/securedrop-i18n' + help=("root of the SecureDrop git repository" " (default {})".format(root)), + ) + url = "https://github.com/freedomofpress/securedrop-i18n" parser.add_argument( - '--url', - default=url, - help=('URL of the weblate repository' - ' (default {})'.format(url))) + "--url", default=url, help=("URL of the weblate repository" " (default {})".format(url)) + ) parser.add_argument( - '--target', + "--target", default="i18n/i18n", help=( - 'Commit on i18n branch at which to stop gathering translator contributions ' - '(default: i18n/i18n)' - ) + "Commit on i18n branch at which to stop gathering translator contributions " + "(default: i18n/i18n)" + ), ) parser.add_argument( - '--supported-languages', - help='comma separated list of supported languages') + "--supported-languages", help="comma separated list of supported languages" + ) parser.set_defaults(func=self.update_from_weblate) def set_list_locales_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser('list-locales', help='List supported locales') - parser.add_argument( - '--python', - action='store_true', - help=('Print the locales as a Python list suitable for config.py') - ) + parser = subps.add_parser("list-locales", help="List supported locales") parser.add_argument( - '--lines', - action='store_true', - help=('List one locale per line') + "--python", + action="store_true", + help=("Print the locales as a Python list suitable for config.py"), ) + parser.add_argument("--lines", action="store_true", help=("List one locale per line")) parser.set_defaults(func=self.list_locales) def list_locales(self, args: argparse.Namespace) -> None: if args.lines: - for l in sorted(list(self.supported_languages.keys()) + ['en_US']): + for l in sorted(list(self.supported_languages.keys()) + ["en_US"]): print(l) elif args.python: - print(sorted(list(self.supported_languages.keys()) + ['en_US'])) + print(sorted(list(self.supported_languages.keys()) + ["en_US"])) else: - print(" ".join(sorted(list(self.supported_languages.keys()) + ['en_US']))) + print(" ".join(sorted(list(self.supported_languages.keys()) + ["en_US"]))) def set_list_translators_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser('list-translators', - help=('List contributing translators')) - root = join(dirname(realpath(__file__)), '..') + parser = subps.add_parser("list-translators", help=("List contributing translators")) + root = join(dirname(realpath(__file__)), "..") parser.add_argument( - '--root', + "--root", default=root, - help=('root of the SecureDrop git repository' - ' (default {})'.format(root))) - url = 'https://github.com/freedomofpress/securedrop-i18n' + help=("root of the SecureDrop git repository" " (default {})".format(root)), + ) + url = "https://github.com/freedomofpress/securedrop-i18n" parser.add_argument( - '--url', - default=url, - help=('URL of the weblate repository' - ' (default {})'.format(url))) + "--url", default=url, help=("URL of the weblate repository" " (default {})".format(url)) + ) parser.add_argument( - '--target', + "--target", default="i18n/i18n", help=( - 'Commit on i18n branch at which to stop gathering translator contributions ' - '(default: i18n/i18n)' - ) + "Commit on i18n branch at which to stop gathering translator contributions " + "(default: i18n/i18n)" + ), ) parser.add_argument( - '--since', + "--since", help=( - 'Gather translator contributions from the time of this commit ' - '(default: last release tag)' - ) + "Gather translator contributions from the time of this commit " + "(default: last release tag)" + ), ) parser.add_argument( - '--all', + "--all", action="store_true", help=( "List everyone who's ever contributed, instead of just since the last " "release or specified commit." - ) + ), ) parser.set_defaults(func=self.list_translators) @@ -514,9 +567,11 @@ def get_last_release(self, root: str) -> str: """ Returns the last release tag, e.g. 1.5.0. """ - tags = subprocess.check_output( - ["git", "-C", root, "tag", "--list"] - ).decode("utf-8").splitlines() + tags = ( + subprocess.check_output(["git", "-C", root, "tag", "--list"]) + .decode("utf-8") + .splitlines() + ) release_tags = sorted([t.strip() for t in tags if self.release_tag_re.match(t)]) if not release_tags: raise ValueError("Could not find a release tag!") @@ -526,7 +581,7 @@ def get_commit_timestamp(self, root: str, commit: Optional[str]) -> str: """ Returns the UNIX timestamp of the given commit. """ - cmd = ["git", "-C", root, "log", "-n", "1", '--pretty=format:%ct'] + cmd = ["git", "-C", root, "log", "-n", "1", "--pretty=format:%ct"] if commit: cmd.append(commit) @@ -557,19 +612,17 @@ def list_translators(self, args: argparse.Namespace) -> None: print("Could not check git history of {}: {}".format(path, e), file=sys.stderr) print( "{} ({}):{}".format( - code, info["name"], - "\n {}\n".format( - "\n ".join(sorted(translators))) if translators else "\n" + code, + info["name"], + "\n {}\n".format("\n ".join(sorted(translators))) if translators else "\n", ) ) def get_args(self) -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog=__file__, - description='i18n tool for SecureDrop.') + parser = argparse.ArgumentParser(prog=__file__, description="i18n tool for SecureDrop.") parser.set_defaults(func=lambda args: parser.print_help()) - parser.add_argument('-v', '--verbose', action='store_true') + parser.add_argument("-v", "--verbose", action="store_true") subps = parser.add_subparsers() self.set_translate_messages_parser(subps) @@ -583,7 +636,7 @@ def get_args(self) -> argparse.ArgumentParser: def setup_verbosity(self, args: argparse.Namespace) -> None: if args.verbose: - logging.getLogger('sh.command').setLevel(logging.INFO) + logging.getLogger("sh.command").setLevel(logging.INFO) log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) @@ -597,5 +650,5 @@ def main(self, argv: List[str]) -> int: return signal.SIGINT -if __name__ == '__main__': # pragma: no cover +if __name__ == "__main__": # pragma: no cover sys.exit(I18NTool().main(sys.argv[1:])) diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -1,10 +1,9 @@ # -*- coding: utf-8 -*- from encryption import EncryptionManager, GpgKeyNotFoundError -from sdconfig import config - +from execution import asynchronous from journalist_app import create_app from models import Source -from execution import asynchronous +from sdconfig import config app = create_app(config) @@ -25,6 +24,6 @@ def prime_keycache() -> None: if __name__ == "__main__": # pragma: no cover - debug = getattr(config, 'env', 'prod') != 'prod' + debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host - app.run(debug=debug, host='0.0.0.0', port=8081) # nosec + app.run(debug=debug, host="0.0.0.0", port=8081) # nosec diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -1,39 +1,40 @@ # -*- coding: utf-8 -*- +import typing from datetime import datetime, timedelta, timezone -from pathlib import Path - -from flask import (Flask, session, redirect, url_for, flash, g, request, - render_template, json) -from flask_babel import gettext -from flask_wtf.csrf import CSRFProtect, CSRFError from os import path -from werkzeug.exceptions import default_exceptions +from pathlib import Path import i18n import template_filters import version - from db import db -from journalist_app import account, admin, api, main, col -from journalist_app.utils import (get_source, logged_in, - JournalistInterfaceSessionInterface, - cleanup_expired_revoked_tokens) +from flask import Flask, flash, g, json, redirect, render_template, request, session, url_for +from flask_babel import gettext +from flask_wtf.csrf import CSRFError, CSRFProtect +from journalist_app import account, admin, api, col, main +from journalist_app.utils import ( + JournalistInterfaceSessionInterface, + cleanup_expired_revoked_tokens, + get_source, + logged_in, +) from models import InstanceConfig, Journalist +from werkzeug.exceptions import default_exceptions -import typing # https://www.python.org/dev/peps/pep-0484/#runtime-or-type-checking if typing.TYPE_CHECKING: # flake8 can not understand type annotation yet. # That is why all type annotation relative import # statements has to be marked as noqa. # http://flake8.pycqa.org/en/latest/user/error-codes.html?highlight=f401 + from typing import Any, Optional, Tuple, Union # noqa: F401 + from sdconfig import SDConfig # noqa: F401 - from typing import Optional, Union, Tuple, Any # noqa: F401 from werkzeug import Response # noqa: F401 from werkzeug.exceptions import HTTPException # noqa: F401 -_insecure_views = ['main.login', 'static'] +_insecure_views = ["main.login", "static"] # Timezone-naive datetime format expected by SecureDrop Client API_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" @@ -54,24 +55,26 @@ def get_logo_url(app: Flask) -> str: raise FileNotFoundError -def create_app(config: 'SDConfig') -> Flask: - app = Flask(__name__, - template_folder=config.JOURNALIST_TEMPLATES_DIR, - static_folder=path.join(config.SECUREDROP_ROOT, 'static')) +def create_app(config: "SDConfig") -> Flask: + app = Flask( + __name__, + template_folder=config.JOURNALIST_TEMPLATES_DIR, + static_folder=path.join(config.SECUREDROP_ROOT, "static"), + ) app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS) app.session_interface = JournalistInterfaceSessionInterface() csrf = CSRFProtect(app) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI db.init_app(app) class JSONEncoder(json.JSONEncoder): """Custom JSON encoder to use our preferred timestamp format""" - def default(self, obj: 'Any') -> 'Any': + def default(self, obj: "Any") -> "Any": if isinstance(obj, datetime): return obj.strftime(API_DATETIME_FORMAT) super(JSONEncoder, self).default(obj) @@ -81,26 +84,26 @@ def default(self, obj: 'Any') -> 'Any': # TODO: enable type checking once upstream Flask fix is available. See: # https://github.com/pallets/flask/issues/4295 @app.errorhandler(CSRFError) # type: ignore - def handle_csrf_error(e: CSRFError) -> 'Response': + def handle_csrf_error(e: CSRFError) -> "Response": app.logger.error("The CSRF token is invalid.") session.clear() - msg = gettext('You have been logged out due to inactivity.') - flash(msg, 'error') - return redirect(url_for('main.login')) + msg = gettext("You have been logged out due to inactivity.") + flash(msg, "error") + return redirect(url_for("main.login")) def _handle_http_exception( - error: 'HTTPException' - ) -> 'Tuple[Union[Response, str], Optional[int]]': + error: "HTTPException", + ) -> "Tuple[Union[Response, str], Optional[int]]": # Workaround for no blueprint-level 404/5 error handlers, see: # https://github.com/pallets/flask/issues/503#issuecomment-71383286 # TODO: clean up API error handling such that all except 404/5s are # registered in the blueprint and 404/5s are handled at the application # level. - handler = list(app.error_handler_spec['api'][error.code].values())[0] - if request.path.startswith('/api/') and handler: + handler = list(app.error_handler_spec["api"][error.code].values())[0] + if request.path.startswith("/api/") and handler: return handler(error) # type: ignore - return render_template('error.html', error=error), error.code + return render_template("error.html", error=error), error.code for code in default_exceptions: app.errorhandler(code)(_handle_http_exception) @@ -109,13 +112,11 @@ def _handle_http_exception( app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True - app.jinja_env.globals['version'] = version.__version__ - app.jinja_env.filters['rel_datetime_format'] = \ - template_filters.rel_datetime_format - app.jinja_env.filters['filesizeformat'] = template_filters.filesizeformat - app.jinja_env.filters['html_datetime_format'] = \ - template_filters.html_datetime_format - app.jinja_env.add_extension('jinja2.ext.do') + app.jinja_env.globals["version"] = version.__version__ + app.jinja_env.filters["rel_datetime_format"] = template_filters.rel_datetime_format + app.jinja_env.filters["filesizeformat"] = template_filters.filesizeformat + app.jinja_env.filters["html_datetime_format"] = template_filters.html_datetime_format + app.jinja_env.add_extension("jinja2.ext.do") @app.before_first_request def expire_blacklisted_tokens() -> None: @@ -126,52 +127,49 @@ def update_instance_config() -> None: InstanceConfig.get_default(refresh=True) @app.before_request - def setup_g() -> 'Optional[Response]': + def setup_g() -> "Optional[Response]": """Store commonly used values in Flask's special g object""" - if 'expires' in session and datetime.now(timezone.utc) >= session['expires']: + if "expires" in session and datetime.now(timezone.utc) >= session["expires"]: session.clear() - flash(gettext('You have been logged out due to inactivity.'), - 'error') + flash(gettext("You have been logged out due to inactivity."), "error") - uid = session.get('uid', None) + uid = session.get("uid", None) if uid: user = Journalist.query.get(uid) - if user and 'nonce' in session and \ - session['nonce'] != user.session_nonce: + if user and "nonce" in session and session["nonce"] != user.session_nonce: session.clear() - flash(gettext('You have been logged out due to password change'), - 'error') + flash(gettext("You have been logged out due to password change"), "error") - session['expires'] = datetime.now(timezone.utc) + \ - timedelta(minutes=getattr(config, - 'SESSION_EXPIRATION_MINUTES', - 120)) + session["expires"] = datetime.now(timezone.utc) + timedelta( + minutes=getattr(config, "SESSION_EXPIRATION_MINUTES", 120) + ) - uid = session.get('uid', None) + uid = session.get("uid", None) if uid: g.user = Journalist.query.get(uid) # pylint: disable=assigning-non-slot i18n.set_locale(config) if InstanceConfig.get_default().organization_name: - g.organization_name = \ - InstanceConfig.get_default().organization_name # pylint: disable=assigning-non-slot + g.organization_name = ( # pylint: disable=assigning-non-slot + InstanceConfig.get_default().organization_name + ) else: - g.organization_name = gettext('SecureDrop') # pylint: disable=assigning-non-slot + g.organization_name = gettext("SecureDrop") # pylint: disable=assigning-non-slot try: g.logo = get_logo_url(app) # pylint: disable=assigning-non-slot except FileNotFoundError: app.logger.error("Site logo not found.") - if request.path.split('/')[1] == 'api': + if request.path.split("/")[1] == "api": pass # We use the @token_required decorator for the API endpoints else: # We are not using the API if request.endpoint not in _insecure_views and not logged_in(): - return redirect(url_for('main.login')) + return redirect(url_for("main.login")) - if request.method == 'POST': - filesystem_id = request.form.get('filesystem_id') + if request.method == "POST": + filesystem_id = request.form.get("filesystem_id") if filesystem_id: g.filesystem_id = filesystem_id # pylint: disable=assigning-non-slot g.source = get_source(filesystem_id) # pylint: disable=assigning-non-slot @@ -179,12 +177,11 @@ def setup_g() -> 'Optional[Response]': return None app.register_blueprint(main.make_blueprint(config)) - app.register_blueprint(account.make_blueprint(config), - url_prefix='/account') - app.register_blueprint(admin.make_blueprint(config), url_prefix='/admin') - app.register_blueprint(col.make_blueprint(config), url_prefix='/col') + app.register_blueprint(account.make_blueprint(config), url_prefix="/account") + app.register_blueprint(admin.make_blueprint(config), url_prefix="/admin") + app.register_blueprint(col.make_blueprint(config), url_prefix="/col") api_blueprint = api.make_blueprint(config) - app.register_blueprint(api_blueprint, url_prefix='/api/v1') + app.register_blueprint(api_blueprint, url_prefix="/api/v1") csrf.exempt(api_blueprint) return app diff --git a/securedrop/journalist_app/account.py b/securedrop/journalist_app/account.py --- a/securedrop/journalist_app/account.py +++ b/securedrop/journalist_app/account.py @@ -2,83 +2,86 @@ from typing import Union import werkzeug -from flask import (Blueprint, render_template, request, g, redirect, url_for, - flash, session) -from flask_babel import gettext - from db import db -from journalist_app.utils import (set_diceware_password, set_name, validate_user, - validate_hotp_secret) +from flask import Blueprint, flash, g, redirect, render_template, request, session, url_for +from flask_babel import gettext +from journalist_app.utils import ( + set_diceware_password, + set_name, + validate_hotp_secret, + validate_user, +) from passphrases import PassphraseGenerator from sdconfig import SDConfig def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('account', __name__) + view = Blueprint("account", __name__) - @view.route('/account', methods=('GET',)) + @view.route("/account", methods=("GET",)) def edit() -> str: password = PassphraseGenerator.get_default().generate_passphrase( preferred_language=g.localeinfo.language ) - return render_template('edit_account.html', - password=password) + return render_template("edit_account.html", password=password) - @view.route('/change-name', methods=('POST',)) + @view.route("/change-name", methods=("POST",)) def change_name() -> werkzeug.Response: - first_name = request.form.get('first_name') - last_name = request.form.get('last_name') + first_name = request.form.get("first_name") + last_name = request.form.get("last_name") set_name(g.user, first_name, last_name) - return redirect(url_for('account.edit')) + return redirect(url_for("account.edit")) - @view.route('/new-password', methods=('POST',)) + @view.route("/new-password", methods=("POST",)) def new_password() -> werkzeug.Response: user = g.user - current_password = request.form.get('current_password') - token = request.form.get('token') - error_message = gettext('Incorrect password or two-factor code.') + current_password = request.form.get("current_password") + token = request.form.get("token") + error_message = gettext("Incorrect password or two-factor code.") # If the user is validated, change their password - if validate_user(user.username, current_password, token, - error_message): - password = request.form.get('password') + if validate_user(user.username, current_password, token, error_message): + password = request.form.get("password") set_diceware_password(user, password) - session.pop('uid', None) - session.pop('expires', None) - return redirect(url_for('main.login')) - return redirect(url_for('account.edit')) + session.pop("uid", None) + session.pop("expires", None) + return redirect(url_for("main.login")) + return redirect(url_for("account.edit")) - @view.route('/2fa', methods=('GET', 'POST')) + @view.route("/2fa", methods=("GET", "POST")) def new_two_factor() -> Union[str, werkzeug.Response]: - if request.method == 'POST': - token = request.form['token'] + if request.method == "POST": + token = request.form["token"] if g.user.verify_token(token): - flash(gettext("Your two-factor credentials have been reset successfully."), - "notification") - return redirect(url_for('account.edit')) + flash( + gettext("Your two-factor credentials have been reset successfully."), + "notification", + ) + return redirect(url_for("account.edit")) else: - flash(gettext( - "There was a problem verifying the two-factor code. Please try again."), - "error") + flash( + gettext("There was a problem verifying the two-factor code. Please try again."), + "error", + ) - return render_template('account_new_two_factor.html', user=g.user) + return render_template("account_new_two_factor.html", user=g.user) - @view.route('/reset-2fa-totp', methods=['POST']) + @view.route("/reset-2fa-totp", methods=["POST"]) def reset_two_factor_totp() -> werkzeug.Response: g.user.is_totp = True g.user.regenerate_totp_shared_secret() db.session.commit() - return redirect(url_for('account.new_two_factor')) + return redirect(url_for("account.new_two_factor")) - @view.route('/reset-2fa-hotp', methods=['POST']) + @view.route("/reset-2fa-hotp", methods=["POST"]) def reset_two_factor_hotp() -> Union[str, werkzeug.Response]: - otp_secret = request.form.get('otp_secret', None) + otp_secret = request.form.get("otp_secret", None) if otp_secret: if not validate_hotp_secret(g.user, otp_secret): - return render_template('account_edit_hotp_secret.html') + return render_template("account_edit_hotp_secret.html") g.user.set_hotp_secret(otp_secret) db.session.commit() - return redirect(url_for('account.new_two_factor')) + return redirect(url_for("account.new_two_factor")) else: - return render_template('account_edit_hotp_secret.html') + return render_template("account_edit_hotp_secret.html") return view diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -1,39 +1,56 @@ # -*- coding: utf-8 -*- -import os import binascii -from typing import Optional -from typing import Union +import os +from html import escape +from typing import Optional, Union import werkzeug -from flask import (Blueprint, render_template, request, url_for, redirect, g, - current_app, flash, abort) -from flask_babel import gettext -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm.exc import NoResultFound - from db import db -from html import escape -from models import (InstanceConfig, Journalist, InvalidUsernameException, - FirstOrLastNameError, PasswordError, Submission) +from flask import ( + Blueprint, + abort, + current_app, + flash, + g, + redirect, + render_template, + request, + url_for, +) +from flask_babel import gettext from journalist_app.decorators import admin_required -from journalist_app.utils import (commit_account_changes, set_diceware_password, - validate_hotp_secret, revoke_token) -from journalist_app.forms import LogoForm, NewUserForm, SubmissionPreferencesForm, OrgNameForm -from sdconfig import SDConfig +from journalist_app.forms import LogoForm, NewUserForm, OrgNameForm, SubmissionPreferencesForm +from journalist_app.utils import ( + commit_account_changes, + revoke_token, + set_diceware_password, + validate_hotp_secret, +) +from models import ( + FirstOrLastNameError, + InstanceConfig, + InvalidUsernameException, + Journalist, + PasswordError, + Submission, +) from passphrases import PassphraseGenerator +from sdconfig import SDConfig +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm.exc import NoResultFound def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('admin', __name__) + view = Blueprint("admin", __name__) - @view.route('/', methods=('GET', 'POST')) + @view.route("/", methods=("GET", "POST")) @admin_required def index() -> str: users = Journalist.query.filter(Journalist.username != "deleted").all() return render_template("admin.html", users=users) - @view.route('/config', methods=('GET', 'POST')) + @view.route("/config", methods=("GET", "POST")) @admin_required def manage_config() -> Union[str, werkzeug.Response]: if InstanceConfig.get_default().initial_message_min_len > 0: @@ -46,18 +63,18 @@ def manage_config() -> Union[str, werkzeug.Response]: prevent_document_uploads=not InstanceConfig.get_default().allow_document_uploads, prevent_short_messages=prevent_short_messages, min_message_length=InstanceConfig.get_default().initial_message_min_len, - reject_codename_messages=InstanceConfig.get_default().reject_message_with_codename - ) + reject_codename_messages=InstanceConfig.get_default().reject_message_with_codename, + ) organization_name_form = OrgNameForm( - organization_name=InstanceConfig.get_default().organization_name) + organization_name=InstanceConfig.get_default().organization_name + ) logo_form = LogoForm() if logo_form.validate_on_submit(): f = logo_form.logo.data if current_app.static_folder is None: abort(500) - custom_logo_filepath = os.path.join(current_app.static_folder, 'i', - 'custom_logo.png') + custom_logo_filepath = os.path.join(current_app.static_folder, "i", "custom_logo.png") try: f.save(custom_logo_filepath) flash(gettext("Image updated."), "logo-success") @@ -65,7 +82,7 @@ def manage_config() -> Union[str, werkzeug.Response]: flash( # Translators: This error is shown when an uploaded image cannot be used. gettext("Unable to process the image file. Please try another one."), - "logo-error" + "logo-error", ) finally: return redirect(url_for("admin.manage_config") + "#config-logoimage") @@ -73,13 +90,15 @@ def manage_config() -> Union[str, werkzeug.Response]: for field, errors in list(logo_form.errors.items()): for error in errors: flash(error, "logo-error") - return render_template("config.html", - submission_preferences_form=submission_preferences_form, - organization_name_form=organization_name_form, - max_len=Submission.MAX_MESSAGE_LEN, - logo_form=logo_form) + return render_template( + "config.html", + submission_preferences_form=submission_preferences_form, + organization_name_form=organization_name_form, + max_len=Submission.MAX_MESSAGE_LEN, + logo_form=logo_form, + ) - @view.route('/update-submission-preferences', methods=['POST']) + @view.route("/update-submission-preferences", methods=["POST"]) @admin_required def update_submission_preferences() -> Optional[werkzeug.Response]: form = SubmissionPreferencesForm() @@ -96,238 +115,249 @@ def update_submission_preferences() -> Optional[werkzeug.Response]: InstanceConfig.update_submission_prefs(allow_uploads, msg_length, reject_codenames) flash(gettext("Preferences saved."), "submission-preferences-success") - return redirect(url_for('admin.manage_config') + "#config-preventuploads") + return redirect(url_for("admin.manage_config") + "#config-preventuploads") else: for field, errors in list(form.errors.items()): for error in errors: - flash(gettext("Preferences not updated.") + " " + error, - "submission-preferences-error") - return redirect(url_for('admin.manage_config') + "#config-preventuploads") + flash( + gettext("Preferences not updated.") + " " + error, + "submission-preferences-error", + ) + return redirect(url_for("admin.manage_config") + "#config-preventuploads") - @view.route('/update-org-name', methods=['POST']) + @view.route("/update-org-name", methods=["POST"]) @admin_required def update_org_name() -> Union[str, werkzeug.Response]: form = OrgNameForm() if form.validate_on_submit(): try: - value = request.form['organization_name'] + value = request.form["organization_name"] InstanceConfig.set_organization_name(escape(value, quote=True)) flash(gettext("Preferences saved."), "org-name-success") except Exception: - flash(gettext('Failed to update organization name.'), 'org-name-error') - return redirect(url_for('admin.manage_config') + "#config-orgname") + flash(gettext("Failed to update organization name."), "org-name-error") + return redirect(url_for("admin.manage_config") + "#config-orgname") else: for field, errors in list(form.errors.items()): for error in errors: flash(error, "org-name-error") - return redirect(url_for('admin.manage_config') + "#config-orgname") + return redirect(url_for("admin.manage_config") + "#config-orgname") - @view.route('/add', methods=('GET', 'POST')) + @view.route("/add", methods=("GET", "POST")) @admin_required def add_user() -> Union[str, werkzeug.Response]: form = NewUserForm() if form.validate_on_submit(): form_valid = True - username = request.form['username'] - first_name = request.form['first_name'] - last_name = request.form['last_name'] - password = request.form['password'] - is_admin = bool(request.form.get('is_admin')) + username = request.form["username"] + first_name = request.form["first_name"] + last_name = request.form["last_name"] + password = request.form["password"] + is_admin = bool(request.form.get("is_admin")) try: otp_secret = None - if request.form.get('is_hotp', False): - otp_secret = request.form.get('otp_secret', '') - new_user = Journalist(username=username, - password=password, - first_name=first_name, - last_name=last_name, - is_admin=is_admin, - otp_secret=otp_secret) + if request.form.get("is_hotp", False): + otp_secret = request.form.get("otp_secret", "") + new_user = Journalist( + username=username, + password=password, + first_name=first_name, + last_name=last_name, + is_admin=is_admin, + otp_secret=otp_secret, + ) db.session.add(new_user) db.session.commit() except PasswordError: - flash(gettext( - 'There was an error with the autogenerated password. ' - 'User not created. Please try again.'), 'error') + flash( + gettext( + "There was an error with the autogenerated password. " + "User not created. Please try again." + ), + "error", + ) form_valid = False except (binascii.Error, TypeError) as e: if "Non-hexadecimal digit found" in str(e): - flash(gettext( - "Invalid HOTP secret format: " - "please only submit letters A-F and numbers 0-9."), - "error") + flash( + gettext( + "Invalid HOTP secret format: " + "please only submit letters A-F and numbers 0-9." + ), + "error", + ) else: - flash(gettext( - "An unexpected error occurred! " - "Please inform your admin."), "error") + flash( + gettext("An unexpected error occurred! " "Please inform your admin."), + "error", + ) form_valid = False except InvalidUsernameException as e: form_valid = False # Translators: Here, "{message}" explains the problem with the username. - flash(gettext('Invalid username: {message}').format(message=e), "error") + flash(gettext("Invalid username: {message}").format(message=e), "error") except IntegrityError as e: db.session.rollback() form_valid = False if "UNIQUE constraint failed: journalists.username" in str(e): flash( gettext('Username "{username}" already taken.').format(username=username), - "error" + "error", ) else: - flash(gettext("An error occurred saving this user" - " to the database." - " Please inform your admin."), - "error") - current_app.logger.error("Adding user " - "'{}' failed: {}".format( - username, e)) + flash( + gettext( + "An error occurred saving this user" + " to the database." + " Please inform your admin." + ), + "error", + ) + current_app.logger.error("Adding user " "'{}' failed: {}".format(username, e)) if form_valid: - return redirect(url_for('admin.new_user_two_factor', - uid=new_user.id)) + return redirect(url_for("admin.new_user_two_factor", uid=new_user.id)) password = PassphraseGenerator.get_default().generate_passphrase( preferred_language=g.localeinfo.language ) - return render_template("admin_add_user.html", - password=password, - form=form) + return render_template("admin_add_user.html", password=password, form=form) - @view.route('/2fa', methods=('GET', 'POST')) + @view.route("/2fa", methods=("GET", "POST")) @admin_required def new_user_two_factor() -> Union[str, werkzeug.Response]: - user = Journalist.query.get(request.args['uid']) + user = Journalist.query.get(request.args["uid"]) - if request.method == 'POST': - token = request.form['token'] + if request.method == "POST": + token = request.form["token"] if user.verify_token(token): - flash(gettext( - "The two-factor code for user \"{user}\" was verified " - "successfully.").format(user=user.username), - "notification") + flash( + gettext( + 'The two-factor code for user "{user}" was verified ' "successfully." + ).format(user=user.username), + "notification", + ) return redirect(url_for("admin.index")) else: - flash(gettext( - "There was a problem verifying the two-factor code. Please try again."), - "error") + flash( + gettext("There was a problem verifying the two-factor code. Please try again."), + "error", + ) return render_template("admin_new_user_two_factor.html", user=user) - @view.route('/reset-2fa-totp', methods=['POST']) + @view.route("/reset-2fa-totp", methods=["POST"]) @admin_required def reset_two_factor_totp() -> werkzeug.Response: # nosemgrep: python.flask.security.open-redirect.open-redirect - uid = request.form['uid'] + uid = request.form["uid"] user = Journalist.query.get(uid) user.is_totp = True user.regenerate_totp_shared_secret() db.session.commit() - return redirect(url_for('admin.new_user_two_factor', uid=uid)) + return redirect(url_for("admin.new_user_two_factor", uid=uid)) - @view.route('/reset-2fa-hotp', methods=['POST']) + @view.route("/reset-2fa-hotp", methods=["POST"]) @admin_required def reset_two_factor_hotp() -> Union[str, werkzeug.Response]: # nosemgrep: python.flask.security.open-redirect.open-redirect - uid = request.form['uid'] - otp_secret = request.form.get('otp_secret', None) + uid = request.form["uid"] + otp_secret = request.form.get("otp_secret", None) if otp_secret: user = Journalist.query.get(uid) if not validate_hotp_secret(user, otp_secret): - return render_template('admin_edit_hotp_secret.html', uid=uid) + return render_template("admin_edit_hotp_secret.html", uid=uid) db.session.commit() - return redirect(url_for('admin.new_user_two_factor', uid=uid)) + return redirect(url_for("admin.new_user_two_factor", uid=uid)) else: - return render_template('admin_edit_hotp_secret.html', uid=uid) + return render_template("admin_edit_hotp_secret.html", uid=uid) - @view.route('/edit/<int:user_id>', methods=('GET', 'POST')) + @view.route("/edit/<int:user_id>", methods=("GET", "POST")) @admin_required def edit_user(user_id: int) -> Union[str, werkzeug.Response]: user = Journalist.query.get(user_id) - if request.method == 'POST': - if request.form.get('username', None): - new_username = request.form['username'] + if request.method == "POST": + if request.form.get("username", None): + new_username = request.form["username"] try: Journalist.check_username_acceptable(new_username) except InvalidUsernameException as e: - flash(gettext('Invalid username: {message}').format(message=e), "error") - return redirect(url_for("admin.edit_user", - user_id=user_id)) + flash(gettext("Invalid username: {message}").format(message=e), "error") + return redirect(url_for("admin.edit_user", user_id=user_id)) if new_username == user.username: pass - elif Journalist.query.filter_by( - username=new_username).one_or_none(): + elif Journalist.query.filter_by(username=new_username).one_or_none(): flash( gettext('Username "{username}" already taken.').format( username=new_username ), - "error" + "error", ) - return redirect(url_for("admin.edit_user", - user_id=user_id)) + return redirect(url_for("admin.edit_user", user_id=user_id)) else: user.username = new_username try: - first_name = request.form['first_name'] + first_name = request.form["first_name"] Journalist.check_name_acceptable(first_name) user.first_name = first_name except FirstOrLastNameError as e: # Translators: Here, "{message}" explains the problem with the name. - flash(gettext('Name not updated: {message}').format(message=e), "error") + flash(gettext("Name not updated: {message}").format(message=e), "error") return redirect(url_for("admin.edit_user", user_id=user_id)) try: - last_name = request.form['last_name'] + last_name = request.form["last_name"] Journalist.check_name_acceptable(last_name) user.last_name = last_name except FirstOrLastNameError as e: - flash(gettext('Name not updated: {message}').format(message=e), "error") + flash(gettext("Name not updated: {message}").format(message=e), "error") return redirect(url_for("admin.edit_user", user_id=user_id)) - user.is_admin = bool(request.form.get('is_admin')) + user.is_admin = bool(request.form.get("is_admin")) commit_account_changes(user) password = PassphraseGenerator.get_default().generate_passphrase( preferred_language=g.localeinfo.language ) - return render_template("edit_account.html", user=user, - password=password) + return render_template("edit_account.html", user=user, password=password) - @view.route('/delete/<int:user_id>', methods=('POST',)) + @view.route("/delete/<int:user_id>", methods=("POST",)) @admin_required def delete_user(user_id: int) -> werkzeug.Response: user = Journalist.query.get(user_id) if user_id == g.user.id: # Do not flash because the interface already has safe guards. # It can only happen by manually crafting a POST request - current_app.logger.error( - "Admin {} tried to delete itself".format(g.user.username)) + current_app.logger.error("Admin {} tried to delete itself".format(g.user.username)) abort(403) elif not user: current_app.logger.error( "Admin {} tried to delete nonexistent user with pk={}".format( - g.user.username, user_id)) + g.user.username, user_id + ) + ) abort(404) elif user.is_deleted_user(): # Do not flash because the interface does not expose this. # It can only happen by manually crafting a POST request current_app.logger.error( - "Admin {} tried to delete \"deleted\" user".format(g.user.username)) + 'Admin {} tried to delete "deleted" user'.format(g.user.username) + ) abort(403) else: user.delete() db.session.commit() - flash(gettext("Deleted user '{user}'.").format( - user=user.username), "notification") + flash(gettext("Deleted user '{user}'.").format(user=user.username), "notification") - return redirect(url_for('admin.index')) + return redirect(url_for("admin.index")) - @view.route('/edit/<int:user_id>/new-password', methods=('POST',)) + @view.route("/edit/<int:user_id>/new-password", methods=("POST",)) @admin_required def new_password(user_id: int) -> werkzeug.Response: try: @@ -335,20 +365,19 @@ def new_password(user_id: int) -> werkzeug.Response: except NoResultFound: abort(404) - password = request.form.get('password') + password = request.form.get("password") if set_diceware_password(user, password) is not False: if user.last_token is not None: revoke_token(user, user.last_token) user.session_nonce += 1 db.session.commit() - return redirect(url_for('admin.edit_user', user_id=user_id)) + return redirect(url_for("admin.edit_user", user_id=user_id)) - @view.route('/ossec-test', methods=('POST',)) + @view.route("/ossec-test", methods=("POST",)) @admin_required def ossec_test() -> werkzeug.Response: - current_app.logger.error('This is a test OSSEC alert') - flash(gettext('Test alert sent. Please check your email.'), - 'testalert-notification') - return redirect(url_for('admin.manage_config') + "#config-testalert") + current_app.logger.error("This is a test OSSEC alert") + flash(gettext("Test alert sent. Please check your email."), "testalert-notification") + return redirect(url_for("admin.manage_config") + "#config-testalert") return view diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -1,48 +1,53 @@ import collections.abc import json - from datetime import datetime, timedelta, timezone -from typing import Tuple, Callable, Any, Set, Union - -import flask -import werkzeug -from flask import abort, Blueprint, jsonify, request from functools import wraps - -from sqlalchemy import Column -from sqlalchemy.exc import IntegrityError from os import path +from typing import Any, Callable, Set, Tuple, Union from uuid import UUID -from werkzeug.exceptions import default_exceptions +import flask +import werkzeug from db import db +from flask import Blueprint, abort, jsonify, request from journalist_app import utils -from models import (Journalist, Reply, SeenReply, Source, Submission, - LoginThrottledException, InvalidUsernameException, - BadTokenException, InvalidOTPSecretException, - WrongPasswordException) +from models import ( + BadTokenException, + InvalidOTPSecretException, + InvalidUsernameException, + Journalist, + LoginThrottledException, + Reply, + SeenReply, + Source, + Submission, + WrongPasswordException, +) from sdconfig import SDConfig +from sqlalchemy import Column +from sqlalchemy.exc import IntegrityError from store import NotEncrypted, Storage +from werkzeug.exceptions import default_exceptions TOKEN_EXPIRATION_MINS = 60 * 8 def _authenticate_user_from_auth_header(request: flask.Request) -> Journalist: try: - auth_header = request.headers['Authorization'] + auth_header = request.headers["Authorization"] except KeyError: - return abort(403, 'API token not found in Authorization header.') + return abort(403, "API token not found in Authorization header.") if auth_header: split = auth_header.split(" ") - if len(split) != 2 or split[0] != 'Token': - abort(403, 'Malformed authorization header.') + if len(split) != 2 or split[0] != "Token": + abort(403, "Malformed authorization header.") auth_token = split[1] else: - auth_token = '' + auth_token = "" authenticated_user = Journalist.validate_api_token_and_get_user(auth_token) if not authenticated_user: - return abort(403, 'API token is invalid or expired.') + return abort(403, "API token is invalid or expired.") return authenticated_user @@ -51,6 +56,7 @@ def token_required(f: Callable) -> Callable: def decorated_function(*args: Any, **kwargs: Any) -> Any: _authenticate_user_from_auth_header(request) return f(*args, **kwargs) + return decorated_function @@ -62,69 +68,74 @@ def get_or_404(model: db.Model, object_id: str, column: Column) -> db.Model: def make_blueprint(config: SDConfig) -> Blueprint: - api = Blueprint('api', __name__) + api = Blueprint("api", __name__) - @api.route('/') + @api.route("/") def get_endpoints() -> Tuple[flask.Response, int]: - endpoints = {'sources_url': '/api/v1/sources', - 'current_user_url': '/api/v1/user', - 'all_users_url': '/api/v1/users', - 'submissions_url': '/api/v1/submissions', - 'replies_url': '/api/v1/replies', - 'seen_url': '/api/v1/seen', - 'auth_token_url': '/api/v1/token'} + endpoints = { + "sources_url": "/api/v1/sources", + "current_user_url": "/api/v1/user", + "all_users_url": "/api/v1/users", + "submissions_url": "/api/v1/submissions", + "replies_url": "/api/v1/replies", + "seen_url": "/api/v1/seen", + "auth_token_url": "/api/v1/token", + } return jsonify(endpoints), 200 # Before every post, we validate the payload before processing the request @api.before_request def validate_data() -> None: - if request.method == 'POST': + if request.method == "POST": # flag, star, and logout can have empty payloads if not request.data: dataless_endpoints = [ - 'add_star', - 'remove_star', - 'flag', - 'logout', + "add_star", + "remove_star", + "flag", + "logout", ] for endpoint in dataless_endpoints: - if request.endpoint == 'api.' + endpoint: + if request.endpoint == "api." + endpoint: return - abort(400, 'malformed request') + abort(400, "malformed request") # other requests must have valid JSON payload else: try: - json.loads(request.data.decode('utf-8')) + json.loads(request.data.decode("utf-8")) except (ValueError): - abort(400, 'malformed request') + abort(400, "malformed request") - @api.route('/token', methods=['POST']) + @api.route("/token", methods=["POST"]) def get_token() -> Tuple[flask.Response, int]: - creds = json.loads(request.data.decode('utf-8')) + creds = json.loads(request.data.decode("utf-8")) - username = creds.get('username', None) - passphrase = creds.get('passphrase', None) - one_time_code = creds.get('one_time_code', None) + username = creds.get("username", None) + passphrase = creds.get("passphrase", None) + one_time_code = creds.get("one_time_code", None) if username is None: - abort(400, 'username field is missing') + abort(400, "username field is missing") if passphrase is None: - abort(400, 'passphrase field is missing') + abort(400, "passphrase field is missing") if one_time_code is None: - abort(400, 'one_time_code field is missing') + abort(400, "one_time_code field is missing") try: journalist = Journalist.login(username, passphrase, one_time_code) token_expiry = datetime.now(timezone.utc) + timedelta( - seconds=TOKEN_EXPIRATION_MINS * 60) - - response = jsonify({ - 'token': journalist.generate_api_token(expiration=TOKEN_EXPIRATION_MINS * 60), - 'expiration': token_expiry, - 'journalist_uuid': journalist.uuid, - 'journalist_first_name': journalist.first_name, - 'journalist_last_name': journalist.last_name, - }) + seconds=TOKEN_EXPIRATION_MINS * 60 + ) + + response = jsonify( + { + "token": journalist.generate_api_token(expiration=TOKEN_EXPIRATION_MINS * 60), + "expiration": token_expiry, + "journalist_uuid": journalist.uuid, + "journalist_first_name": journalist.first_name, + "journalist_last_name": journalist.last_name, + } + ) # Update access metadata journalist.last_access = datetime.now(timezone.utc) @@ -132,68 +143,73 @@ def get_token() -> Tuple[flask.Response, int]: db.session.commit() return response, 200 - except (LoginThrottledException, InvalidUsernameException, - BadTokenException, InvalidOTPSecretException, WrongPasswordException): - return abort(403, 'Token authentication failed.') - - @api.route('/sources', methods=['GET']) + except ( + LoginThrottledException, + InvalidUsernameException, + BadTokenException, + InvalidOTPSecretException, + WrongPasswordException, + ): + return abort(403, "Token authentication failed.") + + @api.route("/sources", methods=["GET"]) @token_required def get_all_sources() -> Tuple[flask.Response, int]: sources = Source.query.filter_by(pending=False, deleted_at=None).all() - return jsonify( - {'sources': [source.to_json() for source in sources]}), 200 + return jsonify({"sources": [source.to_json() for source in sources]}), 200 - @api.route('/sources/<source_uuid>', methods=['GET', 'DELETE']) + @api.route("/sources/<source_uuid>", methods=["GET", "DELETE"]) @token_required def single_source(source_uuid: str) -> Tuple[flask.Response, int]: - if request.method == 'GET': + if request.method == "GET": source = get_or_404(Source, source_uuid, column=Source.uuid) return jsonify(source.to_json()), 200 - elif request.method == 'DELETE': + elif request.method == "DELETE": source = get_or_404(Source, source_uuid, column=Source.uuid) utils.delete_collection(source.filesystem_id) - return jsonify({'message': 'Source and submissions deleted'}), 200 + return jsonify({"message": "Source and submissions deleted"}), 200 else: abort(405) - @api.route('/sources/<source_uuid>/add_star', methods=['POST']) + @api.route("/sources/<source_uuid>/add_star", methods=["POST"]) @token_required def add_star(source_uuid: str) -> Tuple[flask.Response, int]: source = get_or_404(Source, source_uuid, column=Source.uuid) utils.make_star_true(source.filesystem_id) db.session.commit() - return jsonify({'message': 'Star added'}), 201 + return jsonify({"message": "Star added"}), 201 - @api.route('/sources/<source_uuid>/remove_star', methods=['DELETE']) + @api.route("/sources/<source_uuid>/remove_star", methods=["DELETE"]) @token_required def remove_star(source_uuid: str) -> Tuple[flask.Response, int]: source = get_or_404(Source, source_uuid, column=Source.uuid) utils.make_star_false(source.filesystem_id) db.session.commit() - return jsonify({'message': 'Star removed'}), 200 + return jsonify({"message": "Star removed"}), 200 - @api.route('/sources/<source_uuid>/flag', methods=['POST']) + @api.route("/sources/<source_uuid>/flag", methods=["POST"]) @token_required def flag(source_uuid: str) -> Tuple[flask.Response, int]: - return jsonify({'message': 'Sources no longer need to be flagged for reply'}), 200 + return jsonify({"message": "Sources no longer need to be flagged for reply"}), 200 - @api.route('/sources/<source_uuid>/conversation', methods=['DELETE']) + @api.route("/sources/<source_uuid>/conversation", methods=["DELETE"]) @token_required def source_conversation(source_uuid: str) -> Tuple[flask.Response, int]: - if request.method == 'DELETE': + if request.method == "DELETE": source = get_or_404(Source, source_uuid, column=Source.uuid) utils.delete_source_files(source.filesystem_id) - return jsonify({'message': 'Source data deleted'}), 200 + return jsonify({"message": "Source data deleted"}), 200 else: abort(405) - @api.route('/sources/<source_uuid>/submissions', methods=['GET']) + @api.route("/sources/<source_uuid>/submissions", methods=["GET"]) @token_required def all_source_submissions(source_uuid: str) -> Tuple[flask.Response, int]: source = get_or_404(Source, source_uuid, column=Source.uuid) - return jsonify( - {'submissions': [submission.to_json() for - submission in source.submissions]}), 200 + return ( + jsonify({"submissions": [submission.to_json() for submission in source.submissions]}), + 200, + ) @api.route("/sources/<source_uuid>/submissions/<submission_uuid>/download", methods=["GET"]) @token_required @@ -202,8 +218,7 @@ def download_submission(source_uuid: str, submission_uuid: str) -> flask.Respons submission = get_or_404(Submission, submission_uuid, column=Submission.uuid) return utils.serve_file_with_etag(submission) - @api.route('/sources/<source_uuid>/replies/<reply_uuid>/download', - methods=['GET']) + @api.route("/sources/<source_uuid>/replies/<reply_uuid>/download", methods=["GET"]) @token_required def download_reply(source_uuid: str, reply_uuid: str) -> flask.Response: get_or_404(Source, source_uuid, column=Source.uuid) @@ -211,44 +226,40 @@ def download_reply(source_uuid: str, reply_uuid: str) -> flask.Response: return utils.serve_file_with_etag(reply) - @api.route('/sources/<source_uuid>/submissions/<submission_uuid>', - methods=['GET', 'DELETE']) + @api.route("/sources/<source_uuid>/submissions/<submission_uuid>", methods=["GET", "DELETE"]) @token_required def single_submission(source_uuid: str, submission_uuid: str) -> Tuple[flask.Response, int]: - if request.method == 'GET': + if request.method == "GET": get_or_404(Source, source_uuid, column=Source.uuid) submission = get_or_404(Submission, submission_uuid, column=Submission.uuid) return jsonify(submission.to_json()), 200 - elif request.method == 'DELETE': + elif request.method == "DELETE": get_or_404(Source, source_uuid, column=Source.uuid) submission = get_or_404(Submission, submission_uuid, column=Submission.uuid) utils.delete_file_object(submission) - return jsonify({'message': 'Submission deleted'}), 200 + return jsonify({"message": "Submission deleted"}), 200 else: abort(405) - @api.route('/sources/<source_uuid>/replies', methods=['GET', 'POST']) + @api.route("/sources/<source_uuid>/replies", methods=["GET", "POST"]) @token_required def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: - if request.method == 'GET': + if request.method == "GET": + source = get_or_404(Source, source_uuid, column=Source.uuid) + return jsonify({"replies": [reply.to_json() for reply in source.replies]}), 200 + elif request.method == "POST": source = get_or_404(Source, source_uuid, column=Source.uuid) - return jsonify( - {'replies': [reply.to_json() for - reply in source.replies]}), 200 - elif request.method == 'POST': - source = get_or_404(Source, source_uuid, - column=Source.uuid) if request.json is None: - abort(400, 'please send requests in valid JSON') + abort(400, "please send requests in valid JSON") - if 'reply' not in request.json: - abort(400, 'reply not found in request body') + if "reply" not in request.json: + abort(400, "reply not found in request body") user = _authenticate_user_from_auth_header(request) data = request.json - if not data['reply']: - abort(400, 'reply should not be empty') + if not data["reply"]: + abort(400, "reply should not be empty") source.interaction_count += 1 try: @@ -256,17 +267,17 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: source.filesystem_id, source.interaction_count, source.journalist_filename, - data['reply']) + data["reply"], + ) except NotEncrypted: - return jsonify( - {'message': 'You must encrypt replies client side'}), 400 + return jsonify({"message": "You must encrypt replies client side"}), 400 # issue #3918 filename = path.basename(filename) reply = Reply(user, source, filename, Storage.get_default()) - reply_uuid = data.get('uuid', None) + reply_uuid = data.get("uuid", None) if reply_uuid is not None: # check that is is parseable try: @@ -283,44 +294,57 @@ def all_source_replies(source_uuid: str) -> Tuple[flask.Response, int]: db.session.commit() except IntegrityError as e: db.session.rollback() - if 'UNIQUE constraint failed: replies.uuid' in str(e): - abort(409, 'That UUID is already in use.') + if "UNIQUE constraint failed: replies.uuid" in str(e): + abort(409, "That UUID is already in use.") else: raise e - return jsonify({'message': 'Your reply has been stored', - 'uuid': reply.uuid, - 'filename': reply.filename}), 201 + return ( + jsonify( + { + "message": "Your reply has been stored", + "uuid": reply.uuid, + "filename": reply.filename, + } + ), + 201, + ) else: abort(405) - @api.route('/sources/<source_uuid>/replies/<reply_uuid>', - methods=['GET', 'DELETE']) + @api.route("/sources/<source_uuid>/replies/<reply_uuid>", methods=["GET", "DELETE"]) @token_required def single_reply(source_uuid: str, reply_uuid: str) -> Tuple[flask.Response, int]: get_or_404(Source, source_uuid, column=Source.uuid) reply = get_or_404(Reply, reply_uuid, column=Reply.uuid) - if request.method == 'GET': + if request.method == "GET": return jsonify(reply.to_json()), 200 - elif request.method == 'DELETE': + elif request.method == "DELETE": utils.delete_file_object(reply) - return jsonify({'message': 'Reply deleted'}), 200 + return jsonify({"message": "Reply deleted"}), 200 else: abort(405) - @api.route('/submissions', methods=['GET']) + @api.route("/submissions", methods=["GET"]) @token_required def get_all_submissions() -> Tuple[flask.Response, int]: submissions = Submission.query.all() - return jsonify({'submissions': [submission.to_json() for - submission in submissions if submission.source]}), 200 - - @api.route('/replies', methods=['GET']) + return ( + jsonify( + { + "submissions": [ + submission.to_json() for submission in submissions if submission.source + ] + } + ), + 200, + ) + + @api.route("/replies", methods=["GET"]) @token_required def get_all_replies() -> Tuple[flask.Response, int]: replies = Reply.query.all() - return jsonify( - {'replies': [reply.to_json() for reply in replies if reply.source]}), 200 + return jsonify({"replies": [reply.to_json() for reply in replies if reply.source]}), 200 @api.route("/seen", methods=["POST"]) @token_required @@ -365,34 +389,32 @@ def seen() -> Tuple[flask.Response, int]: abort(405) - @api.route('/user', methods=['GET']) + @api.route("/user", methods=["GET"]) @token_required def get_current_user() -> Tuple[flask.Response, int]: user = _authenticate_user_from_auth_header(request) return jsonify(user.to_json()), 200 - @api.route('/users', methods=['GET']) + @api.route("/users", methods=["GET"]) @token_required def get_all_users() -> Tuple[flask.Response, int]: users = Journalist.query.all() - return jsonify( - {'users': [user.to_json(all_info=False) for user in users]}), 200 + return jsonify({"users": [user.to_json(all_info=False) for user in users]}), 200 - @api.route('/logout', methods=['POST']) + @api.route("/logout", methods=["POST"]) @token_required def logout() -> Tuple[flask.Response, int]: user = _authenticate_user_from_auth_header(request) - auth_token = request.headers['Authorization'].split(" ")[1] + auth_token = request.headers["Authorization"].split(" ")[1] utils.revoke_token(user, auth_token) - return jsonify({'message': 'Your token has been revoked.'}), 200 + return jsonify({"message": "Your token has been revoked."}), 200 def _handle_api_http_exception( - error: werkzeug.exceptions.HTTPException + error: werkzeug.exceptions.HTTPException, ) -> Tuple[flask.Response, int]: # Workaround for no blueprint-level 404/5 error handlers, see: # https://github.com/pallets/flask/issues/503#issuecomment-71383286 - response = jsonify({'error': error.name, - 'message': error.description}) + response = jsonify({"error": error.name, "message": error.description}) return response, error.code # type: ignore diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -2,10 +2,15 @@ from pathlib import Path +import werkzeug +from db import db +from encryption import EncryptionManager, GpgKeyNotFoundError from flask import ( Blueprint, + Markup, abort, current_app, + escape, flash, g, redirect, @@ -13,41 +18,44 @@ request, send_file, url_for, - Markup, - escape, ) -import werkzeug from flask_babel import gettext -from sqlalchemy.orm.exc import NoResultFound - -from db import db -from encryption import GpgKeyNotFoundError, EncryptionManager -from models import Reply, Submission from journalist_app.forms import ReplyForm -from journalist_app.utils import (make_star_true, make_star_false, get_source, - delete_collection, col_download_unread, - col_download_all, col_star, col_un_star, - col_delete, col_delete_data, mark_seen) +from journalist_app.utils import ( + col_delete, + col_delete_data, + col_download_all, + col_download_unread, + col_star, + col_un_star, + delete_collection, + get_source, + make_star_false, + make_star_true, + mark_seen, +) +from models import Reply, Submission from sdconfig import SDConfig +from sqlalchemy.orm.exc import NoResultFound from store import Storage def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('col', __name__) + view = Blueprint("col", __name__) - @view.route('/add_star/<filesystem_id>', methods=('POST',)) + @view.route("/add_star/<filesystem_id>", methods=("POST",)) def add_star(filesystem_id: str) -> werkzeug.Response: make_star_true(filesystem_id) db.session.commit() - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) - @view.route("/remove_star/<filesystem_id>", methods=('POST',)) + @view.route("/remove_star/<filesystem_id>", methods=("POST",)) def remove_star(filesystem_id: str) -> werkzeug.Response: make_star_false(filesystem_id) db.session.commit() - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) - @view.route('/<filesystem_id>') + @view.route("/<filesystem_id>") def col(filesystem_id: str) -> str: form = ReplyForm() source = get_source(filesystem_id) @@ -57,10 +65,9 @@ def col(filesystem_id: str) -> str: except GpgKeyNotFoundError: source.has_key = False - return render_template("col.html", filesystem_id=filesystem_id, - source=source, form=form) + return render_template("col.html", filesystem_id=filesystem_id, source=source, form=form) - @view.route('/delete/<filesystem_id>', methods=('POST',)) + @view.route("/delete/<filesystem_id>", methods=("POST",)) def delete_single(filesystem_id: str) -> werkzeug.Response: """deleting a single collection from its /col page""" source = get_source(filesystem_id) @@ -75,33 +82,44 @@ def delete_single(filesystem_id: str) -> werkzeug.Response: "<b>{}</b> {}".format( # Translators: Precedes a message confirming the success of an operation. escape(gettext("Success!")), - escape(gettext( - "The account and data for the source {} have been deleted.").format( - source.journalist_designation)) + escape( + gettext("The account and data for the source {} have been deleted.").format( + source.journalist_designation + ) + ), ) - ), 'success') + ), + "success", + ) - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) - @view.route('/process', methods=('POST',)) + @view.route("/process", methods=("POST",)) def process() -> werkzeug.Response: - actions = {'download-unread': col_download_unread, - 'download-all': col_download_all, 'star': col_star, - 'un-star': col_un_star, 'delete': col_delete, - 'delete-data': col_delete_data} - if 'cols_selected' not in request.form: + actions = { + "download-unread": col_download_unread, + "download-all": col_download_all, + "star": col_star, + "un-star": col_un_star, + "delete": col_delete, + "delete-data": col_delete_data, + } + if "cols_selected" not in request.form: flash( - Markup("<b>{}</b> {}".format( - # Translators: Error shown when a user has not selected items to act on. - escape(gettext('Nothing Selected')), - escape(gettext('You must select one or more items.')) + Markup( + "<b>{}</b> {}".format( + # Translators: Error shown when a user has not selected items to act on. + escape(gettext("Nothing Selected")), + escape(gettext("You must select one or more items.")), ) - ), 'error') - return redirect(url_for('main.index')) + ), + "error", + ) + return redirect(url_for("main.index")) # getlist is cgi.FieldStorage.getlist - cols_selected = request.form.getlist('cols_selected') - action = request.form['action'] + cols_selected = request.form.getlist("cols_selected") + action = request.form["action"] if action not in actions: return abort(500) @@ -109,14 +127,14 @@ def process() -> werkzeug.Response: method = actions[action] return method(cols_selected) - @view.route('/<filesystem_id>/<fn>') + @view.route("/<filesystem_id>/<fn>") def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: """ Marks the file being download (the file being downloaded is either a submission message, submission file attachement, or journalist reply) as seen by the current logged-in user and send the file to a client to be saved or opened. """ - if '..' in fn or fn.startswith('/'): + if ".." in fn or fn.startswith("/"): abort(404) file = Storage.get_default().path(filesystem_id, fn) @@ -126,7 +144,7 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: "Your download failed because the file could not be found. An admin can find " + "more information in the system and monitoring logs." ), - "error" + "error", ) current_app.logger.error("File {} not found".format(file)) return redirect(url_for("col.col", filesystem_id=filesystem_id)) @@ -146,7 +164,8 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: except NoResultFound as e: current_app.logger.error("Could not mark {} as seen: {}".format(fn, e)) - return send_file(Storage.get_default().path(filesystem_id, fn), - mimetype="application/pgp-encrypted") + return send_file( + Storage.get_default().path(filesystem_id, fn), mimetype="application/pgp-encrypted" + ) return view diff --git a/securedrop/journalist_app/decorators.py b/securedrop/journalist_app/decorators.py --- a/securedrop/journalist_app/decorators.py +++ b/securedrop/journalist_app/decorators.py @@ -1,12 +1,9 @@ # -*- coding: utf-8 -*- -from typing import Any - -from flask import redirect, url_for, flash, g -from flask_babel import gettext from functools import wraps +from typing import Any, Callable -from typing import Callable - +from flask import flash, g, redirect, url_for +from flask_babel import gettext from journalist_app.utils import logged_in @@ -15,7 +12,7 @@ def admin_required(func: Callable) -> Callable: def wrapper(*args: Any, **kwargs: Any) -> Any: if logged_in() and g.user.is_admin: return func(*args, **kwargs) - flash(gettext("Only admins can access this page."), - "notification") - return redirect(url_for('main.index')) + flash(gettext("Only admins can access this page."), "notification") + return redirect(url_for("main.index")) + return wrapper diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -1,26 +1,33 @@ # -*- coding: utf-8 -*- -from flask_babel import lazy_gettext as gettext, ngettext -from flask_wtf import FlaskForm -from flask_wtf.file import FileField, FileAllowed, FileRequired -from wtforms import Field -from wtforms import (TextAreaField, StringField, BooleanField, HiddenField, IntegerField, - ValidationError) -from wtforms.validators import InputRequired, Optional, DataRequired, StopValidation - -from models import Journalist, InstanceConfig, HOTP_SECRET_LENGTH - +import typing from typing import Any -import typing +from flask_babel import lazy_gettext as gettext +from flask_babel import ngettext +from flask_wtf import FlaskForm +from flask_wtf.file import FileAllowed, FileField, FileRequired +from models import HOTP_SECRET_LENGTH, InstanceConfig, Journalist +from wtforms import ( + BooleanField, + Field, + HiddenField, + IntegerField, + StringField, + TextAreaField, + ValidationError, +) +from wtforms.validators import DataRequired, InputRequired, Optional, StopValidation class RequiredIf(DataRequired): - - def __init__(self, - other_field_name: str, - custom_message: typing.Optional[str] = None, - *args: Any, **kwargs: Any) -> None: + def __init__( + self, + other_field_name: str, + custom_message: typing.Optional[str] = None, + *args: Any, + **kwargs: Any + ) -> None: self.other_field_name = other_field_name if custom_message is not None: @@ -36,8 +43,10 @@ def __call__(self, form: FlaskForm, field: Field) -> None: self.message = self.custom_message else: self.message = gettext( - 'The "{name}" field is required when "{other_name}" is set.' - .format(other_name=self.other_field_name, name=field.name)) + 'The "{name}" field is required when "{other_name}" is set.'.format( + other_name=self.other_field_name, name=field.name + ) + ) super(RequiredIf, self).__call__(form, field) else: field.errors[:] = [] @@ -45,20 +54,22 @@ def __call__(self, form: FlaskForm, field: Field) -> None: else: raise ValidationError( gettext( - 'The "{other_name}" field was not found - it is required by "{name}".' - .format(other_name=self.other_field_name, name=field.name)) + 'The "{other_name}" field was not found - it is required by "{name}".'.format( + other_name=self.other_field_name, name=field.name + ) ) + ) def otp_secret_validation(form: FlaskForm, field: Field) -> None: - strip_whitespace = field.data.replace(' ', '') + strip_whitespace = field.data.replace(" ", "") input_length = len(strip_whitespace) if input_length != HOTP_SECRET_LENGTH: raise ValidationError( ngettext( - 'HOTP secrets are 40 characters long - you have entered {num}.', - 'HOTP secrets are 40 characters long - you have entered {num}.', - input_length + "HOTP secrets are 40 characters long - you have entered {num}.", + "HOTP secrets are 40 characters long - you have entered {num}.", + input_length, ).format(num=input_length) ) @@ -67,9 +78,9 @@ def minimum_length_validation(form: FlaskForm, field: Field) -> None: if len(field.data) < Journalist.MIN_USERNAME_LEN: raise ValidationError( ngettext( - 'Must be at least {num} character long.', - 'Must be at least {num} characters long.', - Journalist.MIN_USERNAME_LEN + "Must be at least {num} character long.", + "Must be at least {num} characters long.", + Journalist.MIN_USERNAME_LEN, ).format(num=Journalist.MIN_USERNAME_LEN) ) @@ -78,9 +89,9 @@ def name_length_validation(form: FlaskForm, field: Field) -> None: if len(field.data) > Journalist.MAX_NAME_LEN: raise ValidationError( ngettext( - 'Cannot be longer than {num} character.', - 'Cannot be longer than {num} characters.', - Journalist.MAX_NAME_LEN + "Cannot be longer than {num} character.", + "Cannot be longer than {num} characters.", + Journalist.MAX_NAME_LEN, ).format(num=Journalist.MAX_NAME_LEN) ) @@ -89,17 +100,20 @@ def check_orgname(form: FlaskForm, field: Field) -> None: if len(field.data) > InstanceConfig.MAX_ORG_NAME_LEN: raise ValidationError( ngettext( - 'Cannot be longer than {num} character.', - 'Cannot be longer than {num} characters.', - InstanceConfig.MAX_ORG_NAME_LEN + "Cannot be longer than {num} character.", + "Cannot be longer than {num} characters.", + InstanceConfig.MAX_ORG_NAME_LEN, ).format(num=InstanceConfig.MAX_ORG_NAME_LEN) ) def check_invalid_usernames(form: FlaskForm, field: Field) -> None: if field.data in Journalist.INVALID_USERNAMES: - raise ValidationError(gettext( - "This username is invalid because it is reserved for internal use by the software.")) + raise ValidationError( + gettext( + "This username is invalid because it is reserved for internal use by the software." + ) + ) def check_message_length(form: FlaskForm, field: Field) -> None: @@ -109,71 +123,81 @@ def check_message_length(form: FlaskForm, field: Field) -> None: class NewUserForm(FlaskForm): - username = StringField('username', validators=[ - InputRequired(message=gettext('This field is required.')), - minimum_length_validation, check_invalid_usernames + username = StringField( + "username", + validators=[ + InputRequired(message=gettext("This field is required.")), + minimum_length_validation, + check_invalid_usernames, ], - render_kw={'aria-describedby': 'username-notes'}, + render_kw={"aria-describedby": "username-notes"}, + ) + first_name = StringField( + "first_name", + validators=[name_length_validation, Optional()], + render_kw={"aria-describedby": "name-notes"}, + ) + last_name = StringField( + "last_name", + validators=[name_length_validation, Optional()], + render_kw={"aria-describedby": "name-notes"}, + ) + password = HiddenField("password") + is_admin = BooleanField("is_admin") + is_hotp = BooleanField("is_hotp") + otp_secret = StringField( + "otp_secret", validators=[RequiredIf("is_hotp"), otp_secret_validation] ) - first_name = StringField('first_name', validators=[name_length_validation, Optional()], - render_kw={'aria-describedby': 'name-notes'}) - last_name = StringField('last_name', validators=[name_length_validation, Optional()], - render_kw={'aria-describedby': 'name-notes'}) - password = HiddenField('password') - is_admin = BooleanField('is_admin') - is_hotp = BooleanField('is_hotp') - otp_secret = StringField('otp_secret', validators=[ - RequiredIf("is_hotp"), - otp_secret_validation - ]) class ReplyForm(FlaskForm): message = TextAreaField( - 'Message', + "Message", id="content-area", validators=[ - InputRequired(message=gettext( - 'You cannot send an empty reply.')), + InputRequired(message=gettext("You cannot send an empty reply.")), ], ) class SubmissionPreferencesForm(FlaskForm): prevent_document_uploads = BooleanField( - 'prevent_document_uploads', - false_values=('false', 'False', '') - ) + "prevent_document_uploads", false_values=("false", "False", "") + ) prevent_short_messages = BooleanField( - 'prevent_short_messages', - false_values=('false', 'False', '') - ) - min_message_length = IntegerField('min_message_length', - validators=[ - RequiredIf( - 'prevent_short_messages', - gettext("To configure a minimum message length, " - "you must set the required number of " - "characters.")), - check_message_length], - render_kw={ - 'aria-describedby': 'message-length-notes'}) + "prevent_short_messages", false_values=("false", "False", "") + ) + min_message_length = IntegerField( + "min_message_length", + validators=[ + RequiredIf( + "prevent_short_messages", + gettext( + "To configure a minimum message length, " + "you must set the required number of " + "characters." + ), + ), + check_message_length, + ], + render_kw={"aria-describedby": "message-length-notes"}, + ) reject_codename_messages = BooleanField( - 'reject_codename_messages', - false_values=('false', 'False', '') - ) + "reject_codename_messages", false_values=("false", "False", "") + ) class OrgNameForm(FlaskForm): - organization_name = StringField('organization_name', validators=[ - InputRequired(message=gettext('This field is required.')), - check_orgname - ]) + organization_name = StringField( + "organization_name", + validators=[InputRequired(message=gettext("This field is required.")), check_orgname], + ) class LogoForm(FlaskForm): - logo = FileField(validators=[ - FileRequired(message=gettext('File required.')), - FileAllowed(['png'], - message=gettext("You can only upload PNG image files.")) - ]) + logo = FileField( + validators=[ + FileRequired(message=gettext("File required.")), + FileAllowed(["png"], message=gettext("You can only upload PNG image files.")), + ] + ) diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -3,56 +3,67 @@ from pathlib import Path from typing import Union -import werkzeug -from flask import (Blueprint, request, current_app, session, url_for, redirect, - render_template, g, flash, abort, Markup, escape) -from flask_babel import gettext -from sqlalchemy.orm import joinedload -from sqlalchemy.sql import func - import store - +import werkzeug from db import db from encryption import EncryptionManager -from models import SeenReply, Source, SourceStar, Submission, Reply +from flask import ( + Blueprint, + Markup, + abort, + current_app, + escape, + flash, + g, + redirect, + render_template, + request, + session, + url_for, +) +from flask_babel import gettext from journalist_app.forms import ReplyForm -from journalist_app.utils import (validate_user, bulk_delete, download, - get_source) +from journalist_app.utils import bulk_delete, download, get_source, validate_user +from models import Reply, SeenReply, Source, SourceStar, Submission from sdconfig import SDConfig +from sqlalchemy.orm import joinedload +from sqlalchemy.sql import func from store import Storage def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('main', __name__) + view = Blueprint("main", __name__) - @view.route('/login', methods=('GET', 'POST')) + @view.route("/login", methods=("GET", "POST")) def login() -> Union[str, werkzeug.Response]: - if request.method == 'POST': - user = validate_user(request.form['username'], - request.form['password'], - request.form['token']) + if request.method == "POST": + user = validate_user( + request.form["username"], request.form["password"], request.form["token"] + ) if user: - current_app.logger.info("'{}' logged in with the two-factor code {}" - .format(request.form['username'], - request.form['token'])) + current_app.logger.info( + "'{}' logged in with the two-factor code {}".format( + request.form["username"], request.form["token"] + ) + ) # Update access metadata user.last_access = datetime.now(timezone.utc) db.session.add(user) db.session.commit() - session['uid'] = user.id - session['nonce'] = user.session_nonce - return redirect(url_for('main.index')) + session["uid"] = user.id + session["nonce"] = user.session_nonce + return redirect(url_for("main.index")) return render_template("login.html") - @view.route('/logout') + @view.route("/logout") def logout() -> werkzeug.Response: - session.pop('uid', None) - session.pop('expires', None) - session.pop('nonce', None) - return redirect(url_for('main.index')) + session.pop("uid", None) + session.pop("expires", None) + session.pop("nonce", None) + return redirect(url_for("main.index")) @view.route("/") def index() -> str: @@ -109,7 +120,7 @@ def index() -> str: response = render_template("index.html", unstarred=unstarred, starred=starred) return response - @view.route('/reply', methods=('POST',)) + @view.route("/reply", methods=("POST",)) def reply() -> werkzeug.Response: """Attempt to send a Reply from a Journalist to a Source. Empty messages are rejected, and an informative error message is flashed @@ -128,11 +139,12 @@ def reply() -> werkzeug.Response: if not form.validate_on_submit(): for error in form.message.errors: flash(error, "error") - return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) + return redirect(url_for("col.col", filesystem_id=g.filesystem_id)) g.source.interaction_count += 1 - filename = "{0}-{1}-reply.gpg".format(g.source.interaction_count, - g.source.journalist_filename) + filename = "{0}-{1}-reply.gpg".format( + g.source.interaction_count, g.source.journalist_filename + ) EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=g.filesystem_id, reply_in=form.message.data, @@ -147,16 +159,15 @@ def reply() -> werkzeug.Response: db.session.commit() store.async_add_checksum_for_file(reply, Storage.get_default()) except Exception as exc: - flash(gettext( - "An unexpected error occurred! Please " - "inform your admin."), "error") + flash(gettext("An unexpected error occurred! Please " "inform your admin."), "error") # We take a cautious approach to logging here because we're dealing # with responses to sources. It's possible the exception message # could contain information we don't want to write to disk. current_app.logger.error( - "Reply from '{}' (ID {}) failed: {}!".format(g.user.username, - g.user.id, - exc.__class__)) + "Reply from '{}' (ID {}) failed: {}!".format( + g.user.username, g.user.id, exc.__class__ + ) + ) else: flash( @@ -164,68 +175,71 @@ def reply() -> werkzeug.Response: "<b>{}</b> {}".format( # Translators: Precedes a message confirming the success of an operation. escape(gettext("Success!")), - escape(gettext("The source will receive your reply " - "next time they log in.")) + escape( + gettext("The source will receive your reply " "next time they log in.") + ), ) - ), 'success') + ), + "success", + ) finally: - return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) + return redirect(url_for("col.col", filesystem_id=g.filesystem_id)) - @view.route('/bulk', methods=('POST',)) + @view.route("/bulk", methods=("POST",)) def bulk() -> Union[str, werkzeug.Response]: - action = request.form['action'] - error_redirect = url_for('col.col', filesystem_id=g.filesystem_id) - doc_names_selected = request.form.getlist('doc_names_selected') - selected_docs = [doc for doc in g.source.collection - if doc.filename in doc_names_selected] + action = request.form["action"] + error_redirect = url_for("col.col", filesystem_id=g.filesystem_id) + doc_names_selected = request.form.getlist("doc_names_selected") + selected_docs = [doc for doc in g.source.collection if doc.filename in doc_names_selected] if selected_docs == []: - if action == 'download': + if action == "download": flash( Markup( "<b>{}</b> {}".format( # Translators: Error shown when a user has not selected items to act on. escape(gettext("Nothing Selected")), - escape(gettext("You must select one or more items for download")) + escape(gettext("You must select one or more items for download")), ) - ), 'error') - elif action == 'delete': + ), + "error", + ) + elif action == "delete": flash( Markup( "<b>{}</b> {}".format( # Translators: Error shown when a user has not selected items to act on. escape(gettext("Nothing Selected")), - escape(gettext("You must select one or more items for deletion")) + escape(gettext("You must select one or more items for deletion")), ) - ), 'error') + ), + "error", + ) else: abort(400) return redirect(error_redirect) - if action == 'download': + if action == "download": source = get_source(g.filesystem_id) return download( source.journalist_filename, selected_docs, on_error_redirect=error_redirect ) - elif action == 'delete': + elif action == "delete": return bulk_delete(g.filesystem_id, selected_docs) else: abort(400) - @view.route('/download_unread/<filesystem_id>') + @view.route("/download_unread/<filesystem_id>") def download_unread_filesystem_id(filesystem_id: str) -> werkzeug.Response: unseen_submissions = ( Submission.query.join(Source) - .filter( - Source.deleted_at.is_(None), - Source.filesystem_id == filesystem_id - ) + .filter(Source.deleted_at.is_(None), Source.filesystem_id == filesystem_id) .filter(~Submission.seen_files.any(), ~Submission.seen_messages.any()) .all() ) if len(unseen_submissions) == 0: flash(gettext("No unread submissions for this source."), "error") - return redirect(url_for('col.col', filesystem_id=filesystem_id)) + return redirect(url_for("col.col", filesystem_id=filesystem_id)) source = get_source(filesystem_id) return download(source.journalist_filename, unseen_submissions) diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -1,23 +1,33 @@ # -*- coding: utf-8 -*- import binascii -from datetime import datetime, timezone import os -from typing import Optional, List, Union, Any +from datetime import datetime, timezone +from typing import Any, List, Optional, Union import flask import werkzeug -from flask import (g, flash, current_app, abort, send_file, redirect, url_for, - Markup, sessions, request, escape) -from flask_babel import gettext, ngettext -from sqlalchemy.exc import IntegrityError - from db import db from encryption import EncryptionManager +from flask import ( + Markup, + abort, + current_app, + escape, + flash, + g, + redirect, + request, + send_file, + sessions, + url_for, +) +from flask_babel import gettext, ngettext from models import ( + HOTP_SECRET_LENGTH, BadTokenException, FirstOrLastNameError, - InvalidPasswordLength, InvalidOTPSecretException, + InvalidPasswordLength, InvalidUsernameException, Journalist, LoginThrottledException, @@ -32,8 +42,8 @@ Submission, WrongPasswordException, get_one_or_else, - HOTP_SECRET_LENGTH, ) +from sqlalchemy.exc import IntegrityError from store import Storage, add_checksum_for_file @@ -45,7 +55,7 @@ def logged_in() -> bool: # This check is good for the edge case where a user is deleted but still # has an active session - we will not authenticate a user if they are not # in the database. - return bool(g.get('user', None)) + return bool(g.get("user", None)) def commit_account_changes(user: Journalist) -> None: @@ -54,11 +64,8 @@ def commit_account_changes(user: Journalist) -> None: db.session.add(user) db.session.commit() except Exception as e: - flash(gettext( - "An unexpected error occurred! Please " - "inform your admin."), "error") - current_app.logger.error("Account changes for '{}' failed: {}" - .format(user, e)) + flash(gettext("An unexpected error occurred! Please " "inform your admin."), "error") + current_app.logger.error("Account changes for '{}' failed: {}".format(user, e)) db.session.rollback() else: flash(gettext("Account updated."), "success") @@ -83,7 +90,7 @@ def validate_user( username: str, password: Optional[str], token: Optional[str], - error_message: Optional[str] = None + error_message: Optional[str] = None, ) -> Optional[Journalist]: """ Validates the user by calling the login and handling exceptions @@ -95,15 +102,16 @@ def validate_user( """ try: return Journalist.login(username, password, token) - except (InvalidUsernameException, - InvalidOTPSecretException, - BadTokenException, - WrongPasswordException, - LoginThrottledException, - InvalidPasswordLength) as e: - current_app.logger.error("Login for '{}' failed: {}".format( - username, e)) - login_flashed_msg = error_message if error_message else gettext('Login failed.') + except ( + InvalidUsernameException, + InvalidOTPSecretException, + BadTokenException, + WrongPasswordException, + LoginThrottledException, + InvalidPasswordLength, + ) as e: + current_app.logger.error("Login for '{}' failed: {}".format(username, e)) + login_flashed_msg = error_message if error_message else gettext("Login failed.") if isinstance(e, LoginThrottledException): login_flashed_msg += " " @@ -113,22 +121,22 @@ def validate_user( login_flashed_msg += ngettext( "Please wait at least {num} second before logging in again.", "Please wait at least {num} seconds before logging in again.", - period + period, ).format(num=period) elif isinstance(e, InvalidOTPSecretException): - login_flashed_msg += ' ' + login_flashed_msg += " " login_flashed_msg += gettext( - "Your 2FA details are invalid" - " - please contact an administrator to reset them.") + "Your 2FA details are invalid" " - please contact an administrator to reset them." + ) else: try: - user = Journalist.query.filter_by( - username=username).one() + user = Journalist.query.filter_by(username=username).one() if user.is_totp: login_flashed_msg += " " login_flashed_msg += gettext( "Please wait for a new code from your two-factor mobile" - " app or security key before trying again.") + " app or security key before trying again." + ) except Exception: pass @@ -143,33 +151,36 @@ def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: :param otp_secret: the new HOTP secret :return: True if it validates, False if it does not """ - strip_whitespace = otp_secret.replace(' ', '') + strip_whitespace = otp_secret.replace(" ", "") secret_length = len(strip_whitespace) if secret_length != HOTP_SECRET_LENGTH: - flash(ngettext( - 'HOTP secrets are 40 characters long - you have entered {num}.', - 'HOTP secrets are 40 characters long - you have entered {num}.', - secret_length - ).format(num=secret_length), "error") + flash( + ngettext( + "HOTP secrets are 40 characters long - you have entered {num}.", + "HOTP secrets are 40 characters long - you have entered {num}.", + secret_length, + ).format(num=secret_length), + "error", + ) return False try: user.set_hotp_secret(otp_secret) except (binascii.Error, TypeError) as e: if "Non-hexadecimal digit found" in str(e): - flash(gettext( - "Invalid HOTP secret format: " - "please only submit letters A-F and numbers 0-9."), - "error") + flash( + gettext( + "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9." + ), + "error", + ) return False else: - flash(gettext( - "An unexpected error occurred! " - "Please inform your admin."), "error") + flash(gettext("An unexpected error occurred! " "Please inform your admin."), "error") current_app.logger.error( - "set_hotp_secret '{}' (id {}) failed: {}".format( - otp_secret, user.id, e)) + "set_hotp_secret '{}' (id {}) failed: {}".format(otp_secret, user.id, e) + ) return False return True @@ -195,7 +206,7 @@ def mark_seen(targets: List[Union[Submission, Reply]], user: Journalist) -> None db.session.commit() except IntegrityError as e: db.session.rollback() - if 'UNIQUE constraint failed' in str(e): + if "UNIQUE constraint failed" in str(e): continue raise @@ -203,7 +214,7 @@ def mark_seen(targets: List[Union[Submission, Reply]], user: Journalist) -> None def download( zip_basename: str, submissions: List[Union[Submission, Reply]], - on_error_redirect: Optional[str] = None + on_error_redirect: Optional[str] = None, ) -> werkzeug.Response: """Send client contents of ZIP-file *zip_basename*-<timestamp>.zip containing *submissions*. The ZIP-file, being a @@ -224,12 +235,12 @@ def download( + "more information in the system and monitoring logs.", "Your download failed because a file could not be found. An admin can find " + "more information in the system and monitoring logs.", - len(submissions) + len(submissions), ), - "error" + "error", ) if on_error_redirect is None: - on_error_redirect = url_for('main.index') + on_error_redirect = url_for("main.index") return redirect(on_error_redirect) attachment_filename = "{}--{}.zip".format( @@ -259,8 +270,7 @@ def delete_file_object(file_object: Union[Submission, Reply]) -> None: def bulk_delete( - filesystem_id: str, - items_selected: List[Union[Submission, Reply]] + filesystem_id: str, items_selected: List[Union[Submission, Reply]] ) -> werkzeug.Response: deletion_errors = 0 for item in items_selected: @@ -271,19 +281,25 @@ def bulk_delete( num_selected = len(items_selected) success_message = ngettext( - "The item has been deleted.", "{num} items have been deleted.", - num_selected).format(num=num_selected) + "The item has been deleted.", "{num} items have been deleted.", num_selected + ).format(num=num_selected) flash( Markup( - "<b>{}</b> {}".format( - # Translators: Precedes a message confirming the success of an operation. - escape(gettext("Success!")), escape(success_message))), 'success') + "<b>{}</b> {}".format( + # Translators: Precedes a message confirming the success of an operation. + escape(gettext("Success!")), + escape(success_message), + ) + ), + "success", + ) if deletion_errors > 0: - current_app.logger.error("Disconnected submission entries (%d) were detected", - deletion_errors) - return redirect(url_for('col.col', filesystem_id=filesystem_id)) + current_app.logger.error( + "Disconnected submission entries (%d) were detected", deletion_errors + ) + return redirect(url_for("col.col", filesystem_id=filesystem_id)) def make_star_true(filesystem_id: str) -> None: @@ -309,7 +325,7 @@ def col_star(cols_selected: List[str]) -> werkzeug.Response: make_star_true(filesystem_id) db.session.commit() - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) def col_un_star(cols_selected: List[str]) -> werkzeug.Response: @@ -317,7 +333,7 @@ def col_un_star(cols_selected: List[str]) -> werkzeug.Response: make_star_false(filesystem_id) db.session.commit() - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) def col_delete(cols_selected: List[str]) -> werkzeug.Response: @@ -335,15 +351,21 @@ def col_delete(cols_selected: List[str]) -> werkzeug.Response: success_message = ngettext( "The account and all data for the source have been deleted.", "The accounts and all data for {n} sources have been deleted.", - num).format(n=num) + num, + ).format(n=num) flash( Markup( - "<b>{}</b> {}".format( - # Translators: Precedes a message confirming the success of an operation. - escape(gettext("Success!")), escape(success_message))), 'success') + "<b>{}</b> {}".format( + # Translators: Precedes a message confirming the success of an operation. + escape(gettext("Success!")), + escape(success_message), + ) + ), + "success", + ) - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) def delete_source_files(filesystem_id: str) -> None: @@ -366,8 +388,11 @@ def col_delete_data(cols_selected: List[str]) -> werkzeug.Response: "<b>{}</b> {}".format( # Translators: Error shown when a user has not selected items to act on. escape(gettext("Nothing Selected")), - escape(gettext("You must select one or more items for deletion."))) - ), 'error') + escape(gettext("You must select one or more items for deletion.")), + ) + ), + "error", + ) else: for filesystem_id in cols_selected: @@ -378,10 +403,13 @@ def col_delete_data(cols_selected: List[str]) -> werkzeug.Response: "<b>{}</b> {}".format( # Translators: Precedes a message confirming the success of an operation. escape(gettext("Success!")), - escape(gettext("The files and messages have been deleted."))) - ), 'success') + escape(gettext("The files and messages have been deleted.")), + ) + ), + "success", + ) - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) def delete_collection(filesystem_id: str) -> None: @@ -418,9 +446,9 @@ def set_name(user: Journalist, first_name: Optional[str], last_name: Optional[st try: user.set_name(first_name, last_name) db.session.commit() - flash(gettext('Name updated.'), "success") + flash(gettext("Name updated."), "success") except FirstOrLastNameError as e: - flash(gettext('Name not updated: {message}').format(message=e), "error") + flash(gettext("Name not updated: {message}").format(message=e), "error") def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: @@ -428,19 +456,21 @@ def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: # nosemgrep: python.django.security.audit.unvalidated-password.unvalidated-password user.set_password(password) except PasswordError: - flash(gettext( - 'The password you submitted is invalid. Password not changed.'), 'error') + flash(gettext("The password you submitted is invalid. Password not changed."), "error") return False try: db.session.commit() except Exception: - flash(gettext( - 'There was an error, and the new password might not have been ' - 'saved correctly. To prevent you from getting locked ' - 'out of your account, you should reset your password again.'), - 'error') - current_app.logger.error('Failed to update a valid password.') + flash( + gettext( + "There was an error, and the new password might not have been " + "saved correctly. To prevent you from getting locked " + "out of your account, you should reset your password again." + ), + "error", + ) + current_app.logger.error("Failed to update a valid password.") return False # using Markup so the HTML isn't escaped @@ -453,10 +483,10 @@ def set_diceware_password(user: Journalist, password: Optional[str]) -> bool: "New password:" ) ), - password=Markup.escape("" if password is None else password) + password=Markup.escape("" if password is None else password), ) ), - 'success' + "success", ) return True @@ -467,10 +497,7 @@ def col_download_unread(cols_selected: List[str]) -> werkzeug.Response: """ unseen_submissions = ( Submission.query.join(Source) - .filter( - Source.deleted_at.is_(None), - Source.filesystem_id.in_(cols_selected) - ) + .filter(Source.deleted_at.is_(None), Source.filesystem_id.in_(cols_selected)) .filter(~Submission.seen_files.any(), ~Submission.seen_messages.any()) .all() ) @@ -486,39 +513,40 @@ def col_download_all(cols_selected: List[str]) -> werkzeug.Response: """Download all submissions from all selected sources.""" submissions = [] # type: List[Union[Source, Submission]] for filesystem_id in cols_selected: - id = Source.query.filter(Source.filesystem_id == filesystem_id) \ - .filter_by(deleted_at=None).one().id - submissions += Submission.query.filter( - Submission.source_id == id).all() + id = ( + Source.query.filter(Source.filesystem_id == filesystem_id) + .filter_by(deleted_at=None) + .one() + .id + ) + submissions += Submission.query.filter(Submission.source_id == id).all() return download("all", submissions) def serve_file_with_etag(db_obj: Union[Reply, Submission]) -> flask.Response: file_path = Storage.get_default().path(db_obj.source.filesystem_id, db_obj.filename) - response = send_file(file_path, - mimetype="application/pgp-encrypted", - as_attachment=True, - etag=False) # Disable Flask default ETag + response = send_file( + file_path, mimetype="application/pgp-encrypted", as_attachment=True, etag=False + ) # Disable Flask default ETag if not db_obj.checksum: add_checksum_for_file(db.session, db_obj, file_path) response.direct_passthrough = False - response.headers['Etag'] = db_obj.checksum + response.headers["Etag"] = db_obj.checksum return response -class JournalistInterfaceSessionInterface( - sessions.SecureCookieSessionInterface): +class JournalistInterfaceSessionInterface(sessions.SecureCookieSessionInterface): """A custom session interface that skips storing sessions for api requests but otherwise just uses the default behaviour.""" + def save_session(self, app: flask.Flask, session: Any, response: flask.Response) -> None: # If this is an api request do not save the session if request.path.split("/")[1] == "api": return else: - super(JournalistInterfaceSessionInterface, self).save_session( - app, session, response) + super(JournalistInterfaceSessionInterface, self).save_session(app, session, response) def cleanup_expired_revoked_tokens() -> None: diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -8,17 +8,14 @@ import argparse import datetime import io -from pathlib import Path - import math import os import random import string from itertools import cycle +from pathlib import Path from typing import Optional, Tuple -from sqlalchemy.exc import IntegrityError - import journalist_app from db import db from encryption import EncryptionManager @@ -37,6 +34,7 @@ from sdconfig import config from source_user import create_source_user from specialstrings import strings +from sqlalchemy.exc import IntegrityError from store import Storage messages = cycle(strings) diff --git a/securedrop/manage.py b/securedrop/manage.py --- a/securedrop/manage.py +++ b/securedrop/manage.py @@ -5,18 +5,16 @@ import logging import os import pwd -import subprocess import shutil import signal +import subprocess import sys import time import traceback from argparse import _SubParsersAction -from typing import Optional +from typing import List, Optional from flask.ctx import AppContext -from typing import List - from passphrases import PassphraseGenerator sys.path.insert(0, "/var/www/securedrop") # noqa: E402 @@ -24,17 +22,11 @@ import qrcode # noqa: E402 from sqlalchemy.orm.exc import NoResultFound # noqa: E402 - if not os.environ.get("SECUREDROP_ENV"): - os.environ['SECUREDROP_ENV'] = 'dev' # noqa + os.environ["SECUREDROP_ENV"] = "dev" # noqa from db import db # noqa: E402 -from models import ( # noqa: E402 - FirstOrLastNameError, - InvalidUsernameException, - Journalist, -) from management import app_context, config # noqa: E402 from management.run import run # noqa: E402 from management.submissions import ( # noqa: E402 @@ -46,8 +38,9 @@ add_list_fs_disconnect_parser, add_were_there_submissions_today, ) +from models import FirstOrLastNameError, InvalidUsernameException, Journalist # noqa: E402 -logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s') +logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger(__name__) @@ -65,9 +58,10 @@ def reset(args: argparse.Namespace, context: Optional[AppContext] = None) -> int 3. Erases stored submissions and replies from the store dir. """ # Erase the development db file - if not hasattr(config, 'DATABASE_FILE'): - raise Exception("./manage.py doesn't know how to clear the db " - 'if the backend is not sqlite') + if not hasattr(config, "DATABASE_FILE"): + raise Exception( + "./manage.py doesn't know how to clear the db " "if the backend is not sqlite" + ) # we need to save some data about the old DB file so we can recreate it # with the same state @@ -86,12 +80,12 @@ def reset(args: argparse.Namespace, context: Optional[AppContext] = None) -> int # Regenerate the database # 1. Create it - subprocess.check_call(['sqlite3', config.DATABASE_FILE, '.databases']) + subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) # 2. Set permissions on it os.chown(config.DATABASE_FILE, uid, gid) os.chmod(config.DATABASE_FILE, 0o0640) - if os.environ.get('SECUREDROP_ENV') == 'dev': + if os.environ.get("SECUREDROP_ENV") == "dev": # 3. Create the DB from the metadata directly when in 'dev' so # developers can test application changes without first writing # alembic migration. @@ -100,14 +94,11 @@ def reset(args: argparse.Namespace, context: Optional[AppContext] = None) -> int else: # We have to override the hardcoded .ini file because during testing # the value in the .ini doesn't exist. - ini_dir = os.path.dirname(getattr(config, - 'TEST_ALEMBIC_INI', - 'alembic.ini')) + ini_dir = os.path.dirname(getattr(config, "TEST_ALEMBIC_INI", "alembic.ini")) # 3. Migrate it to 'head' # nosemgrep: python.lang.security.audit.subprocess-shell-true.subprocess-shell-true - subprocess.check_call('cd {} && alembic upgrade head'.format(ini_dir), - shell=True) # nosec + subprocess.check_call("cd {} && alembic upgrade head".format(ini_dir), shell=True) # nosec # Clear submission/reply storage try: @@ -135,47 +126,48 @@ def add_journalist(args: argparse.Namespace) -> int: def _get_username() -> str: while True: - username = obtain_input('Username: ') + username = obtain_input("Username: ") try: Journalist.check_username_acceptable(username) except InvalidUsernameException as e: - print('Invalid username: ' + str(e)) + print("Invalid username: " + str(e)) else: return username def _get_first_name() -> Optional[str]: while True: - first_name = obtain_input('First name: ') + first_name = obtain_input("First name: ") if not first_name: return None try: Journalist.check_name_acceptable(first_name) return first_name except FirstOrLastNameError as e: - print('Invalid name: ' + str(e)) + print("Invalid name: " + str(e)) def _get_last_name() -> Optional[str]: while True: - last_name = obtain_input('Last name: ') + last_name = obtain_input("Last name: ") if not last_name: return None try: Journalist.check_name_acceptable(last_name) return last_name except FirstOrLastNameError as e: - print('Invalid name: ' + str(e)) + print("Invalid name: " + str(e)) def _get_yubikey_usage() -> bool: - '''Function used to allow for test suite mocking''' + """Function used to allow for test suite mocking""" while True: - answer = obtain_input('Will this user be using a YubiKey [HOTP]? ' - '(y/N): ').lower().strip() - if answer in ('y', 'yes'): + answer = ( + obtain_input("Will this user be using a YubiKey [HOTP]? " "(y/N): ").lower().strip() + ) + if answer in ("y", "yes"): return True - elif answer in ('', 'n', 'no'): + elif answer in ("", "n", "no"): return False else: print('Invalid answer. Please type "y" or "n"') @@ -196,66 +188,70 @@ def _add_user(is_admin: bool = False, context: Optional[AppContext] = None) -> i if is_hotp: while True: otp_secret = obtain_input( - "Please configure this user's YubiKey and enter the " - "secret: ") + "Please configure this user's YubiKey and enter the " "secret: " + ) if otp_secret: tmp_str = otp_secret.replace(" ", "") if len(tmp_str) != 40: - print("The length of the secret is not correct. " - "Expected 40 characters, but received {0}. " - "Try again.".format(len(tmp_str))) + print( + "The length of the secret is not correct. " + "Expected 40 characters, but received {0}. " + "Try again.".format(len(tmp_str)) + ) continue if otp_secret: break try: - user = Journalist(username=username, - first_name=first_name, - last_name=last_name, - password=password, - is_admin=is_admin, - otp_secret=otp_secret) + user = Journalist( + username=username, + first_name=first_name, + last_name=last_name, + password=password, + is_admin=is_admin, + otp_secret=otp_secret, + ) db.session.add(user) db.session.commit() except Exception as exc: db.session.rollback() if "UNIQUE constraint failed: journalists.username" in str(exc): - print('ERROR: That username is already taken!') + print("ERROR: That username is already taken!") else: exc_type, exc_value, exc_traceback = sys.exc_info() - print(repr(traceback.format_exception(exc_type, exc_value, - exc_traceback))) + print(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) return 1 else: print('User "{}" successfully added'.format(username)) if not otp_secret: # Print the QR code for FreeOTP - print('\nScan the QR code below with FreeOTP:\n') - uri = user.totp.provisioning_uri(username, - issuer_name='SecureDrop') + print("\nScan the QR code below with FreeOTP:\n") + uri = user.totp.provisioning_uri(username, issuer_name="SecureDrop") qr = qrcode.QRCode() qr.add_data(uri) qr.print_ascii(tty=sys.stdout.isatty()) - print('\nIf the barcode does not render correctly, try ' - "changing your terminal's font (Monospace for Linux, " - 'Menlo for OS X). If you are using iTerm on Mac OS X, ' - 'you will need to change the "Non-ASCII Font", which ' - "is your profile\'s Text settings.\n\nCan't scan the " - 'barcode? Enter following shared secret manually:' - '\n{}\n'.format(user.formatted_otp_secret)) + print( + "\nIf the barcode does not render correctly, try " + "changing your terminal's font (Monospace for Linux, " + "Menlo for OS X). If you are using iTerm on Mac OS X, " + 'you will need to change the "Non-ASCII Font", which ' + "is your profile's Text settings.\n\nCan't scan the " + "barcode? Enter following shared secret manually:" + "\n{}\n".format(user.formatted_otp_secret) + ) return 0 def _get_username_to_delete() -> str: - return obtain_input('Username to delete: ') + return obtain_input("Username to delete: ") def _get_delete_confirmation(username: str) -> bool: - confirmation = obtain_input('Are you sure you want to delete user ' - '"{}" (y/n)?'.format(username)) - if confirmation.lower() != 'y': - print('Confirmation not received: user "{}" was NOT ' - 'deleted'.format(username)) + confirmation = obtain_input( + "Are you sure you want to delete user " '"{}" (y/n)?'.format(username) + ) + if confirmation.lower() != "y": + print('Confirmation not received: user "{}" was NOT ' "deleted".format(username)) return False return True @@ -267,7 +263,7 @@ def delete_user(args: argparse.Namespace, context: Optional[AppContext] = None) try: selected_user = Journalist.query.filter_by(username=username).one() except NoResultFound: - print('ERROR: That user was not found!') + print("ERROR: That user was not found!") return 0 # Confirm deletion if user is found @@ -295,9 +291,9 @@ def delete_user(args: argparse.Namespace, context: Optional[AppContext] = None) def clean_tmp(args: argparse.Namespace) -> int: - """Cleanup the SecureDrop temp directory. """ + """Cleanup the SecureDrop temp directory.""" if not os.path.exists(args.directory): - log.debug('{} does not exist, do nothing'.format(args.directory)) + log.debug("{} does not exist, do nothing".format(args.directory)) return 0 def listdir_fullpath(d: str) -> List[str]: @@ -307,49 +303,53 @@ def listdir_fullpath(d: str) -> List[str]: for path in listdir_fullpath(args.directory): if time.time() - os.stat(path).st_mtime > too_old: os.remove(path) - log.debug('{} removed'.format(path)) + log.debug("{} removed".format(path)) else: - log.debug('{} modified less than {} days ago'.format( - path, args.days)) + log.debug("{} modified less than {} days ago".format(path, args.days)) return 0 def init_db(args: argparse.Namespace) -> None: user = pwd.getpwnam(args.user) - subprocess.check_call(['sqlite3', config.DATABASE_FILE, '.databases']) + subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) os.chown(config.DATABASE_FILE, user.pw_uid, user.pw_gid) os.chmod(config.DATABASE_FILE, 0o0640) - subprocess.check_call(['alembic', 'upgrade', 'head']) + subprocess.check_call(["alembic", "upgrade", "head"]) def get_args() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog=__file__, description='Management ' - 'and testing utility for SecureDrop.') - parser.add_argument('-v', '--verbose', action='store_true') - parser.add_argument('--data-root', - default=config.SECUREDROP_DATA_ROOT, - help=('directory in which the securedrop ' - 'data is stored')) - parser.add_argument('--store-dir', - default=config.STORE_DIR, - help=('directory in which the documents are stored')) + parser = argparse.ArgumentParser( + prog=__file__, description="Management " "and testing utility for SecureDrop." + ) + parser.add_argument("-v", "--verbose", action="store_true") + parser.add_argument( + "--data-root", + default=config.SECUREDROP_DATA_ROOT, + help=("directory in which the securedrop " "data is stored"), + ) + parser.add_argument( + "--store-dir", + default=config.STORE_DIR, + help=("directory in which the documents are stored"), + ) subps = parser.add_subparsers() # Add/remove journalists + admins - admin_subp = subps.add_parser('add-admin', help='Add an admin to the ' - 'application.') + admin_subp = subps.add_parser("add-admin", help="Add an admin to the " "application.") admin_subp.set_defaults(func=add_admin) - admin_subp_a = subps.add_parser('add_admin', help='^') + admin_subp_a = subps.add_parser("add_admin", help="^") admin_subp_a.set_defaults(func=add_admin) - journalist_subp = subps.add_parser('add-journalist', help='Add a ' - 'journalist to the application.') + journalist_subp = subps.add_parser( + "add-journalist", help="Add a " "journalist to the application." + ) journalist_subp.set_defaults(func=add_journalist) - journalist_subp_a = subps.add_parser('add_journalist', help='^') + journalist_subp_a = subps.add_parser("add_journalist", help="^") journalist_subp_a.set_defaults(func=add_journalist) - delete_user_subp = subps.add_parser('delete-user', help='Delete a user ' - 'from the application.') + delete_user_subp = subps.add_parser( + "delete-user", help="Delete a user " "from the application." + ) delete_user_subp.set_defaults(func=delete_user) - delete_user_subp_a = subps.add_parser('delete_user', help='^') + delete_user_subp_a = subps.add_parser("delete_user", help="^") delete_user_subp_a.set_defaults(func=delete_user) add_check_db_disconnect_parser(subps) @@ -360,46 +360,52 @@ def get_args() -> argparse.ArgumentParser: add_list_fs_disconnect_parser(subps) # Cleanup the SD temp dir - set_clean_tmp_parser(subps, 'clean-tmp') - set_clean_tmp_parser(subps, 'clean_tmp') + set_clean_tmp_parser(subps, "clean-tmp") + set_clean_tmp_parser(subps, "clean_tmp") - init_db_subp = subps.add_parser('init-db', help='Initialize the database.\n') - init_db_subp.add_argument('-u', '--user', - help='Unix user for the DB', - required=True) + init_db_subp = subps.add_parser("init-db", help="Initialize the database.\n") + init_db_subp.add_argument("-u", "--user", help="Unix user for the DB", required=True) init_db_subp.set_defaults(func=init_db) add_were_there_submissions_today(subps) # Run WSGI app - run_subp = subps.add_parser('run', help='DANGER!!! ONLY FOR DEVELOPMENT ' - 'USE. DO NOT USE IN PRODUCTION. Run the ' - 'Werkzeug source and journalist WSGI apps.\n') + run_subp = subps.add_parser( + "run", + help="DANGER!!! ONLY FOR DEVELOPMENT " + "USE. DO NOT USE IN PRODUCTION. Run the " + "Werkzeug source and journalist WSGI apps.\n", + ) run_subp.set_defaults(func=run) # Reset application state - reset_subp = subps.add_parser('reset', help='DANGER!!! ONLY FOR DEVELOPMENT ' - 'USE. DO NOT USE IN PRODUCTION. Clear the ' - 'SecureDrop application\'s state.\n') + reset_subp = subps.add_parser( + "reset", + help="DANGER!!! ONLY FOR DEVELOPMENT " + "USE. DO NOT USE IN PRODUCTION. Clear the " + "SecureDrop application's state.\n", + ) reset_subp.set_defaults(func=reset) return parser def set_clean_tmp_parser(subps: _SubParsersAction, name: str) -> None: - parser = subps.add_parser(name, help='Cleanup the ' - 'SecureDrop temp directory.') + parser = subps.add_parser(name, help="Cleanup the " "SecureDrop temp directory.") default_days = 7 parser.add_argument( - '--days', + "--days", default=default_days, type=int, - help=('remove files not modified in a given number of DAYS ' - '(default {} days)'.format(default_days))) + help=( + "remove files not modified in a given number of DAYS " + "(default {} days)".format(default_days) + ), + ) parser.add_argument( - '--directory', + "--directory", default=config.TEMP_DIR, - help=('remove old files from DIRECTORY ' - '(default {})'.format(config.TEMP_DIR))) + help=("remove old files from DIRECTORY " "(default {})".format(config.TEMP_DIR)), + ) parser.set_defaults(func=clean_tmp) @@ -425,5 +431,5 @@ def _run_from_commandline() -> None: # pragma: no cover sys.exit(signal.SIGINT) -if __name__ == '__main__': # pragma: no cover +if __name__ == "__main__": # pragma: no cover _run_from_commandline() diff --git a/securedrop/management/run.py b/securedrop/management/run.py --- a/securedrop/management/run.py +++ b/securedrop/management/run.py @@ -5,14 +5,9 @@ import subprocess import sys -__all__ = ['run'] +__all__ = ["run"] -from typing import Any - -from typing import List -from typing import TextIO - -from typing import Callable +from typing import Any, Callable, List, TextIO def colorize(s: str, color: str, bold: bool = False) -> str: @@ -22,36 +17,35 @@ def colorize(s: str, color: str, bold: bool = False) -> str: """ # List of shell colors from https://www.siafoo.net/snippet/88 shell_colors = { - 'gray': '30', - 'red': '31', - 'green': '32', - 'yellow': '33', - 'blue': '34', - 'magenta': '35', - 'cyan': '36', - 'white': '37', - 'crimson': '38', - 'highlighted_red': '41', - 'highlighted_green': '42', - 'highlighted_brown': '43', - 'highlighted_blue': '44', - 'highlighted_magenta': '45', - 'highlighted_cyan': '46', - 'highlighted_gray': '47', - 'highlighted_crimson': '48' + "gray": "30", + "red": "31", + "green": "32", + "yellow": "33", + "blue": "34", + "magenta": "35", + "cyan": "36", + "white": "37", + "crimson": "38", + "highlighted_red": "41", + "highlighted_green": "42", + "highlighted_brown": "43", + "highlighted_blue": "44", + "highlighted_magenta": "45", + "highlighted_cyan": "46", + "highlighted_gray": "47", + "highlighted_crimson": "48", } # Based on http://stackoverflow.com/a/2330297/1093000 attrs = [] attrs.append(shell_colors[color]) if bold: - attrs.append('1') + attrs.append("1") - return '\x1b[{}m{}\x1b[0m'.format(';'.join(attrs), s) + return "\x1b[{}m{}\x1b[0m".format(";".join(attrs), s) class DevServerProcess(subprocess.Popen): # pragma: no cover - def __init__(self, label: str, cmd: List[str], color: str) -> None: self.label = label self.cmd = cmd @@ -62,7 +56,8 @@ def __init__(self, label: str, cmd: List[str], color: str) -> None: stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - preexec_fn=os.setsid) + preexec_fn=os.setsid, + ) def print_label(self, to: TextIO) -> None: label = "\n => {} <= \n\n".format(self.label) @@ -86,7 +81,6 @@ def fileno(self) -> int: class DevServerProcessMonitor: # pragma: no cover - def __init__(self, proc_funcs: List[Callable]) -> None: self.procs = [] self.last_proc = None @@ -108,19 +102,23 @@ def monitor(self) -> None: self.last_proc = proc line = proc.stdout.readline() - sys.stdout.write(line.decode('utf-8')) + sys.stdout.write(line.decode("utf-8")) sys.stdout.flush() if any(proc.poll() is not None for proc in self.procs): # If any of the processes terminates (for example, due to # a syntax error causing a reload to fail), kill them all # so we don't get stuck. - sys.stdout.write(colorize( - "\nOne of the development servers exited unexpectedly. " - "See the traceback above for details.\n" - "Once you have resolved the issue, you can re-run " - "'./manage.py run' to continue developing.\n\n", - "red", True)) + sys.stdout.write( + colorize( + "\nOne of the development servers exited unexpectedly. " + "See the traceback above for details.\n" + "Once you have resolved the issue, you can re-run " + "'./manage.py run' to continue developing.\n\n", + "red", + True, + ) + ) self.cleanup() break @@ -152,28 +150,26 @@ def run(args: Any) -> None: # pragma: no cover * https://stackoverflow.com/q/22565606/837471 """ - print(""" - ____ ____ -/\\ _`\\ /\\ _`\\ -\\ \\,\\L\\_\\ __ ___ __ __ _ __ __\\ \\ \\/\\ \\ _ __ ___ _____ - \\/_\\__ \\ /'__`\\ /'___\\/\\ \\/\\ \\/\\`'__\\/'__`\\ \\ \\ \\ \\/\\`'__\\/ __`\\/\\ '__`\\ - /\\ \\L\\ \\/\\ __//\\ \\__/\\ \\ \\_\\ \\ \\ \\//\\ __/\\ \\ \\_\\ \\ \\ \\//\\ \\L\\ \\ \\ \\L\\ \\ + print( + """ + ____ ____ +/\\ _`\\ /\\ _`\\ +\\ \\,\\L\\_\\ __ ___ __ __ _ __ __\\ \\ \\/\\ \\ _ __ ___ _____ + \\/_\\__ \\ /'__`\\ /'___\\/\\ \\/\\ \\/\\`'__\\/'__`\\ \\ \\ \\ \\/\\`'__\\/ __`\\/\\ '__`\\ + /\\ \\L\\ \\/\\ __//\\ \\__/\\ \\ \\_\\ \\ \\ \\//\\ __/\\ \\ \\_\\ \\ \\ \\//\\ \\L\\ \\ \\ \\L\\ \\ # noqa: E501 \\ `\\____\\ \\____\\ \\____\\\\ \\____/\\ \\_\\\\ \\____\\\\ \\____/\\ \\_\\\\ \\____/\\ \\ ,__/ - \\/_____/\\/____/\\/____/ \\/___/ \\/_/ \\/____/ \\/___/ \\/_/ \\/___/ \\ \\ \\/ - \\ \\_\\ - \\/_/ -""") # noqa + \\/_____/\\/____/\\/____/ \\/___/ \\/_/ \\/____/ \\/___/ \\/_/ \\/___/ \\ \\ \\/ + \\ \\_\\ + \\/_/ +""" + ) # noqa procs = [ - lambda: DevServerProcess('Source Interface', - ['python', 'source.py'], - 'blue'), - lambda: DevServerProcess('Journalist Interface', - ['python', 'journalist.py'], - 'cyan'), - lambda: DevServerProcess('SASS Compiler', - ['sass', '--watch', 'sass:static/css'], - 'magenta'), + lambda: DevServerProcess("Source Interface", ["python", "source.py"], "blue"), + lambda: DevServerProcess("Journalist Interface", ["python", "journalist.py"], "cyan"), + lambda: DevServerProcess( + "SASS Compiler", ["sass", "--watch", "sass:static/css"], "magenta" + ), ] monitor = DevServerProcessMonitor(procs) diff --git a/securedrop/management/submissions.py b/securedrop/management/submissions.py --- a/securedrop/management/submissions.py +++ b/securedrop/management/submissions.py @@ -4,16 +4,13 @@ import sys import time from argparse import _SubParsersAction - -from typing import List -from typing import Optional - -from flask.ctx import AppContext +from typing import List, Optional from db import db -from rm import secure_delete -from models import Reply, Source, Submission +from flask.ctx import AppContext from management import app_context +from models import Reply, Source, Submission +from rm import secure_delete def find_disconnected_db_submissions(path: str) -> List[Submission]: diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -1,42 +1,39 @@ # -*- coding: utf-8 -*- +import base64 import binascii import datetime -import base64 import os +import uuid +from io import BytesIO +from logging import Logger +from typing import Any, Callable, Dict, List, Optional, Union + import pyotp import qrcode + # Using svg because it doesn't require additional dependencies import qrcode.image.svg -import uuid -from io import BytesIO - from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf import scrypt +from db import db +from encryption import EncryptionManager, GpgKeyNotFoundError from flask import current_app, url_for from flask_babel import gettext, ngettext -from itsdangerous import TimedJSONWebSignatureSerializer, BadData +from itsdangerous import BadData, TimedJSONWebSignatureSerializer from markupsafe import Markup from passlib.hash import argon2 -from sqlalchemy import ForeignKey -from sqlalchemy.orm import relationship, backref, Query -from sqlalchemy import Column, Integer, String, Boolean, DateTime, LargeBinary +from passphrases import PassphraseGenerator +from pyotp import HOTP, TOTP +from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, LargeBinary, String from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Query, backref, relationship from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound - -from db import db - -from typing import Callable, Optional, Union, Dict, List, Any -from logging import Logger -from pyotp import TOTP, HOTP - -from encryption import EncryptionManager, GpgKeyNotFoundError -from passphrases import PassphraseGenerator from store import Storage _default_instance_config: Optional["InstanceConfig"] = None LOGIN_HARDENING = True -if os.environ.get('SECUREDROP_ENV') == 'test': +if os.environ.get("SECUREDROP_ENV") == "test": LOGIN_HARDENING = False ARGON2_PARAMS = dict(memory_cost=2**16, rounds=4, parallelism=2) @@ -49,15 +46,19 @@ OTP_SECRET_MIN_ASCII_LENGTH = 16 # 80 bits == 40 hex digits (== 16 ascii-encoded chars in db) -def get_one_or_else(query: Query, - logger: 'Logger', - failure_method: 'Callable[[int], None]') -> db.Model: +def get_one_or_else( + query: Query, logger: "Logger", failure_method: "Callable[[int], None]" +) -> db.Model: try: return query.one() except MultipleResultsFound as e: logger.error( - "Found multiple while executing %s when one was expected: %s" % - (query, e, )) + "Found multiple while executing %s when one was expected: %s" + % ( + query, + e, + ) + ) failure_method(500) except NoResultFound as e: logger.error("Found none when one was expected: %s" % (e,)) @@ -65,15 +66,13 @@ def get_one_or_else(query: Query, class Source(db.Model): - __tablename__ = 'sources' + __tablename__ = "sources" id = Column(Integer, primary_key=True) uuid = Column(String(36), unique=True, nullable=False) filesystem_id = Column(String(96), unique=True, nullable=False) journalist_designation = Column(String(255), nullable=False) last_updated = Column(DateTime) - star = relationship( - "SourceStar", uselist=False, backref="source" - ) + star = relationship("SourceStar", uselist=False, backref="source") # sources are "pending" and don't get displayed to journalists until they # submit something @@ -85,24 +84,23 @@ class Source(db.Model): # when deletion of the source was requested deleted_at = Column(DateTime) - def __init__(self, - filesystem_id: str, - journalist_designation: str) -> None: + def __init__(self, filesystem_id: str, journalist_designation: str) -> None: self.filesystem_id = filesystem_id self.journalist_designation = journalist_designation self.uuid = str(uuid.uuid4()) def __repr__(self) -> str: - return '<Source %r>' % (self.journalist_designation) + return "<Source %r>" % (self.journalist_designation) @property def journalist_filename(self) -> str: - valid_chars = 'abcdefghijklmnopqrstuvwxyz1234567890-_' - return ''.join([c for c in self.journalist_designation.lower().replace( - ' ', '_') if c in valid_chars]) + valid_chars = "abcdefghijklmnopqrstuvwxyz1234567890-_" + return "".join( + [c for c in self.journalist_designation.lower().replace(" ", "_") if c in valid_chars] + ) - def documents_messages_count(self) -> 'Dict[str, int]': - self.docs_msgs_count = {'messages': 0, 'documents': 0} + def documents_messages_count(self) -> "Dict[str, int]": + self.docs_msgs_count = {"messages": 0, "documents": 0} for submission in self.submissions: if submission.is_message: self.docs_msgs_count["messages"] += 1 @@ -111,30 +109,30 @@ def documents_messages_count(self) -> 'Dict[str, int]': return self.docs_msgs_count @property - def collection(self) -> 'List[Union[Submission, Reply]]': + def collection(self) -> "List[Union[Submission, Reply]]": """Return the list of submissions and replies for this source, sorted in ascending order by the filename/interaction count.""" collection = [] # type: List[Union[Submission, Reply]] collection.extend(self.submissions) collection.extend(self.replies) - collection.sort(key=lambda x: int(x.filename.split('-')[0])) + collection.sort(key=lambda x: int(x.filename.split("-")[0])) return collection @property - def fingerprint(self) -> 'Optional[str]': + def fingerprint(self) -> "Optional[str]": try: return EncryptionManager.get_default().get_source_key_fingerprint(self.filesystem_id) except GpgKeyNotFoundError: return None @property - def public_key(self) -> 'Optional[str]': + def public_key(self) -> "Optional[str]": try: return EncryptionManager.get_default().get_source_public_key(self.filesystem_id) except GpgKeyNotFoundError: return None - def to_json(self) -> 'Dict[str, object]': + def to_json(self) -> "Dict[str, object]": docs_msg_count = self.documents_messages_count() if self.last_updated: @@ -148,51 +146,41 @@ def to_json(self) -> 'Dict[str, object]': starred = False json_source = { - 'uuid': self.uuid, - 'url': url_for('api.single_source', source_uuid=self.uuid), - 'journalist_designation': self.journalist_designation, - 'is_flagged': False, - 'is_starred': starred, - 'last_updated': last_updated, - 'interaction_count': self.interaction_count, - 'key': { - 'type': 'PGP', - 'public': self.public_key, - 'fingerprint': self.fingerprint - }, - 'number_of_documents': docs_msg_count['documents'], - 'number_of_messages': docs_msg_count['messages'], - 'submissions_url': url_for('api.all_source_submissions', - source_uuid=self.uuid), - 'add_star_url': url_for('api.add_star', source_uuid=self.uuid), - 'remove_star_url': url_for('api.remove_star', - source_uuid=self.uuid), - 'replies_url': url_for('api.all_source_replies', - source_uuid=self.uuid) - } + "uuid": self.uuid, + "url": url_for("api.single_source", source_uuid=self.uuid), + "journalist_designation": self.journalist_designation, + "is_flagged": False, + "is_starred": starred, + "last_updated": last_updated, + "interaction_count": self.interaction_count, + "key": {"type": "PGP", "public": self.public_key, "fingerprint": self.fingerprint}, + "number_of_documents": docs_msg_count["documents"], + "number_of_messages": docs_msg_count["messages"], + "submissions_url": url_for("api.all_source_submissions", source_uuid=self.uuid), + "add_star_url": url_for("api.add_star", source_uuid=self.uuid), + "remove_star_url": url_for("api.remove_star", source_uuid=self.uuid), + "replies_url": url_for("api.all_source_replies", source_uuid=self.uuid), + } return json_source class Submission(db.Model): MAX_MESSAGE_LEN = 100000 - __tablename__ = 'submissions' + __tablename__ = "submissions" id = Column(Integer, primary_key=True) uuid = Column(String(36), unique=True, nullable=False) - source_id = Column(Integer, ForeignKey('sources.id')) - source = relationship( - "Source", - backref=backref("submissions", order_by=id, cascade="delete") - ) + source_id = Column(Integer, ForeignKey("sources.id")) + source = relationship("Source", backref=backref("submissions", order_by=id, cascade="delete")) filename = Column(String(255), nullable=False) size = Column(Integer, nullable=False) downloaded = Column(Boolean, default=False) - ''' + """ The checksum of the encrypted file on disk. Format: $hash_name:$hex_encoded_hash_value Example: sha256:05fa5efd7d1b608ac1fbdf19a61a5a439d05b05225e81faa63fdd188296b614a - ''' + """ checksum = Column(String(255)) def __init__(self, source: Source, filename: str, storage: Storage) -> None: @@ -202,7 +190,7 @@ def __init__(self, source: Source, filename: str, storage: Storage) -> None: self.size = os.stat(storage.path(source.filesystem_id, filename)).st_size def __repr__(self) -> str: - return '<Submission %r>' % (self.filename) + return "<Submission %r>" % (self.filename) @property def is_file(self) -> bool: @@ -212,31 +200,40 @@ def is_file(self) -> bool: def is_message(self) -> bool: return self.filename.endswith("msg.gpg") - def to_json(self) -> 'Dict[str, Any]': + def to_json(self) -> "Dict[str, Any]": seen_by = { - f.journalist.uuid for f in SeenFile.query.filter(SeenFile.file_id == self.id) + f.journalist.uuid + for f in SeenFile.query.filter(SeenFile.file_id == self.id) if f.journalist } - seen_by.update({ - m.journalist.uuid for m in SeenMessage.query.filter(SeenMessage.message_id == self.id) - if m.journalist - }) + seen_by.update( + { + m.journalist.uuid + for m in SeenMessage.query.filter(SeenMessage.message_id == self.id) + if m.journalist + } + ) json_submission = { - 'source_url': url_for('api.single_source', - source_uuid=self.source.uuid) if self.source else None, - 'submission_url': url_for('api.single_submission', - source_uuid=self.source.uuid, - submission_uuid=self.uuid) if self.source else None, - 'filename': self.filename, - 'size': self.size, + "source_url": url_for("api.single_source", source_uuid=self.source.uuid) + if self.source + else None, + "submission_url": url_for( + "api.single_submission", source_uuid=self.source.uuid, submission_uuid=self.uuid + ) + if self.source + else None, + "filename": self.filename, + "size": self.size, "is_file": self.is_file, "is_message": self.is_message, "is_read": self.seen, - 'uuid': self.uuid, - 'download_url': url_for('api.download_submission', - source_uuid=self.source.uuid, - submission_uuid=self.uuid) if self.source else None, - 'seen_by': list(seen_by) + "uuid": self.uuid, + "download_url": url_for( + "api.download_submission", source_uuid=self.source.uuid, submission_uuid=self.uuid + ) + if self.source + else None, + "seen_by": list(seen_by), } return json_submission @@ -257,36 +254,26 @@ class Reply(db.Model): id = Column(Integer, primary_key=True) uuid = Column(String(36), unique=True, nullable=False) - journalist_id = Column(Integer, ForeignKey('journalists.id'), nullable=False) - journalist = relationship( - "Journalist", - backref=backref( - 'replies', - order_by=id) - ) + journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) + journalist = relationship("Journalist", backref=backref("replies", order_by=id)) - source_id = Column(Integer, ForeignKey('sources.id')) - source = relationship( - "Source", - backref=backref("replies", order_by=id, cascade="delete") - ) + source_id = Column(Integer, ForeignKey("sources.id")) + source = relationship("Source", backref=backref("replies", order_by=id, cascade="delete")) filename = Column(String(255), nullable=False) size = Column(Integer, nullable=False) - ''' + """ The checksum of the encrypted file on disk. Format: $hash_name:$hex_encoded_hash_value Example: sha256:05fa5efd7d1b608ac1fbdf19a61a5a439d05b05225e81faa63fdd188296b614a - ''' + """ checksum = Column(String(255)) deleted_by_source = Column(Boolean, default=False, nullable=False) - def __init__(self, - journalist: 'Journalist', - source: Source, - filename: str, - storage: Storage) -> None: + def __init__( + self, journalist: "Journalist", source: Source, filename: str, storage: Storage + ) -> None: self.journalist = journalist self.source_id = source.id self.uuid = str(uuid.uuid4()) @@ -294,41 +281,45 @@ def __init__(self, self.size = os.stat(storage.path(source.filesystem_id, filename)).st_size def __repr__(self) -> str: - return '<Reply %r>' % (self.filename) + return "<Reply %r>" % (self.filename) - def to_json(self) -> 'Dict[str, Any]': - seen_by = [ - r.journalist.uuid for r in SeenReply.query.filter(SeenReply.reply_id == self.id) - ] + def to_json(self) -> "Dict[str, Any]": + seen_by = [r.journalist.uuid for r in SeenReply.query.filter(SeenReply.reply_id == self.id)] json_reply = { - 'source_url': url_for('api.single_source', - source_uuid=self.source.uuid) if self.source else None, - 'reply_url': url_for('api.single_reply', - source_uuid=self.source.uuid, - reply_uuid=self.uuid) if self.source else None, - 'filename': self.filename, - 'size': self.size, - 'journalist_username': self.journalist.username, - 'journalist_first_name': self.journalist.first_name or '', - 'journalist_last_name': self.journalist.last_name or '', - 'journalist_uuid': self.journalist.uuid, - 'uuid': self.uuid, - 'is_deleted_by_source': self.deleted_by_source, - 'seen_by': seen_by + "source_url": url_for("api.single_source", source_uuid=self.source.uuid) + if self.source + else None, + "reply_url": url_for( + "api.single_reply", source_uuid=self.source.uuid, reply_uuid=self.uuid + ) + if self.source + else None, + "filename": self.filename, + "size": self.size, + "journalist_username": self.journalist.username, + "journalist_first_name": self.journalist.first_name or "", + "journalist_last_name": self.journalist.last_name or "", + "journalist_uuid": self.journalist.uuid, + "uuid": self.uuid, + "is_deleted_by_source": self.deleted_by_source, + "seen_by": seen_by, } return json_reply class SourceStar(db.Model): - __tablename__ = 'source_stars' + __tablename__ = "source_stars" id = Column("id", Integer, primary_key=True) - source_id = Column("source_id", Integer, ForeignKey('sources.id')) + source_id = Column("source_id", Integer, ForeignKey("sources.id")) starred = Column("starred", Boolean, default=True) - def __eq__(self, other: 'Any') -> bool: + def __eq__(self, other: "Any") -> bool: if isinstance(other, SourceStar): - return (self.source_id == other.source_id and - self.id == other.id and self.starred == other.starred) + return ( + self.source_id == other.source_id + and self.id == other.id + and self.starred == other.starred + ) return False def __init__(self, source: Source, starred: bool = True) -> None: @@ -378,13 +369,12 @@ class InvalidOTPSecretException(Exception): class PasswordError(Exception): - """Generic error for passwords that are invalid. - """ + """Generic error for passwords that are invalid.""" class InvalidPasswordLength(PasswordError): """Raised when attempting to create a Journalist or log in with an invalid - password length. + password length. """ def __init__(self, passphrase: str) -> None: @@ -395,13 +385,12 @@ def __str__(self) -> str: return "Password is too long." if self.passphrase_len < Journalist.MIN_PASSWORD_LEN: return "Password is too short." - return "" # return empty string that can be appended harmlessly + return "" # return empty string that can be appended harmlessly class NonDicewarePassword(PasswordError): - """Raised when attempting to validate a password that is not diceware-like - """ + """Raised when attempting to validate a password that is not diceware-like""" class Journalist(db.Model): @@ -421,36 +410,29 @@ class Journalist(db.Model): hotp_counter = Column(Integer, default=0) last_token = Column(String(6)) - created_on = Column( - DateTime, - default=datetime.datetime.utcnow - ) + created_on = Column(DateTime, default=datetime.datetime.utcnow) last_access = Column(DateTime) passphrase_hash = Column(String(256)) login_attempts = relationship( - "JournalistLoginAttempt", - backref="journalist", - cascade="all, delete" - ) - revoked_tokens = relationship( - "RevokedToken", - backref="journalist", - cascade="all, delete" + "JournalistLoginAttempt", backref="journalist", cascade="all, delete" ) + revoked_tokens = relationship("RevokedToken", backref="journalist", cascade="all, delete") MIN_USERNAME_LEN = 3 MIN_NAME_LEN = 0 MAX_NAME_LEN = 100 - INVALID_USERNAMES = ['deleted'] - - def __init__(self, - username: str, - password: str, - first_name: 'Optional[str]' = None, - last_name: 'Optional[str]' = None, - is_admin: bool = False, - otp_secret: 'Optional[str]' = None) -> None: + INVALID_USERNAMES = ["deleted"] + + def __init__( + self, + username: str, + password: str, + first_name: "Optional[str]" = None, + last_name: "Optional[str]" = None, + is_admin: bool = False, + otp_secret: "Optional[str]" = None, + ) -> None: self.check_username_acceptable(username) self.username = username @@ -469,9 +451,7 @@ def __init__(self, self.set_hotp_secret(otp_secret) def __repr__(self) -> str: - return "<Journalist {0}{1}>".format( - self.username, - " [admin]" if self.is_admin else "") + return "<Journalist {0}{1}>".format(self.username, " [admin]" if self.is_admin else "") def _scrypt_hash(self, password: str, salt: bytes) -> bytes: backend = default_backend() @@ -488,7 +468,7 @@ def _scrypt_hash(self, password: str, salt: bytes) -> bytes: MAX_PASSWORD_LEN = 128 MIN_PASSWORD_LEN = 14 - def set_password(self, passphrase: 'Optional[str]') -> None: + def set_password(self, passphrase: "Optional[str]") -> None: if passphrase is None: raise PasswordError() @@ -496,8 +476,7 @@ def set_password(self, passphrase: 'Optional[str]') -> None: # "migrate" from the legacy case if not self.passphrase_hash: - self.passphrase_hash = \ - argon2.using(**ARGON2_PARAMS).hash(passphrase) + self.passphrase_hash = argon2.using(**ARGON2_PARAMS).hash(passphrase) # passlib creates one merged field that embeds randomly generated # salt in the output like $alg$salt$hash self.pw_hash = None @@ -522,9 +501,9 @@ def check_username_acceptable(cls, username: str) -> None: if len(username) < cls.MIN_USERNAME_LEN: raise InvalidUsernameException( ngettext( - 'Must be at least {num} character long.', - 'Must be at least {num} characters long.', - cls.MIN_USERNAME_LEN + "Must be at least {num} character long.", + "Must be at least {num} characters long.", + cls.MIN_USERNAME_LEN, ).format(num=cls.MIN_USERNAME_LEN) ) if username in cls.INVALID_USERNAMES: @@ -555,7 +534,7 @@ def check_password_acceptable(cls, password: str) -> None: if len(password.split()) < 7: raise NonDicewarePassword() - def valid_password(self, passphrase: 'Optional[str]') -> bool: + def valid_password(self, passphrase: "Optional[str]") -> bool: if not passphrase: return False @@ -580,13 +559,12 @@ def valid_password(self, passphrase: 'Optional[str]') -> bool: assert isinstance(self.pw_hash, bytes) is_valid = pyotp.utils.compare_digest( - self._scrypt_hash(passphrase, self.pw_salt), - self.pw_hash) + self._scrypt_hash(passphrase, self.pw_salt), self.pw_hash + ) # migrate new passwords if is_valid and not self.passphrase_hash: - self.passphrase_hash = \ - argon2.using(**ARGON2_PARAMS).hash(passphrase) + self.passphrase_hash = argon2.using(**ARGON2_PARAMS).hash(passphrase) # passlib creates one merged field that embeds randomly generated # salt in the output like $alg$salt$hash self.pw_salt = None @@ -600,42 +578,37 @@ def regenerate_totp_shared_secret(self) -> None: self.otp_secret = pyotp.random_base32() def set_hotp_secret(self, otp_secret: str) -> None: - self.otp_secret = base64.b32encode( - binascii.unhexlify(otp_secret.replace(" ", "")) - ).decode("ascii") + self.otp_secret = base64.b32encode(binascii.unhexlify(otp_secret.replace(" ", ""))).decode( + "ascii" + ) self.is_totp = False self.hotp_counter = 0 @property - def totp(self) -> 'TOTP': + def totp(self) -> "TOTP": if self.is_totp: return pyotp.TOTP(self.otp_secret) else: - raise ValueError('{} is not using TOTP'.format(self)) + raise ValueError("{} is not using TOTP".format(self)) @property - def hotp(self) -> 'HOTP': + def hotp(self) -> "HOTP": if not self.is_totp: return pyotp.HOTP(self.otp_secret) else: - raise ValueError('{} is not using HOTP'.format(self)) + raise ValueError("{} is not using HOTP".format(self)) @property def shared_secret_qrcode(self) -> Markup: - uri = self.totp.provisioning_uri( - self.username, - issuer_name="SecureDrop") + uri = self.totp.provisioning_uri(self.username, issuer_name="SecureDrop") - qr = qrcode.QRCode( - box_size=15, - image_factory=qrcode.image.svg.SvgPathImage - ) + qr = qrcode.QRCode(box_size=15, image_factory=qrcode.image.svg.SvgPathImage) qr.add_data(uri) img = qr.make_image() svg_out = BytesIO() img.save(svg_out) - return Markup(svg_out.getvalue().decode('utf-8')) + return Markup(svg_out.getvalue().decode("utf-8")) @property def formatted_otp_secret(self) -> str: @@ -643,15 +616,15 @@ def formatted_otp_secret(self) -> str: lowercase and split into four groups of four characters. The secret is base32-encoded, so it is case insensitive.""" sec = self.otp_secret - chunks = [sec[i:i + 4] for i in range(0, len(sec), 4)] - return ' '.join(chunks).lower() + chunks = [sec[i : i + 4] for i in range(0, len(sec), 4)] + return " ".join(chunks).lower() def _format_token(self, token: str) -> str: """Strips from authentication tokens the whitespace that many clients add for readability""" - return ''.join(token.split()) + return "".join(token.split()) - def verify_token(self, token: 'Optional[str]') -> bool: + def verify_token(self, token: "Optional[str]") -> bool: if not token: return False @@ -663,9 +636,7 @@ def verify_token(self, token: 'Optional[str]') -> bool: return self.totp.verify(token, valid_window=1) if self.hotp_counter is not None: - for counter_val in range( - self.hotp_counter, - self.hotp_counter + 20): + for counter_val in range(self.hotp_counter, self.hotp_counter + 20): if self.hotp.verify(token, counter_val): self.hotp_counter = counter_val + 1 db.session.commit() @@ -677,29 +648,32 @@ def verify_token(self, token: 'Optional[str]') -> bool: _MAX_LOGIN_ATTEMPTS_PER_PERIOD = 5 @classmethod - def throttle_login(cls, user: 'Journalist') -> None: + def throttle_login(cls, user: "Journalist") -> None: # Record the login attempt... login_attempt = JournalistLoginAttempt(user) db.session.add(login_attempt) db.session.commit() # ...and reject it if they have exceeded the threshold - login_attempt_period = datetime.datetime.utcnow() - \ - datetime.timedelta(seconds=cls._LOGIN_ATTEMPT_PERIOD) - attempts_within_period = JournalistLoginAttempt.query.filter( - JournalistLoginAttempt.journalist_id == user.id).filter( - JournalistLoginAttempt.timestamp > login_attempt_period).all() + login_attempt_period = datetime.datetime.utcnow() - datetime.timedelta( + seconds=cls._LOGIN_ATTEMPT_PERIOD + ) + attempts_within_period = ( + JournalistLoginAttempt.query.filter(JournalistLoginAttempt.journalist_id == user.id) + .filter(JournalistLoginAttempt.timestamp > login_attempt_period) + .all() + ) if len(attempts_within_period) > cls._MAX_LOGIN_ATTEMPTS_PER_PERIOD: raise LoginThrottledException( "throttled ({} attempts in last {} seconds)".format( - len(attempts_within_period), - cls._LOGIN_ATTEMPT_PERIOD)) + len(attempts_within_period), cls._LOGIN_ATTEMPT_PERIOD + ) + ) @classmethod - def login(cls, - username: str, - password: 'Optional[str]', - token: 'Optional[str]') -> 'Journalist': + def login( + cls, username: str, password: "Optional[str]", token: "Optional[str]" + ) -> "Journalist": try: user = Journalist.query.filter_by(username=username).one() @@ -723,8 +697,7 @@ def login(cls, # For type checking assert isinstance(token, str) if pyotp.utils.compare_digest(token, user.last_token): - raise BadTokenException("previously used two-factor code " - "{}".format(token)) + raise BadTokenException("previously used two-factor code " "{}".format(token)) if not user.verify_token(token): raise BadTokenException("invalid two-factor code") @@ -738,13 +711,12 @@ def login(cls, return user def generate_api_token(self, expiration: int) -> str: - s = TimedJSONWebSignatureSerializer( - current_app.config['SECRET_KEY'], expires_in=expiration) - return s.dumps({'id': self.id}).decode('ascii') # type:ignore + s = TimedJSONWebSignatureSerializer(current_app.config["SECRET_KEY"], expires_in=expiration) + return s.dumps({"id": self.id}).decode("ascii") # type:ignore @staticmethod def validate_token_is_not_expired_or_invalid(token: str) -> bool: - s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) + s = TimedJSONWebSignatureSerializer(current_app.config["SECRET_KEY"]) try: s.loads(token) except BadData: @@ -753,8 +725,8 @@ def validate_token_is_not_expired_or_invalid(token: str) -> bool: return True @staticmethod - def validate_api_token_and_get_user(token: str) -> 'Optional[Journalist]': - s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) + def validate_api_token_and_get_user(token: str) -> "Optional[Journalist]": + s = TimedJSONWebSignatureSerializer(current_app.config["SECRET_KEY"]) try: data = s.loads(token) except BadData: @@ -764,26 +736,26 @@ def validate_api_token_and_get_user(token: str) -> 'Optional[Journalist]': if revoked_token is not None: return None - return Journalist.query.get(data['id']) + return Journalist.query.get(data["id"]) def to_json(self, all_info: bool = True) -> Dict[str, Any]: """Returns a JSON representation of the journalist user. If all_info is - False, potentially sensitive or extraneous fields are excluded. Note - that both representations do NOT include credentials.""" + False, potentially sensitive or extraneous fields are excluded. Note + that both representations do NOT include credentials.""" json_user = { - 'username': self.username, - 'uuid': self.uuid, - 'first_name': self.first_name, - 'last_name': self.last_name + "username": self.username, + "uuid": self.uuid, + "first_name": self.first_name, + "last_name": self.last_name, } # type: Dict[str, Any] if all_info is True: - json_user['is_admin'] = self.is_admin + json_user["is_admin"] = self.is_admin if self.last_access: - json_user['last_login'] = self.last_access + json_user["last_login"] = self.last_access else: - json_user['last_login'] = None + json_user["last_login"] = None return json_user @@ -797,7 +769,7 @@ def get_deleted(cls) -> "Journalist": Callers must commit the session themselves """ - deleted = Journalist.query.filter_by(username='deleted').one_or_none() + deleted = Journalist.query.filter_by(username="deleted").one_or_none() if deleted is None: # Lazily create deleted = cls( @@ -806,7 +778,7 @@ def get_deleted(cls) -> "Journalist": username="placeholder", # We store a randomly generated passphrase for this account that is # never revealed to anyone. - password=PassphraseGenerator.get_default().generate_passphrase() + password=PassphraseGenerator.get_default().generate_passphrase(), ) deleted.username = "deleted" db.session.add(deleted) @@ -826,8 +798,8 @@ def delete(self) -> None: # For seen indicators, we need to make sure one doesn't already exist # otherwise it'll hit a unique key conflict already_seen_files = { - file.file_id for file in - SeenFile.query.filter_by(journalist_id=deleted.id).all()} + file.file_id for file in SeenFile.query.filter_by(journalist_id=deleted.id).all() + } for file in SeenFile.query.filter_by(journalist_id=self.id).all(): if file.file_id in already_seen_files: db.session.delete(file) @@ -836,8 +808,9 @@ def delete(self) -> None: db.session.add(file) already_seen_messages = { - message.message_id for message in - SeenMessage.query.filter_by(journalist_id=deleted.id).all()} + message.message_id + for message in SeenMessage.query.filter_by(journalist_id=deleted.id).all() + } for message in SeenMessage.query.filter_by(journalist_id=self.id).all(): if message.message_id in already_seen_messages: db.session.delete(message) @@ -846,8 +819,8 @@ def delete(self) -> None: db.session.add(message) already_seen_replies = { - reply.reply_id for reply in - SeenReply.query.filter_by(journalist_id=deleted.id).all()} + reply.reply_id for reply in SeenReply.query.filter_by(journalist_id=deleted.id).all() + } for reply in SeenReply.query.filter_by(journalist_id=self.id).all(): if reply.reply_id in already_seen_replies: db.session.delete(reply) @@ -868,9 +841,7 @@ class SeenFile(db.Model): file = relationship( "Submission", backref=backref("seen_files", lazy="dynamic", cascade="all,delete") ) - journalist = relationship( - "Journalist", backref=backref("seen_files") - ) + journalist = relationship("Journalist", backref=backref("seen_files")) class SeenMessage(db.Model): @@ -882,9 +853,7 @@ class SeenMessage(db.Model): message = relationship( "Submission", backref=backref("seen_messages", lazy="dynamic", cascade="all,delete") ) - journalist = relationship( - "Journalist", backref=backref("seen_messages") - ) + journalist = relationship("Journalist", backref=backref("seen_messages")) class SeenReply(db.Model): @@ -893,12 +862,8 @@ class SeenReply(db.Model): id = Column(Integer, primary_key=True) reply_id = Column(Integer, ForeignKey("replies.id"), nullable=False) journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) - reply = relationship( - "Reply", backref=backref("seen_replies", cascade="all,delete") - ) - journalist = relationship( - "Journalist", backref=backref("seen_replies") - ) + reply = relationship("Reply", backref=backref("seen_replies", cascade="all,delete")) + journalist = relationship("Journalist", backref=backref("seen_replies")) class JournalistLoginAttempt(db.Model): @@ -906,13 +871,11 @@ class JournalistLoginAttempt(db.Model): """This model keeps track of journalist's login attempts so we can rate limit them in order to prevent attackers from brute forcing passwords or two-factor tokens.""" + __tablename__ = "journalist_login_attempt" id = Column(Integer, primary_key=True) - timestamp = Column( - DateTime, - default=datetime.datetime.utcnow - ) - journalist_id = Column(Integer, ForeignKey('journalists.id'), nullable=False) + timestamp = Column(DateTime, default=datetime.datetime.utcnow) + journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) def __init__(self, journalist: Journalist) -> None: self.journalist = journalist @@ -924,51 +887,56 @@ class RevokedToken(db.Model): API tokens that have been revoked either through a logout or other revocation mechanism. """ - __tablename__ = 'revoked_tokens' + __tablename__ = "revoked_tokens" id = Column(Integer, primary_key=True) - journalist_id = Column(Integer, ForeignKey('journalists.id'), nullable=False) + journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) token = db.Column(db.Text, nullable=False, unique=True) class InstanceConfig(db.Model): - '''Versioned key-value store of settings configurable from the journalist + """Versioned key-value store of settings configurable from the journalist interface. The current version has valid_until=0 (unix epoch start) - ''' + """ # Limits length of org name used in SI and JI titles, image alt texts etc. MAX_ORG_NAME_LEN = 64 - __tablename__ = 'instance_config' + __tablename__ = "instance_config" version = Column(Integer, primary_key=True) - valid_until = Column(DateTime, default=datetime.datetime.fromtimestamp(0), - nullable=False, unique=True) + valid_until = Column( + DateTime, default=datetime.datetime.fromtimestamp(0), nullable=False, unique=True + ) allow_document_uploads = Column(Boolean, default=True) organization_name = Column(String(255), nullable=True, default="SecureDrop") initial_message_min_len = Column(Integer, nullable=False, default=0, server_default="0") - reject_message_with_codename = Column(Boolean, nullable=False, - default=False, server_default="0") + reject_message_with_codename = Column( + Boolean, nullable=False, default=False, server_default="0" + ) # Columns not listed here will be included by InstanceConfig.copy() when # updating the configuration. - metadata_cols = ['version', 'valid_until'] + metadata_cols = ["version", "valid_until"] def __repr__(self) -> str: - return "<InstanceConfig(version=%s, valid_until=%s, " \ - "allow_document_uploads=%s, organization_name=%s, " \ - "initial_message_min_len=%s, reject_message_with_codename=%s)>" % ( - self.version, - self.valid_until, - self.allow_document_uploads, - self.organization_name, - self.initial_message_min_len, - self.reject_message_with_codename - ) + return ( + "<InstanceConfig(version=%s, valid_until=%s, " + "allow_document_uploads=%s, organization_name=%s, " + "initial_message_min_len=%s, reject_message_with_codename=%s)>" + % ( + self.version, + self.valid_until, + self.allow_document_uploads, + self.organization_name, + self.initial_message_min_len, + self.reject_message_with_codename, + ) + ) def copy(self) -> "InstanceConfig": - '''Make a copy of only the configuration columns of the given + """Make a copy of only the configuration columns of the given InstanceConfig object: i.e., excluding metadata_cols. - ''' + """ new = type(self)() for col in self.__table__.columns: @@ -988,11 +956,11 @@ def get_default(cls, refresh: bool = False) -> "InstanceConfig": @classmethod def get_current(cls) -> "InstanceConfig": - '''If the database was created via db.create_all(), data migrations + """If the database was created via db.create_all(), data migrations weren't run, and the "instance_config" table is empty. In this case, save and return a base configuration derived from each setting's column-level default. - ''' + """ try: return cls.query.filter(cls.valid_until == datetime.datetime.fromtimestamp(0)).one() @@ -1015,9 +983,9 @@ def check_name_acceptable(cls, name: str) -> None: @classmethod def set_organization_name(cls, name: str) -> None: - '''Invalidate the current configuration and append a new one with the + """Invalidate the current configuration and append a new one with the new organization name. - ''' + """ old = cls.get_current() old.valid_until = datetime.datetime.utcnow() @@ -1032,14 +1000,11 @@ def set_organization_name(cls, name: str) -> None: @classmethod def update_submission_prefs( - cls, - allow_uploads: bool, - min_length: int, - reject_codenames: bool - ) -> None: - '''Invalidate the current configuration and append a new one with the + cls, allow_uploads: bool, min_length: int, reject_codenames: bool + ) -> None: + """Invalidate the current configuration and append a new one with the updated submission preferences. - ''' + """ old = cls.get_current() old.valid_until = datetime.datetime.utcnow() diff --git a/securedrop/passphrases.py b/securedrop/passphrases.py --- a/securedrop/passphrases.py +++ b/securedrop/passphrases.py @@ -1,9 +1,6 @@ from pathlib import Path from random import SystemRandom -from typing import Optional, NewType, Set - -from typing import Dict -from typing import List +from typing import Dict, List, NewType, Optional, Set from sdconfig import config diff --git a/securedrop/request_that_secures_file_uploads.py b/securedrop/request_that_secures_file_uploads.py --- a/securedrop/request_that_secures_file_uploads.py +++ b/securedrop/request_that_secures_file_uploads.py @@ -1,14 +1,12 @@ from io import BytesIO -from typing import Optional, IO +from typing import IO, Optional from flask import wrappers -from werkzeug.formparser import FormDataParser - from secure_tempfile import SecureTemporaryFile +from werkzeug.formparser import FormDataParser class RequestThatSecuresFileUploads(wrappers.Request): - def _secure_file_stream( self, total_content_length: Optional[int], @@ -31,13 +29,15 @@ def _secure_file_stream( # note in `config.py` for more info. Instead, we just use # `/tmp`, which has the additional benefit of being # automatically cleared on reboot. - return SecureTemporaryFile('/tmp') # nosec + return SecureTemporaryFile("/tmp") # nosec return BytesIO() def make_form_data_parser(self) -> FormDataParser: - return self.form_data_parser_class(self._secure_file_stream, - self.charset, - self.encoding_errors, - self.max_form_memory_size, - self.max_content_length, - self.parameter_storage_class) + return self.form_data_parser_class( + self._secure_file_stream, + self.charset, + self.encoding_errors, + self.max_form_memory_size, + self.max_content_length, + self.parameter_storage_class, + ) diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -1,12 +1,7 @@ from pathlib import Path -from typing import Dict -from typing import Optional - -from typing import Type +from typing import Dict, Optional, Set, Type import config as _config -from typing import Set - FALLBACK_LOCALE = "en_US" @@ -90,9 +85,7 @@ def __init__(self) -> None: except AttributeError: pass - self.SESSION_EXPIRATION_MINUTES: int = getattr( - _config, "SESSION_EXPIRATION_MINUTES", 120 - ) + self.SESSION_EXPIRATION_MINUTES: int = getattr(_config, "SESSION_EXPIRATION_MINUTES", 120) try: self.SOURCE_TEMPLATES_DIR = _config.SOURCE_TEMPLATES_DIR # type: str @@ -114,20 +107,22 @@ def __init__(self) -> None: except AttributeError: pass - self.env = getattr(_config, 'env', 'prod') # type: str - if self.env == 'test': - self.RQ_WORKER_NAME = 'test' # type: str + self.env = getattr(_config, "env", "prod") # type: str + if self.env == "test": + self.RQ_WORKER_NAME = "test" # type: str else: - self.RQ_WORKER_NAME = 'default' + self.RQ_WORKER_NAME = "default" # Config entries used by i18n.py # Use en_US as the default locale if the key is not defined in _config self.DEFAULT_LOCALE = getattr( - _config, "DEFAULT_LOCALE", FALLBACK_LOCALE, + _config, + "DEFAULT_LOCALE", + FALLBACK_LOCALE, ) # type: str - supported_locales = set(getattr( - _config, "SUPPORTED_LOCALES", [self.DEFAULT_LOCALE] - )) # type: Set[str] + supported_locales = set( + getattr(_config, "SUPPORTED_LOCALES", [self.DEFAULT_LOCALE]) + ) # type: Set[str] supported_locales.add(self.DEFAULT_LOCALE) self.SUPPORTED_LOCALES = sorted(list(supported_locales)) @@ -143,8 +138,7 @@ def __init__(self) -> None: @property def DATABASE_URI(self) -> str: if self.DATABASE_ENGINE == "sqlite": - db_uri = (self.DATABASE_ENGINE + ":///" + - self.DATABASE_FILE) + db_uri = self.DATABASE_ENGINE + ":///" + self.DATABASE_FILE else: if self.DATABASE_USERNAME is None: raise RuntimeError("Missing DATABASE_USERNAME entry from config.py") @@ -156,11 +150,15 @@ def DATABASE_URI(self) -> str: raise RuntimeError("Missing DATABASE_NAME entry from config.py") db_uri = ( - self.DATABASE_ENGINE + '://' + - self.DATABASE_USERNAME + ':' + - self.DATABASE_PASSWORD + '@' + - self.DATABASE_HOST + '/' + - self.DATABASE_NAME + self.DATABASE_ENGINE + + "://" + + self.DATABASE_USERNAME + + ":" + + self.DATABASE_PASSWORD + + "@" + + self.DATABASE_HOST + + "/" + + self.DATABASE_NAME ) return db_uri diff --git a/securedrop/secure_tempfile.py b/securedrop/secure_tempfile.py --- a/securedrop/secure_tempfile.py +++ b/securedrop/secure_tempfile.py @@ -1,17 +1,16 @@ # -*- coding: utf-8 -*- import base64 -import os import io +import os from tempfile import _TemporaryFileWrapper # type: ignore -from typing import Optional -from typing import Union +from typing import Optional, Union -from pretty_bad_protocol._util import _STREAMLIKE_TYPES from cryptography.exceptions import AlreadyFinalized from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers.modes import CTR -from cryptography.hazmat.primitives.ciphers import Cipher +from pretty_bad_protocol._util import _STREAMLIKE_TYPES class SecureTemporaryFile(_TemporaryFileWrapper, object): @@ -33,6 +32,7 @@ class SecureTemporaryFile(_TemporaryFileWrapper, object): overwritten), and then it's contents may be read only once (although it may be done in chunks) and only after it's been written to. """ + AES_key_size = 256 AES_block_size = 128 @@ -47,15 +47,14 @@ def __init__(self, store_dir: str) -> None: Returns: self """ - self.last_action = 'init' + self.last_action = "init" self.create_key() data = base64.urlsafe_b64encode(os.urandom(32)) - self.tmp_file_id = data.decode('utf-8').strip('=') + self.tmp_file_id = data.decode("utf-8").strip("=") - self.filepath = os.path.join(store_dir, - '{}.aes'.format(self.tmp_file_id)) - self.file = io.open(self.filepath, 'w+b') + self.filepath = os.path.join(store_dir, "{}.aes".format(self.tmp_file_id)) + self.file = io.open(self.filepath, "w+b") super(SecureTemporaryFile, self).__init__(self.file, self.filepath) def create_key(self) -> None: @@ -84,12 +83,12 @@ def write(self, data: Union[bytes, str]) -> int: but after calling :meth:`read`, you cannot write to the file again. """ - if self.last_action == 'read': - raise AssertionError('You cannot write after reading!') - self.last_action = 'write' + if self.last_action == "read": + raise AssertionError("You cannot write after reading!") + self.last_action = "write" if isinstance(data, str): - data_as_bytes = data.encode('utf-8') + data_as_bytes = data.encode("utf-8") else: data_as_bytes = data @@ -113,11 +112,11 @@ def read(self, count: Optional[int] = None) -> bytes: count (int): the number of bytes to try to read from the file from the current position. """ - if self.last_action == 'init': - raise AssertionError('You must write before reading!') - if self.last_action == 'write': + if self.last_action == "init": + raise AssertionError("You must write before reading!") + if self.last_action == "write": self.seek(0, 0) - self.last_action = 'read' + self.last_action = "read" if count: return self.decryptor.update(self.file.read(count)) diff --git a/securedrop/server_os.py b/securedrop/server_os.py --- a/securedrop/server_os.py +++ b/securedrop/server_os.py @@ -10,5 +10,5 @@ def get_os_release() -> str: ["/usr/bin/lsb_release", "--release", "--short"], check=True, stdout=subprocess.PIPE, - universal_newlines=True + universal_newlines=True, ).stdout.strip() diff --git a/securedrop/source.py b/securedrop/source.py --- a/securedrop/source.py +++ b/securedrop/source.py @@ -1,13 +1,12 @@ # -*- coding: utf-8 -*- from sdconfig import config - from source_app import create_app app = create_app(config) if __name__ == "__main__": # pragma: no cover - debug = getattr(config, 'env', 'prod') != 'prod' + debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host - app.run(debug=debug, host='0.0.0.0', port=8080) # nosec + app.run(debug=debug, host="0.0.0.0", port=8080) # nosec diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -1,24 +1,21 @@ -from pathlib import Path -from typing import Optional - import os import time -import werkzeug -from flask import (Flask, render_template, request, g, session, redirect, url_for) -from flask_babel import gettext -from flask_wtf.csrf import CSRFProtect, CSRFError from os import path -from typing import Tuple +from pathlib import Path +from typing import Optional, Tuple import i18n import template_filters import version - +import werkzeug from db import db +from flask import Flask, g, redirect, render_template, request, session, url_for +from flask_babel import gettext +from flask_wtf.csrf import CSRFError, CSRFProtect from models import InstanceConfig from request_that_secures_file_uploads import RequestThatSecuresFileUploads from sdconfig import SDConfig -from source_app import main, info, api +from source_app import api, info, main from source_app.decorators import ignore_static from source_app.utils import clear_session_and_redirect_to_logged_out_page @@ -40,9 +37,11 @@ def get_logo_url(app: Flask) -> str: def create_app(config: SDConfig) -> Flask: - app = Flask(__name__, - template_folder=config.SOURCE_TEMPLATES_DIR, - static_folder=path.join(config.SECUREDROP_ROOT, 'static')) + app = Flask( + __name__, + template_folder=config.SOURCE_TEMPLATES_DIR, + static_folder=path.join(config.SECUREDROP_ROOT, "static"), + ) app.request_class = RequestThatSecuresFileUploads app.config.from_object(config.SOURCE_APP_FLASK_CONFIG_CLS) @@ -56,11 +55,11 @@ def setup_i18n() -> None: # The default CSRF token expiration is 1 hour. Since large uploads can # take longer than an hour over Tor, we increase the valid window to 24h. - app.config['WTF_CSRF_TIME_LIMIT'] = 60 * 60 * 24 + app.config["WTF_CSRF_TIME_LIMIT"] = 60 * 60 * 24 CSRFProtect(app) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI db.init_app(app) # TODO: enable typechecking once upstream Flask fix is available. See: @@ -71,16 +70,14 @@ def handle_csrf_error(e: CSRFError) -> werkzeug.Response: app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True - app.jinja_env.globals['version'] = version.__version__ + app.jinja_env.globals["version"] = version.__version__ # Exported to source templates for being included in instructions - app.jinja_env.globals['submission_key_fpr'] = config.JOURNALIST_KEY - app.jinja_env.filters['rel_datetime_format'] = \ - template_filters.rel_datetime_format - app.jinja_env.filters['nl2br'] = template_filters.nl2br - app.jinja_env.filters['filesizeformat'] = template_filters.filesizeformat - app.jinja_env.filters['html_datetime_format'] = \ - template_filters.html_datetime_format - app.jinja_env.add_extension('jinja2.ext.do') + app.jinja_env.globals["submission_key_fpr"] = config.JOURNALIST_KEY + app.jinja_env.filters["rel_datetime_format"] = template_filters.rel_datetime_format + app.jinja_env.filters["nl2br"] = template_filters.nl2br + app.jinja_env.filters["filesizeformat"] = template_filters.filesizeformat + app.jinja_env.filters["html_datetime_format"] = template_filters.html_datetime_format + app.jinja_env.add_extension("jinja2.ext.do") for module in [main, info, api]: app.register_blueprint(module.make_blueprint(config)) # type: ignore @@ -91,10 +88,11 @@ def handle_csrf_error(e: CSRFError) -> werkzeug.Response: @ignore_static def setup_g() -> Optional[werkzeug.Response]: if InstanceConfig.get_default(refresh=True).organization_name: - g.organization_name = \ - InstanceConfig.get_default().organization_name # pylint: disable=assigning-non-slot + g.organization_name = ( # pylint: disable=assigning-non-slot + InstanceConfig.get_default().organization_name + ) else: - g.organization_name = gettext('SecureDrop') # pylint: disable=assigning-non-slot + g.organization_name = gettext("SecureDrop") # pylint: disable=assigning-non-slot try: g.logo = get_logo_url(app) # pylint: disable=assigning-non-slot @@ -107,25 +105,25 @@ def setup_g() -> Optional[werkzeug.Response]: @ignore_static def check_tor2web() -> Optional[werkzeug.Response]: # TODO: expand header checking logic to catch modern tor2web proxies - if 'X-tor2web' in request.headers: - if request.path != url_for('info.tor2web_warning'): - return redirect(url_for('info.tor2web_warning')) + if "X-tor2web" in request.headers: + if request.path != url_for("info.tor2web_warning"): + return redirect(url_for("info.tor2web_warning")) return None @app.errorhandler(404) def page_not_found(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: - return render_template('notfound.html'), 404 + return render_template("notfound.html"), 404 @app.errorhandler(500) def internal_error(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: - return render_template('error.html'), 500 + return render_template("error.html"), 500 # Obscure the creation time of source private keys by touching them all # on startup. - private_keys = Path(config.GPG_KEY_DIR) / 'private-keys-v1.d' + private_keys = Path(config.GPG_KEY_DIR) / "private-keys-v1.d" now = time.time() for entry in os.scandir(private_keys): - if not entry.is_file() or not entry.name.endswith('.key'): + if not entry.is_file() or not entry.name.endswith(".key"): continue os.utime(entry.path, times=(now, now)) # So the ctime is also updated diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -1,32 +1,30 @@ import json import flask +import server_os +import version from flask import Blueprint, make_response - -from sdconfig import SDConfig from models import InstanceConfig +from sdconfig import SDConfig from source_app.utils import get_sourcev3_url -import server_os -import version - def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('api', __name__) + view = Blueprint("api", __name__) - @view.route('/metadata') + @view.route("/metadata") def metadata() -> flask.Response: meta = { - 'organization_name': InstanceConfig.get_default().organization_name, - 'allow_document_uploads': InstanceConfig.get_default().allow_document_uploads, - 'gpg_fpr': config.JOURNALIST_KEY, - 'sd_version': version.__version__, - 'server_os': server_os.get_os_release(), - 'supported_languages': config.SUPPORTED_LOCALES, - 'v3_source_url': get_sourcev3_url() + "organization_name": InstanceConfig.get_default().organization_name, + "allow_document_uploads": InstanceConfig.get_default().allow_document_uploads, + "gpg_fpr": config.JOURNALIST_KEY, + "sd_version": version.__version__, + "server_os": server_os.get_os_release(), + "supported_languages": config.SUPPORTED_LOCALES, + "v3_source_url": get_sourcev3_url(), } resp = make_response(json.dumps(meta)) - resp.headers['Content-Type'] = 'application/json' + resp.headers["Content-Type"] = "application/json" return resp return view diff --git a/securedrop/source_app/decorators.py b/securedrop/source_app/decorators.py --- a/securedrop/source_app/decorators.py +++ b/securedrop/source_app/decorators.py @@ -1,15 +1,15 @@ -from typing import Any - -from db import db - -from flask import redirect, url_for, request, session from functools import wraps +from typing import Any, Callable -from typing import Callable - +from db import db +from flask import redirect, request, session, url_for +from source_app.session_manager import ( + SessionManager, + UserHasBeenDeleted, + UserNotLoggedIn, + UserSessionExpired, +) from source_app.utils import clear_session_and_redirect_to_logged_out_page -from source_app.session_manager import SessionManager, UserNotLoggedIn, \ - UserSessionExpired, UserHasBeenDeleted def login_required(f: Callable) -> Callable: @@ -25,15 +25,18 @@ def decorated_function(*args: Any, **kwargs: Any) -> Any: return redirect(url_for("main.login")) return f(*args, **kwargs, logged_in_source=logged_in_source) + return decorated_function def ignore_static(f: Callable) -> Callable: """Only executes the wrapped function if we're not loading a static resource.""" + @wraps(f) def decorated_function(*args: Any, **kwargs: Any) -> Any: if request.path.startswith("/static"): return # don't execute the decorated function return f(*args, **kwargs) + return decorated_function diff --git a/securedrop/source_app/forms.py b/securedrop/source_app/forms.py --- a/securedrop/source_app/forms.py +++ b/securedrop/source_app/forms.py @@ -2,30 +2,42 @@ from flask import abort from flask_babel import lazy_gettext as gettext from flask_wtf import FlaskForm -from wtforms import FileField, PasswordField, StringField, TextAreaField -from wtforms.validators import InputRequired, Regexp, Length, ValidationError - -from models import Submission, InstanceConfig +from models import InstanceConfig, Submission from passphrases import PassphraseGenerator +from wtforms import FileField, PasswordField, StringField, TextAreaField +from wtforms.validators import InputRequired, Length, Regexp, ValidationError class LoginForm(FlaskForm): - codename = PasswordField('codename', validators=[ - InputRequired(message=gettext('This field is required.')), - Length(1, PassphraseGenerator.MAX_PASSPHRASE_LENGTH, - message=gettext( - 'Field must be between 1 and ' - '{max_codename_len} characters long.'.format( - max_codename_len=PassphraseGenerator.MAX_PASSPHRASE_LENGTH))), - # Make sure to allow dashes since some words in the wordlist have them - Regexp(r'[\sA-Za-z0-9-]+$', message=gettext('Invalid input.')) - ]) + codename = PasswordField( + "codename", + validators=[ + InputRequired(message=gettext("This field is required.")), + Length( + 1, + PassphraseGenerator.MAX_PASSPHRASE_LENGTH, + message=gettext( + "Field must be between 1 and " + "{max_codename_len} characters long.".format( + max_codename_len=PassphraseGenerator.MAX_PASSPHRASE_LENGTH + ) + ), + ), + # Make sure to allow dashes since some words in the wordlist have them + Regexp(r"[\sA-Za-z0-9-]+$", message=gettext("Invalid input.")), + ], + ) class SubmissionForm(FlaskForm): - msg = TextAreaField("msg", render_kw={"placeholder": gettext("Write a message."), - "aria-label": gettext("Write a message.")}) + msg = TextAreaField( + "msg", + render_kw={ + "placeholder": gettext("Write a message."), + "aria-label": gettext("Write a message."), + }, + ) fh = FileField("fh", render_kw={"aria-label": gettext("Select a file to upload.")}) antispam = StringField(id="text", name="text") @@ -37,7 +49,7 @@ def validate_msg(self, field: wtforms.Field) -> None: message, gettext( "Large blocks of text must be uploaded as a file, not copied and pasted." - ) + ), ) raise ValidationError(message) diff --git a/securedrop/source_app/info.py b/securedrop/source_app/info.py --- a/securedrop/source_app/info.py +++ b/securedrop/source_app/info.py @@ -1,44 +1,45 @@ # -*- coding: utf-8 -*- -import flask -from flask import Blueprint, render_template, send_file, redirect, url_for -from flask_babel import gettext -import werkzeug - from io import BytesIO # noqa +import flask +import werkzeug from encryption import EncryptionManager +from flask import Blueprint, redirect, render_template, send_file, url_for +from flask_babel import gettext from sdconfig import SDConfig -from source_app.utils import get_sourcev3_url, flash_msg +from source_app.utils import flash_msg, get_sourcev3_url def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('info', __name__) + view = Blueprint("info", __name__) - @view.route('/tor2web-warning') + @view.route("/tor2web-warning") def tor2web_warning() -> flask.Response: flash_msg("error", None, gettext("Your connection is not anonymous right now!")) return flask.Response( - render_template("tor2web-warning.html", source_url=get_sourcev3_url()), - 403) + render_template("tor2web-warning.html", source_url=get_sourcev3_url()), 403 + ) - @view.route('/use-tor') + @view.route("/use-tor") def recommend_tor_browser() -> str: return render_template("use-tor-browser.html") - @view.route('/public-key') + @view.route("/public-key") def download_public_key() -> flask.Response: journalist_pubkey = EncryptionManager.get_default().get_journalist_public_key() - data = BytesIO(journalist_pubkey.encode('utf-8')) - return send_file(data, - mimetype="application/pgp-keys", - attachment_filename=config.JOURNALIST_KEY + ".asc", - as_attachment=True) - - @view.route('/journalist-key') + data = BytesIO(journalist_pubkey.encode("utf-8")) + return send_file( + data, + mimetype="application/pgp-keys", + attachment_filename=config.JOURNALIST_KEY + ".asc", + as_attachment=True, + ) + + @view.route("/journalist-key") def download_journalist_key() -> werkzeug.wrappers.Response: - return redirect(url_for('.download_public_key'), code=301) + return redirect(url_for(".download_public_key"), code=301) - @view.route('/why-public-key') + @view.route("/why-public-key") def why_download_public_key() -> str: return render_template("why-public-key.html") diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -1,58 +1,78 @@ +import io import operator import os -import io - from base64 import urlsafe_b64encode from datetime import datetime, timedelta, timezone from typing import Union -import werkzeug -from flask import (Blueprint, render_template, redirect, url_for, - session, current_app, request, abort, g, make_response) -from flask_babel import gettext - import store - -from store import Storage - +import werkzeug from db import db from encryption import EncryptionManager, GpgKeyNotFoundError - -from models import Submission, Reply, get_one_or_else, InstanceConfig -from passphrases import PassphraseGenerator, DicewarePassphrase +from flask import ( + Blueprint, + abort, + current_app, + g, + make_response, + redirect, + render_template, + request, + session, + url_for, +) +from flask_babel import gettext +from models import InstanceConfig, Reply, Submission, get_one_or_else +from passphrases import DicewarePassphrase, PassphraseGenerator from sdconfig import SDConfig from source_app.decorators import login_required -from source_app.session_manager import SessionManager -from source_app.utils import normalize_timestamps, fit_codenames_into_cookie, \ - clear_session_and_redirect_to_logged_out_page, codename_detected, flash_msg from source_app.forms import LoginForm, SubmissionForm -from source_user import InvalidPassphraseError, create_source_user, \ - SourcePassphraseCollisionError, SourceDesignationCollisionError, SourceUser +from source_app.session_manager import SessionManager +from source_app.utils import ( + clear_session_and_redirect_to_logged_out_page, + codename_detected, + fit_codenames_into_cookie, + flash_msg, + normalize_timestamps, +) +from source_user import ( + InvalidPassphraseError, + SourceDesignationCollisionError, + SourcePassphraseCollisionError, + SourceUser, + create_source_user, +) +from store import Storage def make_blueprint(config: SDConfig) -> Blueprint: - view = Blueprint('main', __name__) + view = Blueprint("main", __name__) - @view.route('/') + @view.route("/") def index() -> str: - return render_template('index.html') + return render_template("index.html") - @view.route('/generate', methods=('POST', 'GET')) + @view.route("/generate", methods=("POST", "GET")) def generate() -> Union[str, werkzeug.Response]: - if request.method == 'POST': + if request.method == "POST": # Try to detect Tor2Web usage by looking to see if tor2web_check got mangled - tor2web_check = request.form.get('tor2web_check') + tor2web_check = request.form.get("tor2web_check") if tor2web_check is None: # Missing form field abort(403) elif tor2web_check != 'href="fake.onion"': - return redirect(url_for('info.tor2web_warning')) + return redirect(url_for("info.tor2web_warning")) if SessionManager.is_user_logged_in(db_session=db.session): - flash_msg("notification", None, gettext( - "You were redirected because you are already logged in. " - "If you want to create a new account, you should log out first.")) - return redirect(url_for('.lookup')) + flash_msg( + "notification", + None, + gettext( + "You were redirected because you are already logged in. " + "If you want to create a new account, you should log out first." + ), + ) + return redirect(url_for(".lookup")) codename = PassphraseGenerator.get_default().generate_passphrase( preferred_language=g.localeinfo.language ) @@ -61,29 +81,34 @@ def generate() -> Union[str, werkzeug.Response]: # This will allow retrieval of the codename displayed in the tab from which the source has # clicked to proceed to /generate (ref. issue #4458) tab_id = urlsafe_b64encode(os.urandom(64)).decode() - codenames = session.get('codenames', {}) + codenames = session.get("codenames", {}) codenames[tab_id] = codename - session['codenames'] = fit_codenames_into_cookie(codenames) + session["codenames"] = fit_codenames_into_cookie(codenames) session["codenames_expire"] = datetime.now(timezone.utc) + timedelta( minutes=config.SESSION_EXPIRATION_MINUTES ) - return render_template('generate.html', codename=codename, tab_id=tab_id) + return render_template("generate.html", codename=codename, tab_id=tab_id) - @view.route('/create', methods=['POST']) + @view.route("/create", methods=["POST"]) def create() -> werkzeug.Response: if SessionManager.is_user_logged_in(db_session=db.session): - flash_msg("notification", None, gettext( - "You are already logged in. Please verify your codename as it " - "may differ from the one displayed on the previous page.")) + flash_msg( + "notification", + None, + gettext( + "You are already logged in. Please verify your codename as it " + "may differ from the one displayed on the previous page." + ), + ) else: # Ensure the codenames have not expired date_codenames_expire = session.get("codenames_expire") if not date_codenames_expire or datetime.now(timezone.utc) >= date_codenames_expire: return clear_session_and_redirect_to_logged_out_page(flask_session=session) - tab_id = request.form['tab_id'] - codename = session['codenames'][tab_id] - del session['codenames'] + tab_id = request.form["tab_id"] + codename = session["codenames"][tab_id] + del session["codenames"] try: current_app.logger.info("Creating new source user...") @@ -94,19 +119,25 @@ def create() -> werkzeug.Response: ) except (SourcePassphraseCollisionError, SourceDesignationCollisionError) as e: current_app.logger.error("Could not create a source: {}".format(e)) - flash_msg("error", None, gettext( - "There was a temporary problem creating your account. Please try again.")) - return redirect(url_for('.index')) + flash_msg( + "error", + None, + gettext( + "There was a temporary problem creating your account. Please try again." + ), + ) + return redirect(url_for(".index")) # All done - source user was successfully created current_app.logger.info("New source user created") - session['new_user_codename'] = codename - SessionManager.log_user_in(db_session=db.session, - supplied_passphrase=DicewarePassphrase(codename)) + session["new_user_codename"] = codename + SessionManager.log_user_in( + db_session=db.session, supplied_passphrase=DicewarePassphrase(codename) + ) - return redirect(url_for('.lookup')) + return redirect(url_for(".lookup")) - @view.route('/lookup', methods=('GET',)) + @view.route("/lookup", methods=("GET",)) @login_required def lookup(logged_in_source: SourceUser) -> str: replies = [] @@ -131,23 +162,19 @@ def lookup(logged_in_source: SourceUser) -> str: with io.open(reply_path, "rb") as f: contents = f.read() decrypted_reply = EncryptionManager.get_default().decrypt_journalist_reply( - for_source_user=logged_in_source, - ciphertext_in=contents + for_source_user=logged_in_source, ciphertext_in=contents ) reply.decrypted = decrypted_reply except UnicodeDecodeError: - current_app.logger.error("Could not decode reply %s" % - reply.filename) + current_app.logger.error("Could not decode reply %s" % reply.filename) except FileNotFoundError: - current_app.logger.error("Reply file missing: %s" % - reply.filename) + current_app.logger.error("Reply file missing: %s" % reply.filename) else: - reply.date = datetime.utcfromtimestamp( - os.stat(reply_path).st_mtime) + reply.date = datetime.utcfromtimestamp(os.stat(reply_path).st_mtime) replies.append(reply) # Sort the replies by date - replies.sort(key=operator.attrgetter('date'), reverse=True) + replies.sort(key=operator.attrgetter("date"), reverse=True) # If not done yet, generate a keypair to encrypt replies from the journalist encryption_mgr = EncryptionManager.get_default() @@ -157,16 +184,16 @@ def lookup(logged_in_source: SourceUser) -> str: encryption_mgr.generate_source_key_pair(logged_in_source) return render_template( - 'lookup.html', + "lookup.html", is_user_logged_in=True, allow_document_uploads=InstanceConfig.get_default().allow_document_uploads, replies=replies, min_len=min_message_length, - new_user_codename=session.get('new_user_codename', None), + new_user_codename=session.get("new_user_codename", None), form=SubmissionForm(), ) - @view.route('/submit', methods=('POST',)) + @view.route("/submit", methods=("POST",)) @login_required def submit(logged_in_source: SourceUser) -> werkzeug.Response: allow_document_uploads = InstanceConfig.get_default().allow_document_uploads @@ -175,12 +202,12 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: for field, errors in form.errors.items(): for error in errors: flash_msg("error", None, error) - return redirect(url_for('main.lookup')) + return redirect(url_for("main.lookup")) - msg = request.form['msg'] + msg = request.form["msg"] fh = None - if allow_document_uploads and 'fh' in request.files: - fh = request.files['fh'] + if allow_document_uploads and "fh" in request.files: + fh = request.files["fh"] # Don't submit anything if it was an "empty" submission. #878 if not (msg or fh): @@ -190,7 +217,7 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: html_contents = gettext("You must enter a message.") flash_msg("error", None, html_contents) - return redirect(url_for('main.lookup')) + return redirect(url_for("main.lookup")) fnames = [] logged_in_source_in_db = logged_in_source.get_db_record() @@ -199,25 +226,39 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: if first_submission: min_len = InstanceConfig.get_default().initial_message_min_len if (min_len > 0) and (msg and not fh) and (len(msg) < min_len): - flash_msg("error", None, gettext( - "Your first message must be at least {} characters long.").format(min_len)) - return redirect(url_for('main.lookup')) + flash_msg( + "error", + None, + gettext("Your first message must be at least {} characters long.").format( + min_len + ), + ) + return redirect(url_for("main.lookup")) # if the new_user_codename key is not present in the session, this is # not a first session - new_codename = session.get('new_user_codename', None) + new_codename = session.get("new_user_codename", None) codenames_rejected = InstanceConfig.get_default().reject_message_with_codename if new_codename is not None: if codenames_rejected and codename_detected(msg, new_codename): - flash_msg("error", None, gettext("Please do not submit your codename!"), - gettext("Keep your codename secret, and use it to log in later to " - "check for replies.")) - return redirect(url_for('main.lookup')) + flash_msg( + "error", + None, + gettext("Please do not submit your codename!"), + gettext( + "Keep your codename secret, and use it to log in later to " + "check for replies." + ), + ) + return redirect(url_for("main.lookup")) if not os.path.exists(Storage.get_default().path(logged_in_source.filesystem_id)): - current_app.logger.debug("Store directory not found for source '{}', creating one." - .format(logged_in_source_in_db.journalist_designation)) + current_app.logger.debug( + "Store directory not found for source '{}', creating one.".format( + logged_in_source_in_db.journalist_designation + ) + ) os.mkdir(Storage.get_default().path(logged_in_source.filesystem_id)) if msg: @@ -227,7 +268,9 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: logged_in_source_in_db.filesystem_id, logged_in_source_in_db.interaction_count, logged_in_source_in_db.journalist_filename, - msg)) + msg, + ) + ) if fh: logged_in_source_in_db.interaction_count += 1 fnames.append( @@ -236,12 +279,16 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: logged_in_source_in_db.interaction_count, logged_in_source_in_db.journalist_filename, fh.filename, - fh.stream)) + fh.stream, + ) + ) if first_submission or msg or fh: if first_submission: - html_contents = gettext("Thank you for sending this information to us. Please " - "check back later for replies.") + html_contents = gettext( + "Thank you for sending this information to us. Please " + "check back later for replies." + ) elif msg and not fh: html_contents = gettext("Thanks! We received your message.") elif fh and not msg: @@ -266,9 +313,9 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: normalize_timestamps(logged_in_source) - return redirect(url_for('main.lookup')) + return redirect(url_for("main.lookup")) - @view.route('/delete', methods=('POST',)) + @view.route("/delete", methods=("POST",)) @login_required def delete(logged_in_source: SourceUser) -> werkzeug.Response: """This deletes the reply from the source's inbox, but preserves @@ -277,25 +324,27 @@ def delete(logged_in_source: SourceUser) -> werkzeug.Response: """ query = Reply.query.filter_by( - filename=request.form['reply_filename'], - source_id=logged_in_source.db_record_id) + filename=request.form["reply_filename"], source_id=logged_in_source.db_record_id + ) reply = get_one_or_else(query, current_app.logger, abort) reply.deleted_by_source = True db.session.add(reply) db.session.commit() flash_msg("success", gettext("Success!"), gettext("Reply deleted")) - return redirect(url_for('.lookup')) + return redirect(url_for(".lookup")) - @view.route('/delete-all', methods=('POST',)) + @view.route("/delete-all", methods=("POST",)) @login_required def batch_delete(logged_in_source: SourceUser) -> werkzeug.Response: - replies = Reply.query.filter(Reply.source_id == logged_in_source.db_record_id) \ - .filter(Reply.deleted_by_source == False).all() # noqa + replies = ( + Reply.query.filter(Reply.source_id == logged_in_source.db_record_id) + .filter(Reply.deleted_by_source == False) + .all() + ) # noqa if len(replies) == 0: - current_app.logger.error("Found no replies when at least one was " - "expected") - return redirect(url_for('.lookup')) + current_app.logger.error("Found no replies when at least one was " "expected") + return redirect(url_for(".lookup")) for reply in replies: reply.deleted_by_source = True @@ -303,27 +352,27 @@ def batch_delete(logged_in_source: SourceUser) -> werkzeug.Response: db.session.commit() flash_msg("success", gettext("Success!"), gettext("All replies have been deleted")) - return redirect(url_for('.lookup')) + return redirect(url_for(".lookup")) - @view.route('/login', methods=('GET', 'POST')) + @view.route("/login", methods=("GET", "POST")) def login() -> Union[str, werkzeug.Response]: form = LoginForm() if form.validate_on_submit(): try: SessionManager.log_user_in( db_session=db.session, - supplied_passphrase=DicewarePassphrase(request.form['codename'].strip()) + supplied_passphrase=DicewarePassphrase(request.form["codename"].strip()), ) except InvalidPassphraseError: current_app.logger.info("Login failed for invalid codename") flash_msg("error", None, gettext("Sorry, that is not a recognized codename.")) else: # Success: a valid passphrase was supplied - return redirect(url_for('.lookup', from_login='1')) + return redirect(url_for(".lookup", from_login="1")) - return render_template('login.html', form=form) + return render_template("login.html", form=form) - @view.route('/logout') + @view.route("/logout") def logout() -> Union[str, werkzeug.Response]: """ If a user is logged in, show them a logout page that prompts them to @@ -336,13 +385,13 @@ def logout() -> Union[str, werkzeug.Response]: # Clear the session after we render the message so it's localized # If a user specified a locale, save it and restore it session.clear() - session['locale'] = g.localeinfo.id + session["locale"] = g.localeinfo.id - return render_template('logout.html') + return render_template("logout.html") else: - return redirect(url_for('.index')) + return redirect(url_for(".index")) - @view.route('/robots.txt') + @view.route("/robots.txt") def robots_txt() -> werkzeug.Response: """Tell robots we don't want them""" resp = make_response("User-agent: *\nDisallow: /") diff --git a/securedrop/source_app/session_manager.py b/securedrop/source_app/session_manager.py --- a/securedrop/source_app/session_manager.py +++ b/securedrop/source_app/session_manager.py @@ -3,8 +3,7 @@ import sqlalchemy from flask import session - -from source_user import SourceUser, authenticate_source_user, InvalidPassphraseError +from source_user import InvalidPassphraseError, SourceUser, authenticate_source_user if TYPE_CHECKING: from passphrases import DicewarePassphrase @@ -35,9 +34,7 @@ class SessionManager: @classmethod def log_user_in( - cls, - db_session: sqlalchemy.orm.Session, - supplied_passphrase: "DicewarePassphrase" + cls, db_session: sqlalchemy.orm.Session, supplied_passphrase: "DicewarePassphrase" ) -> SourceUser: # Late import so the module can be used without a config.py in the parent folder from sdconfig import config @@ -52,8 +49,9 @@ def log_user_in( # Save the session expiration date in the user's session cookie session_duration = timedelta(minutes=config.SESSION_EXPIRATION_MINUTES) - session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] = datetime.now( - timezone.utc) + session_duration + session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] = ( + datetime.now(timezone.utc) + session_duration + ) return source_user diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -1,23 +1,16 @@ import json +import re import subprocess +import typing +from hmac import compare_digest import werkzeug -from flask import flash -from flask import redirect -from flask import render_template -from flask import current_app -from flask import url_for +from flask import current_app, flash, redirect, render_template, url_for from flask.sessions import SessionMixin -from markupsafe import Markup, escape -from store import Storage -from hmac import compare_digest from flask_babel import gettext - -import typing - -import re - +from markupsafe import Markup, escape from source_user import SourceUser +from store import Storage if typing.TYPE_CHECKING: from typing import Optional @@ -35,8 +28,8 @@ def codename_detected(message: str, codename: str) -> bool: def flash_msg( category: str, - declarative: 'Optional[str]', - *msg_contents: 'str', + declarative: "Optional[str]", + *msg_contents: "str", ) -> None: """ Render flash message with a (currently) optional declarative heading. @@ -44,7 +37,7 @@ def flash_msg( contents = Markup("<br>".join([escape(part) for part in msg_contents])) msg = render_template( - 'flash_message.html', + "flash_message.html", declarative=declarative, msg_contents=contents, ) @@ -53,20 +46,23 @@ def flash_msg( def clear_session_and_redirect_to_logged_out_page(flask_session: SessionMixin) -> werkzeug.Response: msg = render_template( - 'flash_message.html', + "flash_message.html", declarative=gettext("Important"), - msg_contents=Markup(gettext( - 'You were logged out due to inactivity. Click the <img src={icon} alt="" width="16" ' - 'height="16">&nbsp;<b>New Identity</b> button in your Tor Browser\'s toolbar before ' - 'moving on. This will clear your Tor Browser activity data on this device.') - .format(icon=url_for("static", filename="i/torbroom.png"))) + msg_contents=Markup( + gettext( + 'You were logged out due to inactivity. Click the <img src={icon} alt="" ' + 'width="16" height="16">&nbsp;<b>New Identity</b> button in your Tor Browser\'s ' + "toolbar before moving on. This will clear your Tor Browser activity data on " + "this device." + ).format(icon=url_for("static", filename="i/torbroom.png")) + ), ) # Clear the session after we render the message so it's localized flask_session.clear() flash(Markup(msg), "error") - return redirect(url_for('main.index')) + return redirect(url_for("main.index")) def normalize_timestamps(logged_in_source: SourceUser) -> None: @@ -76,20 +72,21 @@ def normalize_timestamps(logged_in_source: SourceUser) -> None: #301. """ source_in_db = logged_in_source.get_db_record() - sub_paths = [Storage.get_default().path(logged_in_source.filesystem_id, submission.filename) - for submission in source_in_db.submissions] + sub_paths = [ + Storage.get_default().path(logged_in_source.filesystem_id, submission.filename) + for submission in source_in_db.submissions + ] if len(sub_paths) > 1: args = ["touch", "--no-create"] args.extend(sub_paths) rc = subprocess.call(args) if rc != 0: current_app.logger.warning( - "Couldn't normalize submission " - "timestamps (touch exited with %d)" % - rc) + "Couldn't normalize submission " "timestamps (touch exited with %d)" % rc + ) -def check_url_file(path: str, regexp: str) -> 'Optional[str]': +def check_url_file(path: str, regexp: str) -> "Optional[str]": """ Check that a file exists at the path given and contains a single line matching the regexp. Used for checking the source interface address @@ -107,9 +104,8 @@ def check_url_file(path: str, regexp: str) -> 'Optional[str]': return None -def get_sourcev3_url() -> 'Optional[str]': - return check_url_file("/var/lib/securedrop/source_v3_url", - r"^[a-z0-9]{56}\.onion$") +def get_sourcev3_url() -> "Optional[str]": + return check_url_file("/var/lib/securedrop/source_v3_url", r"^[a-z0-9]{56}\.onion$") def fit_codenames_into_cookie(codenames: dict) -> dict: @@ -122,9 +118,11 @@ def fit_codenames_into_cookie(codenames: dict) -> dict: serialized = json.dumps(codenames).encode() if len(codenames) > 1 and len(serialized) > 4000: # werkzeug.Response.max_cookie_size = 4093 if current_app: - current_app.logger.warn(f"Popping oldest of {len(codenames)} " - f"codenames ({len(serialized)} bytes) to " - f"fit within maximum cookie size") + current_app.logger.warn( + f"Popping oldest of {len(codenames)} " + f"codenames ({len(serialized)} bytes) to " + f"fit within maximum cookie size" + ) del codenames[list(codenames)[0]] # FIFO return fit_codenames_into_cookie(codenames) diff --git a/securedrop/source_user.py b/securedrop/source_user.py --- a/securedrop/source_user.py +++ b/securedrop/source_user.py @@ -1,19 +1,16 @@ import os - from base64 import b32encode from functools import lru_cache from pathlib import Path from random import SystemRandom -from typing import Optional, List -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, List, Optional +import models from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf import scrypt from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session -import models - if TYPE_CHECKING: from passphrases import DicewarePassphrase from store import Storage @@ -87,9 +84,11 @@ def create_source_user( new_designation = designation_generator.generate_journalist_designation() # Check to see if it's already used by an existing source - existing_source_with_same_designation = db_session.query( - models.Source - ).filter_by(journalist_designation=new_designation).one_or_none() + existing_source_with_same_designation = ( + db_session.query(models.Source) + .filter_by(journalist_designation=new_designation) + .one_or_none() + ) if not existing_source_with_same_designation: # The designation is not already used - good to go valid_designation = new_designation @@ -189,7 +188,6 @@ def get_default(cls) -> "_SourceScryptManager": class _DesignationGenerator: - def __init__(self, nouns: List[str], adjectives: List[str]): self._random_generator = SystemRandom() diff --git a/securedrop/specialstrings.py b/securedrop/specialstrings.py --- a/securedrop/specialstrings.py +++ b/securedrop/specialstrings.py @@ -1,7 +1,7 @@ strings = [ """This is a test message without markup!""", - """This is a test message with markup and characters such as \, \\, \', \" and ". """ + # noqa: W605, E501 - """<strong>This text should not be bold</strong>!""", + """This is a test message with markup and characters such as \, \\, \', \" and ". """ + + """<strong>This text should not be bold</strong>!""", # noqa: W605, E501 """~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%""", """Ω≈ç√∫˜µ≤≥÷ åß∂ƒ©˙∆˚¬…æ @@ -12,9 +12,7 @@ Œ„´‰ˇÁ¨ˆØ∏”""", """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$""", # noqa: W605, E501 """............................................................................................................................ .""", # noqa: W605, E501 - """thisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwit💩houtspacesordashes""", # noqa: W605, E501 - """😍😍😍😍🔥🔥🔥🔥🔥🖧Thelastwas3networkedcomuters📟📸longwordwit💩houtspacesordashes""", # noqa: W605, E501 """WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW""", """.................................................................................................................................""", # noqa: W605, E501 @@ -129,8 +127,7 @@ 社會科學院語學研究所 울란바토르 𠜎𠜱𠝹𠱓𠱸𠲖𠳏 -""", # noqa: W605, E501 - +""", # noqa: W605, E501 """𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆""", # noqa: W605, E501 """ The quick brown fox jumps over the lazy dog diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -1,37 +1,33 @@ # -*- coding: utf-8 -*- -from pathlib import Path - import binascii import gzip import os import re import tempfile +import typing import zipfile +from hashlib import sha256 +from pathlib import Path +import rm +from encryption import EncryptionManager from flask import current_app -from hashlib import sha256 +from secure_tempfile import SecureTemporaryFile from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from werkzeug.utils import secure_filename - -from encryption import EncryptionManager -from secure_tempfile import SecureTemporaryFile - -import rm from worker import create_queue -import typing - - if typing.TYPE_CHECKING: # flake8 can not understand type annotation yet. # That is why all type annotation relative import # statements has to be marked as noqa. # http://flake8.pycqa.org/en/latest/user/error-codes.html?highlight=f401 - from typing import List, Type, Union, Optional, IO # noqa: F401 from tempfile import _TemporaryFileWrapper # type: ignore # noqa: F401 - from sqlalchemy.orm import Session # noqa: F401 + from typing import IO, List, Optional, Type, Union # noqa: F401 + from models import Reply, Submission # noqa: F401 + from sqlalchemy.orm import Session # noqa: F401 _default_storage: typing.Optional["Storage"] = None @@ -45,6 +41,7 @@ class PathException(Exception): """An exception raised by `util.verify` when it encounters a bad path. A path can be bad when it is not absolute or not normalized. """ + pass @@ -54,6 +51,7 @@ class TooManyFilesException(Exception): This could be due to a very unlikely collision between journalist_designations. """ + pass @@ -62,6 +60,7 @@ class NoFileFoundException(Exception): not be found for a given submission or reply. This is likely due to an admin manually deleting files from the server. """ + pass @@ -69,6 +68,7 @@ class NotEncrypted(Exception): """An exception raised if a file expected to be encrypted client-side is actually plaintext. """ + pass @@ -92,16 +92,13 @@ def safe_renames(old: str, new: str) -> None: class Storage: - def __init__(self, storage_path: str, temp_dir: str) -> None: if not os.path.isabs(storage_path): - raise PathException("storage_path {} is not absolute".format( - storage_path)) + raise PathException("storage_path {} is not absolute".format(storage_path)) self.__storage_path = storage_path if not os.path.isabs(temp_dir): - raise PathException("temp_dir {} is not absolute".format( - temp_dir)) + raise PathException("temp_dir {} is not absolute".format(temp_dir)) self.__temp_dir = temp_dir # where files and directories are sent to be securely deleted @@ -119,10 +116,7 @@ def get_default(cls) -> "Storage": global _default_storage if _default_storage is None: - _default_storage = cls( - config.STORE_DIR, - config.TEMP_DIR - ) + _default_storage = cls(config.STORE_DIR, config.TEMP_DIR) return _default_storage @@ -167,7 +161,7 @@ def verify(self, p: str) -> bool: raise PathException("Path not valid in store: {}".format(p)) - def path(self, filesystem_id: str, filename: str = '') -> str: + def path(self, filesystem_id: str, filename: str = "") -> str: """ Returns the path resolved within `self.__storage_path`. @@ -185,8 +179,8 @@ def path(self, filesystem_id: str, filename: str = '') -> str: def path_without_filesystem_id(self, filename: str) -> str: """Get the normalized, absolute file path, within - `self.__storage_path` for a filename when the filesystem_id - is not known. + `self.__storage_path` for a filename when the filesystem_id + is not known. """ joined_paths = [] @@ -196,9 +190,9 @@ def path_without_filesystem_id(self, filename: str) -> str: joined_paths.append(os.path.join(rootdir, file_)) if len(joined_paths) > 1: - raise TooManyFilesException('Found duplicate files!') + raise TooManyFilesException("Found duplicate files!") elif len(joined_paths) == 0: - raise NoFileFoundException('File not found: {}'.format(filename)) + raise NoFileFoundException("File not found: {}".format(filename)) else: absolute = joined_paths[0] @@ -208,40 +202,41 @@ def path_without_filesystem_id(self, filename: str) -> str: ) return absolute - def get_bulk_archive(self, - selected_submissions: 'List', - zip_directory: str = '') -> '_TemporaryFileWrapper': + def get_bulk_archive( + self, selected_submissions: "List", zip_directory: str = "" + ) -> "_TemporaryFileWrapper": """Generate a zip file from the selected submissions""" zip_file = tempfile.NamedTemporaryFile( - prefix='tmp_securedrop_bulk_dl_', - dir=self.__temp_dir, - delete=False) - sources = set([i.source.journalist_designation - for i in selected_submissions]) + prefix="tmp_securedrop_bulk_dl_", dir=self.__temp_dir, delete=False + ) + sources = set([i.source.journalist_designation for i in selected_submissions]) # The below nested for-loops are there to create a more usable # folder structure per #383 missing_files = False - with zipfile.ZipFile(zip_file, 'w') as zip: + with zipfile.ZipFile(zip_file, "w") as zip: for source in sources: fname = "" - submissions = [s for s in selected_submissions - if s.source.journalist_designation == source] + submissions = [ + s for s in selected_submissions if s.source.journalist_designation == source + ] for submission in submissions: filename = self.path(submission.source.filesystem_id, submission.filename) if os.path.exists(filename): - document_number = submission.filename.split('-')[0] + document_number = submission.filename.split("-")[0] if zip_directory == submission.source.journalist_filename: fname = zip_directory else: fname = os.path.join(zip_directory, source) - zip.write(filename, arcname=os.path.join( - fname, - "%s_%s" % (document_number, - submission.source.last_updated.date()), - os.path.basename(filename) - )) + zip.write( + filename, + arcname=os.path.join( + fname, + "%s_%s" % (document_number, submission.source.last_updated.date()), + os.path.basename(filename), + ), + ) else: missing_files = True current_app.logger.error("File {} not found".format(filename)) @@ -266,14 +261,10 @@ def move_to_shredder(self, path: str) -> None: shredder directory. """ if not self.verify(path): - raise ValueError( - """Path is not within the store: "{}" """.format(path) - ) + raise ValueError("""Path is not within the store: "{}" """.format(path)) if not os.path.exists(path): - raise ValueError( - """Path does not exist: "{}" """.format(path) - ) + raise ValueError("""Path does not exist: "{}" """.format(path)) relpath = os.path.relpath(path, start=self.storage_path) dest = os.path.join(tempfile.mkdtemp(dir=self.__shredder_path), relpath) @@ -301,9 +292,7 @@ def clear_shredder(self) -> None: # result in the file data being shredded once for # each link. current_app.logger.info( - "Deleting link {} to {}".format( - abs_file, os.readlink(abs_file) - ) + "Deleting link {} to {}".format(abs_file, os.readlink(abs_file)) ) os.unlink(abs_file) continue @@ -324,12 +313,14 @@ def clear_shredder(self) -> None: os.rmdir(d) current_app.logger.debug("Removed directory {}/{}: {}".format(i, dir_count, d)) - def save_file_submission(self, - filesystem_id: str, - count: int, - journalist_filename: str, - filename: typing.Optional[str], - stream: 'IO[bytes]') -> str: + def save_file_submission( + self, + filesystem_id: str, + count: int, + journalist_filename: str, + filename: typing.Optional[str], + stream: "IO[bytes]", + ) -> str: if filename is not None: sanitized_filename = secure_filename(filename) @@ -349,13 +340,10 @@ def save_file_submission(self, # file. Given various usability constraints in GPG and Tails, this # is the most user-friendly way we have found to do this. - encrypted_file_name = "{0}-{1}-doc.gz.gpg".format( - count, - journalist_filename) + encrypted_file_name = "{0}-{1}-doc.gz.gpg".format(count, journalist_filename) encrypted_file_path = self.path(filesystem_id, encrypted_file_name) with SecureTemporaryFile("/tmp") as stf: # nosec - with gzip.GzipFile(filename=sanitized_filename, - mode='wb', fileobj=stf, mtime=0) as gzf: + with gzip.GzipFile(filename=sanitized_filename, mode="wb", fileobj=stf, mtime=0) as gzf: # Buffer the stream into the gzip file to avoid excessive # memory consumption while True: @@ -371,28 +359,23 @@ def save_file_submission(self, return encrypted_file_name - def save_pre_encrypted_reply(self, - filesystem_id: str, - count: int, - journalist_filename: str, - content: str) -> str: - if '-----BEGIN PGP MESSAGE-----' not in content.split('\n')[0]: + def save_pre_encrypted_reply( + self, filesystem_id: str, count: int, journalist_filename: str, content: str + ) -> str: + if "-----BEGIN PGP MESSAGE-----" not in content.split("\n")[0]: raise NotEncrypted - encrypted_file_name = "{0}-{1}-reply.gpg".format(count, - journalist_filename) + encrypted_file_name = "{0}-{1}-reply.gpg".format(count, journalist_filename) encrypted_file_path = self.path(filesystem_id, encrypted_file_name) - with open(encrypted_file_path, 'w') as fh: + with open(encrypted_file_path, "w") as fh: fh.write(content) return encrypted_file_path - def save_message_submission(self, - filesystem_id: str, - count: int, - journalist_filename: str, - message: str) -> str: + def save_message_submission( + self, filesystem_id: str, count: int, journalist_filename: str, message: str + ) -> str: filename = "{0}-{1}-msg.gpg".format(count, journalist_filename) msg_loc = self.path(filesystem_id, filename) EncryptionManager.get_default().encrypt_source_message( @@ -402,20 +385,19 @@ def save_message_submission(self, return filename -def async_add_checksum_for_file(db_obj: 'Union[Submission, Reply]', storage: Storage) -> str: +def async_add_checksum_for_file(db_obj: "Union[Submission, Reply]", storage: Storage) -> str: return create_queue().enqueue( queued_add_checksum_for_file, type(db_obj), db_obj.id, storage.path(db_obj.source.filesystem_id, db_obj.filename), - current_app.config['SQLALCHEMY_DATABASE_URI'], + current_app.config["SQLALCHEMY_DATABASE_URI"], ) -def queued_add_checksum_for_file(db_model: 'Union[Type[Submission], Type[Reply]]', - model_id: int, - file_path: str, - db_uri: str) -> str: +def queued_add_checksum_for_file( + db_model: "Union[Type[Submission], Type[Reply]]", model_id: int, file_path: str, db_uri: str +) -> str: # we have to create our own DB session because there is no app context session = sessionmaker(bind=create_engine(db_uri))() db_obj = session.query(db_model).filter_by(id=model_id).one() @@ -424,19 +406,19 @@ def queued_add_checksum_for_file(db_model: 'Union[Type[Submission], Type[Reply]] return "success" -def add_checksum_for_file(session: 'Session', - db_obj: 'Union[Submission, Reply]', - file_path: str) -> None: +def add_checksum_for_file( + session: "Session", db_obj: "Union[Submission, Reply]", file_path: str +) -> None: hasher = sha256() - with open(file_path, 'rb') as f: + with open(file_path, "rb") as f: while True: read_bytes = f.read(4096) if not read_bytes: break hasher.update(read_bytes) - digest = binascii.hexlify(hasher.digest()).decode('utf-8') - digest_str = u'sha256:' + digest + digest = binascii.hexlify(hasher.digest()).decode("utf-8") + digest_str = "sha256:" + digest db_obj.checksum = digest_str session.add(db_obj) diff --git a/securedrop/template_filters.py b/securedrop/template_filters.py --- a/securedrop/template_filters.py +++ b/securedrop/template_filters.py @@ -1,30 +1,26 @@ # -*- coding: utf-8 -*- -from jinja2 import pass_eval_context -from flask_babel import gettext, get_locale -from babel import units, dates -from datetime import datetime -from markupsafe import Markup, escape import math +from datetime import datetime +from babel import dates, units +from flask_babel import get_locale, gettext +from jinja2 import pass_eval_context from jinja2.nodes import EvalContext +from markupsafe import Markup, escape -def rel_datetime_format( - dt: datetime, fmt: str = 'long', - relative: bool = False -) -> str: +def rel_datetime_format(dt: datetime, fmt: str = "long", relative: bool = False) -> str: """Template filter for readable formatting of datetime.datetime""" if relative: - time = dates.format_timedelta(datetime.utcnow() - dt, - locale=get_locale()) - return gettext('{time} ago').format(time=time) + time = dates.format_timedelta(datetime.utcnow() - dt, locale=get_locale()) + return gettext("{time} ago").format(time=time) else: return dates.format_datetime(dt, fmt, locale=get_locale()) @pass_eval_context def nl2br(context: EvalContext, value: str) -> str: - formatted = '<br>\n'.join(escape(value).split('\n')) + formatted = "<br>\n".join(escape(value).split("\n")) if context.autoescape: formatted = Markup(formatted) return formatted @@ -32,10 +28,10 @@ def nl2br(context: EvalContext, value: str) -> str: def filesizeformat(value: int) -> str: prefixes = [ - 'digital-kilobyte', - 'digital-megabyte', - 'digital-gigabyte', - 'digital-terabyte', + "digital-kilobyte", + "digital-megabyte", + "digital-gigabyte", + "digital-terabyte", ] locale = get_locale() base = 1024 @@ -55,4 +51,4 @@ def filesizeformat(value: int) -> str: def html_datetime_format(dt: datetime) -> str: """Return a datetime string that will pass HTML validation""" - return dates.format_datetime(dt, 'yyyy-MM-dd HH:mm:ss.SSS') + return dates.format_datetime(dt, "yyyy-MM-dd HH:mm:ss.SSS") diff --git a/securedrop/upload-screenshots.py b/securedrop/upload-screenshots.py --- a/securedrop/upload-screenshots.py +++ b/securedrop/upload-screenshots.py @@ -1,19 +1,15 @@ #!/usr/bin/env python3 -from glob import glob -from urllib.parse import urljoin - import os import re -import requests import sys +from glob import glob # Used to generate URLs for API endpoints and links; exposed as argument -from typing import List - -from typing import Tuple +from typing import Dict, List, Tuple +from urllib.parse import urljoin -from typing import Dict +import requests DEFAULT_BASE_URL = "https://weblate.securedrop.org" @@ -55,9 +51,7 @@ def main() -> None: screenshot_files = glob(os.path.join(SCREENSHOTS_DIRECTORY, SCREENSHOTS_GLOB)) if len(screenshot_files) == 0: - print( - "Page layout test results not found. Run this command from the SecureDrop" - ) + print("Page layout test results not found. Run this command from the SecureDrop") print("base directory to generate the English language screenshots:\n") print(" LOCALES=en_US make translation-test") print("\nThis will take several minutes to complete.") @@ -136,9 +130,7 @@ def get_existing_screenshots(self) -> List[Dict[str, str]]: screenshots += screenshots_page["results"] request_count += 1 if request_count >= self.request_limit: - msg = "Request limit of {} exceeded. Aborting.".format( - self.request_limit - ) + msg = "Request limit of {} exceeded. Aborting.".format(self.request_limit) raise RequestLimitError(msg) return screenshots @@ -186,9 +178,7 @@ def upload(self, check_existing_screenshots: bool = True) -> None: "component_slug": "securedrop", } print("Uploading new screenshot {}".format(basename)) - response = self.session.post( - self.screenshots_endpoint, files=image, data=fields - ) + response = self.session.post(self.screenshots_endpoint, files=image, data=fields) response.raise_for_status() result_url = urljoin( @@ -199,9 +189,7 @@ def upload(self, check_existing_screenshots: bool = True) -> None: class BadOrMissingTokenError(Exception): def __init__(self, reason: str, base_url: str) -> None: - reason += " Obtain token via {}".format( - urljoin(base_url, "accounts/profile/#api") - ) + reason += " Obtain token via {}".format(urljoin(base_url, "accounts/profile/#api")) super().__init__(reason) diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = '2.5.0~rc1' +__version__ = "2.5.0~rc1" diff --git a/securedrop/worker.py b/securedrop/worker.py --- a/securedrop/worker.py +++ b/securedrop/worker.py @@ -1,13 +1,12 @@ import logging import os -from typing import Optional, List +from typing import List, Optional from redis import Redis -from rq.queue import Queue -from rq.worker import Worker, WorkerStatus from rq.exceptions import InvalidJobOperation, NoSuchJobError +from rq.queue import Queue from rq.registry import StartedJobRegistry - +from rq.worker import Worker, WorkerStatus from sdconfig import config @@ -91,9 +90,7 @@ def requeue_interrupted_jobs(queue_name: Optional[str] = None) -> None: try: job = started_job_registry.job_class.fetch(job_id, started_job_registry.connection) except NoSuchJobError as e: - logging.error( - "Could not find details for job %s: %s", job_id, e - ) + logging.error("Could not find details for job %s: %s", job_id, e) continue logging.debug(
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -1,23 +1,24 @@ -from flaky import flaky -import os import io -import pexpect -import pytest +import os import re -import requests import shutil import subprocess import tempfile -SD_DIR = '' +import pexpect +import pytest +import requests +from flaky import flaky + +SD_DIR = "" CURRENT_DIR = os.path.dirname(__file__) -ANSIBLE_BASE = '' +ANSIBLE_BASE = "" # Regex to strip ANSI escape chars # https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python -ANSI_ESCAPE = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') +ANSI_ESCAPE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]") -OUTPUT1 = '''app_hostname: app +OUTPUT1 = """app_hostname: app app_ip: 10.20.2.2 daily_reboot_time: 5 dns_server: @@ -47,9 +48,9 @@ smtp_relay: smtp.gmail.com smtp_relay_port: 587 ssh_users: sd -''' +""" -JOURNALIST_ALERT_OUTPUT = '''app_hostname: app +JOURNALIST_ALERT_OUTPUT = """app_hostname: app app_ip: 10.20.2.2 daily_reboot_time: 5 dns_server: @@ -79,9 +80,9 @@ smtp_relay: smtp.gmail.com smtp_relay_port: 587 ssh_users: sd -''' +""" -HTTPS_OUTPUT = '''app_hostname: app +HTTPS_OUTPUT = """app_hostname: app app_ip: 10.20.2.2 daily_reboot_time: 5 dns_server: @@ -111,39 +112,38 @@ smtp_relay: smtp.gmail.com smtp_relay_port: 587 ssh_users: sd -''' +""" def setup_function(function): global SD_DIR SD_DIR = tempfile.mkdtemp() - ANSIBLE_BASE = '{0}/install_files/ansible-base'.format(SD_DIR) + ANSIBLE_BASE = "{0}/install_files/ansible-base".format(SD_DIR) for name in ["roles", "tasks"]: shutil.copytree( os.path.join(CURRENT_DIR, "../../install_files/ansible-base", name), - os.path.join(ANSIBLE_BASE, name) + os.path.join(ANSIBLE_BASE, name), ) for name in ["ansible.cfg", "securedrop-prod.yml"]: shutil.copy( - os.path.join(CURRENT_DIR, '../../install_files/ansible-base', name), - ANSIBLE_BASE + os.path.join(CURRENT_DIR, "../../install_files/ansible-base", name), ANSIBLE_BASE ) - cmd = 'mkdir -p {0}/group_vars/all'.format(ANSIBLE_BASE).split() + cmd = "mkdir -p {0}/group_vars/all".format(ANSIBLE_BASE).split() subprocess.check_call(cmd) - for name in ['sd_admin_test.pub', 'ca.crt', 'sd.crt', 'key.asc']: - subprocess.check_call('cp -r {0}/files/{1} {2}'.format(CURRENT_DIR, - name, ANSIBLE_BASE).split()) - for name in ['de_DE', 'es_ES', 'fr_FR', 'pt_BR']: - dircmd = 'mkdir -p {0}/securedrop/translations/{1}'.format( - SD_DIR, name) + for name in ["sd_admin_test.pub", "ca.crt", "sd.crt", "key.asc"]: + subprocess.check_call( + "cp -r {0}/files/{1} {2}".format(CURRENT_DIR, name, ANSIBLE_BASE).split() + ) + for name in ["de_DE", "es_ES", "fr_FR", "pt_BR"]: + dircmd = "mkdir -p {0}/securedrop/translations/{1}".format(SD_DIR, name) subprocess.check_call(dircmd.split()) def teardown_function(function): - subprocess.check_call('rm -rf {0}'.format(SD_DIR).split()) + subprocess.check_call("rm -rf {0}".format(SD_DIR).split()) def verify_username_prompt(child): @@ -151,126 +151,143 @@ def verify_username_prompt(child): def verify_reboot_prompt(child): - child.expect( - rb"Daily reboot time of the server \(24\-hour clock\):", timeout=2) - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == '4' # noqa: E501 + child.expect(rb"Daily reboot time of the server \(24\-hour clock\):", timeout=2) + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "4" # noqa: E501 def verify_ipv4_appserver_prompt(child): - child.expect(rb'Local IPv4 address for the Application Server\:', timeout=2) # noqa: E501 + child.expect(rb"Local IPv4 address for the Application Server\:", timeout=2) # noqa: E501 # Expected default - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == '10.20.2.2' # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "10.20.2.2" # noqa: E501 def verify_ipv4_monserver_prompt(child): - child.expect(rb'Local IPv4 address for the Monitor Server\:', timeout=2) + child.expect(rb"Local IPv4 address for the Monitor Server\:", timeout=2) # Expected default - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == '10.20.3.2' # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "10.20.3.2" # noqa: E501 def verify_hostname_app_prompt(child): - child.expect(rb'Hostname for Application Server\:', timeout=2) - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'app' # noqa: E501 + child.expect(rb"Hostname for Application Server\:", timeout=2) + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "app" # noqa: E501 def verify_hostname_mon_prompt(child): - child.expect(rb'Hostname for Monitor Server\:', timeout=2) - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'mon' # noqa: E501 + child.expect(rb"Hostname for Monitor Server\:", timeout=2) + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "mon" # noqa: E501 def verify_dns_prompt(child): - child.expect(rb'DNS server\(s\):', timeout=2) - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == '8.8.8.8 8.8.4.4' # noqa: E501 + child.expect(rb"DNS server\(s\):", timeout=2) + assert ( + ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "8.8.8.8 8.8.4.4" + ) # noqa: E501 def verify_app_gpg_key_prompt(child): - child.expect(rb'Local filepath to public key for SecureDrop Application GPG public key\:', timeout=2) # noqa: E501 + child.expect( + rb"Local filepath to public key for SecureDrop Application GPG public key\:", timeout=2 + ) # noqa: E501 def verify_https_prompt(child): - child.expect(rb'Whether HTTPS should be enabled on Source Interface \(requires EV cert\)\:', timeout=2) # noqa: E501 + child.expect( + rb"Whether HTTPS should be enabled on Source Interface \(requires EV cert\)\:", timeout=2 + ) # noqa: E501 def verify_https_cert_prompt(child): - child.expect(rb'Local filepath to HTTPS certificate\:', timeout=2) + child.expect(rb"Local filepath to HTTPS certificate\:", timeout=2) def verify_https_cert_key_prompt(child): - child.expect(rb'Local filepath to HTTPS certificate key\:', timeout=2) + child.expect(rb"Local filepath to HTTPS certificate key\:", timeout=2) def verify_https_cert_chain_file_prompt(child): - child.expect(rb'Local filepath to HTTPS certificate chain file\:', timeout=2) # noqa: E501 + child.expect(rb"Local filepath to HTTPS certificate chain file\:", timeout=2) # noqa: E501 def verify_app_gpg_fingerprint_prompt(child): - child.expect(rb'Full fingerprint for the SecureDrop Application GPG Key\:', timeout=2) # noqa: E501 + child.expect( + rb"Full fingerprint for the SecureDrop Application GPG Key\:", timeout=2 + ) # noqa: E501 def verify_ossec_gpg_key_prompt(child): - child.expect(rb'Local filepath to OSSEC alerts GPG public key\:', timeout=2) # noqa: E501 + child.expect(rb"Local filepath to OSSEC alerts GPG public key\:", timeout=2) # noqa: E501 def verify_ossec_gpg_fingerprint_prompt(child): - child.expect(rb'Full fingerprint for the OSSEC alerts GPG public key\:', timeout=2) # noqa: E501 + child.expect( + rb"Full fingerprint for the OSSEC alerts GPG public key\:", timeout=2 + ) # noqa: E501 def verify_admin_email_prompt(child): - child.expect(rb'Admin email address for receiving OSSEC alerts\:', timeout=2) # noqa: E501 + child.expect(rb"Admin email address for receiving OSSEC alerts\:", timeout=2) # noqa: E501 def verify_journalist_gpg_key_prompt(child): - child.expect(rb'Local filepath to journalist alerts GPG public key \(optional\)\:', timeout=2) # noqa: E501 + child.expect( + rb"Local filepath to journalist alerts GPG public key \(optional\)\:", timeout=2 + ) # noqa: E501 def verify_journalist_fingerprint_prompt(child): - child.expect(rb'Full fingerprint for the journalist alerts GPG public key \(optional\)\:', timeout=2) # noqa: E501 + child.expect( + rb"Full fingerprint for the journalist alerts GPG public key \(optional\)\:", timeout=2 + ) # noqa: E501 def verify_journalist_email_prompt(child): - child.expect(rb'Email address for receiving journalist alerts \(optional\)\:', timeout=2) # noqa: E501 + child.expect( + rb"Email address for receiving journalist alerts \(optional\)\:", timeout=2 + ) # noqa: E501 def verify_smtp_relay_prompt(child): - child.expect(rb'SMTP relay for sending OSSEC alerts\:', timeout=2) + child.expect(rb"SMTP relay for sending OSSEC alerts\:", timeout=2) # Expected default - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'smtp.gmail.com' # noqa: E501 + assert ( + ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "smtp.gmail.com" + ) # noqa: E501 def verify_smtp_port_prompt(child): - child.expect(rb'SMTP port for sending OSSEC alerts\:', timeout=2) - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == '587' # noqa: E501 + child.expect(rb"SMTP port for sending OSSEC alerts\:", timeout=2) + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "587" # noqa: E501 def verify_sasl_domain_prompt(child): - child.expect(rb'SASL domain for sending OSSEC alerts\:', timeout=2) + child.expect(rb"SASL domain for sending OSSEC alerts\:", timeout=2) # Expected default - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'gmail.com' # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "gmail.com" # noqa: E501 def verify_sasl_username_prompt(child): - child.expect(rb'SASL username for sending OSSEC alerts\:', timeout=2) + child.expect(rb"SASL username for sending OSSEC alerts\:", timeout=2) def verify_sasl_password_prompt(child): - child.expect(rb'SASL password for sending OSSEC alerts\:', timeout=2) + child.expect(rb"SASL password for sending OSSEC alerts\:", timeout=2) def verify_ssh_over_lan_prompt(child): - child.expect(rb'will be available over LAN only\:', timeout=2) - assert ANSI_ESCAPE.sub('', child.buffer.decode("utf-8")).strip() == 'yes' # noqa: E501 + child.expect(rb"will be available over LAN only\:", timeout=2) + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "yes" # noqa: E501 def verify_locales_prompt(child): - child.expect(rb'Space separated list of additional locales to support') # noqa: E501 + child.expect(rb"Space separated list of additional locales to support") # noqa: E501 def verify_install_has_valid_config(): """ Checks that securedrop-admin install validates the configuration. """ - cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} install'.format(cmd, SD_DIR)) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + child = pexpect.spawn("python {0} --force --root {1} install".format(cmd, SD_DIR)) child.expect(b"SUDO password:", timeout=5) child.close() @@ -279,8 +296,8 @@ def test_install_with_no_config(): """ Checks that securedrop-admin install complains about a missing config file. """ - cmd = os.path.join(os.path.dirname(CURRENT_DIR), 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} install'.format(cmd, SD_DIR)) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + child = pexpect.spawn("python {0} --force --root {1} install".format(cmd, SD_DIR)) child.expect(b'ERROR: Please run "securedrop-admin sdconfig" first.', timeout=5) child.expect(pexpect.EOF, timeout=5) child.close() @@ -289,61 +306,62 @@ def test_install_with_no_config(): def test_sdconfig_on_first_run(): - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + child = pexpect.spawn("python {0} --force --root {1} sdconfig".format(cmd, SD_DIR)) verify_username_prompt(child) - child.sendline('') + child.sendline("") verify_reboot_prompt(child) - child.sendline('\b5') # backspace and put 5 + child.sendline("\b5") # backspace and put 5 verify_ipv4_appserver_prompt(child) - child.sendline('') + child.sendline("") verify_ipv4_monserver_prompt(child) - child.sendline('') + child.sendline("") verify_hostname_app_prompt(child) - child.sendline('') + child.sendline("") verify_hostname_mon_prompt(child) - child.sendline('') + child.sendline("") verify_dns_prompt(child) - child.sendline('') + child.sendline("") verify_app_gpg_key_prompt(child) - child.sendline('\b' * 14 + 'sd_admin_test.pub') + child.sendline("\b" * 14 + "sd_admin_test.pub") verify_https_prompt(child) # Default answer is no - child.sendline('') + child.sendline("") verify_app_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_ossec_gpg_key_prompt(child) - child.sendline('\b' * 9 + 'sd_admin_test.pub') + child.sendline("\b" * 9 + "sd_admin_test.pub") verify_ossec_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_admin_email_prompt(child) - child.sendline('[email protected]') + child.sendline("[email protected]") verify_journalist_gpg_key_prompt(child) - child.sendline('') + child.sendline("") verify_smtp_relay_prompt(child) - child.sendline('') + child.sendline("") verify_smtp_port_prompt(child) - child.sendline('') + child.sendline("") verify_sasl_domain_prompt(child) - child.sendline('') + child.sendline("") verify_sasl_username_prompt(child) - child.sendline('testuser') + child.sendline("testuser") verify_sasl_password_prompt(child) - child.sendline('testpassword') + child.sendline("testpassword") verify_ssh_over_lan_prompt(child) - child.sendline('') + child.sendline("") verify_locales_prompt(child) - child.sendline('de_DE es_ES') - child.sendline('\b' * 3 + 'no') - child.sendline('\b' * 4 + 'yes') + child.sendline("de_DE es_ES") + child.sendline("\b" * 3 + "no") + child.sendline("\b" * 4 + "yes") child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur child.close() assert child.exitstatus == 0 assert child.signalstatus is None - with open(os.path.join(SD_DIR, 'install_files/ansible-base/group_vars/all/site-specific')) as fobj: # noqa: E501 + with open( + os.path.join(SD_DIR, "install_files/ansible-base/group_vars/all/site-specific") + ) as fobj: # noqa: E501 data = fobj.read() assert data == OUTPUT1 @@ -351,64 +369,65 @@ def test_sdconfig_on_first_run(): def test_sdconfig_enable_journalist_alerts(): - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + child = pexpect.spawn("python {0} --force --root {1} sdconfig".format(cmd, SD_DIR)) verify_username_prompt(child) - child.sendline('') + child.sendline("") verify_reboot_prompt(child) - child.sendline('\b5') # backspace and put 5 + child.sendline("\b5") # backspace and put 5 verify_ipv4_appserver_prompt(child) - child.sendline('') + child.sendline("") verify_ipv4_monserver_prompt(child) - child.sendline('') + child.sendline("") verify_hostname_app_prompt(child) - child.sendline('') + child.sendline("") verify_hostname_mon_prompt(child) - child.sendline('') + child.sendline("") verify_dns_prompt(child) - child.sendline('') + child.sendline("") verify_app_gpg_key_prompt(child) - child.sendline('\b' * 14 + 'sd_admin_test.pub') + child.sendline("\b" * 14 + "sd_admin_test.pub") verify_https_prompt(child) # Default answer is no - child.sendline('') + child.sendline("") verify_app_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_ossec_gpg_key_prompt(child) - child.sendline('\b' * 9 + 'sd_admin_test.pub') + child.sendline("\b" * 9 + "sd_admin_test.pub") verify_ossec_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_admin_email_prompt(child) - child.sendline('[email protected]') + child.sendline("[email protected]") # We will provide a key for this question verify_journalist_gpg_key_prompt(child) - child.sendline('sd_admin_test.pub') + child.sendline("sd_admin_test.pub") verify_journalist_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_journalist_email_prompt(child) - child.sendline('[email protected]') + child.sendline("[email protected]") verify_smtp_relay_prompt(child) - child.sendline('') + child.sendline("") verify_smtp_port_prompt(child) - child.sendline('') + child.sendline("") verify_sasl_domain_prompt(child) - child.sendline('') + child.sendline("") verify_sasl_username_prompt(child) - child.sendline('testuser') + child.sendline("testuser") verify_sasl_password_prompt(child) - child.sendline('testpassword') + child.sendline("testpassword") verify_ssh_over_lan_prompt(child) - child.sendline('') + child.sendline("") verify_locales_prompt(child) - child.sendline('de_DE es_ES') + child.sendline("de_DE es_ES") child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur child.close() assert child.exitstatus == 0 assert child.signalstatus is None - with open(os.path.join(SD_DIR, 'install_files/ansible-base/group_vars/all/site-specific')) as fobj: # noqa: E501 + with open( + os.path.join(SD_DIR, "install_files/ansible-base/group_vars/all/site-specific") + ) as fobj: # noqa: E501 data = fobj.read() assert JOURNALIST_ALERT_OUTPUT == data @@ -416,71 +435,72 @@ def test_sdconfig_enable_journalist_alerts(): def test_sdconfig_enable_https_on_source_interface(): - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - child = pexpect.spawn('python {0} --force --root {1} sdconfig'.format(cmd, SD_DIR)) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + child = pexpect.spawn("python {0} --force --root {1} sdconfig".format(cmd, SD_DIR)) verify_username_prompt(child) - child.sendline('') + child.sendline("") verify_reboot_prompt(child) - child.sendline('\b5') # backspace and put 5 + child.sendline("\b5") # backspace and put 5 verify_ipv4_appserver_prompt(child) - child.sendline('') + child.sendline("") verify_ipv4_monserver_prompt(child) - child.sendline('') + child.sendline("") verify_hostname_app_prompt(child) - child.sendline('') + child.sendline("") verify_hostname_mon_prompt(child) - child.sendline('') + child.sendline("") verify_dns_prompt(child) - child.sendline('') + child.sendline("") verify_app_gpg_key_prompt(child) - child.sendline('\b' * 14 + 'sd_admin_test.pub') + child.sendline("\b" * 14 + "sd_admin_test.pub") verify_https_prompt(child) # Default answer is no # We will press backspace twice and type yes - child.sendline('\b\byes') + child.sendline("\b\byes") verify_https_cert_prompt(child) - child.sendline('sd.crt') + child.sendline("sd.crt") verify_https_cert_key_prompt(child) - child.sendline('key.asc') + child.sendline("key.asc") verify_https_cert_chain_file_prompt(child) - child.sendline('ca.crt') + child.sendline("ca.crt") verify_app_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_ossec_gpg_key_prompt(child) - child.sendline('\b' * 9 + 'sd_admin_test.pub') + child.sendline("\b" * 9 + "sd_admin_test.pub") verify_ossec_gpg_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_admin_email_prompt(child) - child.sendline('[email protected]') + child.sendline("[email protected]") # We will provide a key for this question verify_journalist_gpg_key_prompt(child) - child.sendline('sd_admin_test.pub') + child.sendline("sd_admin_test.pub") verify_journalist_fingerprint_prompt(child) - child.sendline('1F544B31C845D698EB31F2FF364F1162D32E7E58') + child.sendline("1F544B31C845D698EB31F2FF364F1162D32E7E58") verify_journalist_email_prompt(child) - child.sendline('[email protected]') + child.sendline("[email protected]") verify_smtp_relay_prompt(child) - child.sendline('') + child.sendline("") verify_smtp_port_prompt(child) - child.sendline('') + child.sendline("") verify_sasl_domain_prompt(child) - child.sendline('') + child.sendline("") verify_sasl_username_prompt(child) - child.sendline('testuser') + child.sendline("testuser") verify_sasl_password_prompt(child) - child.sendline('testpassword') + child.sendline("testpassword") verify_ssh_over_lan_prompt(child) - child.sendline('') + child.sendline("") verify_locales_prompt(child) - child.sendline('de_DE es_ES') + child.sendline("de_DE es_ES") child.expect(pexpect.EOF, timeout=10) # Wait for validation to occur child.close() assert child.exitstatus == 0 assert child.signalstatus is None - with open(os.path.join(SD_DIR, 'install_files/ansible-base/group_vars/all/site-specific')) as fobj: # noqa: E501 + with open( + os.path.join(SD_DIR, "install_files/ansible-base/group_vars/all/site-specific") + ) as fobj: # noqa: E501 data = fobj.read() assert HTTPS_OUTPUT == data @@ -491,7 +511,7 @@ def test_sdconfig_enable_https_on_source_interface(): # from the SecureDrop Github repository. We want to use this because the # developers may have the git setup to fetch from [email protected]: instead # of the https, and that requires authentication information. -GIT_CONFIG = u'''[core] +GIT_CONFIG = """[core] repositoryformatversion = 0 filemode = true bare = false @@ -499,7 +519,7 @@ def test_sdconfig_enable_https_on_source_interface(): [remote "origin"] url = https://github.com/freedomofpress/securedrop.git fetch = +refs/heads/*:refs/remotes/origin/* -''' +""" @pytest.fixture @@ -507,24 +527,27 @@ def securedrop_git_repo(tmpdir): cwd = os.getcwd() os.chdir(str(tmpdir)) # Clone the SecureDrop repository into the temp directory. - cmd = ['git', 'clone', - 'https://github.com/freedomofpress/securedrop.git'] + cmd = ["git", "clone", "https://github.com/freedomofpress/securedrop.git"] subprocess.check_call(cmd) - os.chdir(os.path.join(str(tmpdir), 'securedrop/admin')) - subprocess.check_call('git reset --hard'.split()) + os.chdir(os.path.join(str(tmpdir), "securedrop/admin")) + subprocess.check_call("git reset --hard".split()) # Now we will put in our own git configuration - with io.open('../.git/config', 'w') as fobj: + with io.open("../.git/config", "w") as fobj: fobj.write(GIT_CONFIG) # Let us move to an older tag - subprocess.check_call('git checkout 0.6'.split()) + subprocess.check_call("git checkout 0.6".split()) yield tmpdir # Save coverage information in same directory as unit test coverage - test_name = str(tmpdir).split('/')[-1] + test_name = str(tmpdir).split("/")[-1] try: subprocess.check_call( - ['cp', '{}/securedrop/admin/.coverage'.format(str(tmpdir)), - '{}/../.coverage.{}'.format(CURRENT_DIR, test_name)]) + [ + "cp", + "{}/securedrop/admin/.coverage".format(str(tmpdir)), + "{}/../.coverage.{}".format(CURRENT_DIR, test_name), + ] + ) except subprocess.CalledProcessError: # It means the coverage file may not exist, don't error pass @@ -535,11 +558,11 @@ def securedrop_git_repo(tmpdir): def set_reliable_keyserver(gpgdir): # If gpg.conf doesn't exist, create it and set a reliable default # keyserver for the tests. - gpgconf_path = os.path.join(gpgdir, 'gpg.conf') + gpgconf_path = os.path.join(gpgdir, "gpg.conf") if not os.path.exists(gpgconf_path): os.mkdir(gpgdir) - with open(gpgconf_path, 'a') as f: - f.write('keyserver hkps://keys.openpgp.org') + with open(gpgconf_path, "a") as f: + f.write("keyserver hkps://keys.openpgp.org") # Ensure correct permissions on .gnupg home directory. os.chmod(gpgdir, 0o0700) @@ -547,14 +570,11 @@ def set_reliable_keyserver(gpgdir): @flaky(max_runs=3) def test_check_for_update_when_updates_needed(securedrop_git_repo): - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - ansible_base = os.path.join(str(securedrop_git_repo), - 'securedrop/install_files/ansible-base') - fullcmd = 'coverage run {0} --root {1} check_for_updates'.format( - cmd, ansible_base) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") + fullcmd = "coverage run {0} --root {1} check_for_updates".format(cmd, ansible_base) child = pexpect.spawn(fullcmd) - child.expect(b'Update needed', timeout=20) + child.expect(b"Update needed", timeout=20) child.expect(pexpect.EOF, timeout=10) # Wait for CLI to exit child.close() @@ -565,20 +585,19 @@ def test_check_for_update_when_updates_needed(securedrop_git_repo): @flaky(max_runs=3) def test_check_for_update_when_updates_not_needed(securedrop_git_repo): # Determine latest production tag using GitHub release object - github_url = 'https://api.github.com/repos/freedomofpress/securedrop/releases/latest' # noqa: E501 + github_url = ( + "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" # noqa: E501 + ) latest_release = requests.get(github_url).json() latest_tag = str(latest_release["tag_name"]) subprocess.check_call(["git", "checkout", latest_tag]) - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - ansible_base = os.path.join(str(securedrop_git_repo), - 'securedrop/install_files/ansible-base') - fullcmd = 'coverage run {0} --root {1} check_for_updates'.format( - cmd, ansible_base) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") + fullcmd = "coverage run {0} --root {1} check_for_updates".format(cmd, ansible_base) child = pexpect.spawn(fullcmd) - child.expect(b'All updates applied', timeout=20) + child.expect(b"All updates applied", timeout=20) child.expect(pexpect.EOF, timeout=10) # Wait for CLI to exit child.close() @@ -588,19 +607,16 @@ def test_check_for_update_when_updates_not_needed(securedrop_git_repo): @flaky(max_runs=3) def test_update(securedrop_git_repo): - gpgdir = os.path.join(os.path.expanduser('~'), '.gnupg') + gpgdir = os.path.join(os.path.expanduser("~"), ".gnupg") set_reliable_keyserver(gpgdir) - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - ansible_base = os.path.join(str(securedrop_git_repo), - 'securedrop/install_files/ansible-base') - child = pexpect.spawn('coverage run {0} --root {1} update'.format( - cmd, ansible_base)) + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") + child = pexpect.spawn("coverage run {0} --root {1} update".format(cmd, ansible_base)) output = child.read() - assert b'Updated to SecureDrop' in output - assert b'Signature verification successful' in output + assert b"Updated to SecureDrop" in output + assert b"Signature verification successful" in output child.expect(pexpect.EOF, timeout=10) # Wait for CLI to exit child.close() @@ -610,27 +626,24 @@ def test_update(securedrop_git_repo): @flaky(max_runs=3) def test_update_fails_when_no_signature_present(securedrop_git_repo): - gpgdir = os.path.join(os.path.expanduser('~'), '.gnupg') + gpgdir = os.path.join(os.path.expanduser("~"), ".gnupg") set_reliable_keyserver(gpgdir) # First we make a very high version tag of SecureDrop so that the # updater will try to update to it. Since the tag is unsigned, it # should fail. - subprocess.check_call('git checkout develop'.split()) - subprocess.check_call('git tag 9999999.0.0'.split()) + subprocess.check_call("git checkout develop".split()) + subprocess.check_call("git tag 9999999.0.0".split()) # Switch back to an older branch for the test - subprocess.check_call('git checkout 0.6'.split()) - - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - ansible_base = os.path.join(str(securedrop_git_repo), - 'securedrop/install_files/ansible-base') - child = pexpect.spawn('coverage run {0} --root {1} update'.format( - cmd, ansible_base)) + subprocess.check_call("git checkout 0.6".split()) + + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") + child = pexpect.spawn("coverage run {0} --root {1} update".format(cmd, ansible_base)) output = child.read() - assert b'Updated to SecureDrop' not in output - assert b'Signature verification failed' in output + assert b"Updated to SecureDrop" not in output + assert b"Signature verification failed" in output child.expect(pexpect.EOF, timeout=10) # Wait for CLI to exit child.close() @@ -642,30 +655,29 @@ def test_update_fails_when_no_signature_present(securedrop_git_repo): @flaky(max_runs=3) def test_update_with_duplicate_branch_and_tag(securedrop_git_repo): - gpgdir = os.path.join(os.path.expanduser('~'), '.gnupg') + gpgdir = os.path.join(os.path.expanduser("~"), ".gnupg") set_reliable_keyserver(gpgdir) - github_url = 'https://api.github.com/repos/freedomofpress/securedrop/releases/latest' # noqa: E501 + github_url = ( + "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" # noqa: E501 + ) latest_release = requests.get(github_url).json() latest_tag = str(latest_release["tag_name"]) # Create a branch with the same name as a tag. - subprocess.check_call(['git', 'checkout', '-b', latest_tag]) + subprocess.check_call(["git", "checkout", "-b", latest_tag]) # Checkout the older tag again in preparation for the update. - subprocess.check_call('git checkout 0.6'.split()) + subprocess.check_call("git checkout 0.6".split()) - cmd = os.path.join(os.path.dirname(CURRENT_DIR), - 'securedrop_admin/__init__.py') - ansible_base = os.path.join(str(securedrop_git_repo), - 'securedrop/install_files/ansible-base') + cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") + ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") - child = pexpect.spawn('coverage run {0} --root {1} update'.format( - cmd, ansible_base)) + child = pexpect.spawn("coverage run {0} --root {1} update".format(cmd, ansible_base)) output = child.read() # Verify that we do not falsely check out a branch instead of a tag. - assert b'Switched to branch' not in output - assert b'Updated to SecureDrop' not in output - assert b'Signature verification failed' in output + assert b"Switched to branch" not in output + assert b"Updated to SecureDrop" not in output + assert b"Signature verification failed" in output child.expect(pexpect.EOF, timeout=10) # Wait for CLI to exit child.close() diff --git a/admin/tests/test_securedrop-admin-setup.py b/admin/tests/test_securedrop-admin-setup.py --- a/admin/tests/test_securedrop-admin-setup.py +++ b/admin/tests/test_securedrop-admin-setup.py @@ -18,105 +18,103 @@ # import argparse -import mock import os -import pytest import subprocess import bootstrap +import mock +import pytest class TestSecureDropAdmin(object): - def test_verbose(self, capsys): bootstrap.setup_logger(verbose=True) - bootstrap.sdlog.debug('VISIBLE') + bootstrap.sdlog.debug("VISIBLE") out, err = capsys.readouterr() - assert 'VISIBLE' in out + assert "VISIBLE" in out def test_not_verbose(self, capsys): bootstrap.setup_logger(verbose=False) - bootstrap.sdlog.debug('HIDDEN') - bootstrap.sdlog.info('VISIBLE') + bootstrap.sdlog.debug("HIDDEN") + bootstrap.sdlog.info("VISIBLE") out, err = capsys.readouterr() - assert 'HIDDEN' not in out - assert 'VISIBLE' in out + assert "HIDDEN" not in out + assert "VISIBLE" in out def test_run_command(self): - for output_line in bootstrap.run_command( - ['/bin/echo', 'something']): - assert output_line.strip() == b'something' + for output_line in bootstrap.run_command(["/bin/echo", "something"]): + assert output_line.strip() == b"something" lines = [] with pytest.raises(subprocess.CalledProcessError): for output_line in bootstrap.run_command( - ['sh', '-c', - 'echo in stdout ; echo in stderr >&2 ; false']): + ["sh", "-c", "echo in stdout ; echo in stderr >&2 ; false"] + ): lines.append(output_line.strip()) - assert lines[0] == b'in stdout' - assert lines[1] == b'in stderr' + assert lines[0] == b"in stdout" + assert lines[1] == b"in stderr" def test_install_pip_dependencies_up_to_date(self, caplog): args = argparse.Namespace() with mock.patch.object(subprocess, "check_output", return_value=b"up to date"): bootstrap.install_pip_dependencies(args) - assert 'securedrop-admin are up-to-date' in caplog.text + assert "securedrop-admin are up-to-date" in caplog.text def test_install_pip_dependencies_upgraded(self, caplog): args = argparse.Namespace() with mock.patch.object(subprocess, "check_output", return_value=b"Successfully installed"): bootstrap.install_pip_dependencies(args) - assert 'securedrop-admin upgraded' in caplog.text + assert "securedrop-admin upgraded" in caplog.text def test_install_pip_dependencies_fail(self, caplog): args = argparse.Namespace() with mock.patch.object( subprocess, "check_output", - side_effect=subprocess.CalledProcessError(returncode=2, cmd="", output=b"failed") + side_effect=subprocess.CalledProcessError(returncode=2, cmd="", output=b"failed"), ): with pytest.raises(subprocess.CalledProcessError): bootstrap.install_pip_dependencies(args) - assert 'Failed to install' in caplog.text + assert "Failed to install" in caplog.text def test_python3_buster_venv_deleted_in_bullseye(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(str(tmpdir), 'lib/python3.7') + python_lib_path = os.path.join(str(tmpdir), "lib/python3.7") os.makedirs(python_lib_path) - with mock.patch('bootstrap.is_tails', return_value=True): - with mock.patch('subprocess.check_output', return_value=b"bullseye"): + with mock.patch("bootstrap.is_tails", return_value=True): + with mock.patch("subprocess.check_output", return_value=b"bullseye"): bootstrap.clean_up_old_tails_venv(venv_path) - assert 'Tails 4 virtualenv detected.' in caplog.text - assert 'Tails 4 virtualenv deleted.' in caplog.text + assert "Tails 4 virtualenv detected." in caplog.text + assert "Tails 4 virtualenv deleted." in caplog.text assert not os.path.exists(venv_path) def test_python3_bullseye_venv_not_deleted_in_bullseye(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(venv_path, 'lib/python3.9') + python_lib_path = os.path.join(venv_path, "lib/python3.9") os.makedirs(python_lib_path) - with mock.patch('bootstrap.is_tails', return_value=True): - with mock.patch('subprocess.check_output', return_value="bullseye"): + with mock.patch("bootstrap.is_tails", return_value=True): + with mock.patch("subprocess.check_output", return_value="bullseye"): bootstrap.clean_up_old_tails_venv(venv_path) - assert 'Tails 4 virtualenv detected' not in caplog.text + assert "Tails 4 virtualenv detected" not in caplog.text assert os.path.exists(venv_path) def test_python3_buster_venv_not_deleted_in_buster(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(venv_path, 'lib/python3.7') + python_lib_path = os.path.join(venv_path, "lib/python3.7") os.makedirs(python_lib_path) - with mock.patch('bootstrap.is_tails', return_value=True): - with mock.patch('subprocess.check_output', return_value="buster"): + with mock.patch("bootstrap.is_tails", return_value=True): + with mock.patch("subprocess.check_output", return_value="buster"): bootstrap.clean_up_old_tails_venv(venv_path) assert os.path.exists(venv_path) def test_venv_cleanup_subprocess_exception(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(venv_path, 'lib/python3.7') + python_lib_path = os.path.join(venv_path, "lib/python3.7") os.makedirs(python_lib_path) - with mock.patch('bootstrap.is_tails', return_value=True): - with mock.patch('subprocess.check_output', - side_effect=subprocess.CalledProcessError(1, - ':o')): + with mock.patch("bootstrap.is_tails", return_value=True): + with mock.patch( + "subprocess.check_output", side_effect=subprocess.CalledProcessError(1, ":o") + ): bootstrap.clean_up_old_tails_venv(venv_path) assert os.path.exists(venv_path) @@ -124,14 +122,15 @@ def test_envsetup_cleanup(self, tmpdir, caplog): venv = os.path.join(str(tmpdir), "empty_dir") args = "" with pytest.raises(subprocess.CalledProcessError): - with mock.patch('subprocess.check_output', - side_effect=self.side_effect_venv_bootstrap(venv)): + with mock.patch( + "subprocess.check_output", side_effect=self.side_effect_venv_bootstrap(venv) + ): bootstrap.envsetup(args, venv) assert not os.path.exists(venv) - assert 'Cleaning up virtualenv' in caplog.text + assert "Cleaning up virtualenv" in caplog.text def side_effect_venv_bootstrap(self, venv_path): # emulate the venv being created, and raise exception to simulate # failure in virtualenv creation os.makedirs(venv_path) - raise subprocess.CalledProcessError(1, ':o') + raise subprocess.CalledProcessError(1, ":o") diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -17,20 +17,20 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # -import io -import os import argparse -from flaky import flaky -from os.path import dirname, join, basename, exists +import io import json -import mock -from prompt_toolkit.validation import ValidationError -import pytest +import os import subprocess import textwrap -import yaml +from os.path import basename, dirname, exists, join +import mock +import pytest import securedrop_admin +import yaml +from flaky import flaky +from prompt_toolkit.validation import ValidationError class Document(object): @@ -40,20 +40,19 @@ def __init__(self, text): @flaky class TestSecureDropAdmin(object): - def test_verbose(self, capsys): securedrop_admin.setup_logger(verbose=True) - securedrop_admin.sdlog.debug('VISIBLE') + securedrop_admin.sdlog.debug("VISIBLE") out, err = capsys.readouterr() - assert 'VISIBLE' in out + assert "VISIBLE" in out def test_not_verbose(self, capsys): securedrop_admin.setup_logger(verbose=False) - securedrop_admin.sdlog.debug('HIDDEN') - securedrop_admin.sdlog.info('VISIBLE') + securedrop_admin.sdlog.debug("HIDDEN") + securedrop_admin.sdlog.info("VISIBLE") out, err = capsys.readouterr() - assert 'HIDDEN' not in out - assert 'VISIBLE' in out + assert "HIDDEN" not in out + assert "VISIBLE" in out def test_update_check_decorator_when_no_update_needed(self, caplog): """ @@ -69,16 +68,16 @@ def test_update_check_decorator_when_no_update_needed(self, caplog): "securedrop_admin.check_for_updates", side_effect=[[False, "1.5.0"]] ) as mocked_check, mock.patch( "securedrop_admin.get_git_branch", side_effect=["develop"] - ), mock.patch("sys.exit") as mocked_exit: + ), mock.patch( + "sys.exit" + ) as mocked_exit: # The decorator itself interprets --force args = argparse.Namespace(force=False) - rv = securedrop_admin.update_check_required("update_check_test")( - lambda _: 100 - )(args) + rv = securedrop_admin.update_check_required("update_check_test")(lambda _: 100)(args) assert mocked_check.called assert not mocked_exit.called assert rv == 100 - assert caplog.text == '' + assert caplog.text == "" def test_update_check_decorator_when_update_needed(self, caplog): """ @@ -94,12 +93,12 @@ def test_update_check_decorator_when_update_needed(self, caplog): "securedrop_admin.check_for_updates", side_effect=[[True, "1.5.0"]] ) as mocked_check, mock.patch( "securedrop_admin.get_git_branch", side_effect=["bad_branch"] - ), mock.patch("sys.exit") as mocked_exit: + ), mock.patch( + "sys.exit" + ) as mocked_exit: # The decorator itself interprets --force args = argparse.Namespace(force=False) - securedrop_admin.update_check_required("update_check_test")( - lambda _: _ - )(args) + securedrop_admin.update_check_required("update_check_test")(lambda _: _)(args) assert mocked_check.called assert mocked_exit.called assert "update_check_test" in caplog.text @@ -118,12 +117,12 @@ def test_update_check_decorator_when_skipped(self, caplog): "securedrop_admin.check_for_updates", side_effect=[[True, "1.5.0"]] ) as mocked_check, mock.patch( "securedrop_admin.get_git_branch", side_effect=["develop"] - ), mock.patch("sys.exit") as mocked_exit: + ), mock.patch( + "sys.exit" + ) as mocked_exit: # The decorator itself interprets --force args = argparse.Namespace(force=True) - rv = securedrop_admin.update_check_required("update_check_test")( - lambda _: 100 - )(args) + rv = securedrop_admin.update_check_required("update_check_test")(lambda _: 100)(args) assert not mocked_check.called assert not mocked_exit.called assert "--force" in caplog.text @@ -135,13 +134,12 @@ def test_check_for_updates_update_needed(self, tmpdir, caplog): current_tag = b"0.6" tags_available = b"0.6\n0.6-rc1\n0.6.1\n" - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - side_effect=[current_tag, tags_available]): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", side_effect=[current_tag, tags_available]): update_status, tag = securedrop_admin.check_for_updates(args) assert "Update needed" in caplog.text assert update_status is True - assert tag == '0.6.1' + assert tag == "0.6.1" def test_check_for_updates_higher_version(self, tmpdir, caplog): git_repo_path = str(tmpdir) @@ -149,13 +147,12 @@ def test_check_for_updates_higher_version(self, tmpdir, caplog): current_tag = b"0.6" tags_available = b"0.1\n0.10.0\n0.6.2\n0.6\n0.6-rc1\n0.9.0\n" - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - side_effect=[current_tag, tags_available]): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", side_effect=[current_tag, tags_available]): update_status, tag = securedrop_admin.check_for_updates(args) assert "Update needed" in caplog.text assert update_status is True - assert tag == '0.10.0' + assert tag == "0.10.0" def test_check_for_updates_ensure_newline_stripped(self, tmpdir, caplog): """Regression test for #3426""" @@ -164,13 +161,12 @@ def test_check_for_updates_ensure_newline_stripped(self, tmpdir, caplog): current_tag = b"0.6.1\n" tags_available = b"0.6\n0.6-rc1\n0.6.1\n" - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - side_effect=[current_tag, tags_available]): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", side_effect=[current_tag, tags_available]): update_status, tag = securedrop_admin.check_for_updates(args) assert "All updates applied" in caplog.text assert update_status is False - assert tag == '0.6.1' + assert tag == "0.6.1" def test_check_for_updates_update_not_needed(self, tmpdir, caplog): git_repo_path = str(tmpdir) @@ -178,13 +174,12 @@ def test_check_for_updates_update_not_needed(self, tmpdir, caplog): current_tag = b"0.6.1" tags_available = b"0.6\n0.6-rc1\n0.6.1\n" - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - side_effect=[current_tag, tags_available]): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", side_effect=[current_tag, tags_available]): update_status, tag = securedrop_admin.check_for_updates(args) assert "All updates applied" in caplog.text assert update_status is False - assert tag == '0.6.1' + assert tag == "0.6.1" def test_check_for_updates_if_most_recent_tag_is_rc(self, tmpdir, caplog): """During pre-release QA, the most recent tag ends in *-rc. Let's @@ -194,32 +189,25 @@ def test_check_for_updates_if_most_recent_tag_is_rc(self, tmpdir, caplog): current_tag = b"0.6.1" tags_available = b"0.6\n0.6-rc1\n0.6.1\n0.6.1-rc1\n" - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - side_effect=[current_tag, tags_available]): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", side_effect=[current_tag, tags_available]): update_status, tag = securedrop_admin.check_for_updates(args) assert "All updates applied" in caplog.text assert update_status is False - assert tag == '0.6.1' + assert tag == "0.6.1" @pytest.mark.parametrize( "git_output, expected_rv", [ - (b'* develop\n', - 'develop'), - (b' develop\n' - b'* release/1.7.0\n', - 'release/1.7.0'), - (b'* (HEAD detached at 1.7.0)\n' - b' develop\n' - b' release/1.7.0\n', - '(HEAD detached at 1.7.0)'), - (b' main\n' - b'* valid_+!@#$%&_branch_name\n', - 'valid_+!@#$%&_branch_name'), - (b'Unrecognized output.', - None) - ] + (b"* develop\n", "develop"), + (b" develop\n" b"* release/1.7.0\n", "release/1.7.0"), + ( + b"* (HEAD detached at 1.7.0)\n" b" develop\n" b" release/1.7.0\n", + "(HEAD detached at 1.7.0)", + ), + (b" main\n" b"* valid_+!@#$%&_branch_name\n", "valid_+!@#$%&_branch_name"), + (b"Unrecognized output.", None), + ], ) def test_get_git_branch(self, git_output, expected_rv): """ @@ -232,7 +220,7 @@ def test_get_git_branch(self, git_output, expected_rv): Then `get_git_branch` should return `None` """ args = argparse.Namespace(root=None) - with mock.patch('subprocess.check_output', side_effect=[git_output]): + with mock.patch("subprocess.check_output", side_effect=[git_output]): rv = securedrop_admin.get_git_branch(args) assert rv == expected_rv @@ -240,8 +228,7 @@ def test_update_exits_if_not_needed(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - with mock.patch('securedrop_admin.check_for_updates', - return_value=(False, "0.6.1")): + with mock.patch("securedrop_admin.check_for_updates", return_value=(False, "0.6.1")): ret_code = securedrop_admin.update(args) assert "Applying SecureDrop updates..." in caplog.text assert "Updated to SecureDrop" not in caplog.text @@ -250,72 +237,72 @@ def test_update_exits_if_not_needed(self, tmpdir, caplog): def test_get_release_key_from_valid_keyserver(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - with mock.patch('subprocess.check_call'): + with mock.patch("subprocess.check_call"): # Check that no exception is raised when the process is fast securedrop_admin.get_release_key_from_keyserver(args) # Check that use of the keyword arg also raises no exception - securedrop_admin.get_release_key_from_keyserver( - args, keyserver='test.com') - - @pytest.mark.parametrize("git_output", - [b'gpg: Signature made Tue 13 Mar ' - b'2018 01:14:11 AM UTC\n' - b'gpg: using RSA key ' - b'22245C81E3BAEB4138B36061310F561200F4AD77\n' - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n', - - b'gpg: Signature made Thu 20 Jul ' - b'2017 08:12:25 PM EDT\n' - b'gpg: using RSA key ' - b'22245C81E3BAEB4138B36061310F561200F4AD77\n' - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key ' - b'<[email protected]>"\n', - - b'gpg: Signature made Thu 20 Jul ' - b'2017 08:12:25 PM EDT\n' - b'gpg: using RSA key ' - b'2359E6538C0613E652955E6C188EDD3B7B22E6A3\n' - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key ' - b'<[email protected]>"\n', - - b'gpg: Signature made Thu 20 Jul ' - b'2017 08:12:25 PM EDT\n' - b'gpg: using RSA key ' - b'2359E6538C0613E652955E6C188EDD3B7B22E6A3\n' - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n' - b'gpg: aka "SecureDrop Release ' - b'Signing Key ' - b'<[email protected]>" ' - b'[unknown]\n', - - b'gpg: Signature made Thu 20 Jul ' - b'2017 08:12:25 PM EDT\n' - b'gpg: using RSA key ' - b'22245C81E3BAEB4138B36061310F561200F4AD77\n' - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n' - b'gpg: aka "SecureDrop Release ' - b'Signing Key ' - b'<[email protected]>" ' - b'[unknown]\n']) + securedrop_admin.get_release_key_from_keyserver(args, keyserver="test.com") + + @pytest.mark.parametrize( + "git_output", + [ + b"gpg: Signature made Tue 13 Mar " + b"2018 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"22245C81E3BAEB4138B36061310F561200F4AD77\n" + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key" [unknown]\n', + b"gpg: Signature made Thu 20 Jul " + b"2017 08:12:25 PM EDT\n" + b"gpg: using RSA key " + b"22245C81E3BAEB4138B36061310F561200F4AD77\n" + b'gpg: Good signature from "SecureDrop Release ' + b"Signing Key " + b'<[email protected]>"\n', + b"gpg: Signature made Thu 20 Jul " + b"2017 08:12:25 PM EDT\n" + b"gpg: using RSA key " + b"2359E6538C0613E652955E6C188EDD3B7B22E6A3\n" + b'gpg: Good signature from "SecureDrop Release ' + b"Signing Key " + b'<[email protected]>"\n', + b"gpg: Signature made Thu 20 Jul " + b"2017 08:12:25 PM EDT\n" + b"gpg: using RSA key " + b"2359E6538C0613E652955E6C188EDD3B7B22E6A3\n" + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key" [unknown]\n' + b'gpg: aka "SecureDrop Release ' + b"Signing Key " + b'<[email protected]>" ' + b"[unknown]\n", + b"gpg: Signature made Thu 20 Jul " + b"2017 08:12:25 PM EDT\n" + b"gpg: using RSA key " + b"22245C81E3BAEB4138B36061310F561200F4AD77\n" + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key" [unknown]\n' + b'gpg: aka "SecureDrop Release ' + b"Signing Key " + b'<[email protected]>" ' + b"[unknown]\n", + ], + ) def test_update_signature_verifies(self, tmpdir, caplog, git_output): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) patchers = [ - mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")), - mock.patch('subprocess.check_call'), - mock.patch('subprocess.check_output', - side_effect=[ - git_output, - subprocess.CalledProcessError(1, 'cmd', - b'not a valid ref')]), - ] + mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")), + mock.patch("subprocess.check_call"), + mock.patch( + "subprocess.check_output", + side_effect=[ + git_output, + subprocess.CalledProcessError(1, "cmd", b"not a valid ref"), + ], + ), + ] for patcher in patchers: patcher.start() @@ -334,22 +321,25 @@ def test_update_unexpected_exception_git_refs(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - git_output = (b'gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n' - b'gpg: using RSA key ' - b'22245C81E3BAEB4138B36061310F561200F4AD77\n' - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n') + git_output = ( + b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"22245C81E3BAEB4138B36061310F561200F4AD77\n" + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key" [unknown]\n' + ) patchers = [ - mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")), - mock.patch('subprocess.check_call'), - mock.patch('subprocess.check_output', - side_effect=[ - git_output, - subprocess.CalledProcessError(1, 'cmd', - b'a random error')]), - ] + mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")), + mock.patch("subprocess.check_call"), + mock.patch( + "subprocess.check_output", + side_effect=[ + git_output, + subprocess.CalledProcessError(1, "cmd", b"a random error"), + ], + ), + ] for patcher in patchers: patcher.start() @@ -368,17 +358,17 @@ def test_update_signature_does_not_verify(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - git_output = (b'gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n' - b'gpg: using RSA key ' - b'22245C81E3BAEB4138B36061310F561200F4AD77\n' - b'gpg: BAD signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n') - - with mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")): - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - return_value=git_output): + git_output = ( + b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"22245C81E3BAEB4138B36061310F561200F4AD77\n" + b'gpg: BAD signature from "SecureDrop Release ' + b'Signing Key" [unknown]\n' + ) + + with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", return_value=git_output): ret_code = securedrop_admin.update(args) assert "Applying SecureDrop updates..." in caplog.text assert "Signature verification failed." in caplog.text @@ -389,17 +379,17 @@ def test_update_malicious_key_named_fingerprint(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - git_output = (b'gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n' - b'gpg: using RSA key ' - b'1234567812345678123456781234567812345678\n' - b'gpg: Good signature from "22245C81E3BAEB4138' - b'B36061310F561200F4AD77" [unknown]\n') - - with mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")): - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - return_value=git_output): + git_output = ( + b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"1234567812345678123456781234567812345678\n" + b'gpg: Good signature from "22245C81E3BAEB4138' + b'B36061310F561200F4AD77" [unknown]\n' + ) + + with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", return_value=git_output): ret_code = securedrop_admin.update(args) assert "Applying SecureDrop updates..." in caplog.text assert "Signature verification failed." in caplog.text @@ -410,40 +400,39 @@ def test_update_malicious_key_named_good_sig(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - git_output = (b'gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n' - b'gpg: using RSA key ' - b'1234567812345678123456781234567812345678\n' - b'gpg: Good signature from Good signature from ' - b'"SecureDrop Release Signing Key" [unknown]\n') - - with mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")): - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - return_value=git_output): + git_output = ( + b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"1234567812345678123456781234567812345678\n" + b"gpg: Good signature from Good signature from " + b'"SecureDrop Release Signing Key" [unknown]\n' + ) + + with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", return_value=git_output): ret_code = securedrop_admin.update(args) assert "Applying SecureDrop updates..." in caplog.text assert "Signature verification failed." in caplog.text assert "Updated to SecureDrop" not in caplog.text assert ret_code != 0 - def test_update_malicious_key_named_good_sig_fingerprint(self, tmpdir, - caplog): + def test_update_malicious_key_named_good_sig_fingerprint(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - git_output = (b'gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n' - b'gpg: using RSA key ' - b'1234567812345678123456781234567812345678\n' - b'gpg: Good signature from 22245C81E3BAEB4138' - b'B36061310F561200F4AD77 Good signature from ' - b'"SecureDrop Release Signing Key" [unknown]\n') - - with mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")): - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - return_value=git_output): + git_output = ( + b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"1234567812345678123456781234567812345678\n" + b"gpg: Good signature from 22245C81E3BAEB4138" + b"B36061310F561200F4AD77 Good signature from " + b'"SecureDrop Release Signing Key" [unknown]\n' + ) + + with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): + with mock.patch("subprocess.check_call"): + with mock.patch("subprocess.check_output", return_value=git_output): ret_code = securedrop_admin.update(args) assert "Applying SecureDrop updates..." in caplog.text assert "Signature verification failed." in caplog.text @@ -454,13 +443,14 @@ def test_no_signature_on_update(self, tmpdir, caplog): git_repo_path = str(tmpdir) args = argparse.Namespace(root=git_repo_path) - with mock.patch('securedrop_admin.check_for_updates', - return_value=(True, "0.6.1")): - with mock.patch('subprocess.check_call'): - with mock.patch('subprocess.check_output', - side_effect=subprocess.CalledProcessError( - 1, 'git', 'error: no signature found') - ): + with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): + with mock.patch("subprocess.check_call"): + with mock.patch( + "subprocess.check_output", + side_effect=subprocess.CalledProcessError( + 1, "git", "error: no signature found" + ), + ): ret_code = securedrop_admin.update(args) assert "Applying SecureDrop updates..." in caplog.text assert "Signature verification failed." in caplog.text @@ -469,108 +459,101 @@ def test_no_signature_on_update(self, tmpdir, caplog): def test_exit_codes(self, tmpdir): """Ensure that securedrop-admin returns the correct - exit codes for success or failure.""" - with mock.patch( - 'securedrop_admin.install_securedrop', - return_value=True): + exit codes for success or failure.""" + with mock.patch("securedrop_admin.install_securedrop", return_value=True): with pytest.raises(SystemExit) as e: - securedrop_admin.main( - ['--root', str(tmpdir), 'install']) + securedrop_admin.main(["--root", str(tmpdir), "install"]) assert e.value.code == securedrop_admin.EXIT_SUCCESS with mock.patch( - 'securedrop_admin.install_securedrop', - side_effect=subprocess.CalledProcessError(1, 'TestError')): + "securedrop_admin.install_securedrop", + side_effect=subprocess.CalledProcessError(1, "TestError"), + ): with pytest.raises(SystemExit) as e: - securedrop_admin.main( - ['--root', str(tmpdir), 'install']) + securedrop_admin.main(["--root", str(tmpdir), "install"]) assert e.value.code == securedrop_admin.EXIT_SUBPROCESS_ERROR - with mock.patch( - 'securedrop_admin.install_securedrop', - side_effect=KeyboardInterrupt): + with mock.patch("securedrop_admin.install_securedrop", side_effect=KeyboardInterrupt): with pytest.raises(SystemExit) as e: - securedrop_admin.main( - ['--root', str(tmpdir), 'install']) + securedrop_admin.main(["--root", str(tmpdir), "install"]) assert e.value.code == securedrop_admin.EXIT_INTERRUPT class TestSiteConfig(object): - def test_exists(self): - args = argparse.Namespace(site_config='DOES_NOT_EXIST', - ansible_path='.', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="DOES_NOT_EXIST", ansible_path=".", app_path=dirname(__file__) + ) assert not securedrop_admin.SiteConfig(args).exists() - args = argparse.Namespace(site_config=__file__, - ansible_path='.', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config=__file__, ansible_path=".", app_path=dirname(__file__) + ) assert securedrop_admin.SiteConfig(args).exists() def test_validate_not_empty(self): validator = securedrop_admin.SiteConfig.ValidateNotEmpty() - assert validator.validate(Document('something')) + assert validator.validate(Document("something")) with pytest.raises(ValidationError): - validator.validate(Document('')) + validator.validate(Document("")) def test_validate_time(self): validator = securedrop_admin.SiteConfig.ValidateTime() - assert validator.validate(Document('4')) + assert validator.validate(Document("4")) with pytest.raises(ValidationError): - validator.validate(Document('')) + validator.validate(Document("")) with pytest.raises(ValidationError): - validator.validate(Document('four')) + validator.validate(Document("four")) with pytest.raises(ValidationError): - validator.validate(Document('4.30')) + validator.validate(Document("4.30")) with pytest.raises(ValidationError): - validator.validate(Document('25')) + validator.validate(Document("25")) with pytest.raises(ValidationError): - validator.validate(Document('-4')) + validator.validate(Document("-4")) def test_validate_ossec_username(self): validator = securedrop_admin.SiteConfig.ValidateOSSECUsername() - assert validator.validate(Document('username')) + assert validator.validate(Document("username")) with pytest.raises(ValidationError): - validator.validate(Document('bad@user')) + validator.validate(Document("bad@user")) with pytest.raises(ValidationError): - validator.validate(Document('test')) + validator.validate(Document("test")) def test_validate_ossec_password(self): validator = securedrop_admin.SiteConfig.ValidateOSSECPassword() - assert validator.validate(Document('goodpassword')) + assert validator.validate(Document("goodpassword")) with pytest.raises(ValidationError): - validator.validate(Document('password123')) + validator.validate(Document("password123")) with pytest.raises(ValidationError): - validator.validate(Document('')) + validator.validate(Document("")) with pytest.raises(ValidationError): - validator.validate(Document('short')) + validator.validate(Document("short")) def test_validate_email(self): validator = securedrop_admin.SiteConfig.ValidateEmail() - assert validator.validate(Document('[email protected]')) + assert validator.validate(Document("[email protected]")) with pytest.raises(ValidationError): - validator.validate(Document('badmail')) + validator.validate(Document("badmail")) with pytest.raises(ValidationError): - validator.validate(Document('')) + validator.validate(Document("")) def test_validate_ossec_email(self): validator = securedrop_admin.SiteConfig.ValidateOSSECEmail() - assert validator.validate(Document('[email protected]')) + assert validator.validate(Document("[email protected]")) with pytest.raises(ValidationError) as e: - validator.validate(Document('[email protected]')) - assert 'something other than [email protected]' in str(e) + validator.validate(Document("[email protected]")) + assert "something other than [email protected]" in str(e) def test_validate_optional_email(self): validator = securedrop_admin.SiteConfig.ValidateOptionalEmail() - assert validator.validate(Document('[email protected]')) - assert validator.validate(Document('')) + assert validator.validate(Document("[email protected]")) + assert validator.validate(Document("")) def test_validate_user(self): validator = securedrop_admin.SiteConfig.ValidateUser() @@ -616,41 +599,34 @@ def test_validate_yes_no(self): def test_validate_fingerprint(self): validator = securedrop_admin.SiteConfig.ValidateFingerprint() - assert validator.validate(Document( - "012345678901234567890123456789ABCDEFABCD")) - assert validator.validate(Document( - "01234 5678901234567890123456789ABCDE FABCD")) + assert validator.validate(Document("012345678901234567890123456789ABCDEFABCD")) + assert validator.validate(Document("01234 5678901234567890123456789ABCDE FABCD")) with pytest.raises(ValidationError) as e: - validator.validate(Document( - "65A1B5FF195B56353CC63DFFCC40EF1228271441")) - assert 'TEST journalist' in str(e) + validator.validate(Document("65A1B5FF195B56353CC63DFFCC40EF1228271441")) + assert "TEST journalist" in str(e) with pytest.raises(ValidationError) as e: - validator.validate(Document( - "600BC6D5142C68F35DDBCEA87B597104EDDDC102")) - assert 'TEST admin' in str(e) + validator.validate(Document("600BC6D5142C68F35DDBCEA87B597104EDDDC102")) + assert "TEST admin" in str(e) with pytest.raises(ValidationError) as e: - validator.validate(Document( - "0000")) - assert '40 hexadecimal' in str(e) + validator.validate(Document("0000")) + assert "40 hexadecimal" in str(e) with pytest.raises(ValidationError) as e: - validator.validate(Document( - "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")) - assert '40 hexadecimal' in str(e) + validator.validate(Document("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")) + assert "40 hexadecimal" in str(e) def test_validate_optional_fingerprint(self): validator = securedrop_admin.SiteConfig.ValidateOptionalFingerprint() - assert validator.validate(Document( - "012345678901234567890123456789ABCDEFABCD")) + assert validator.validate(Document("012345678901234567890123456789ABCDEFABCD")) assert validator.validate(Document("")) def test_sanitize_fingerprint(self): - args = argparse.Namespace(site_config='DOES_NOT_EXIST', - ansible_path='.', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="DOES_NOT_EXIST", ansible_path=".", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) assert "ABC" == site_config.sanitize_fingerprint(" A bc") @@ -663,129 +639,105 @@ def test_validate_int(self): def test_locales(self): locales = securedrop_admin.SiteConfig.Locales(dirname(__file__)) translations = locales.get_translations() - assert 'en_US' in translations - assert 'fr_FR' in translations + assert "en_US" in translations + assert "fr_FR" in translations def test_validate_locales(self): - validator = securedrop_admin.SiteConfig.ValidateLocales( - dirname(__file__)) - assert validator.validate(Document('en_US fr_FR ')) + validator = securedrop_admin.SiteConfig.ValidateLocales(dirname(__file__)) + assert validator.validate(Document("en_US fr_FR ")) with pytest.raises(ValidationError) as e: - validator.validate(Document('BAD')) - assert 'BAD' in str(e) + validator.validate(Document("BAD")) + assert "BAD" in str(e) def test_save(self, tmpdir): - site_config_path = join(str(tmpdir), 'site_config') - args = argparse.Namespace(site_config=site_config_path, - ansible_path='.', - app_path=dirname(__file__)) + site_config_path = join(str(tmpdir), "site_config") + args = argparse.Namespace( + site_config=site_config_path, ansible_path=".", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) - site_config.config = {'var1': u'val1', 'var2': u'val2'} + site_config.config = {"var1": "val1", "var2": "val2"} site_config.save() - expected = textwrap.dedent("""\ + expected = textwrap.dedent( + """\ var1: val1 var2: val2 - """) + """ + ) assert expected == io.open(site_config_path).read() def test_validate_gpg_key(self, caplog): - args = argparse.Namespace(site_config='INVALID', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="INVALID", ansible_path="tests/files", app_path=dirname(__file__) + ) good_config = { - 'securedrop_app_gpg_public_key': - 'test_journalist_key.pub', - - 'securedrop_app_gpg_fingerprint': - '65A1B5FF195B56353CC63DFFCC40EF1228271441', - - 'ossec_alert_gpg_public_key': - 'test_journalist_key.pub', - - 'ossec_gpg_fpr': - '65A1B5FF195B56353CC63DFFCC40EF1228271441', - - 'journalist_alert_gpg_public_key': - 'test_journalist_key.pub', - - 'journalist_gpg_fpr': - '65A1B5FF195B56353CC63DFFCC40EF1228271441', + "securedrop_app_gpg_public_key": "test_journalist_key.pub", + "securedrop_app_gpg_fingerprint": "65A1B5FF195B56353CC63DFFCC40EF1228271441", + "ossec_alert_gpg_public_key": "test_journalist_key.pub", + "ossec_gpg_fpr": "65A1B5FF195B56353CC63DFFCC40EF1228271441", + "journalist_alert_gpg_public_key": "test_journalist_key.pub", + "journalist_gpg_fpr": "65A1B5FF195B56353CC63DFFCC40EF1228271441", } site_config = securedrop_admin.SiteConfig(args) site_config.config = good_config assert site_config.validate_gpg_keys() - for key in ('securedrop_app_gpg_fingerprint', - 'ossec_gpg_fpr', - 'journalist_gpg_fpr'): + for key in ("securedrop_app_gpg_fingerprint", "ossec_gpg_fpr", "journalist_gpg_fpr"): bad_config = good_config.copy() - bad_config[key] = 'FAIL' + bad_config[key] = "FAIL" site_config.config = bad_config with pytest.raises(securedrop_admin.FingerprintException) as e: site_config.validate_gpg_keys() - assert 'FAIL does not match' in str(e) + assert "FAIL does not match" in str(e) def test_journalist_alert_email(self): - args = argparse.Namespace(site_config='INVALID', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="INVALID", ansible_path="tests/files", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) site_config.config = { - 'journalist_alert_gpg_public_key': - '', - - 'journalist_gpg_fpr': - '', + "journalist_alert_gpg_public_key": "", + "journalist_gpg_fpr": "", } assert site_config.validate_journalist_alert_email() site_config.config = { - 'journalist_alert_gpg_public_key': - 'test_journalist_key.pub', - - 'journalist_gpg_fpr': - '65A1B5FF195B56353CC63DFFCC40EF1228271441', + "journalist_alert_gpg_public_key": "test_journalist_key.pub", + "journalist_gpg_fpr": "65A1B5FF195B56353CC63DFFCC40EF1228271441", } - site_config.config['journalist_alert_email'] = '' - with pytest.raises( - securedrop_admin.JournalistAlertEmailException) as e: + site_config.config["journalist_alert_email"] = "" + with pytest.raises(securedrop_admin.JournalistAlertEmailException) as e: site_config.validate_journalist_alert_email() - assert 'not be empty' in str(e) + assert "not be empty" in str(e) - site_config.config['journalist_alert_email'] = 'bademail' - with pytest.raises( - securedrop_admin.JournalistAlertEmailException) as e: + site_config.config["journalist_alert_email"] = "bademail" + with pytest.raises(securedrop_admin.JournalistAlertEmailException) as e: site_config.validate_journalist_alert_email() - assert 'Must contain a @' in str(e) + assert "Must contain a @" in str(e) - site_config.config['journalist_alert_email'] = '[email protected]' + site_config.config["journalist_alert_email"] = "[email protected]" assert site_config.validate_journalist_alert_email() - @mock.patch('securedrop_admin.SiteConfig.validated_input', - side_effect=lambda p, d, v, t: d) - @mock.patch('securedrop_admin.SiteConfig.save') + @mock.patch("securedrop_admin.SiteConfig.validated_input", side_effect=lambda p, d, v, t: d) + @mock.patch("securedrop_admin.SiteConfig.save") def test_update_config(self, mock_save, mock_validate_input): - args = argparse.Namespace(site_config='tests/files/site-specific', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="tests/files/site-specific", + ansible_path="tests/files", + app_path=dirname(__file__), + ) site_config = securedrop_admin.SiteConfig(args) assert site_config.load_and_update_config() - assert 'user_defined_variable' in site_config.config + assert "user_defined_variable" in site_config.config mock_save.assert_called_once() mock_validate_input.assert_called() - @mock.patch('securedrop_admin.SiteConfig.validated_input', - side_effect=lambda p, d, v, t: d) - @mock.patch('securedrop_admin.SiteConfig.validate_gpg_keys') - def test_update_config_no_site_specific( - self, - validate_gpg_keys, - mock_validate_input, - tmpdir): - site_config_path = join(str(tmpdir), 'site_config') - args = argparse.Namespace(site_config=site_config_path, - ansible_path='.', - app_path=dirname(__file__)) + @mock.patch("securedrop_admin.SiteConfig.validated_input", side_effect=lambda p, d, v, t: d) + @mock.patch("securedrop_admin.SiteConfig.validate_gpg_keys") + def test_update_config_no_site_specific(self, validate_gpg_keys, mock_validate_input, tmpdir): + site_config_path = join(str(tmpdir), "site_config") + args = argparse.Namespace( + site_config=site_config_path, ansible_path=".", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) assert site_config.load_and_update_config() mock_validate_input.assert_called() @@ -793,28 +745,31 @@ def test_update_config_no_site_specific( assert exists(site_config_path) def test_load_and_update_config(self): - args = argparse.Namespace(site_config='tests/files/site-specific', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="tests/files/site-specific", + ansible_path="tests/files", + app_path=dirname(__file__), + ) site_config = securedrop_admin.SiteConfig(args) - with mock.patch('securedrop_admin.SiteConfig.update_config'): + with mock.patch("securedrop_admin.SiteConfig.update_config"): site_config.load_and_update_config() assert site_config.config != {} args = argparse.Namespace( - site_config='tests/files/site-specific-missing-entries', - ansible_path='tests/files', - app_path=dirname(__file__)) + site_config="tests/files/site-specific-missing-entries", + ansible_path="tests/files", + app_path=dirname(__file__), + ) site_config = securedrop_admin.SiteConfig(args) - with mock.patch('securedrop_admin.SiteConfig.update_config'): + with mock.patch("securedrop_admin.SiteConfig.update_config"): site_config.load_and_update_config() assert site_config.config != {} - args = argparse.Namespace(site_config='UNKNOWN', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) - with mock.patch('securedrop_admin.SiteConfig.update_config'): + with mock.patch("securedrop_admin.SiteConfig.update_config"): site_config.load_and_update_config() assert site_config.config == {} @@ -834,56 +789,61 @@ def verify_desc_consistency_optional(self, site_config, desc): def verify_desc_consistency(self, site_config, desc): self.verify_desc_consistency_optional(site_config, desc) - def verify_prompt_boolean( - self, site_config, desc): + def verify_prompt_boolean(self, site_config, desc): self.verify_desc_consistency(site_config, desc) (var, default, etype, prompt, validator, transform, condition) = desc assert site_config.user_prompt_config_one(desc, True) is True assert site_config.user_prompt_config_one(desc, False) is False - assert site_config.user_prompt_config_one(desc, 'YES') is True - assert site_config.user_prompt_config_one(desc, 'NO') is False + assert site_config.user_prompt_config_one(desc, "YES") is True + assert site_config.user_prompt_config_one(desc, "NO") is False def test_desc_conditional(self): """Ensure that conditional prompts behave correctly. - Prompts which depend on another question should only be - asked if the prior question was answered appropriately.""" + Prompts which depend on another question should only be + asked if the prior question was answered appropriately.""" questions = [ - ('first_question', - False, - bool, - u'Test Question 1', - None, - lambda x: x.lower() == 'yes', - lambda config: True), - ('dependent_question', - 'default_value', - str, - u'Test Question 2', - None, - None, - lambda config: config.get('first_question', False)) + ( + "first_question", + False, + bool, + "Test Question 1", + None, + lambda x: x.lower() == "yes", + lambda config: True, + ), + ( + "dependent_question", + "default_value", + str, + "Test Question 2", + None, + None, + lambda config: config.get("first_question", False), + ), ] - args = argparse.Namespace(site_config='tests/files/site-specific', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="tests/files/site-specific", + ansible_path="tests/files", + app_path=dirname(__file__), + ) site_config = securedrop_admin.SiteConfig(args) site_config.desc = questions def auto_prompt(prompt, default, **kwargs): return default - with mock.patch('prompt_toolkit.prompt', side_effect=auto_prompt): + with mock.patch("prompt_toolkit.prompt", side_effect=auto_prompt): config = site_config.user_prompt_config() - assert config['dependent_question'] != 'default_value' + assert config["dependent_question"] != "default_value" edited_first_question = list(site_config.desc[0]) edited_first_question[1] = True site_config.desc[0] = tuple(edited_first_question) config = site_config.user_prompt_config() - assert config['dependent_question'] == 'default_value' + assert config["dependent_question"] == "default_value" verify_prompt_ssh_users = verify_desc_consistency verify_prompt_app_ip = verify_desc_consistency @@ -892,15 +852,14 @@ def auto_prompt(prompt, default, **kwargs): verify_prompt_monitor_hostname = verify_desc_consistency verify_prompt_dns_server = verify_desc_consistency - verify_prompt_securedrop_app_https_on_source_interface = \ - verify_prompt_boolean + verify_prompt_securedrop_app_https_on_source_interface = verify_prompt_boolean verify_prompt_enable_ssh_over_tor = verify_prompt_boolean verify_prompt_securedrop_app_gpg_public_key = verify_desc_consistency def verify_prompt_not_empty(self, site_config, desc): with pytest.raises(ValidationError): - site_config.user_prompt_config_one(desc, '') + site_config.user_prompt_config_one(desc, "") def verify_prompt_fingerprint_optional(self, site_config, desc): fpr = "0123456 789012 34567890123456789ABCDEFABCD" @@ -921,16 +880,12 @@ def verify_prompt_fingerprint(self, site_config, desc): verify_prompt_ossec_alert_gpg_public_key = verify_desc_consistency verify_prompt_ossec_gpg_fpr = verify_prompt_fingerprint verify_prompt_ossec_alert_email = verify_prompt_not_empty - verify_prompt_journalist_alert_gpg_public_key = ( - verify_desc_consistency_optional) + verify_prompt_journalist_alert_gpg_public_key = verify_desc_consistency_optional verify_prompt_journalist_gpg_fpr = verify_prompt_fingerprint_optional verify_prompt_journalist_alert_email = verify_desc_consistency_optional - verify_prompt_securedrop_app_https_certificate_chain_src = ( - verify_desc_consistency_optional) - verify_prompt_securedrop_app_https_certificate_key_src = ( - verify_desc_consistency_optional) - verify_prompt_securedrop_app_https_certificate_cert_src = ( - verify_desc_consistency_optional) + verify_prompt_securedrop_app_https_certificate_chain_src = verify_desc_consistency_optional + verify_prompt_securedrop_app_https_certificate_key_src = verify_desc_consistency_optional + verify_prompt_securedrop_app_https_certificate_cert_src = verify_desc_consistency_optional verify_prompt_smtp_relay = verify_prompt_not_empty verify_prompt_smtp_relay_port = verify_desc_consistency verify_prompt_daily_reboot_time = verify_desc_consistency @@ -943,82 +898,76 @@ def verify_prompt_securedrop_supported_locales(self, site_config, desc): # verify the default passes validation assert site_config.user_prompt_config_one(desc, None) == default assert type(default) == etype - assert site_config.user_prompt_config_one( - desc, 'fr_FR en_US') == ['fr_FR', 'en_US'] - assert site_config.user_prompt_config_one( - desc, ['fr_FR', 'en_US']) == ['fr_FR', 'en_US'] - assert site_config.user_prompt_config_one(desc, '') == [] + assert site_config.user_prompt_config_one(desc, "fr_FR en_US") == ["fr_FR", "en_US"] + assert site_config.user_prompt_config_one(desc, ["fr_FR", "en_US"]) == ["fr_FR", "en_US"] + assert site_config.user_prompt_config_one(desc, "") == [] with pytest.raises(ValidationError): - site_config.user_prompt_config_one(desc, 'wrong') + site_config.user_prompt_config_one(desc, "wrong") def test_user_prompt_config_one(self): - args = argparse.Namespace(site_config='UNKNOWN', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) def auto_prompt(prompt, default, **kwargs): - if 'validator' in kwargs and kwargs['validator']: - assert kwargs['validator'].validate(Document(default)) + if "validator" in kwargs and kwargs["validator"]: + assert kwargs["validator"].validate(Document(default)) return default - with mock.patch('prompt_toolkit.prompt', side_effect=auto_prompt): + with mock.patch("prompt_toolkit.prompt", side_effect=auto_prompt): for desc in site_config.desc: - (var, default, etype, prompt, validator, transform, - condition) = desc - method = 'verify_prompt_' + var + (var, default, etype, prompt, validator, transform, condition) = desc + method = "verify_prompt_" + var print("checking " + method) getattr(self, method)(site_config, desc) def test_validated_input(self): - args = argparse.Namespace(site_config='UNKNOWN', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) def auto_prompt(prompt, default, **kwargs): return default - with mock.patch('prompt_toolkit.prompt', side_effect=auto_prompt): - value = 'VALUE' - assert value == site_config.validated_input( - '', value, lambda: True, None) - assert value.lower() == site_config.validated_input( - '', value, lambda: True, str.lower) - assert 'yes' == site_config.validated_input( - '', True, lambda: True, None) - assert 'no' == site_config.validated_input( - '', False, lambda: True, None) - assert '1234' == site_config.validated_input( - '', 1234, lambda: True, None) - assert "a b" == site_config.validated_input( - '', ['a', 'b'], lambda: True, None) - assert "{}" == site_config.validated_input( - '', {}, lambda: True, None) + with mock.patch("prompt_toolkit.prompt", side_effect=auto_prompt): + value = "VALUE" + assert value == site_config.validated_input("", value, lambda: True, None) + assert value.lower() == site_config.validated_input("", value, lambda: True, str.lower) + assert "yes" == site_config.validated_input("", True, lambda: True, None) + assert "no" == site_config.validated_input("", False, lambda: True, None) + assert "1234" == site_config.validated_input("", 1234, lambda: True, None) + assert "a b" == site_config.validated_input("", ["a", "b"], lambda: True, None) + assert "{}" == site_config.validated_input("", {}, lambda: True, None) def test_load(self, caplog): - args = argparse.Namespace(site_config='tests/files/site-specific', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="tests/files/site-specific", + ansible_path="tests/files", + app_path=dirname(__file__), + ) site_config = securedrop_admin.SiteConfig(args) - assert 'app_hostname' in site_config.load() + assert "app_hostname" in site_config.load() - args = argparse.Namespace(site_config='UNKNOWN', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + ) site_config = securedrop_admin.SiteConfig(args) with pytest.raises(IOError) as e: site_config.load() - assert 'No such file' in e.value.strerror - assert 'Config file missing' in caplog.text + assert "No such file" in e.value.strerror + assert "Config file missing" in caplog.text - args = argparse.Namespace(site_config='tests/files/corrupted', - ansible_path='tests/files', - app_path=dirname(__file__)) + args = argparse.Namespace( + site_config="tests/files/corrupted", + ansible_path="tests/files", + app_path=dirname(__file__), + ) site_config = securedrop_admin.SiteConfig(args) with pytest.raises(yaml.YAMLError) as e: site_config.load() - assert 'issue processing' in caplog.text + assert "issue processing" in caplog.text def test_generate_new_v3_keys(): @@ -1026,7 +975,7 @@ def test_generate_new_v3_keys(): for key in [public, private]: # base32 padding characters should be removed - assert '=' not in key + assert "=" not in key assert len(key) == 52 @@ -1036,21 +985,22 @@ def test_find_or_generate_new_torv3_keys_first_run(tmpdir, capsys): return_code = securedrop_admin.find_or_generate_new_torv3_keys(args) out, err = capsys.readouterr() - assert 'Tor v3 onion service keys generated' in out + assert "Tor v3 onion service keys generated" in out assert return_code == 0 - secret_key_path = os.path.join(args.ansible_path, - "tor_v3_keys.json") + secret_key_path = os.path.join(args.ansible_path, "tor_v3_keys.json") with open(secret_key_path) as f: v3_onion_service_keys = json.load(f) - expected_keys = ['app_journalist_public_key', - 'app_journalist_private_key', - 'app_ssh_public_key', - 'app_ssh_private_key', - 'mon_ssh_public_key', - 'mon_ssh_private_key'] + expected_keys = [ + "app_journalist_public_key", + "app_journalist_private_key", + "app_ssh_public_key", + "app_ssh_private_key", + "mon_ssh_public_key", + "mon_ssh_private_key", + ] for key in expected_keys: assert key in v3_onion_service_keys.keys() @@ -1058,16 +1008,15 @@ def test_find_or_generate_new_torv3_keys_first_run(tmpdir, capsys): def test_find_or_generate_new_torv3_keys_subsequent_run(tmpdir, capsys): args = argparse.Namespace(ansible_path=str(tmpdir)) - secret_key_path = os.path.join(args.ansible_path, - "tor_v3_keys.json") - old_keys = {'foo': 'bar'} - with open(secret_key_path, 'w') as f: + secret_key_path = os.path.join(args.ansible_path, "tor_v3_keys.json") + old_keys = {"foo": "bar"} + with open(secret_key_path, "w") as f: json.dump(old_keys, f) return_code = securedrop_admin.find_or_generate_new_torv3_keys(args) out, err = capsys.readouterr() - assert 'Tor v3 onion service keys already exist' in out + assert "Tor v3 onion service keys already exist" in out assert return_code == 0 with open(secret_key_path) as f: diff --git a/journalist_gui/test_gui.py b/journalist_gui/test_gui.py --- a/journalist_gui/test_gui.py +++ b/journalist_gui/test_gui.py @@ -1,23 +1,28 @@ -import unittest import subprocess -import pexpect -import pytest +import unittest from unittest import mock from unittest.mock import MagicMock + +import pexpect +import pytest from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import (QApplication, QSizePolicy, QInputDialog) from PyQt5.QtTest import QTest +from PyQt5.QtWidgets import QApplication, QInputDialog, QSizePolicy -from journalist_gui.SecureDropUpdater import UpdaterApp, strings, FLAG_LOCATION -from journalist_gui.SecureDropUpdater import prevent_second_instance +from journalist_gui.SecureDropUpdater import ( + FLAG_LOCATION, + UpdaterApp, + prevent_second_instance, + strings, +) [email protected]('journalist_gui.SecureDropUpdater.sys.exit') [email protected]('syslog.syslog') [email protected]("journalist_gui.SecureDropUpdater.sys.exit") [email protected]("syslog.syslog") class TestSecondInstancePrevention(unittest.TestCase): def setUp(self): self.mock_app = mock.MagicMock() - self.mock_app.applicationName = mock.MagicMock(return_value='sd') + self.mock_app.applicationName = mock.MagicMock(return_value="sd") @staticmethod def socket_mock_generator(already_bound_errno=98): @@ -37,33 +42,33 @@ def kernel_bind(addr): def test_diff_name(self, mock_msgbox, mock_exit): mock_socket = self.socket_mock_generator() - with mock.patch('journalist_gui.SecureDropUpdater.socket', new=mock_socket): - prevent_second_instance(self.mock_app, 'name1') - prevent_second_instance(self.mock_app, 'name2') + with mock.patch("journalist_gui.SecureDropUpdater.socket", new=mock_socket): + prevent_second_instance(self.mock_app, "name1") + prevent_second_instance(self.mock_app, "name2") mock_exit.assert_not_called() def test_same_name(self, mock_msgbox, mock_exit): mock_socket = self.socket_mock_generator() - with mock.patch('journalist_gui.SecureDropUpdater.socket', new=mock_socket): - prevent_second_instance(self.mock_app, 'name1') - prevent_second_instance(self.mock_app, 'name1') + with mock.patch("journalist_gui.SecureDropUpdater.socket", new=mock_socket): + prevent_second_instance(self.mock_app, "name1") + prevent_second_instance(self.mock_app, "name1") mock_exit.assert_any_call() def test_unknown_kernel_error(self, mock_msgbox, mock_exit): mock_socket = self.socket_mock_generator(131) # crazy unexpected error - with mock.patch('journalist_gui.SecureDropUpdater.socket', new=mock_socket): + with mock.patch("journalist_gui.SecureDropUpdater.socket", new=mock_socket): with pytest.raises(OSError): - prevent_second_instance(self.mock_app, 'name1') - prevent_second_instance(self.mock_app, 'name1') + prevent_second_instance(self.mock_app, "name1") + prevent_second_instance(self.mock_app, "name1") class AppTestCase(unittest.TestCase): def setUp(self): qApp = QApplication.instance() if qApp is None: - self.app = QApplication(['']) + self.app = QApplication([""]) else: self.app = qApp @@ -99,71 +104,62 @@ def test_output_tab(self): tab = self.window.tabWidget.tabBar() QTest.mouseClick(tab, Qt.LeftButton) - self.assertEqual(self.window.tabWidget.currentIndex(), - self.window.tabWidget.indexOf(self.window.tab_2)) + self.assertEqual( + self.window.tabWidget.currentIndex(), self.window.tabWidget.indexOf(self.window.tab_2) + ) - @mock.patch('subprocess.check_output', - return_value=b'Python dependencies for securedrop-admin') + @mock.patch("subprocess.check_output", return_value=b"Python dependencies for securedrop-admin") def test_setupThread(self, check_output): - with mock.patch.object(self.window, "call_tailsconfig", - return_value=MagicMock()): - with mock.patch('builtins.open') as mock_open: + with mock.patch.object(self.window, "call_tailsconfig", return_value=MagicMock()): + with mock.patch("builtins.open") as mock_open: self.window.setup_thread.run() # Call run directly - mock_open.assert_called_once_with(FLAG_LOCATION, 'a') + mock_open.assert_called_once_with(FLAG_LOCATION, "a") self.assertEqual(self.window.update_success, True) self.assertEqual(self.window.progressBar.value(), 70) - @mock.patch('subprocess.check_output', - return_value=b'Failed to install pip dependencies') + @mock.patch("subprocess.check_output", return_value=b"Failed to install pip dependencies") def test_setupThread_failure(self, check_output): - with mock.patch.object(self.window, "call_tailsconfig", - return_value=MagicMock()): - with mock.patch('builtins.open') as mock_open: + with mock.patch.object(self.window, "call_tailsconfig", return_value=MagicMock()): + with mock.patch("builtins.open") as mock_open: self.window.setup_thread.run() # Call run directly - mock_open.assert_called_once_with(FLAG_LOCATION, 'a') + mock_open.assert_called_once_with(FLAG_LOCATION, "a") self.assertEqual(self.window.update_success, False) self.assertEqual(self.window.progressBar.value(), 0) - self.assertEqual(self.window.failure_reason, - strings.update_failed_generic_reason) + self.assertEqual(self.window.failure_reason, strings.update_failed_generic_reason) - @mock.patch('subprocess.check_output', - return_value=b'Signature verification successful') + @mock.patch("subprocess.check_output", return_value=b"Signature verification successful") def test_updateThread(self, check_output): - with mock.patch.object(self.window, "setup_thread", - return_value=MagicMock()): + with mock.patch.object(self.window, "setup_thread", return_value=MagicMock()): self.window.update_thread.run() # Call run directly self.assertEqual(self.window.update_success, True) self.assertEqual(self.window.progressBar.value(), 50) - @mock.patch('subprocess.check_output', - side_effect=subprocess.CalledProcessError( - 1, 'cmd', b'Signature verification failed')) + @mock.patch( + "subprocess.check_output", + side_effect=subprocess.CalledProcessError(1, "cmd", b"Signature verification failed"), + ) def test_updateThread_failure(self, check_output): - with mock.patch.object(self.window, "setup_thread", - return_value=MagicMock()): + with mock.patch.object(self.window, "setup_thread", return_value=MagicMock()): self.window.update_thread.run() # Call run directly self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, - strings.update_failed_sig_failure) + self.assertEqual(self.window.failure_reason, strings.update_failed_sig_failure) - @mock.patch('subprocess.check_output', - side_effect=subprocess.CalledProcessError( - 1, 'cmd', b'Generic other failure')) + @mock.patch( + "subprocess.check_output", + side_effect=subprocess.CalledProcessError(1, "cmd", b"Generic other failure"), + ) def test_updateThread_generic_failure(self, check_output): - with mock.patch.object(self.window, "setup_thread", - return_value=MagicMock()): + with mock.patch.object(self.window, "setup_thread", return_value=MagicMock()): self.window.update_thread.run() # Call run directly self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, - strings.update_failed_generic_reason) + self.assertEqual(self.window.failure_reason, strings.update_failed_generic_reason) def test_get_sudo_password_when_password_provided(self): expected_password = "password" - with mock.patch.object(QInputDialog, 'getText', - return_value=[expected_password, True]): + with mock.patch.object(QInputDialog, "getText", return_value=[expected_password, True]): sudo_password = self.window.get_sudo_password() self.assertEqual(sudo_password, expected_password) @@ -171,11 +167,10 @@ def test_get_sudo_password_when_password_provided(self): def test_get_sudo_password_when_password_not_provided(self): test_password = "" - with mock.patch.object(QInputDialog, 'getText', - return_value=[test_password, False]): + with mock.patch.object(QInputDialog, "getText", return_value=[test_password, False]): self.assertIsNone(self.window.get_sudo_password()) - @mock.patch('pexpect.spawn') + @mock.patch("pexpect.spawn") def test_tailsconfigThread_no_failures(self, pt): child = pt() before = MagicMock() @@ -183,14 +178,14 @@ def test_tailsconfigThread_no_failures(self, pt): before.decode.side_effect = ["SUDO: ", "Update successful. failed=0"] child.before = before child.exitstatus = 0 - with mock.patch('os.remove') as mock_remove: + with mock.patch("os.remove") as mock_remove: self.window.tails_thread.run() mock_remove.assert_called_once_with(FLAG_LOCATION) self.assertIn("failed=0", self.window.output) self.assertEqual(self.window.update_success, True) - @mock.patch('pexpect.spawn') + @mock.patch("pexpect.spawn") def test_tailsconfigThread_generic_failure(self, pt): child = pt() before = MagicMock() @@ -199,10 +194,9 @@ def test_tailsconfigThread_generic_failure(self, pt): self.window.tails_thread.run() self.assertNotIn("failed=0", self.window.output) self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, - strings.tailsconfig_failed_generic_reason) + self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_generic_reason) - @mock.patch('pexpect.spawn') + @mock.patch("pexpect.spawn") def test_tailsconfigThread_sudo_password_is_wrong(self, pt): child = pt() before = MagicMock() @@ -211,40 +205,36 @@ def test_tailsconfigThread_sudo_password_is_wrong(self, pt): self.window.tails_thread.run() self.assertNotIn("failed=0", self.window.output) self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, - strings.tailsconfig_failed_sudo_password) + self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_sudo_password) - @mock.patch('pexpect.spawn') + @mock.patch("pexpect.spawn") def test_tailsconfigThread_timeout(self, pt): child = pt() before = MagicMock() - before.decode.side_effect = ["some data", - pexpect.exceptions.TIMEOUT(1)] + before.decode.side_effect = ["some data", pexpect.exceptions.TIMEOUT(1)] child.before = before self.window.tails_thread.run() self.assertNotIn("failed=0", self.window.output) self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, - strings.tailsconfig_failed_timeout) + self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_timeout) - @mock.patch('pexpect.spawn') + @mock.patch("pexpect.spawn") def test_tailsconfigThread_some_other_subprocess_error(self, pt): child = pt() before = MagicMock() before.decode.side_effect = subprocess.CalledProcessError( - 1, 'cmd', b'Generic other failure') + 1, "cmd", b"Generic other failure" + ) child.before = before self.window.tails_thread.run() self.assertNotIn("failed=0", self.window.output) self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, - strings.tailsconfig_failed_generic_reason) + self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_generic_reason) def test_tails_status_success(self): - result = {'status': True, "output": "successful.", - 'failure_reason': ''} + result = {"status": True, "output": "successful.", "failure_reason": ""} - with mock.patch('os.remove') as mock_remove: + with mock.patch("os.remove") as mock_remove: self.window.tails_status(result) # We do remove the flag file if the update does finish @@ -252,24 +242,22 @@ def test_tails_status_success(self): self.assertEqual(self.window.progressBar.value(), 100) def test_tails_status_failure(self): - result = {'status': False, "output": "successful.", - 'failure_reason': '42'} + result = {"status": False, "output": "successful.", "failure_reason": "42"} - with mock.patch('os.remove') as mock_remove: + with mock.patch("os.remove") as mock_remove: self.window.tails_status(result) # We do not remove the flag file if the update does not finish mock_remove.assert_not_called() self.assertEqual(self.window.progressBar.value(), 0) - @mock.patch('journalist_gui.SecureDropUpdater.QtWidgets.QMessageBox') + @mock.patch("journalist_gui.SecureDropUpdater.QtWidgets.QMessageBox") def test_no_update_without_password(self, mock_msgbox): - with mock.patch('journalist_gui.SecureDropUpdater.password_is_set', - return_value=False): + with mock.patch("journalist_gui.SecureDropUpdater.password_is_set", return_value=False): self.window.update_securedrop() self.assertEqual(self.window.pushButton.isEnabled(), True) self.assertEqual(self.window.pushButton_2.isEnabled(), False) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/molecule/ansible-config/tests/test_play_configuration.py b/molecule/ansible-config/tests/test_play_configuration.py --- a/molecule/ansible-config/tests/test_play_configuration.py +++ b/molecule/ansible-config/tests/test_play_configuration.py @@ -1,18 +1,21 @@ -import os import io +import os + import pytest import yaml - # Lots of parent directories to dig out of the Molecule test dir. # Could also inspect the Molecule env vars and go from there. -REPO_ROOT = os.path.abspath(os.path.join(__file__, - os.path.pardir, - os.path.pardir, - os.path.pardir, - os.path.pardir, - )) -ANSIBLE_BASE = os.path.join(REPO_ROOT, 'install_files', 'ansible-base') +REPO_ROOT = os.path.abspath( + os.path.join( + __file__, + os.path.pardir, + os.path.pardir, + os.path.pardir, + os.path.pardir, + ) +) +ANSIBLE_BASE = os.path.join(REPO_ROOT, "install_files", "ansible-base") def find_ansible_playbooks(): @@ -36,7 +39,7 @@ def find_ansible_playbooks(): return playbooks [email protected]('playbook', find_ansible_playbooks()) [email protected]("playbook", find_ansible_playbooks()) def test_max_fail_percentage(host, playbook): """ All SecureDrop playbooks should set `max_fail_percentage` to "0" @@ -55,15 +58,15 @@ def test_max_fail_percentage(host, playbook): the parameter, but we'll play it safe and require it everywhere, to avoid mistakes down the road. """ - with io.open(playbook, 'r') as f: + with io.open(playbook, "r") as f: playbook_yaml = yaml.safe_load(f) # Descend into playbook list structure to validate play attributes. for play in playbook_yaml: - assert 'max_fail_percentage' in play - assert play['max_fail_percentage'] == 0 + assert "max_fail_percentage" in play + assert play["max_fail_percentage"] == 0 [email protected]('playbook', find_ansible_playbooks()) [email protected]("playbook", find_ansible_playbooks()) def test_any_errors_fatal(host, playbook): """ All SecureDrop playbooks should set `any_errors_fatal` to "yes" @@ -71,23 +74,23 @@ def test_any_errors_fatal(host, playbook): to "0", doing so ensures that any errors will cause an immediate failure on the playbook. """ - with io.open(playbook, 'r') as f: + with io.open(playbook, "r") as f: playbook_yaml = yaml.safe_load(f) # Descend into playbook list structure to validate play attributes. for play in playbook_yaml: - assert 'any_errors_fatal' in play + assert "any_errors_fatal" in play # Ansible coerces booleans, so bare assert is sufficient - assert play['any_errors_fatal'] + assert play["any_errors_fatal"] [email protected]('playbook', find_ansible_playbooks()) [email protected]("playbook", find_ansible_playbooks()) def test_locale(host, playbook): """ The securedrop-prod and securedrop-staging playbooks should control the locale in the host environment by setting LC_ALL=C. """ - with io.open(os.path.join(ANSIBLE_BASE, playbook), 'r') as f: + with io.open(os.path.join(ANSIBLE_BASE, playbook), "r") as f: playbook_yaml = yaml.safe_load(f) for play in playbook_yaml: - assert 'environment' in play - assert play['environment']['LC_ALL'] == 'C' + assert "environment" in play + assert play["environment"]["LC_ALL"] == "C" diff --git a/molecule/builder-focal/tests/conftest.py b/molecule/builder-focal/tests/conftest.py --- a/molecule/builder-focal/tests/conftest.py +++ b/molecule/builder-focal/tests/conftest.py @@ -2,8 +2,8 @@ Import variables from vars.yml and inject into testutils namespace """ -from pathlib import Path import subprocess +from pathlib import Path import pytest @@ -14,9 +14,7 @@ def securedrop_root() -> Path: Returns the root of the SecureDrop working tree for the test session. """ return Path( - subprocess.run( - ["git", "rev-parse", "--show-toplevel"], stdout=subprocess.PIPE, check=True - ) + subprocess.run(["git", "rev-parse", "--show-toplevel"], stdout=subprocess.PIPE, check=True) .stdout.decode("utf-8") .strip() ) diff --git a/molecule/builder-focal/tests/test_build_dependencies.py b/molecule/builder-focal/tests/test_build_dependencies.py --- a/molecule/builder-focal/tests/test_build_dependencies.py +++ b/molecule/builder-focal/tests/test_build_dependencies.py @@ -1,14 +1,12 @@ -import pytest import os +import pytest SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") SECUREDROP_PYTHON_VERSION = os.environ.get("SECUREDROP_PYTHON_VERSION", "3.5") DH_VIRTUALENV_VERSION = "1.2.2" -testinfra_hosts = [ - "docker://{}-sd-app".format(SECUREDROP_TARGET_DISTRIBUTION) -] +testinfra_hosts = ["docker://{}-sd-app".format(SECUREDROP_TARGET_DISTRIBUTION)] def test_sass_gem_installed(host): @@ -20,8 +18,7 @@ def test_sass_gem_installed(host): assert c.rc == 0 [email protected](reason="This check conflicts with the concept of pegging" - "dependencies") [email protected](reason="This check conflicts with the concept of pegging" "dependencies") def test_build_all_packages_updated(host): """ Ensure a dist-upgrade has already been run, by checking that no @@ -29,7 +26,7 @@ def test_build_all_packages_updated(host): all upgrades, security and otherwise, have been applied to the VM used to build packages. """ - c = host.run('apt-get --simulate -y dist-upgrade') + c = host.run("apt-get --simulate -y dist-upgrade") assert c.rc == 0 assert "No packages will be installed, upgraded, or removed." in c.stdout diff --git a/molecule/builder-focal/tests/test_legacy_paths.py b/molecule/builder-focal/tests/test_legacy_paths.py --- a/molecule/builder-focal/tests/test_legacy_paths.py +++ b/molecule/builder-focal/tests/test_legacy_paths.py @@ -1,14 +1,17 @@ import pytest [email protected]('build_path', [ - '/tmp/build-', - '/tmp/rsync-filter', - '/tmp/src_install_files', - '/tmp/build-securedrop-keyring', - '/tmp/build-securedrop-ossec-agent', - '/tmp/build-securedrop-ossec-server', -]) [email protected]( + "build_path", + [ + "/tmp/build-", + "/tmp/rsync-filter", + "/tmp/src_install_files", + "/tmp/build-securedrop-keyring", + "/tmp/build-securedrop-ossec-agent", + "/tmp/build-securedrop-ossec-server", + ], +) def test_build_ossec_apt_dependencies(host, build_path): """ Ensure that unwanted build paths are absent. Most of these were created diff --git a/molecule/builder-focal/tests/test_securedrop_deb_package.py b/molecule/builder-focal/tests/test_securedrop_deb_package.py --- a/molecule/builder-focal/tests/test_securedrop_deb_package.py +++ b/molecule/builder-focal/tests/test_securedrop_deb_package.py @@ -7,11 +7,8 @@ import yaml from testinfra.host import Host - SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -testinfra_hosts = [ - "docker://{}-sd-dpkg-verification".format(SECUREDROP_TARGET_DISTRIBUTION) -] +testinfra_hosts = ["docker://{}-sd-dpkg-verification".format(SECUREDROP_TARGET_DISTRIBUTION)] def extract_package_name_from_filepath(filepath: str) -> str: @@ -43,9 +40,7 @@ def load_securedrop_test_vars() -> Dict[str, Any]: test_vars = yaml.safe_load(open(filepath)) # Tack on target OS for use in tests - test_vars["securedrop_target_distribution"] = os.environ.get( - "SECUREDROP_TARGET_DISTRIBUTION" - ) + test_vars["securedrop_target_distribution"] = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") return test_vars @@ -63,8 +58,7 @@ def make_deb_paths() -> Dict[str, Path]: """ grsec_version = "{}+{}".format( - securedrop_test_vars["grsec_version_focal"], - SECUREDROP_TARGET_DISTRIBUTION + securedrop_test_vars["grsec_version_focal"], SECUREDROP_TARGET_DISTRIBUTION ) substitutions = dict( @@ -131,15 +125,11 @@ def get_static_asset_paths(securedrop_root: Path, pattern: str) -> List[Path]: Returns static assets matching the pattern. """ static_dir = securedrop_root / "securedrop/static" - skip = [ - re.compile(p) for p in [r"\.map$", r"\.webassets-cache$", "custom_logo.png$"] - ] + skip = [re.compile(p) for p in [r"\.map$", r"\.webassets-cache$", "custom_logo.png$"]] return get_source_paths(static_dir, pattern, skip) -def verify_static_assets( - securedrop_app_code_contents: str, securedrop_root: Path, pattern -) -> None: +def verify_static_assets(securedrop_app_code_contents: str, securedrop_root: Path, pattern) -> None: """ Verifies that the securedrop-app-code package contains the given static assets. @@ -181,10 +171,7 @@ def test_deb_packages_appear_installable(host: Host, deb: Path) -> None: # sudo is required to call `dpkg --install`, even as dry-run. with host.sudo(): c = host.run("dpkg --install --dry-run {}".format(deb)) - assert ( - "Selecting previously unselected package {}".format(package_name) - in c.stdout - ) + assert "Selecting previously unselected package {}".format(package_name) in c.stdout regex = "Preparing to unpack [./]+{} ...".format(re.escape(deb.name)) assert re.search(regex, c.stdout, re.M) assert c.rc == 0 @@ -230,9 +217,7 @@ def test_securedrop_app_code_contains_no_config_file(securedrop_app_code_content Ensures the `securedrop-app-code` package does not ship a `config.py` file. Doing so would clobber the site-specific changes made via Ansible. """ - assert not re.search( - r"^ ./var/www/securedrop/config.py$", securedrop_app_code_contents, re.M - ) + assert not re.search(r"^ ./var/www/securedrop/config.py$", securedrop_app_code_contents, re.M) def test_securedrop_app_code_contains_pot_file(securedrop_app_code_contents: str): diff --git a/molecule/builder-focal/tests/test_security_updates.py b/molecule/builder-focal/tests/test_security_updates.py --- a/molecule/builder-focal/tests/test_security_updates.py +++ b/molecule/builder-focal/tests/test_security_updates.py @@ -1,21 +1,22 @@ import os -from subprocess import check_output import re +from subprocess import check_output + import pytest SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -testinfra_hosts = [ - "docker://{}-sd-sec-update".format(SECUREDROP_TARGET_DISTRIBUTION) -] +testinfra_hosts = ["docker://{}-sd-sec-update".format(SECUREDROP_TARGET_DISTRIBUTION)] def test_should_run(): command = ["git", "describe", "--all"] version = check_output(command).decode("utf8")[0:-1] - candidates = (r"(^tags/[\d]+\.[\d]+\.[\d]+-rc[\d]+)|" - r"(^tags/[\d]+\.[\d]+\.[\d]+)|" - r"(^heads/release/[\d]+\.[\d]+\.[\d]+)|" - r"(^heads/update-builder.*)") + candidates = ( + r"(^tags/[\d]+\.[\d]+\.[\d]+-rc[\d]+)|" + r"(^tags/[\d]+\.[\d]+\.[\d]+)|" + r"(^heads/release/[\d]+\.[\d]+\.[\d]+)|" + r"(^heads/update-builder.*)" + ) result = re.match(candidates, version) if result: return True @@ -26,17 +27,19 @@ def test_should_run(): @pytest.mark.skipif(not test_should_run(), reason="Only tested for RCs and builder updates") def test_ensure_no_updates_avail(host): """ - Test to make sure that there are no security-updates in the - base builder container. + Test to make sure that there are no security-updates in the + base builder container. """ # Filter out all the security repos to their own file # without this change all the package updates appeared as if they were # coming from normal ubuntu update channel (since they get posted to both) host.run('egrep "^deb.*security" /etc/apt/sources.list > /tmp/sec.list') - dist_upgrade_simulate = host.run('apt-get -s dist-upgrade ' - '-oDir::Etc::Sourcelist=/tmp/sec.list ' - '|grep "^Inst" |grep -i security') + dist_upgrade_simulate = host.run( + "apt-get -s dist-upgrade " + "-oDir::Etc::Sourcelist=/tmp/sec.list " + '|grep "^Inst" |grep -i security' + ) # If the grep was successful that means security package updates found # otherwise we get a non-zero exit code so no updates needed. diff --git a/molecule/testinfra/app-code/test_securedrop_app_code.py b/molecule/testinfra/app-code/test_securedrop_app_code.py --- a/molecule/testinfra/app-code/test_securedrop_app_code.py +++ b/molecule/testinfra/app-code/test_securedrop_app_code.py @@ -1,6 +1,4 @@ import pytest - - import testutils securedrop_test_vars = testutils.securedrop_test_vars @@ -14,23 +12,26 @@ def test_apache_default_docroot_is_absent(host): under Debian, has been removed. Leaving it in place can be a privacy leak, as it displays version information by default. """ - assert not host.file('/var/www/html').exists - - [email protected]('package', [ - 'apache2', - 'apparmor-utils', - 'coreutils', - 'gnupg2', - 'libapache2-mod-xsendfile', - 'libpython{}'.format(python_version), - 'paxctld', - 'python3', - 'redis-server', - 'securedrop-config', - 'securedrop-keyring', - 'sqlite3', -]) + assert not host.file("/var/www/html").exists + + [email protected]( + "package", + [ + "apache2", + "apparmor-utils", + "coreutils", + "gnupg2", + "libapache2-mod-xsendfile", + "libpython{}".format(python_version), + "paxctld", + "python3", + "redis-server", + "securedrop-config", + "securedrop-keyring", + "sqlite3", + ], +) def test_securedrop_application_apt_dependencies(host, package): """ Ensure apt dependencies required to install `securedrop-app-code` @@ -40,14 +41,9 @@ def test_securedrop_application_apt_dependencies(host, package): assert host.package(package).is_installed [email protected]('package', [ - 'cron-apt', - 'haveged', - 'libapache2-mod-wsgi', - 'ntp', - 'ntpdate', - 'supervisor' -]) [email protected]( + "package", ["cron-apt", "haveged", "libapache2-mod-wsgi", "ntp", "ntpdate", "supervisor"] +) def test_unwanted_packages_absent(host, package): """ Ensure packages that conflict with `securedrop-app-code` @@ -61,8 +57,7 @@ def test_securedrop_application_test_locale(host): """ Ensure both SecureDrop DEFAULT_LOCALE and SUPPORTED_LOCALES are present. """ - securedrop_config = host.file("{}/config.py".format( - securedrop_test_vars.securedrop_code)) + securedrop_config = host.file("{}/config.py".format(securedrop_test_vars.securedrop_code)) with host.sudo(): assert securedrop_config.is_file assert securedrop_config.contains("^DEFAULT_LOCALE") @@ -77,8 +72,9 @@ def test_securedrop_application_test_journalist_key(host): Ensure the SecureDrop Application GPG public key file is present. This is a test-only pubkey provided in the repository strictly for testing. """ - pubkey_file = host.file("{}/test_journalist_key.pub".format( - securedrop_test_vars.securedrop_data)) + pubkey_file = host.file( + "{}/test_journalist_key.pub".format(securedrop_test_vars.securedrop_data) + ) # sudo is only necessary when testing against app hosts, since the # permissions are tighter. Let's elevate privileges so we're sure # we can read the correct file attributes and test them. @@ -90,17 +86,15 @@ def test_securedrop_application_test_journalist_key(host): # Let's make sure the corresponding fingerprint is specified # in the SecureDrop app configuration. - securedrop_config = host.file("{}/config.py".format( - securedrop_test_vars.securedrop_code)) + securedrop_config = host.file("{}/config.py".format(securedrop_test_vars.securedrop_code)) with host.sudo(): assert securedrop_config.is_file - assert securedrop_config.user == \ - securedrop_test_vars.securedrop_user - assert securedrop_config.group == \ - securedrop_test_vars.securedrop_user + assert securedrop_config.user == securedrop_test_vars.securedrop_user + assert securedrop_config.group == securedrop_test_vars.securedrop_user assert securedrop_config.mode == 0o600 assert securedrop_config.contains( - "^JOURNALIST_KEY = '65A1B5FF195B56353CC63DFFCC40EF1228271441'$") + "^JOURNALIST_KEY = '65A1B5FF195B56353CC63DFFCC40EF1228271441'$" + ) def test_securedrop_application_sqlite_db(host): diff --git a/molecule/testinfra/app-code/test_securedrop_rqrequeue.py b/molecule/testinfra/app-code/test_securedrop_rqrequeue.py --- a/molecule/testinfra/app-code/test_securedrop_rqrequeue.py +++ b/molecule/testinfra/app-code/test_securedrop_rqrequeue.py @@ -9,33 +9,36 @@ def test_securedrop_rqrequeue_service(host): Verify configuration of securedrop_rqrequeue systemd service. """ service_file = "/lib/systemd/system/securedrop_rqrequeue.service" - expected_content = "\n".join([ - "[Unit]", - "Description=SecureDrop rqrequeue process", - "After=redis-server.service", - "Wants=redis-server.service", - "", - "[Service]", - 'Environment=PYTHONPATH="{}:{}"'.format( - securedrop_test_vars.securedrop_code, securedrop_test_vars.securedrop_venv_site_packages - ), - "ExecStart={}/python /var/www/securedrop/scripts/rqrequeue --interval 60".format( - securedrop_test_vars.securedrop_venv_bin - ), - "PrivateDevices=yes", - "PrivateTmp=yes", - "ProtectSystem=full", - "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), - "Restart=always", - "RestartSec=10s", - "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), - "", - "[Install]", - "WantedBy=multi-user.target\n", - ]) + expected_content = "\n".join( + [ + "[Unit]", + "Description=SecureDrop rqrequeue process", + "After=redis-server.service", + "Wants=redis-server.service", + "", + "[Service]", + 'Environment=PYTHONPATH="{}:{}"'.format( + securedrop_test_vars.securedrop_code, + securedrop_test_vars.securedrop_venv_site_packages, + ), + "ExecStart={}/python /var/www/securedrop/scripts/rqrequeue --interval 60".format( + securedrop_test_vars.securedrop_venv_bin + ), + "PrivateDevices=yes", + "PrivateTmp=yes", + "ProtectSystem=full", + "ReadOnlyDirectories=/", + "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + "Restart=always", + "RestartSec=10s", + "UMask=077", + "User={}".format(securedrop_test_vars.securedrop_user), + "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + "", + "[Install]", + "WantedBy=multi-user.target\n", + ] + ) f = host.file(service_file) assert f.is_file diff --git a/molecule/testinfra/app-code/test_securedrop_rqworker.py b/molecule/testinfra/app-code/test_securedrop_rqworker.py --- a/molecule/testinfra/app-code/test_securedrop_rqworker.py +++ b/molecule/testinfra/app-code/test_securedrop_rqworker.py @@ -11,31 +11,34 @@ def test_securedrop_rqworker_service(host): securedrop_test_vars = sdvars service_file = "/lib/systemd/system/securedrop_rqworker.service" - expected_content = "\n".join([ - "[Unit]", - "Description=SecureDrop rq worker", - "After=redis-server.service", - "Wants=redis-server.service", - "", - "[Service]", - 'Environment=PYTHONPATH="{}:{}"'.format( - securedrop_test_vars.securedrop_code, securedrop_test_vars.securedrop_venv_site_packages - ), - "ExecStart={}/rqworker".format(securedrop_test_vars.securedrop_venv_bin), - "PrivateDevices=yes", - "PrivateTmp=yes", - "ProtectSystem=full", - "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), - "Restart=always", - "RestartSec=10s", - "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), - "", - "[Install]", - "WantedBy=multi-user.target\n", - ]) + expected_content = "\n".join( + [ + "[Unit]", + "Description=SecureDrop rq worker", + "After=redis-server.service", + "Wants=redis-server.service", + "", + "[Service]", + 'Environment=PYTHONPATH="{}:{}"'.format( + securedrop_test_vars.securedrop_code, + securedrop_test_vars.securedrop_venv_site_packages, + ), + "ExecStart={}/rqworker".format(securedrop_test_vars.securedrop_venv_bin), + "PrivateDevices=yes", + "PrivateTmp=yes", + "ProtectSystem=full", + "ReadOnlyDirectories=/", + "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + "Restart=always", + "RestartSec=10s", + "UMask=077", + "User={}".format(securedrop_test_vars.securedrop_user), + "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + "", + "[Install]", + "WantedBy=multi-user.target\n", + ] + ) f = host.file(service_file) assert f.is_file diff --git a/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py b/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py --- a/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py +++ b/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py @@ -10,31 +10,34 @@ def test_securedrop_shredder_service(host): """ securedrop_test_vars = sdvars service_file = "/lib/systemd/system/securedrop_shredder.service" - expected_content = "\n".join([ - "[Unit]", - "Description=SecureDrop shredder", - "", - "[Service]", - 'Environment=PYTHONPATH="{}:{}"'.format( - securedrop_test_vars.securedrop_code, securedrop_test_vars.securedrop_venv_site_packages - ), - "ExecStart={}/python /var/www/securedrop/scripts/shredder --interval 60".format( - securedrop_test_vars.securedrop_venv_bin - ), - "PrivateDevices=yes", - "PrivateTmp=yes", - "ProtectSystem=full", - "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), - "Restart=always", - "RestartSec=10s", - "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), - "", - "[Install]", - "WantedBy=multi-user.target\n", - ]) + expected_content = "\n".join( + [ + "[Unit]", + "Description=SecureDrop shredder", + "", + "[Service]", + 'Environment=PYTHONPATH="{}:{}"'.format( + securedrop_test_vars.securedrop_code, + securedrop_test_vars.securedrop_venv_site_packages, + ), + "ExecStart={}/python /var/www/securedrop/scripts/shredder --interval 60".format( + securedrop_test_vars.securedrop_venv_bin + ), + "PrivateDevices=yes", + "PrivateTmp=yes", + "ProtectSystem=full", + "ReadOnlyDirectories=/", + "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + "Restart=always", + "RestartSec=10s", + "UMask=077", + "User={}".format(securedrop_test_vars.securedrop_user), + "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + "", + "[Install]", + "WantedBy=multi-user.target\n", + ] + ) f = host.file(service_file) assert f.is_file diff --git a/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py b/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py --- a/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py +++ b/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py @@ -9,31 +9,34 @@ def test_securedrop_source_deleter_service(host): Verify configuration of securedrop_source_deleter systemd service. """ service_file = "/lib/systemd/system/securedrop_source_deleter.service" - expected_content = "\n".join([ - "[Unit]", - "Description=SecureDrop Source deleter", - "", - "[Service]", - 'Environment=PYTHONPATH="{}:{}"'.format( - securedrop_test_vars.securedrop_code, securedrop_test_vars.securedrop_venv_site_packages - ), - "ExecStart={}/python /var/www/securedrop/scripts/source_deleter --interval 10".format( - securedrop_test_vars.securedrop_venv_bin - ), - "PrivateDevices=yes", - "PrivateTmp=yes", - "ProtectSystem=full", - "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), - "Restart=always", - "RestartSec=10s", - "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), - "", - "[Install]", - "WantedBy=multi-user.target\n", - ]) + expected_content = "\n".join( + [ + "[Unit]", + "Description=SecureDrop Source deleter", + "", + "[Service]", + 'Environment=PYTHONPATH="{}:{}"'.format( + securedrop_test_vars.securedrop_code, + securedrop_test_vars.securedrop_venv_site_packages, + ), + "ExecStart={}/python /var/www/securedrop/scripts/source_deleter --interval 10".format( + securedrop_test_vars.securedrop_venv_bin + ), + "PrivateDevices=yes", + "PrivateTmp=yes", + "ProtectSystem=full", + "ReadOnlyDirectories=/", + "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + "Restart=always", + "RestartSec=10s", + "UMask=077", + "User={}".format(securedrop_test_vars.securedrop_user), + "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + "", + "[Install]", + "WantedBy=multi-user.target\n", + ] + ) f = host.file(service_file) assert f.is_file diff --git a/molecule/testinfra/app/apache/test_apache_journalist_interface.py b/molecule/testinfra/app/apache/test_apache_journalist_interface.py --- a/molecule/testinfra/app/apache/test_apache_journalist_interface.py +++ b/molecule/testinfra/app/apache/test_apache_journalist_interface.py @@ -1,6 +1,6 @@ -import pytest import re +import pytest import testutils securedrop_test_vars = testutils.securedrop_test_vars @@ -19,30 +19,33 @@ def test_apache_headers_journalist_interface(host, header, value): assert f.mode == 0o644 header_unset = "Header onsuccess unset {}".format(header) assert f.contains(header_unset) - header_set = "Header always set {} \"{}\"".format(header, value) + header_set = 'Header always set {} "{}"'.format(header, value) assert f.contains(header_set) # declare journalist-specific Apache configs [email protected]("apache_opt", [ - "<VirtualHost {}:8080>".format( - securedrop_test_vars.apache_listening_address), - "WSGIDaemonProcess journalist processes=2 threads=30 display-name=%{{GROUP}} python-path={}".format( # noqa - securedrop_test_vars.securedrop_code), - ( - 'WSGIScriptAlias / /var/www/journalist.wsgi ' - 'process-group=journalist application-group=journalist' - ), - 'WSGIPassAuthorization On', - 'Header set Cache-Control "no-store"', - "Alias /static {}/static".format(securedrop_test_vars.securedrop_code), - 'XSendFile On', - 'LimitRequestBody 524288000', - 'XSendFilePath /var/lib/securedrop/store/', - 'XSendFilePath /var/lib/securedrop/tmp/', - 'ErrorLog /var/log/apache2/journalist-error.log', - 'CustomLog /var/log/apache2/journalist-access.log combined', -]) [email protected]( + "apache_opt", + [ + "<VirtualHost {}:8080>".format(securedrop_test_vars.apache_listening_address), + "WSGIDaemonProcess journalist processes=2 threads=30 display-name=%{{GROUP}} python-path={}".format( # noqa + securedrop_test_vars.securedrop_code + ), + ( + "WSGIScriptAlias / /var/www/journalist.wsgi " + "process-group=journalist application-group=journalist" + ), + "WSGIPassAuthorization On", + 'Header set Cache-Control "no-store"', + "Alias /static {}/static".format(securedrop_test_vars.securedrop_code), + "XSendFile On", + "LimitRequestBody 524288000", + "XSendFilePath /var/lib/securedrop/store/", + "XSendFilePath /var/lib/securedrop/tmp/", + "ErrorLog /var/log/apache2/journalist-error.log", + "CustomLog /var/log/apache2/journalist-access.log combined", + ], +) def test_apache_config_journalist_interface(host, apache_opt): """ Ensure the necessary Apache settings for serving the application @@ -68,9 +71,9 @@ def test_apache_config_journalist_interface_headers_per_distro(host): f = host.file("/etc/apache2/sites-available/journalist.conf") assert f.contains("Header onsuccess unset X-Frame-Options") assert f.contains('Header always set X-Frame-Options "DENY"') - assert f.contains('Header onsuccess unset Referrer-Policy') + assert f.contains("Header onsuccess unset Referrer-Policy") assert f.contains('Header always set Referrer-Policy "no-referrer"') - assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') + assert f.contains("Header edit Set-Cookie ^(.*)$ $1;HttpOnly") def test_apache_logging_journalist_interface(host): @@ -99,22 +102,30 @@ def test_apache_logging_journalist_interface(host): assert f.contains("GET") [email protected]("apache_opt", [ - """ [email protected]( + "apache_opt", + [ + """ <Directory /> Options None AllowOverride None Require all denied </Directory> -""".strip('\n'), - """ +""".strip( + "\n" + ), + """ <Directory {}/static> Require all granted # Cache static resources for 1 hour Header set Cache-Control "max-age=3600" </Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), - """ +""".strip( + "\n" + ).format( + securedrop_test_vars.securedrop_code + ), + """ <Directory {}> Options None AllowOverride None @@ -125,8 +136,13 @@ def test_apache_logging_journalist_interface(host): Require all denied </LimitExcept> </Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), -]) +""".strip( + "\n" + ).format( + securedrop_test_vars.securedrop_code + ), + ], +) def test_apache_config_journalist_interface_access_control(host, apache_opt): """ Verifies the access control directives for the Journalist Interface. diff --git a/molecule/testinfra/app/apache/test_apache_service.py b/molecule/testinfra/app/apache/test_apache_service.py --- a/molecule/testinfra/app/apache/test_apache_service.py +++ b/molecule/testinfra/app/apache/test_apache_service.py @@ -1,15 +1,17 @@ import pytest - import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] [email protected]("apache_site", [ - "source", - "journalist", -]) [email protected]( + "apache_site", + [ + "source", + "journalist", + ], +) def test_apache_enabled_sites(host, apache_site): """ Ensure the Source and Journalist interfaces are enabled. @@ -20,9 +22,12 @@ def test_apache_enabled_sites(host, apache_site): assert c.rc == 0 [email protected]("apache_site", [ - "000-default", -]) [email protected]( + "apache_site", + [ + "000-default", + ], +) def test_apache_disabled_sites(host, apache_site): """ Ensure the default HTML document root is disabled. @@ -54,10 +59,13 @@ def test_apache_user(host): assert u.shell == "/usr/sbin/nologin" [email protected]("port", [ - "80", - "8080", -]) [email protected]( + "port", + [ + "80", + "8080", + ], +) def test_apache_listening(host, port): """ Ensure Apache is listening on proper ports and interfaces. @@ -66,6 +74,5 @@ def test_apache_listening(host, port): """ # sudo is necessary to read from /proc/net/tcp. with host.sudo(): - s = host.socket("tcp://{}:{}".format( - securedrop_test_vars.apache_listening_address, port)) + s = host.socket("tcp://{}:{}".format(securedrop_test_vars.apache_listening_address, port)) assert s.is_listening diff --git a/molecule/testinfra/app/apache/test_apache_source_interface.py b/molecule/testinfra/app/apache/test_apache_source_interface.py --- a/molecule/testinfra/app/apache/test_apache_source_interface.py +++ b/molecule/testinfra/app/apache/test_apache_source_interface.py @@ -1,6 +1,6 @@ -import pytest import re +import pytest import testutils securedrop_test_vars = testutils.securedrop_test_vars @@ -19,24 +19,27 @@ def test_apache_headers_source_interface(host, header, value): assert f.mode == 0o644 header_unset = "Header onsuccess unset {}".format(header) assert f.contains(header_unset) - header_set = "Header always set {} \"{}\"".format(header, value) + header_set = 'Header always set {} "{}"'.format(header, value) assert f.contains(header_set) [email protected]("apache_opt", [ - "<VirtualHost {}:80>".format( - securedrop_test_vars.apache_listening_address), - "WSGIDaemonProcess source processes=2 threads=30 display-name=%{{GROUP}} python-path={}".format( # noqa - securedrop_test_vars.securedrop_code), - 'WSGIProcessGroup source', - 'WSGIScriptAlias / /var/www/source.wsgi', - 'Header set Cache-Control "no-store"', - 'Header unset Etag', - "Alias /static {}/static".format(securedrop_test_vars.securedrop_code), - 'XSendFile Off', - 'LimitRequestBody 524288000', - "ErrorLog {}".format(securedrop_test_vars.apache_source_log), -]) [email protected]( + "apache_opt", + [ + "<VirtualHost {}:80>".format(securedrop_test_vars.apache_listening_address), + "WSGIDaemonProcess source processes=2 threads=30 display-name=%{{GROUP}} python-path={}".format( # noqa + securedrop_test_vars.securedrop_code + ), + "WSGIProcessGroup source", + "WSGIScriptAlias / /var/www/source.wsgi", + 'Header set Cache-Control "no-store"', + "Header unset Etag", + "Alias /static {}/static".format(securedrop_test_vars.securedrop_code), + "XSendFile Off", + "LimitRequestBody 524288000", + "ErrorLog {}".format(securedrop_test_vars.apache_source_log), + ], +) def test_apache_config_source_interface(host, apache_opt): """ Ensure the necessary Apache settings for serving the application @@ -62,27 +65,35 @@ def test_apache_config_source_interface_headers_per_distro(host): f = host.file("/etc/apache2/sites-available/source.conf") assert f.contains("Header onsuccess unset X-Frame-Options") assert f.contains('Header always set X-Frame-Options "DENY"') - assert f.contains('Header onsuccess unset Referrer-Policy') + assert f.contains("Header onsuccess unset Referrer-Policy") assert f.contains('Header always set Referrer-Policy "same-origin"') - assert f.contains('Header edit Set-Cookie ^(.*)$ $1;HttpOnly') + assert f.contains("Header edit Set-Cookie ^(.*)$ $1;HttpOnly") [email protected]("apache_opt", [ - """ [email protected]( + "apache_opt", + [ + """ <Directory /> Options None AllowOverride None Require all denied </Directory> -""".strip('\n'), - """ +""".strip( + "\n" + ), + """ <Directory {}/static> Require all granted # Cache static resources for 1 hour Header set Cache-Control "max-age=3600" </Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), - """ +""".strip( + "\n" + ).format( + securedrop_test_vars.securedrop_code + ), + """ <Directory {}> Options None AllowOverride None @@ -93,8 +104,13 @@ def test_apache_config_source_interface_headers_per_distro(host): Require all denied </LimitExcept> </Directory> -""".strip('\n').format(securedrop_test_vars.securedrop_code), -]) +""".strip( + "\n" + ).format( + securedrop_test_vars.securedrop_code + ), + ], +) def test_apache_config_source_interface_access_control(host, apache_opt): """ Verifies the access control directives for the Source Interface. diff --git a/molecule/testinfra/app/apache/test_apache_system_config.py b/molecule/testinfra/app/apache/test_apache_system_config.py --- a/molecule/testinfra/app/apache/test_apache_system_config.py +++ b/molecule/testinfra/app/apache/test_apache_system_config.py @@ -1,15 +1,18 @@ -import pytest import re +import pytest import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] [email protected]("package", [ - "libapache2-mod-xsendfile", -]) [email protected]( + "package", + [ + "libapache2-mod-xsendfile", + ], +) def test_apache_apt_packages(host, package): """ Ensure required Apache packages are installed. @@ -26,28 +29,31 @@ def test_apache_security_config_deprecated(host): assert not host.file("/etc/apache2/security").exists [email protected]("apache_opt", [ - 'Mutex file:${APACHE_LOCK_DIR} default', - 'PidFile ${APACHE_PID_FILE}', - 'Timeout 60', - 'KeepAlive On', - 'MaxKeepAliveRequests 100', - 'KeepAliveTimeout 5', - 'User www-data', - 'Group www-data', - 'AddDefaultCharset UTF-8', - 'DefaultType None', - 'HostnameLookups Off', - 'ErrorLog /dev/null', - 'LogLevel crit', - 'IncludeOptional mods-enabled/*.load', - 'IncludeOptional mods-enabled/*.conf', - 'Include ports.conf', - 'IncludeOptional sites-enabled/*.conf', - 'ServerTokens Prod', - 'ServerSignature Off', - 'TraceEnable Off', -]) [email protected]( + "apache_opt", + [ + "Mutex file:${APACHE_LOCK_DIR} default", + "PidFile ${APACHE_PID_FILE}", + "Timeout 60", + "KeepAlive On", + "MaxKeepAliveRequests 100", + "KeepAliveTimeout 5", + "User www-data", + "Group www-data", + "AddDefaultCharset UTF-8", + "DefaultType None", + "HostnameLookups Off", + "ErrorLog /dev/null", + "LogLevel crit", + "IncludeOptional mods-enabled/*.load", + "IncludeOptional mods-enabled/*.conf", + "Include ports.conf", + "IncludeOptional sites-enabled/*.conf", + "ServerTokens Prod", + "ServerSignature Off", + "TraceEnable Off", + ], +) def test_apache_config_settings(host, apache_opt): """ Check required Apache config settings for general server. @@ -63,10 +69,13 @@ def test_apache_config_settings(host, apache_opt): assert re.search("^{}$".format(re.escape(apache_opt)), f.content_string, re.M) [email protected]("port", [ - "80", - "8080", -]) [email protected]( + "port", + [ + "80", + "8080", + ], +) def test_apache_ports_config(host, port): """ Ensure Apache ports config items, which specify how the @@ -81,30 +90,34 @@ def test_apache_ports_config(host, port): assert f.group == "root" assert f.mode == 0o644 - listening_regex = "^Listen {}:{}$".format(re.escape( - securedrop_test_vars.apache_listening_address), port) + listening_regex = "^Listen {}:{}$".format( + re.escape(securedrop_test_vars.apache_listening_address), port + ) assert f.contains(listening_regex) [email protected]("apache_module", [ - 'access_compat', - 'authn_core', - 'alias', - 'authz_core', - 'authz_host', - 'authz_user', - 'deflate', - 'filter', - 'dir', - 'headers', - 'mime', - 'mpm_event', - 'negotiation', - 'reqtimeout', - 'rewrite', - 'wsgi', - 'xsendfile', -]) [email protected]( + "apache_module", + [ + "access_compat", + "authn_core", + "alias", + "authz_core", + "authz_host", + "authz_user", + "deflate", + "filter", + "dir", + "headers", + "mime", + "mpm_event", + "negotiation", + "reqtimeout", + "rewrite", + "wsgi", + "xsendfile", + ], +) def test_apache_modules_present(host, apache_module): """ Ensure presence of required Apache modules. Application will not work @@ -117,13 +130,16 @@ def test_apache_modules_present(host, apache_module): assert c.rc == 0 [email protected]("apache_module", [ - 'auth_basic', - 'authn_file', - 'autoindex', - 'env', - 'status', -]) [email protected]( + "apache_module", + [ + "auth_basic", + "authn_file", + "autoindex", + "env", + "status", + ], +) def test_apache_modules_absent(host, apache_module): """ Ensure absence of unwanted Apache modules. Application does not require @@ -132,15 +148,13 @@ def test_apache_modules_absent(host, apache_module): """ with host.sudo(): c = host.run("/usr/sbin/a2query -m {}".format(apache_module)) - assert "No module matches {} (disabled".format(apache_module) in \ - c.stderr + assert "No module matches {} (disabled".format(apache_module) in c.stderr assert c.rc == 32 [email protected]("logfile", - securedrop_test_vars.allowed_apache_logfiles) [email protected]("logfile", securedrop_test_vars.allowed_apache_logfiles) def test_apache_logfiles_present(host, logfile): - """" + """ " Ensure that whitelisted Apache log files for the Source and Journalist Interfaces are present. In staging, we permit a "source-error" log, but on prod even that is not allowed. A separate test will confirm @@ -166,5 +180,4 @@ def test_apache_logfiles_no_extras(host): # We need elevated privileges to read files inside /var/log/apache2 with host.sudo(): c = host.run("find /var/log/apache2 -mindepth 1 -name '*.log' | wc -l") - assert int(c.stdout) == \ - len(securedrop_test_vars.allowed_apache_logfiles) + assert int(c.stdout) == len(securedrop_test_vars.allowed_apache_logfiles) diff --git a/molecule/testinfra/app/test_app_network.py b/molecule/testinfra/app/test_app_network.py --- a/molecule/testinfra/app/test_app_network.py +++ b/molecule/testinfra/app/test_app_network.py @@ -1,11 +1,10 @@ -import os -import io import difflib -import pytest -from jinja2 import Template - +import io +import os +import pytest import testutils +from jinja2 import Template securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.app_hostname] @@ -18,14 +17,14 @@ def test_app_iptables_rules(host): # Build a dict of variables to pass to jinja for iptables comparison kwargs = dict( - mon_ip=os.environ.get('MON_IP', securedrop_test_vars.mon_ip), - default_interface=host.check_output("ip r | head -n 1 | " - "awk '{ print $5 }'"), + mon_ip=os.environ.get("MON_IP", securedrop_test_vars.mon_ip), + default_interface=host.check_output("ip r | head -n 1 | " "awk '{ print $5 }'"), tor_user_id=host.check_output("id -u debian-tor"), time_service_user=host.check_output("id -u systemd-timesync"), securedrop_user_id=host.check_output("id -u www-data"), ssh_group_gid=host.check_output("getent group ssh | cut -d: -f3"), - dns_server=securedrop_test_vars.dns_server) + dns_server=securedrop_test_vars.dns_server, + ) # Required for testing under Qubes. if local.interface("eth0").exists: @@ -35,11 +34,11 @@ def test_app_iptables_rules(host): iptables = r"iptables-save | sed 's/ \[[0-9]*\:[0-9]*\]//g' | egrep -v '^#'" environment = os.environ.get("SECUREDROP_TESTINFRA_TARGET_HOST", "staging") iptables_file = "{}/iptables-app-{}.j2".format( - os.path.dirname(os.path.abspath(__file__)), - environment) + os.path.dirname(os.path.abspath(__file__)), environment + ) # template out a local iptables jinja file - jinja_iptables = Template(io.open(iptables_file, 'r').read()) + jinja_iptables = Template(io.open(iptables_file, "r").read()) iptables_expected = jinja_iptables.render(**kwargs) with host.sudo(): @@ -47,8 +46,9 @@ def test_app_iptables_rules(host): iptables = host.check_output(iptables) # print diff comparison (only shows up in pytests if test fails or # verbosity turned way up) - for iptablesdiff in difflib.context_diff(iptables_expected.split('\n'), - iptables.split('\n')): + for iptablesdiff in difflib.context_diff( + iptables_expected.split("\n"), iptables.split("\n") + ): print(iptablesdiff) # Conduct the string comparison of the expected and actual iptables # ruleset diff --git a/molecule/testinfra/app/test_apparmor.py b/molecule/testinfra/app/test_apparmor.py --- a/molecule/testinfra/app/test_apparmor.py +++ b/molecule/testinfra/app/test_apparmor.py @@ -1,35 +1,28 @@ import pytest - - import testutils sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] [email protected]('pkg', ['apparmor', 'apparmor-utils']) [email protected]("pkg", ["apparmor", "apparmor-utils"]) def test_apparmor_pkg(host, pkg): - """ Apparmor package dependencies """ + """Apparmor package dependencies""" assert host.package(pkg).is_installed def test_apparmor_enabled(host): - """ Check that apparmor is enabled """ + """Check that apparmor is enabled""" with host.sudo(): assert host.run("aa-status --enabled").rc == 0 -apache2_capabilities = [ - 'dac_override', - 'kill', - 'net_bind_service', - 'sys_ptrace' -] +apache2_capabilities = ["dac_override", "kill", "net_bind_service", "sys_ptrace"] [email protected]('cap', apache2_capabilities) [email protected]("cap", apache2_capabilities) def test_apparmor_apache_capabilities(host, cap): - """ check for exact list of expected app-armor capabilities for apache2 """ + """check for exact list of expected app-armor capabilities for apache2""" c = host.run( r"perl -nE '/^\s+capability\s+(\w+),$/ && say $1' /etc/apparmor.d/usr.sbin.apache2" ) @@ -37,29 +30,28 @@ def test_apparmor_apache_capabilities(host, cap): def test_apparmor_apache_exact_capabilities(host): - """ ensure no extra capabilities are defined for apache2 """ + """ensure no extra capabilities are defined for apache2""" c = host.check_output("grep -ic capability /etc/apparmor.d/usr.sbin.apache2") assert str(len(apache2_capabilities)) == c -tor_capabilities = ['setgid'] +tor_capabilities = ["setgid"] [email protected]('cap', tor_capabilities) [email protected]("cap", tor_capabilities) def test_apparmor_tor_capabilities(host, cap): - """ check for exact list of expected app-armor capabilities for Tor """ + """check for exact list of expected app-armor capabilities for Tor""" c = host.run(r"perl -nE '/^\s+capability\s+(\w+),$/ && say $1' /etc/apparmor.d/usr.sbin.tor") assert cap in c.stdout def test_apparmor_tor_exact_capabilities(host): - """ ensure no extra capabilities are defined for Tor """ - c = host.check_output("grep -ic capability " - "/etc/apparmor.d/usr.sbin.tor") + """ensure no extra capabilities are defined for Tor""" + c = host.check_output("grep -ic capability " "/etc/apparmor.d/usr.sbin.tor") assert str(len(tor_capabilities)) == c [email protected]('profile', sdvars.apparmor_enforce) [email protected]("profile", sdvars.apparmor_enforce) def test_apparmor_ensure_not_disabled(host, profile): """ Explicitly check that enforced profiles are NOT in /etc/apparmor.d/disable @@ -71,56 +63,55 @@ def test_apparmor_ensure_not_disabled(host, profile): assert not f.exists [email protected]('complain_pkg', sdvars.apparmor_complain) [email protected]("complain_pkg", sdvars.apparmor_complain) def test_app_apparmor_complain(host, complain_pkg): - """ Ensure app-armor profiles are in complain mode for staging """ + """Ensure app-armor profiles are in complain mode for staging""" with host.sudo(): - awk = ("awk '/[0-9]+ profiles.*complain." - "/{flag=1;next}/^[0-9]+.*/{flag=0}flag'") + awk = "awk '/[0-9]+ profiles.*complain." "/{flag=1;next}/^[0-9]+.*/{flag=0}flag'" c = host.check_output("aa-status | {}".format(awk)) assert complain_pkg in c def test_app_apparmor_complain_count(host): - """ Ensure right number of app-armor profiles are in complain mode """ + """Ensure right number of app-armor profiles are in complain mode""" with host.sudo(): c = host.check_output("aa-status --complaining") assert c == str(len(sdvars.apparmor_complain)) [email protected]('aa_enforced', sdvars.apparmor_enforce_actual) [email protected]("aa_enforced", sdvars.apparmor_enforce_actual) def test_apparmor_enforced(host, aa_enforced): - awk = ("awk '/[0-9]+ profiles.*enforce./" - "{flag=1;next}/^[0-9]+.*/{flag=0}flag'") + awk = "awk '/[0-9]+ profiles.*enforce./" "{flag=1;next}/^[0-9]+.*/{flag=0}flag'" with host.sudo(): c = host.check_output("aa-status | {}".format(awk)) assert aa_enforced in c def test_apparmor_total_profiles(host): - """ Ensure number of total profiles is sum of enforced and - complaining profiles """ + """Ensure number of total profiles is sum of enforced and + complaining profiles""" with host.sudo(): total_expected = len(sdvars.apparmor_enforce) + len(sdvars.apparmor_complain) assert int(host.check_output("aa-status --profiled")) >= total_expected def test_aastatus_unconfined(host): - """ Ensure that there are no processes that are unconfined but have - a profile """ + """Ensure that there are no processes that are unconfined but have + a profile""" # There should be 0 unconfined processes. expected_unconfined = 0 - unconfined_chk = str("{} processes are unconfined but have" - " a profile defined".format(expected_unconfined)) + unconfined_chk = str( + "{} processes are unconfined but have" " a profile defined".format(expected_unconfined) + ) with host.sudo(): aa_status_output = host.check_output("aa-status") assert unconfined_chk in aa_status_output def test_aa_no_denies_in_syslog(host): - """ Ensure that there are no apparmor denials in syslog """ + """Ensure that there are no apparmor denials in syslog""" with host.sudo(): f = host.file("/var/log/syslog") assert 'apparmor="DENIED"' not in f.content_string diff --git a/molecule/testinfra/app/test_appenv.py b/molecule/testinfra/app/test_appenv.py --- a/molecule/testinfra/app/test_appenv.py +++ b/molecule/testinfra/app/test_appenv.py @@ -1,43 +1,42 @@ import pytest - import testutils sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] [email protected]('exp_pip_pkg', sdvars.pip_deps) [email protected]("exp_pip_pkg", sdvars.pip_deps) def test_app_pip_deps(host, exp_pip_pkg): - """ Ensure expected package versions are installed """ - cmd = "{}/bin/python3 -c \"from importlib.metadata import version; print(version('{}'))\"".format( # noqa - sdvars.securedrop_venv, exp_pip_pkg['name'] + """Ensure expected package versions are installed""" + cmd = "{}/bin/python3 -c \"from importlib.metadata import version; print(version('{}'))\"".format( # noqa + sdvars.securedrop_venv, exp_pip_pkg["name"] ) result = host.run(cmd) - assert result.stdout.strip() == exp_pip_pkg['version'] + assert result.stdout.strip() == exp_pip_pkg["version"] @pytest.mark.skip_in_prod def test_app_wsgi(host): - """ ensure logging is enabled for source interface in staging """ + """ensure logging is enabled for source interface in staging""" f = host.file("/var/www/source.wsgi") with host.sudo(): assert f.is_file assert f.mode == 0o640 - assert f.user == 'www-data' - assert f.group == 'www-data' + assert f.user == "www-data" + assert f.group == "www-data" assert f.contains("^import logging$") assert f.contains(r"^logging\.basicConfig(stream=sys\.stderr)$") def test_pidfile(host): - """ ensure there are no pid files """ - assert not host.file('/tmp/journalist.pid').exists - assert not host.file('/tmp/source.pid').exists + """ensure there are no pid files""" + assert not host.file("/tmp/journalist.pid").exists + assert not host.file("/tmp/source.pid").exists [email protected]('app_dir', sdvars.app_directories) [email protected]("app_dir", sdvars.app_directories) def test_app_directories(host, app_dir): - """ ensure securedrop app directories exist with correct permissions """ + """ensure securedrop app directories exist with correct permissions""" f = host.file(app_dir) with host.sudo(): assert f.is_directory @@ -47,7 +46,7 @@ def test_app_directories(host, app_dir): def test_app_code_pkg(host): - """ ensure securedrop-app-code package is installed """ + """ensure securedrop-app-code package is installed""" assert host.package("securedrop-app-code").is_installed @@ -64,22 +63,21 @@ def test_app_code_venv(host): def test_supervisor_not_installed(host): - """ ensure supervisor package is not installed """ + """ensure supervisor package is not installed""" assert host.package("supervisor").is_installed is False @pytest.mark.skip_in_prod def test_gpg_key_in_keyring(host): - """ ensure test gpg key is present in app keyring """ + """ensure test gpg key is present in app keyring""" with host.sudo(sdvars.securedrop_user): - c = host.run("gpg --homedir /var/lib/securedrop/keys " - "--list-keys 28271441") + c = host.run("gpg --homedir /var/lib/securedrop/keys " "--list-keys 28271441") assert "2013-10-12" in c.stdout assert "28271441" in c.stdout def test_ensure_logo(host): - """ ensure default logo header file exists """ + """ensure default logo header file exists""" f = host.file("{}/static/i/logo.png".format(sdvars.securedrop_code)) with host.sudo(): assert f.mode == 0o644 @@ -88,7 +86,7 @@ def test_ensure_logo(host): def test_securedrop_tmp_clean_cron(host): - """ Ensure securedrop tmp clean cron job in place """ + """Ensure securedrop tmp clean cron job in place""" with host.sudo(): cronlist = host.run("crontab -l").stdout cronjob = "@daily {}/manage.py clean-tmp".format(sdvars.securedrop_code) diff --git a/molecule/testinfra/app/test_ossec_agent.py b/molecule/testinfra/app/test_ossec_agent.py --- a/molecule/testinfra/app/test_ossec_agent.py +++ b/molecule/testinfra/app/test_ossec_agent.py @@ -1,7 +1,7 @@ import os import re -import pytest +import pytest import testutils sdvars = testutils.securedrop_test_vars @@ -9,16 +9,14 @@ def test_hosts_files(host): - """ Ensure host files mapping are in place """ - f = host.file('/etc/hosts') + """Ensure host files mapping are in place""" + f = host.file("/etc/hosts") - mon_ip = os.environ.get('MON_IP', sdvars.mon_ip) + mon_ip = os.environ.get("MON_IP", sdvars.mon_ip) mon_host = sdvars.monitor_hostname - assert f.contains(r'^127.0.0.1\s*localhost') - assert f.contains(r'^{}\s*{}\s*securedrop-monitor-server-alias$'.format( - mon_ip, - mon_host)) + assert f.contains(r"^127.0.0.1\s*localhost") + assert f.contains(r"^{}\s*{}\s*securedrop-monitor-server-alias$".format(mon_ip, mon_host)) def test_ossec_service_start_style(host): @@ -31,22 +29,22 @@ def test_ossec_service_start_style(host): def test_hosts_duplicate(host): - """ Regression test for duplicate entries """ + """Regression test for duplicate entries""" assert host.check_output("uniq --repeated /etc/hosts") == "" def test_ossec_agent_installed(host): - """ Check that ossec-agent package is present """ + """Check that ossec-agent package is present""" assert host.package("securedrop-ossec-agent").is_installed # Permissions don't match between Ansible and OSSEC deb packages postinst. @pytest.mark.xfail def test_ossec_keyfile_present(host): - """ ensure client keyfile for ossec-agent is present """ + """ensure client keyfile for ossec-agent is present""" pattern = "^1024 {} {} [0-9a-f]{{64}}$".format( - sdvars.app_hostname, - os.environ.get('APP_IP', sdvars.app_ip)) + sdvars.app_hostname, os.environ.get("APP_IP", sdvars.app_ip) + ) regex = re.compile(pattern) with host.sudo(): diff --git a/molecule/testinfra/app/test_tor_config.py b/molecule/testinfra/app/test_tor_config.py --- a/molecule/testinfra/app/test_tor_config.py +++ b/molecule/testinfra/app/test_tor_config.py @@ -1,15 +1,18 @@ -import pytest import re +import pytest import testutils sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname] [email protected]('package', [ - 'tor', -]) [email protected]( + "package", + [ + "tor", + ], +) def test_tor_packages(host, package): """ Ensure Tor packages are installed. Does not include the Tor keyring @@ -29,11 +32,14 @@ def test_tor_service_running(host): assert s.is_enabled [email protected]('torrc_option', [ - 'SocksPort 0', - 'SafeLogging 1', - 'RunAsDaemon 1', -]) [email protected]( + "torrc_option", + [ + "SocksPort 0", + "SafeLogging 1", + "RunAsDaemon 1", + ], +) def test_tor_torrc_options(host, torrc_option): """ Check for required options in the system Tor config file. diff --git a/molecule/testinfra/app/test_tor_hidden_services.py b/molecule/testinfra/app/test_tor_hidden_services.py --- a/molecule/testinfra/app/test_tor_hidden_services.py +++ b/molecule/testinfra/app/test_tor_hidden_services.py @@ -1,6 +1,6 @@ -import pytest import re +import pytest import testutils sdvars = testutils.securedrop_test_vars @@ -9,13 +9,13 @@ # Prod Tor services may have unexpected configs # TODO: read from admin workstation site-specific file if available @pytest.mark.skip_in_prod [email protected]('tor_service', sdvars.tor_services) [email protected]("tor_service", sdvars.tor_services) def test_tor_service_directories(host, tor_service): """ Check mode and ownership on Tor service directories. """ with host.sudo(): - f = host.file("/var/lib/tor/services/{}".format(tor_service['name'])) + f = host.file("/var/lib/tor/services/{}".format(tor_service["name"])) assert f.is_directory assert f.mode == 0o700 assert f.user == "debian-tor" @@ -23,7 +23,7 @@ def test_tor_service_directories(host, tor_service): @pytest.mark.skip_in_prod [email protected]('tor_service', sdvars.tor_services) [email protected]("tor_service", sdvars.tor_services) def test_tor_service_hostnames(host, tor_service): """ Check contents of Tor service hostname file. For v3 onion services, @@ -35,8 +35,7 @@ def test_tor_service_hostnames(host, tor_service): ths_hostname_regex_v3 = r"[a-z0-9]{56}\.onion" with host.sudo(): - f = host.file("/var/lib/tor/services/{}/hostname".format( - tor_service['name'])) + f = host.file("/var/lib/tor/services/{}/hostname".format(tor_service["name"])) assert f.is_file assert f.mode == 0o600 assert f.user == "debian-tor" @@ -45,19 +44,21 @@ def test_tor_service_hostnames(host, tor_service): # All hostnames should contain at *least* the hostname. assert re.search(ths_hostname_regex, f.content_string) - if tor_service['authenticated'] and tor_service['version'] == 3: + if tor_service["authenticated"] and tor_service["version"] == 3: # For authenticated version 3 onion services, the authorized_client # directory will exist and contain a file called client.auth. client_auth = host.file( "/var/lib/tor/services/{}/authorized_clients/client.auth".format( - tor_service['name'])) + tor_service["name"] + ) + ) assert client_auth.is_file else: assert re.search("^{}$".format(ths_hostname_regex_v3), f.content_string) @pytest.mark.skip_in_prod [email protected]('tor_service', sdvars.tor_services) [email protected]("tor_service", sdvars.tor_services) def test_tor_services_config(host, tor_service): """ Ensure torrc file contains relevant lines for onion service declarations. @@ -67,19 +68,17 @@ def test_tor_services_config(host, tor_service): * HiddenServicePort """ f = host.file("/etc/tor/torrc") - dir_regex = "HiddenServiceDir /var/lib/tor/services/{}".format( - tor_service['name']) + dir_regex = "HiddenServiceDir /var/lib/tor/services/{}".format(tor_service["name"]) # We need at least one port, but it may be used for both config values. # On the Journalist Interface, we reuse the "80" remote port but map it to # a different local port, so Apache can listen on several sockets. - remote_port = tor_service['ports'][0] + remote_port = tor_service["ports"][0] try: - local_port = tor_service['ports'][1] + local_port = tor_service["ports"][1] except IndexError: local_port = remote_port - port_regex = "HiddenServicePort {} 127.0.0.1:{}".format( - remote_port, local_port) + port_regex = "HiddenServicePort {} 127.0.0.1:{}".format(remote_port, local_port) assert f.contains("^{}$".format(dir_regex)) assert f.contains("^{}$".format(port_regex)) diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -1,6 +1,6 @@ -import pytest import re +import pytest import testutils test_vars = testutils.securedrop_test_vars @@ -27,33 +27,34 @@ def test_cron_apt_config(host): Ensure custom cron-apt config is absent, as of Focal """ assert not host.file("/etc/cron-apt/config").exists - assert not host.file('/etc/cron-apt/action.d/0-update').exists - assert not host.file('/etc/cron-apt/action.d/5-security').exists - assert not host.file('/etc/cron-apt/action.d/9-remove').exists - assert not host.file('/etc/cron.d/cron-apt').exists + assert not host.file("/etc/cron-apt/action.d/0-update").exists + assert not host.file("/etc/cron-apt/action.d/5-security").exists + assert not host.file("/etc/cron-apt/action.d/9-remove").exists + assert not host.file("/etc/cron.d/cron-apt").exists assert not host.file("/etc/apt/security.list").exists assert not host.file("/etc/cron-apt/action.d/3-download").exists [email protected]('repo', [ - 'deb http://security.ubuntu.com/ubuntu {securedrop_target_platform}-security main', - 'deb http://security.ubuntu.com/ubuntu {securedrop_target_platform}-security universe', - 'deb http://archive.ubuntu.com/ubuntu/ {securedrop_target_platform}-updates main', - 'deb http://archive.ubuntu.com/ubuntu/ {securedrop_target_platform} main' -]) [email protected]( + "repo", + [ + "deb http://security.ubuntu.com/ubuntu {securedrop_target_platform}-security main", + "deb http://security.ubuntu.com/ubuntu {securedrop_target_platform}-security universe", + "deb http://archive.ubuntu.com/ubuntu/ {securedrop_target_platform}-updates main", + "deb http://archive.ubuntu.com/ubuntu/ {securedrop_target_platform} main", + ], +) def test_sources_list(host, repo): """ Ensure the correct apt repositories are specified in the sources.list for apt. """ - repo_config = repo.format( - securedrop_target_platform=host.system_info.codename - ) - f = host.file('/etc/apt/sources.list') + repo_config = repo.format(securedrop_target_platform=host.system_info.codename) + f = host.file("/etc/apt/sources.list") assert f.is_file assert f.user == "root" assert f.mode == 0o644 - repo_regex = '^{}$'.format(re.escape(repo_config)) + repo_regex = "^{}$".format(re.escape(repo_config)) assert f.contains(repo_regex) @@ -103,7 +104,7 @@ def test_unattended_securedrop_specific(host): it will include unattended-upgrade settings. Under all hosts, it will disable installing 'recommended' packages. """ - f = host.file('/etc/apt/apt.conf.d/80securedrop') + f = host.file("/etc/apt/apt.conf.d/80securedrop") assert f.is_file assert f.user == "root" assert f.mode == 0o644 @@ -116,7 +117,7 @@ def test_unattended_upgrades_functional(host): Ensure unatteded-upgrades completes successfully and ensures all packages are up-to-date. """ - c = host.run('sudo unattended-upgrades --dry-run --debug') + c = host.run("sudo unattended-upgrades --dry-run --debug") assert c.rc == 0 expected_origins = ( "Allowed origins are: origin=Ubuntu,archive=focal, origin=Ubuntu,archive=focal-security" @@ -130,12 +131,15 @@ def test_unattended_upgrades_functional(host): assert expected_result in c.stdout [email protected]('service', [ - 'apt-daily', - 'apt-daily.timer', - 'apt-daily-upgrade', - 'apt-daily-upgrade.timer', - ]) [email protected]( + "service", + [ + "apt-daily", + "apt-daily.timer", + "apt-daily-upgrade", + "apt-daily-upgrade.timer", + ], +) def test_apt_daily_services_and_timers_enabled(host, service): """ Ensure the services and timers used for unattended upgrades are enabled @@ -176,12 +180,12 @@ def test_reboot_required_cron(host): Here, we ensure that reboot-required flag is dropped twice daily to ensure the system is rebooted every day at the scheduled time. """ - f = host.file('/etc/cron.d/reboot-flag') + f = host.file("/etc/cron.d/reboot-flag") assert f.is_file assert f.user == "root" assert f.mode == 0o644 - line = '^{}$'.format(re.escape("0 */12 * * * root touch /var/run/reboot-required")) + line = "^{}$".format(re.escape("0 */12 * * * root touch /var/run/reboot-required")) assert f.contains(line) @@ -194,7 +198,7 @@ def test_all_packages_updated(host): for use with Selenium. Therefore apt will report it's possible to upgrade Firefox, which we'll need to mark as "OK" in terms of the tests. """ - c = host.run('apt-get dist-upgrade --simulate') + c = host.run("apt-get dist-upgrade --simulate") assert c.rc == 0 # Staging hosts will have locally built deb packages, marked as held. # Staging and development will have a version-locked Firefox pinned for diff --git a/molecule/testinfra/common/test_basic_configuration.py b/molecule/testinfra/common/test_basic_configuration.py --- a/molecule/testinfra/common/test_basic_configuration.py +++ b/molecule/testinfra/common/test_basic_configuration.py @@ -1,7 +1,5 @@ -from testinfra.host import Host - import testutils - +from testinfra.host import Host test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] diff --git a/molecule/testinfra/common/test_fpf_apt_repo.py b/molecule/testinfra/common/test_fpf_apt_repo.py --- a/molecule/testinfra/common/test_fpf_apt_repo.py +++ b/molecule/testinfra/common/test_fpf_apt_repo.py @@ -1,7 +1,6 @@ -import pytest import re - +import pytest import testutils test_vars = testutils.securedrop_test_vars @@ -26,12 +25,12 @@ def test_fpf_apt_repo_present(host): # If the var fpf_apt_repo_url test var is apt-test, validate that the # apt repository is configured on the host if test_vars.fpf_apt_repo_url == "https://apt-test.freedom.press": - f = host.file('/etc/apt/sources.list.d/apt_test_freedom_press.list') + f = host.file("/etc/apt/sources.list.d/apt_test_freedom_press.list") else: - f = host.file('/etc/apt/sources.list.d/apt_freedom_press.list') - repo_regex = r'^deb \[arch=amd64\] {} {} main$'.format( - re.escape(test_vars.fpf_apt_repo_url), - re.escape(host.system_info.codename)) + f = host.file("/etc/apt/sources.list.d/apt_freedom_press.list") + repo_regex = r"^deb \[arch=amd64\] {} {} main$".format( + re.escape(test_vars.fpf_apt_repo_url), re.escape(host.system_info.codename) + ) assert f.contains(repo_regex) @@ -47,7 +46,7 @@ def test_fpf_apt_repo_fingerprint(host): returned. """ - c = host.run('apt-key finger') + c = host.run("apt-key finger") fpf_gpg_pub_key_info_old = "2224 5C81 E3BA EB41 38B3 6061 310F 5612 00F4 AD77" fpf_gpg_pub_key_info_new = "2359 E653 8C06 13E6 5295 5E6C 188E DD3B 7B22 E6A3" @@ -57,14 +56,17 @@ def test_fpf_apt_repo_fingerprint(host): assert fpf_gpg_pub_key_info_new in c.stdout [email protected]('old_pubkey', [ - 'pub 4096R/FC9F6818 2014-10-26 [expired: 2016-10-27]', - 'pub 4096R/00F4AD77 2016-10-20 [expired: 2017-10-20]', - 'pub 4096R/00F4AD77 2016-10-20 [expired: 2017-10-20]', - 'pub 4096R/7B22E6A3 2021-05-10 [expired: 2022-07-04]', - 'uid Freedom of the Press Foundation Master Signing Key', - 'B89A 29DB 2128 160B 8E4B 1B4C BADD E0C7 FC9F 6818', -]) [email protected]( + "old_pubkey", + [ + "pub 4096R/FC9F6818 2014-10-26 [expired: 2016-10-27]", + "pub 4096R/00F4AD77 2016-10-20 [expired: 2017-10-20]", + "pub 4096R/00F4AD77 2016-10-20 [expired: 2017-10-20]", + "pub 4096R/7B22E6A3 2021-05-10 [expired: 2022-07-04]", + "uid Freedom of the Press Foundation Master Signing Key", + "B89A 29DB 2128 160B 8E4B 1B4C BADD E0C7 FC9F 6818", + ], +) def test_fpf_apt_repo_old_pubkeys_absent(host, old_pubkey): """ Ensure that expired (or about-to-expire) public keys for the FPF @@ -72,5 +74,5 @@ def test_fpf_apt_repo_old_pubkeys_absent(host, old_pubkey): should enforce clobbering of old pubkeys, and this check will confirm absence. """ - c = host.run('apt-key finger') + c = host.run("apt-key finger") assert old_pubkey not in c.stdout diff --git a/molecule/testinfra/common/test_grsecurity.py b/molecule/testinfra/common/test_grsecurity.py --- a/molecule/testinfra/common/test_grsecurity.py +++ b/molecule/testinfra/common/test_grsecurity.py @@ -1,11 +1,11 @@ -import pytest -import warnings -import io import difflib +import io import os -from jinja2 import Template +import warnings +import pytest import testutils +from jinja2 import Template sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname, sdvars.monitor_hostname] @@ -21,10 +21,13 @@ def test_ssh_motd_disabled(host): assert not f.contains(r"pam\.motd") [email protected]("package", [ - 'linux-image-{}-grsec-securedrop', - 'securedrop-grsec', -]) [email protected]( + "package", + [ + "linux-image-{}-grsec-securedrop", + "securedrop-grsec", + ], +) def test_grsecurity_apt_packages(host, package): """ Ensure the grsecurity-related apt packages are present on the system. @@ -37,14 +40,17 @@ def test_grsecurity_apt_packages(host, package): assert host.package(package).is_installed [email protected]("package", [ - 'linux-signed-image-generic-lts-utopic', - 'linux-signed-image-generic', - 'linux-signed-generic-lts-utopic', - 'linux-signed-generic', - '^linux-image-.*generic$', - '^linux-headers-.*', -]) [email protected]( + "package", + [ + "linux-signed-image-generic-lts-utopic", + "linux-signed-image-generic", + "linux-signed-generic-lts-utopic", + "linux-signed-generic", + "^linux-image-.*generic$", + "^linux-headers-.*", + ], +) def test_generic_kernels_absent(host, package): """ Ensure the default Ubuntu-provided kernel packages are absent. @@ -78,16 +84,19 @@ def test_grsecurity_kernel_is_running(host): Make sure the currently running kernel is specific grsec kernel. """ KERNEL_VERSION = sdvars.grsec_version_focal - c = host.run('uname -r') - assert c.stdout.strip().endswith('-grsec-securedrop') - assert c.stdout.strip() == '{}-grsec-securedrop'.format(KERNEL_VERSION) - - [email protected]('sysctl_opt', [ - ('kernel.grsecurity.grsec_lock', 1), - ('kernel.grsecurity.rwxmap_logging', 0), - ('vm.heap_stack_gap', 1048576), -]) + c = host.run("uname -r") + assert c.stdout.strip().endswith("-grsec-securedrop") + assert c.stdout.strip() == "{}-grsec-securedrop".format(KERNEL_VERSION) + + [email protected]( + "sysctl_opt", + [ + ("kernel.grsecurity.grsec_lock", 1), + ("kernel.grsecurity.rwxmap_logging", 0), + ("vm.heap_stack_gap", 1048576), + ], +) def test_grsecurity_sysctl_options(host, sysctl_opt): """ Check that the grsecurity-related sysctl options are set correctly. @@ -118,7 +127,8 @@ def test_grsecurity_paxtest(host): paxtest_results = host.check_output(paxtest_cmd) paxtest_template_path = "{}/paxtest_results.j2".format( - os.path.dirname(os.path.abspath(__file__))) + os.path.dirname(os.path.abspath(__file__)) + ) memcpy_result = "Killed" # Versions of paxtest newer than 0.9.12 or so will report @@ -126,13 +136,14 @@ def test_grsecurity_paxtest(host): # https://github.com/freedomofpress/securedrop/issues/1039 if host.system_info.codename == "focal": memcpy_result = "Vulnerable" - with io.open(paxtest_template_path, 'r') as f: + with io.open(paxtest_template_path, "r") as f: paxtest_template = Template(f.read().rstrip()) paxtest_expected = paxtest_template.render(memcpy_result=memcpy_result) # The stdout prints here will only be displayed if the test fails - for paxtest_diff in difflib.context_diff(paxtest_expected.split('\n'), - paxtest_results.split('\n')): + for paxtest_diff in difflib.context_diff( + paxtest_expected.split("\n"), paxtest_results.split("\n") + ): print(paxtest_diff) assert paxtest_results == paxtest_expected finally: @@ -144,7 +155,7 @@ def test_apt_autoremove(host): """ Ensure old packages have been autoremoved. """ - c = host.run('apt-get --dry-run autoremove') + c = host.run("apt-get --dry-run autoremove") assert c.rc == 0 assert "The following packages will be REMOVED" not in c.stdout @@ -175,8 +186,8 @@ def test_paxctld_focal(host): # out of /opt/ to ensure the file is always clobbered on changes. assert host.file("/opt/securedrop/paxctld.conf").is_file - hostname = host.check_output('hostname -s') - assert (("app" in hostname) or ("mon" in hostname)) + hostname = host.check_output("hostname -s") + assert ("app" in hostname) or ("mon" in hostname) # Under Focal, apache2 pax flags managed by securedrop-grsec metapackage. # Both hosts, app & mon, should have the same exemptions. Check precedence @@ -185,15 +196,18 @@ def test_paxctld_focal(host): assert f.contains("^/usr/sbin/apache2\tm") [email protected]('kernel_opts', [ - 'WLAN', - 'NFC', - 'WIMAX', - 'WIRELESS', - 'HAMRADIO', - 'IRDA', - 'BT', -]) [email protected]( + "kernel_opts", + [ + "WLAN", + "NFC", + "WIMAX", + "WIRELESS", + "HAMRADIO", + "IRDA", + "BT", + ], +) def test_wireless_disabled_in_kernel_config(host, kernel_opts): """ Kernel modules for wireless are blacklisted, but we go one step further and @@ -209,11 +223,14 @@ def test_wireless_disabled_in_kernel_config(host, kernel_opts): assert line in kernel_config or kernel_opts not in kernel_config [email protected]('kernel_opts', [ - 'CONFIG_X86_INTEL_TSX_MODE_OFF', - 'CONFIG_PAX', - 'CONFIG_GRKERNSEC', -]) [email protected]( + "kernel_opts", + [ + "CONFIG_X86_INTEL_TSX_MODE_OFF", + "CONFIG_PAX", + "CONFIG_GRKERNSEC", + ], +) def test_kernel_options_enabled_config(host, kernel_opts): """ Tests kernel config for options that should be enabled diff --git a/molecule/testinfra/common/test_system_hardening.py b/molecule/testinfra/common/test_system_hardening.py --- a/molecule/testinfra/common/test_system_hardening.py +++ b/molecule/testinfra/common/test_system_hardening.py @@ -1,28 +1,31 @@ -import pytest import re +import pytest import testutils sdvars = testutils.securedrop_test_vars testinfra_hosts = [sdvars.app_hostname, sdvars.monitor_hostname] [email protected]('sysctl_opt', [ - ('net.ipv4.conf.all.accept_redirects', 0), - ('net.ipv4.conf.all.accept_source_route', 0), - ('net.ipv4.conf.all.rp_filter', 1), - ('net.ipv4.conf.all.secure_redirects', 0), - ('net.ipv4.conf.all.send_redirects', 0), - ('net.ipv4.conf.default.accept_redirects', 0), - ('net.ipv4.conf.default.accept_source_route', 0), - ('net.ipv4.conf.default.rp_filter', 1), - ('net.ipv4.conf.default.secure_redirects', 0), - ('net.ipv4.conf.default.send_redirects', 0), - ('net.ipv4.icmp_echo_ignore_broadcasts', 1), - ('net.ipv4.ip_forward', 0), - ('net.ipv4.tcp_max_syn_backlog', 4096), - ('net.ipv4.tcp_syncookies', 1), -]) [email protected]( + "sysctl_opt", + [ + ("net.ipv4.conf.all.accept_redirects", 0), + ("net.ipv4.conf.all.accept_source_route", 0), + ("net.ipv4.conf.all.rp_filter", 1), + ("net.ipv4.conf.all.secure_redirects", 0), + ("net.ipv4.conf.all.send_redirects", 0), + ("net.ipv4.conf.default.accept_redirects", 0), + ("net.ipv4.conf.default.accept_source_route", 0), + ("net.ipv4.conf.default.rp_filter", 1), + ("net.ipv4.conf.default.secure_redirects", 0), + ("net.ipv4.conf.default.send_redirects", 0), + ("net.ipv4.icmp_echo_ignore_broadcasts", 1), + ("net.ipv4.ip_forward", 0), + ("net.ipv4.tcp_max_syn_backlog", 4096), + ("net.ipv4.tcp_syncookies", 1), + ], +) def test_sysctl_options(host, sysctl_opt): """ Ensure sysctl flags are set correctly. Most of these checks @@ -41,13 +44,16 @@ def test_dns_setting(host): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - assert f.contains(r'^nameserver 8\.8\.8\.8$') + assert f.contains(r"^nameserver 8\.8\.8\.8$") [email protected]('kernel_module', [ - 'bluetooth', - 'iwlwifi', -]) [email protected]( + "kernel_module", + [ + "bluetooth", + "iwlwifi", + ], +) def test_blacklisted_kernel_modules(host, kernel_module): """ Test that unwanted kernel modules are blacklisted on the system. @@ -67,13 +73,13 @@ def test_swap_disabled(host): Ensure swap space is disabled. Prohibit writing memory to swapfiles to reduce the threat of forensic analysis leaking any sensitive info. """ - hostname = host.check_output('hostname') + hostname = host.check_output("hostname") # Mon doesn't have swap disabled yet - if hostname.startswith('mon'): + if hostname.startswith("mon"): return True - c = host.check_output('swapon --summary') + c = host.check_output("swapon --summary") # A leading slash will indicate full path to a swapfile. assert not re.search("^/", c, re.M) @@ -96,18 +102,21 @@ def test_twofactor_disabled_on_tty(host): assert "pam_ecryptfs.so unwrap" not in pam_auth_file [email protected]('sshd_opts', [ - ('UsePAM', 'no'), - ('ChallengeResponseAuthentication', 'no'), - ('PasswordAuthentication', 'no'), - ('PubkeyAuthentication', 'yes'), - ('RSAAuthentication', 'yes'), - ('AllowGroups', 'ssh'), - ('AllowTcpForwarding', 'no'), - ('AllowAgentForwarding', 'no'), - ('PermitTunnel', 'no'), - ('X11Forwarding', 'no'), -]) [email protected]( + "sshd_opts", + [ + ("UsePAM", "no"), + ("ChallengeResponseAuthentication", "no"), + ("PasswordAuthentication", "no"), + ("PubkeyAuthentication", "yes"), + ("RSAAuthentication", "yes"), + ("AllowGroups", "ssh"), + ("AllowTcpForwarding", "no"), + ("AllowAgentForwarding", "no"), + ("PermitTunnel", "no"), + ("X11Forwarding", "no"), + ], +) def test_sshd_config(host, sshd_opts): """ Let's ensure sshd does not fall back to password-based authentication @@ -119,10 +128,13 @@ def test_sshd_config(host, sshd_opts): assert line in sshd_config_file [email protected]('logfile', [ - '/var/log/auth.log', - '/var/log/syslog', -]) [email protected]( + "logfile", + [ + "/var/log/auth.log", + "/var/log/syslog", + ], +) def test_no_ecrypt_messages_in_logs(host, logfile): """ Ensure pam_ecryptfs is removed from /etc/pam.d/common-auth : not only is @@ -137,18 +149,21 @@ def test_no_ecrypt_messages_in_logs(host, logfile): assert error_message not in f.content_string [email protected]('package', [ - 'aptitude', - 'cloud-init', - 'libiw30', - 'python-is-python2', - 'snapd', - 'torsocks', - 'wireless-tools', - 'wpasupplicant', -]) [email protected]( + "package", + [ + "aptitude", + "cloud-init", + "libiw30", + "python-is-python2", + "snapd", + "torsocks", + "wireless-tools", + "wpasupplicant", + ], +) def test_unused_packages_are_removed(host, package): - """ Check if unused package is present """ + """Check if unused package is present""" assert not host.package(package).is_installed diff --git a/molecule/testinfra/common/test_tor_mirror.py b/molecule/testinfra/common/test_tor_mirror.py --- a/molecule/testinfra/common/test_tor_mirror.py +++ b/molecule/testinfra/common/test_tor_mirror.py @@ -1,14 +1,16 @@ import pytest - import testutils test_vars = testutils.securedrop_test_vars testinfra_hosts = [test_vars.app_hostname, test_vars.monitor_hostname] [email protected]('repo_file', [ - "/etc/apt/sources.list.d/deb_torproject_org_torproject_org.list", -]) [email protected]( + "repo_file", + [ + "/etc/apt/sources.list.d/deb_torproject_org_torproject_org.list", + ], +) def test_tor_mirror_absent(host, repo_file): """ Ensure that neither the Tor Project repo, nor the FPF mirror of the @@ -36,11 +38,14 @@ def test_tor_keyring_absent(host): assert error_text in c.stderr.strip() [email protected]('tor_key_info', [ - "pub 2048R/886DDD89 2009-09-04 [expires: 2020-08-29]", - "Key fingerprint = A3C4 F0F9 79CA A22C DBA8 F512 EE8C BC9E 886D DD89", - "deb.torproject.org archive signing key", -]) [email protected]( + "tor_key_info", + [ + "pub 2048R/886DDD89 2009-09-04 [expires: 2020-08-29]", + "Key fingerprint = A3C4 F0F9 79CA A22C DBA8 F512 EE8C BC9E 886D DD89", + "deb.torproject.org archive signing key", + ], +) def test_tor_mirror_fingerprint(host, tor_key_info): """ Legacy test. The Tor Project key was added to SecureDrop servers @@ -51,16 +56,19 @@ def test_tor_mirror_fingerprint(host, tor_key_info): running instances, the public key will still be present. We'll need to remove those packages separately. """ - c = host.run('apt-key finger') + c = host.run("apt-key finger") assert c.rc == 0 assert tor_key_info not in c.stdout [email protected]('repo_pattern', [ - 'deb.torproject.org', - 'tor-apt.freedom.press', - 'tor-apt-test.freedom.press', -]) [email protected]( + "repo_pattern", + [ + "deb.torproject.org", + "tor-apt.freedom.press", + "tor-apt-test.freedom.press", + ], +) def test_tor_repo_absent(host, repo_pattern): """ Ensure that no apt source list files contain the entry for diff --git a/molecule/testinfra/common/test_user_config.py b/molecule/testinfra/common/test_user_config.py --- a/molecule/testinfra/common/test_user_config.py +++ b/molecule/testinfra/common/test_user_config.py @@ -1,8 +1,7 @@ import re import textwrap -import pytest - +import pytest import testutils sdvars = testutils.securedrop_test_vars @@ -27,15 +26,17 @@ def test_sudoers_config(host): # Using re.search rather than `f.contains` since the basic grep # matching doesn't support PCRE, so `\s` won't work. - assert re.search(r'^Defaults\s+env_reset$', sudoers_config, re.M) - assert re.search(r'^Defaults\s+env_reset$', sudoers_config, re.M) - assert re.search(r'^Defaults\s+mail_badpass$', sudoers_config, re.M) - assert re.search(r'Defaults\s+secure_path="/usr/local/sbin:' - r'/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"', - sudoers_config, re.M) - assert re.search(r'^%sudo\s+ALL=\(ALL\)\s+NOPASSWD:\s+ALL$', - sudoers_config, re.M) - assert re.search(r'Defaults:%sudo\s+!requiretty', sudoers_config, re.M) + assert re.search(r"^Defaults\s+env_reset$", sudoers_config, re.M) + assert re.search(r"^Defaults\s+env_reset$", sudoers_config, re.M) + assert re.search(r"^Defaults\s+mail_badpass$", sudoers_config, re.M) + assert re.search( + r'Defaults\s+secure_path="/usr/local/sbin:' + r'/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"', + sudoers_config, + re.M, + ) + assert re.search(r"^%sudo\s+ALL=\(ALL\)\s+NOPASSWD:\s+ALL$", sudoers_config, re.M) + assert re.search(r"Defaults:%sudo\s+!requiretty", sudoers_config, re.M) def test_sudoers_tmux_env(host): @@ -46,7 +47,7 @@ def test_sudoers_tmux_env(host): the corresponding settings there. """ - host_file = host.file('/etc/profile.d/securedrop_additions.sh') + host_file = host.file("/etc/profile.d/securedrop_additions.sh") expected_content = textwrap.dedent( """\ [[ $- != *i* ]] && return diff --git a/molecule/testinfra/mon/test_mon_network.py b/molecule/testinfra/mon/test_mon_network.py --- a/molecule/testinfra/mon/test_mon_network.py +++ b/molecule/testinfra/mon/test_mon_network.py @@ -1,10 +1,10 @@ +import difflib import io import os -import difflib -import pytest -from jinja2 import Template +import pytest import testutils +from jinja2 import Template securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] @@ -17,14 +17,14 @@ def test_mon_iptables_rules(host): # Build a dict of variables to pass to jinja for iptables comparison kwargs = dict( - app_ip=os.environ.get('APP_IP', securedrop_test_vars.app_ip), - default_interface=host.check_output( - "ip r | head -n 1 | awk '{ print $5 }'"), + app_ip=os.environ.get("APP_IP", securedrop_test_vars.app_ip), + default_interface=host.check_output("ip r | head -n 1 | awk '{ print $5 }'"), tor_user_id=host.check_output("id -u debian-tor"), time_service_user=host.check_output("id -u systemd-timesync"), ssh_group_gid=host.check_output("getent group ssh | cut -d: -f3"), postfix_user_id=host.check_output("id -u postfix"), - dns_server=securedrop_test_vars.dns_server) + dns_server=securedrop_test_vars.dns_server, + ) # Required for testing under Qubes. if local.interface("eth0").exists: @@ -34,11 +34,11 @@ def test_mon_iptables_rules(host): iptables = r"iptables-save | sed 's/ \[[0-9]*\:[0-9]*\]//g' | egrep -v '^#'" environment = os.environ.get("SECUREDROP_TESTINFRA_TARGET_HOST", "staging") iptables_file = "{}/iptables-mon-{}.j2".format( - os.path.dirname(os.path.abspath(__file__)), - environment) + os.path.dirname(os.path.abspath(__file__)), environment + ) # template out a local iptables jinja file - jinja_iptables = Template(io.open(iptables_file, 'r').read()) + jinja_iptables = Template(io.open(iptables_file, "r").read()) iptables_expected = jinja_iptables.render(**kwargs) with host.sudo(): @@ -46,8 +46,9 @@ def test_mon_iptables_rules(host): iptables = host.check_output(iptables) # print diff comparison (only shows up in pytests if test fails or # verbosity turned way up) - for iptablesdiff in difflib.context_diff(iptables_expected.split('\n'), - iptables.split('\n')): + for iptablesdiff in difflib.context_diff( + iptables_expected.split("\n"), iptables.split("\n") + ): print(iptablesdiff) # Conduct the string comparison of the expected and actual iptables # ruleset @@ -55,11 +56,14 @@ def test_mon_iptables_rules(host): @pytest.mark.skip_in_prod [email protected]('ossec_service', [ - dict(host="0.0.0.0", proto="tcp", port=22, listening=True), - dict(host="0.0.0.0", proto="udp", port=1514, listening=True), - dict(host="0.0.0.0", proto="tcp", port=1515, listening=False), -]) [email protected]( + "ossec_service", + [ + dict(host="0.0.0.0", proto="tcp", port=22, listening=True), + dict(host="0.0.0.0", proto="udp", port=1514, listening=True), + dict(host="0.0.0.0", proto="tcp", port=1515, listening=False), + ], +) def test_listening_ports(host, ossec_service): """ Ensure the OSSEC-related services are listening on the @@ -73,5 +77,4 @@ def test_listening_ports(host, ossec_service): """ socket = "{proto}://{host}:{port}".format(**ossec_service) with host.sudo(): - assert (host.socket(socket).is_listening == - ossec_service['listening']) + assert host.socket(socket).is_listening == ossec_service["listening"] diff --git a/molecule/testinfra/mon/test_ossec_ruleset.py b/molecule/testinfra/mon/test_ossec_ruleset.py --- a/molecule/testinfra/mon/test_ossec_ruleset.py +++ b/molecule/testinfra/mon/test_ossec_ruleset.py @@ -1,6 +1,6 @@ -import pytest import re +import pytest import testutils sdvars = testutils.securedrop_test_vars @@ -9,21 +9,17 @@ rule_id_regex = re.compile(r"Rule id: '(\d+)'") [email protected]('log_event', - sdvars.log_events_without_ossec_alerts) [email protected]("log_event", sdvars.log_events_without_ossec_alerts) def test_ossec_false_positives_suppressed(host, log_event): with host.sudo(): - c = host.run('echo "{}" | /var/ossec/bin/ossec-logtest'.format( - log_event["alert"])) + c = host.run('echo "{}" | /var/ossec/bin/ossec-logtest'.format(log_event["alert"])) assert "Alert to be generated" not in c.stderr [email protected]('log_event', - sdvars.log_events_with_ossec_alerts) [email protected]("log_event", sdvars.log_events_with_ossec_alerts) def test_ossec_expected_alerts_are_present(host, log_event): with host.sudo(): - c = host.run('echo "{}" | /var/ossec/bin/ossec-logtest'.format( - log_event["alert"])) + c = host.run('echo "{}" | /var/ossec/bin/ossec-logtest'.format(log_event["alert"])) assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == log_event["level"] diff --git a/molecule/testinfra/mon/test_ossec_server.py b/molecule/testinfra/mon/test_ossec_server.py --- a/molecule/testinfra/mon/test_ossec_server.py +++ b/molecule/testinfra/mon/test_ossec_server.py @@ -1,6 +1,6 @@ import os -import pytest +import pytest import testutils securedrop_test_vars = testutils.securedrop_test_vars @@ -15,8 +15,8 @@ def test_ossec_connectivity(host): that list to make sure it's the host we expect. """ desired_output = "{}-{} is available.".format( - securedrop_test_vars.app_hostname, - os.environ.get('APP_IP', securedrop_test_vars.app_ip)) + securedrop_test_vars.app_hostname, os.environ.get("APP_IP", securedrop_test_vars.app_ip) + ) with host.sudo(): c = host.check_output("/var/ossec/bin/list_agents -a") assert c == desired_output @@ -33,10 +33,13 @@ def test_ossec_service_start_style(host): # Permissions don't match between Ansible and OSSEC deb packages postinst. @pytest.mark.xfail [email protected]('keyfile', [ - '/var/ossec/etc/sslmanager.key', - '/var/ossec/etc/sslmanager.cert', -]) [email protected]( + "keyfile", + [ + "/var/ossec/etc/sslmanager.key", + "/var/ossec/etc/sslmanager.cert", + ], +) def test_ossec_keyfiles(host, keyfile): """ Ensure that the OSSEC transport key pair exists. These keys are used @@ -71,7 +74,7 @@ def test_procmail_log(host): def test_ossec_authd(host): - """ Ensure that authd is not running """ + """Ensure that authd is not running""" with host.sudo(): c = host.run("pgrep ossec-authd") assert c.stdout == "" @@ -79,14 +82,14 @@ def test_ossec_authd(host): def test_hosts_files(host): - """ Ensure host files mapping are in place """ - f = host.file('/etc/hosts') + """Ensure host files mapping are in place""" + f = host.file("/etc/hosts") - app_ip = os.environ.get('APP_IP', securedrop_test_vars.app_ip) + app_ip = os.environ.get("APP_IP", securedrop_test_vars.app_ip) app_host = securedrop_test_vars.app_hostname - assert f.contains('^127.0.0.1.*localhost') - assert f.contains(r'^{}\s*{}$'.format(app_ip, app_host)) + assert f.contains("^127.0.0.1.*localhost") + assert f.contains(r"^{}\s*{}$".format(app_ip, app_host)) def test_ossec_log_contains_no_malformed_events(host): @@ -105,5 +108,5 @@ def test_ossec_log_contains_no_malformed_events(host): def test_regression_hosts(host): - """ Regression test to check for duplicate entries. """ + """Regression test to check for duplicate entries.""" assert host.check_output("uniq --repeated /etc/hosts") == "" diff --git a/molecule/testinfra/mon/test_postfix.py b/molecule/testinfra/mon/test_postfix.py --- a/molecule/testinfra/mon/test_postfix.py +++ b/molecule/testinfra/mon/test_postfix.py @@ -1,19 +1,22 @@ import re -import pytest +import pytest import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] [email protected]('header', [ - '/^X-Originating-IP:/ IGNORE', - '/^X-Mailer:/ IGNORE', - '/^Mime-Version:/ IGNORE', - '/^User-Agent:/ IGNORE', - '/^Received:/ IGNORE', -]) [email protected]( + "header", + [ + "/^X-Originating-IP:/ IGNORE", + "/^X-Mailer:/ IGNORE", + "/^Mime-Version:/ IGNORE", + "/^User-Agent:/ IGNORE", + "/^Received:/ IGNORE", + ], +) def test_postfix_headers(host, header): """ Ensure postfix header filters are set correctly. Common mail headers @@ -23,7 +26,7 @@ def test_postfix_headers(host, header): f = host.file("/etc/postfix/header_checks") assert f.is_file assert f.mode == 0o644 - regex = '^{}$'.format(re.escape(header)) + regex = "^{}$".format(re.escape(header)) assert re.search(regex, f.content_string, re.M) @@ -42,7 +45,8 @@ def test_postfix_generic_maps(host): ) assert host.file("/etc/postfix/main.cf").contains("^smtp_generic_maps") assert host.file("/etc/postfix/main.cf").contains( - "^smtpd_recipient_restrictions = reject_unauth_destination") + "^smtpd_recipient_restrictions = reject_unauth_destination" + ) def test_postfix_service(host): diff --git a/molecule/testinfra/ossec/test_journalist_mail.py b/molecule/testinfra/ossec/test_journalist_mail.py --- a/molecule/testinfra/ossec/test_journalist_mail.py +++ b/molecule/testinfra/ossec/test_journalist_mail.py @@ -1,8 +1,8 @@ -import pytest import os -import testinfra import time +import pytest +import testinfra # DRY declaration of why we're skipping all these tests. # For details, see https://github.com/freedomofpress/securedrop/issues/3689 @@ -10,10 +10,9 @@ class TestBase(object): - @pytest.fixture(autouse=True) def only_mon_staging_sudo(self, host): - if host.backend.host != 'mon-staging': + if host.backend.host != "mon-staging": pytest.skip() with host.sudo(): @@ -21,7 +20,7 @@ def only_mon_staging_sudo(self, host): def ansible(self, host, module, parameters): r = host.ansible(module, parameters, check=False) - assert 'exception' not in r + assert "exception" not in r def run(self, host, cmd): print(host.backend.host + " running: " + cmd) @@ -50,86 +49,77 @@ def wait_for_command(self, host, cmd): def service_started(self, host, name): assert self.run(host, "service {name} start".format(name=name)) assert self.wait_for_command( - host, - "service {name} status | grep -q 'is running'".format(name=name)) + host, "service {name} status | grep -q 'is running'".format(name=name) + ) def service_restarted(self, host, name): assert self.run(host, "service {name} restart".format(name=name)) assert self.wait_for_command( - host, - "service {name} status | grep -q 'is running'".format(name=name)) + host, "service {name} status | grep -q 'is running'".format(name=name) + ) def service_stopped(self, host, name): assert self.run(host, "service {name} stop".format(name=name)) assert self.wait_for_command( - host, - "service {name} status | grep -q 'not running'".format(name=name)) + host, "service {name} status | grep -q 'not running'".format(name=name) + ) class TestJournalistMail(TestBase): - @pytest.mark.skip(reason=SKIP_REASON) def test_procmail(self, host): self.service_started(host, "postfix") for (destination, f) in ( - ('journalist', 'alert-journalist-one.txt'), - ('journalist', 'alert-journalist-two.txt'), - ('ossec', 'alert-ossec.txt')): + ("journalist", "alert-journalist-one.txt"), + ("journalist", "alert-journalist-two.txt"), + ("ossec", "alert-ossec.txt"), + ): # Look up CWD, in case tests move in the future current_dir = os.path.dirname(os.path.abspath(__file__)) - self.ansible(host, "copy", - "dest=/tmp/{f} src={d}/{f}".format(f=f, - d=current_dir)) - assert self.run(host, - "/var/ossec/process_submissions_today.sh forget") + self.ansible(host, "copy", "dest=/tmp/{f} src={d}/{f}".format(f=f, d=current_dir)) + assert self.run(host, "/var/ossec/process_submissions_today.sh forget") assert self.run(host, "postsuper -d ALL") - assert self.run( - host, - "cat /tmp/{f} | mail -s 'abc' root@localhost".format(f=f)) + assert self.run(host, "cat /tmp/{f} | mail -s 'abc' root@localhost".format(f=f)) assert self.wait_for_command( - host, - "mailq | grep -q {destination}@ossec.test".format( - destination=destination)) + host, "mailq | grep -q {destination}@ossec.test".format(destination=destination) + ) self.service_stopped(host, "postfix") @pytest.mark.skip(reason=SKIP_REASON) def test_process_submissions_today(self, host): - assert self.run(host, - "/var/ossec/process_submissions_today.sh " - "test_handle_notification") - assert self.run(host, - "/var/ossec/process_submissions_today.sh " - "test_modified_in_the_past_24h") + assert self.run(host, "/var/ossec/process_submissions_today.sh " "test_handle_notification") + assert self.run( + host, "/var/ossec/process_submissions_today.sh " "test_modified_in_the_past_24h" + ) @pytest.mark.skip(reason=SKIP_REASON) def test_send_encrypted_alert(self, host): self.service_started(host, "postfix") - src = ("../../install_files/ansible-base/roles/ossec/files/" - "test_admin_key.sec") - self.ansible(host, "copy", - "dest=/tmp/test_admin_key.sec src={src}".format(src=src)) + src = "../../install_files/ansible-base/roles/ossec/files/" "test_admin_key.sec" + self.ansible(host, "copy", "dest=/tmp/test_admin_key.sec src={src}".format(src=src)) - self.run(host, "gpg --homedir /var/ossec/.gnupg" - " --import /tmp/test_admin_key.sec") + self.run(host, "gpg --homedir /var/ossec/.gnupg" " --import /tmp/test_admin_key.sec") def trigger(who, payload): - assert self.run( - host, "! mailq | grep -q {who}@ossec.test".format(who=who)) + assert self.run(host, "! mailq | grep -q {who}@ossec.test".format(who=who)) assert self.run( host, """ ( echo 'Subject: TEST' ; echo ; echo -e '{payload}' ) | \ /var/ossec/send_encrypted_alarm.sh {who} - """.format(who=who, payload=payload)) - assert self.wait_for_command( - host, "mailq | grep -q {who}@ossec.test".format(who=who)) + """.format( + who=who, payload=payload + ), + ) + assert self.wait_for_command(host, "mailq | grep -q {who}@ossec.test".format(who=who)) # # encrypted mail to journalist or ossec contact # for (who, payload, expected) in ( - ('journalist', 'JOURNALISTPAYLOAD', 'JOURNALISTPAYLOAD'), - ('ossec', 'OSSECPAYLOAD', 'OSSECPAYLOAD')): + ("journalist", "JOURNALISTPAYLOAD", "JOURNALISTPAYLOAD"), + ("ossec", "OSSECPAYLOAD", "OSSECPAYLOAD"), + ): assert self.run(host, "postsuper -d ALL") trigger(who, payload) assert self.run( @@ -139,20 +129,24 @@ def trigger(who, payload): postcat -q $job | tee /dev/stderr | \ gpg --homedir /var/ossec/.gnupg --decrypt 2>&1 | \ grep -q {expected} - """.format(expected=expected)) + """.format( + expected=expected + ), + ) # # failure to encrypt must trigger an emergency mail to ossec contact # try: assert self.run(host, "postsuper -d ALL") assert self.run(host, "mv /usr/bin/gpg /usr/bin/gpg.save") - trigger(who, 'MYGREATPAYLOAD') + trigger(who, "MYGREATPAYLOAD") assert self.run( host, """ job=$(mailq | sed -n -e '2p' | cut -f1 -d ' ') postcat -q $job | grep -q 'Failed to encrypt OSSEC alert' - """) + """, + ) finally: assert self.run(host, "mv /usr/bin/gpg.save /usr/bin/gpg") self.service_stopped(host, "postfix") @@ -169,24 +163,28 @@ def test_missing_journalist_alert(self, host): bash -x /var/ossec/send_encrypted_alarm.sh journalist | \ tee /dev/stderr | \ grep -q 'no notification sent' - """) + """, + ) # https://ossec-docs.readthedocs.io/en/latest/manual/rules-decoders/testing.html @pytest.mark.skip(reason=SKIP_REASON) def test_ossec_rule_journalist(self, host): - assert self.run(host, """ + assert self.run( + host, + """ set -ex l="ossec: output: 'head -1 /var/lib/securedrop/submissions_today.txt" echo "$l" | /var/ossec/bin/ossec-logtest echo "$l" | /var/ossec/bin/ossec-logtest -U '400600:1:ossec' - """) + """, + ) @pytest.mark.skip(reason=SKIP_REASON) def test_journalist_mail_notification(self, host): mon = host app = testinfra.host.Host.get_host( - 'ansible://app-staging', - ansible_inventory=host.backend.ansible_inventory) + "ansible://app-staging", ansible_inventory=host.backend.ansible_inventory + ) # # run ossec & postfix on mon # @@ -197,11 +195,14 @@ def test_journalist_mail_notification(self, host): # ensure the submission_today.txt file exists # with app.sudo(): - assert self.run(app, """ + assert self.run( + app, + """ cd /var/www/securedrop ./manage.py were-there-submissions-today test -f /var/lib/securedrop/submissions_today.txt - """) + """, + ) # # empty the mailq on mon in case there were leftovers @@ -223,27 +224,25 @@ def test_journalist_mail_notification(self, host): # # wait until at exactly one notification is sent # - assert self.wait_for_command( - mon, - "mailq | grep -q [email protected]") - assert self.run( - mon, - "test 1 = $(mailq | grep [email protected] | wc -l)") + assert self.wait_for_command(mon, "mailq | grep -q [email protected]") + assert self.run(mon, "test 1 = $(mailq | grep [email protected] | wc -l)") assert self.run( - mon, - "grep --count 'notification suppressed' /var/log/syslog " - "> /tmp/before") + mon, "grep --count 'notification suppressed' /var/log/syslog " "> /tmp/before" + ) # # The second notification within less than 24h is suppressed # with app.sudo(): self.service_restarted(app, "ossec") - assert self.wait_for_command(mon, """ + assert self.wait_for_command( + mon, + """ grep --count 'notification suppressed' /var/log/syslog > /tmp/after test $(cat /tmp/before) -lt $(cat /tmp/after) - """) + """, + ) # # teardown the ossec and postfix on mon and app diff --git a/securedrop/tests/__init__.py b/securedrop/tests/__init__.py --- a/securedrop/tests/__init__.py +++ b/securedrop/tests/__init__.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- +import os +import sys from os.path import abspath, dirname, join, realpath + import pytest -import sys -import os # WARNING: This variable must be set before any import of the securedrop code/app # or most tests will fail @@ -11,8 +12,8 @@ # The tests directory should be adjacent to the securedrop directory. By adding # the securedrop directory to sys.path here, all test modules are able to # directly import modules in the securedrop directory. -sys.path.append(abspath(join(dirname(realpath(__file__)), '..', 'securedrop'))) +sys.path.append(abspath(join(dirname(realpath(__file__)), "..", "securedrop"))) # This ensures we get pytest's more detailed assertion output in helper functions -pytest.register_assert_rewrite('tests.functional.journalist_navigation_steps') -pytest.register_assert_rewrite('tests.functional.source_navigation_steps') +pytest.register_assert_rewrite("tests.functional.journalist_navigation_steps") +pytest.register_assert_rewrite("tests.functional.source_navigation_steps") diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -1,47 +1,37 @@ # -*- coding: utf-8 -*- import configparser +import json +import logging +import os +import shutil +import signal +import subprocess +from os import path from pathlib import Path from tempfile import TemporaryDirectory - -from typing import Any, Generator, Tuple - +from typing import Any, Dict, Generator, Tuple from unittest import mock from unittest.mock import PropertyMock +import models import pretty_bad_protocol as gnupg -import logging - -from flask import Flask -from hypothesis import settings -import os -import json import psutil import pytest -import shutil -import signal -import subprocess - -from flask import url_for -from pyotp import TOTP -from typing import Dict - import sdconfig +from db import db from encryption import EncryptionManager - +from flask import Flask, url_for +from hypothesis import settings +from journalist_app import create_app as create_journalist_app from passphrases import PassphraseGenerator +from pyotp import TOTP +from sdconfig import SDConfig +from sdconfig import config as original_config +from source_app import create_app as create_source_app from source_user import _SourceScryptManager, create_source_user - -from sdconfig import SDConfig, config as original_config - from store import Storage -from os import path - -from db import db -from journalist_app import create_app as create_journalist_app -import models -from source_app import create_app as create_source_app from . import utils from .utils import i18n @@ -49,10 +39,10 @@ # Ideally this constant would be provided by a test harness. # It has been intentionally omitted from `config.py.example` # in order to isolate the test vars from prod vars. -TEST_WORKER_PIDFILE = '/tmp/securedrop_test_worker.pid' +TEST_WORKER_PIDFILE = "/tmp/securedrop_test_worker.pid" # Quiet down gnupg output. (See Issue #2595) -GNUPG_LOG_LEVEL = os.environ.get('GNUPG_LOG_LEVEL', "ERROR") +GNUPG_LOG_LEVEL = os.environ.get("GNUPG_LOG_LEVEL", "ERROR") gnupg._util.log.setLevel(getattr(logging, GNUPG_LOG_LEVEL, logging.ERROR)) # `hypothesis` sets a default deadline of 200 milliseconds before failing tests, @@ -62,8 +52,9 @@ def pytest_addoption(parser): - parser.addoption("--page-layout", action="store_true", - default=False, help="run page layout tests") + parser.addoption( + "--page-layout", action="store_true", default=False, help="run page layout tests" + ) def pytest_configure(config): @@ -73,9 +64,7 @@ def pytest_configure(config): def pytest_collection_modifyitems(config, items): if config.getoption("--page-layout"): return - skip_page_layout = pytest.mark.skip( - reason="need --page-layout option to run page layout tests" - ) + skip_page_layout = pytest.mark.skip(reason="need --page-layout option to run page layout tests") for item in items: if "pagelayout" in item.keywords: item.add_marker(skip_page_layout) @@ -87,12 +76,13 @@ def hardening(request): def finalizer(): models.LOGIN_HARDENING = hardening + request.addfinalizer(finalizer) models.LOGIN_HARDENING = True return None [email protected](scope='session') [email protected](scope="session") def setUpTearDown(): _start_test_rqworker(original_config) yield @@ -106,7 +96,7 @@ def insecure_scrypt() -> Generator[None, None, None]: salt_for_gpg_secret=b"abcd", salt_for_filesystem_id=b"1234", # Insecure but fast - scrypt_n=2 ** 1, + scrypt_n=2**1, scrypt_r=1, scrypt_p=1, ) @@ -185,29 +175,29 @@ def config( yield config [email protected](scope='function') [email protected](scope="function") def alembic_config(config: SDConfig) -> str: - base_dir = path.join(path.dirname(__file__), '..') - migrations_dir = path.join(base_dir, 'alembic') + base_dir = path.join(path.dirname(__file__), "..") + migrations_dir = path.join(base_dir, "alembic") ini = configparser.ConfigParser() - ini.read(path.join(base_dir, 'alembic.ini')) + ini.read(path.join(base_dir, "alembic.ini")) - ini.set('alembic', 'script_location', path.join(migrations_dir)) - ini.set('alembic', 'sqlalchemy.url', config.DATABASE_URI) + ini.set("alembic", "script_location", path.join(migrations_dir)) + ini.set("alembic", "sqlalchemy.url", config.DATABASE_URI) - alembic_path = path.join(config.SECUREDROP_DATA_ROOT, 'alembic.ini') - with open(alembic_path, 'w') as f: + alembic_path = path.join(config.SECUREDROP_DATA_ROOT, "alembic.ini") + with open(alembic_path, "w") as f: ini.write(f) return alembic_path [email protected](scope='function') -def app_storage(config: SDConfig) -> 'Storage': [email protected](scope="function") +def app_storage(config: SDConfig) -> "Storage": return Storage(config.STORE_DIR, config.TEMP_DIR) [email protected](scope='function') [email protected](scope="function") def source_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, None]: config.SOURCE_APP_FLASK_CONFIG_CLS.TESTING = True config.SOURCE_APP_FLASK_CONFIG_CLS.USE_X_SENDFILE = False @@ -218,7 +208,7 @@ def source_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = app_storage app = create_source_app(config) - app.config['SERVER_NAME'] = 'localhost.localdomain' + app.config["SERVER_NAME"] = "localhost.localdomain" with app.app_context(): db.create_all() try: @@ -228,7 +218,7 @@ def source_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, db.drop_all() [email protected](scope='function') [email protected](scope="function") def journalist_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, None]: config.JOURNALIST_APP_FLASK_CONFIG_CLS.TESTING = True config.JOURNALIST_APP_FLASK_CONFIG_CLS.USE_X_SENDFILE = False @@ -239,7 +229,7 @@ def journalist_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, N with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = app_storage app = create_journalist_app(config) - app.config['SERVER_NAME'] = 'localhost.localdomain' + app.config["SERVER_NAME"] = "localhost.localdomain" with app.app_context(): db.create_all() try: @@ -249,36 +239,40 @@ def journalist_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, N db.drop_all() [email protected](scope='function') [email protected](scope="function") def test_journo(journalist_app: Flask) -> Dict[str, Any]: with journalist_app.app_context(): user, password = utils.db_helper.init_journalist(is_admin=False) username = user.username otp_secret = user.otp_secret - return {'journalist': user, - 'username': username, - 'password': password, - 'otp_secret': otp_secret, - 'id': user.id, - 'uuid': user.uuid, - 'first_name': user.first_name, - 'last_name': user.last_name} + return { + "journalist": user, + "username": username, + "password": password, + "otp_secret": otp_secret, + "id": user.id, + "uuid": user.uuid, + "first_name": user.first_name, + "last_name": user.last_name, + } [email protected](scope='function') [email protected](scope="function") def test_admin(journalist_app: Flask) -> Dict[str, Any]: with journalist_app.app_context(): user, password = utils.db_helper.init_journalist(is_admin=True) username = user.username otp_secret = user.otp_secret - return {'admin': user, - 'username': username, - 'password': password, - 'otp_secret': otp_secret, - 'id': user.id} + return { + "admin": user, + "username": username, + "password": password, + "otp_secret": otp_secret, + "id": user.id, + } [email protected](scope='function') [email protected](scope="function") def test_source(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: with journalist_app.app_context(): passphrase = PassphraseGenerator.get_default().generate_passphrase() @@ -289,81 +283,102 @@ def test_source(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: ) EncryptionManager.get_default().generate_source_key_pair(source_user) source = source_user.get_db_record() - return {'source_user': source_user, - # TODO(AD): Eventually the next keys could be removed as they are in source_user - 'source': source, - 'codename': passphrase, - 'filesystem_id': source_user.filesystem_id, - 'uuid': source.uuid, - 'id': source.id} + return { + "source_user": source_user, + # TODO(AD): Eventually the next keys could be removed as they are in source_user + "source": source, + "codename": passphrase, + "filesystem_id": source_user.filesystem_id, + "uuid": source.uuid, + "id": source.id, + } [email protected](scope='function') [email protected](scope="function") def test_submissions(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: with journalist_app.app_context(): source, codename = utils.db_helper.init_source(app_storage) utils.db_helper.submit(app_storage, source, 2) - return {'source': source, - 'codename': codename, - 'filesystem_id': source.filesystem_id, - 'uuid': source.uuid, - 'submissions': source.submissions} + return { + "source": source, + "codename": codename, + "filesystem_id": source.filesystem_id, + "uuid": source.uuid, + "submissions": source.submissions, + } [email protected](scope='function') [email protected](scope="function") def test_files(journalist_app, test_journo, app_storage): with journalist_app.app_context(): source, codename = utils.db_helper.init_source(app_storage) utils.db_helper.submit(app_storage, source, 2, submission_type="file") - utils.db_helper.reply(app_storage, test_journo['journalist'], source, 1) - return {'source': source, - 'codename': codename, - 'filesystem_id': source.filesystem_id, - 'uuid': source.uuid, - 'submissions': source.submissions, - 'replies': source.replies} + utils.db_helper.reply(app_storage, test_journo["journalist"], source, 1) + return { + "source": source, + "codename": codename, + "filesystem_id": source.filesystem_id, + "uuid": source.uuid, + "submissions": source.submissions, + "replies": source.replies, + } [email protected](scope='function') [email protected](scope="function") def test_files_deleted_journalist(journalist_app, test_journo, app_storage): with journalist_app.app_context(): source, codename = utils.db_helper.init_source(app_storage) utils.db_helper.submit(app_storage, source, 2) - test_journo['journalist'] + test_journo["journalist"] juser, _ = utils.db_helper.init_journalist("f", "l", is_admin=False) utils.db_helper.reply(app_storage, juser, source, 1) utils.db_helper.delete_journalist(juser) - return {'source': source, - 'codename': codename, - 'filesystem_id': source.filesystem_id, - 'uuid': source.uuid, - 'submissions': source.submissions, - 'replies': source.replies} + return { + "source": source, + "codename": codename, + "filesystem_id": source.filesystem_id, + "uuid": source.uuid, + "submissions": source.submissions, + "replies": source.replies, + } [email protected](scope='function') [email protected](scope="function") def journalist_api_token(journalist_app, test_journo): with journalist_app.test_client() as app: - valid_token = TOTP(test_journo['otp_secret']).now() - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'username': test_journo['username'], - 'passphrase': test_journo['password'], - 'one_time_code': valid_token}), - headers=utils.api_helper.get_api_headers()) - return response.json['token'] + valid_token = TOTP(test_journo["otp_secret"]).now() + response = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + "one_time_code": valid_token, + } + ), + headers=utils.api_helper.get_api_headers(), + ) + return response.json["token"] def _start_test_rqworker(config: SDConfig) -> None: if not psutil.pid_exists(_get_pid_from_file(TEST_WORKER_PIDFILE)): - tmp_logfile = open('/tmp/test_rqworker.log', 'w') - subprocess.Popen(['rqworker', config.RQ_WORKER_NAME, - '-P', config.SECUREDROP_ROOT, - '--pid', TEST_WORKER_PIDFILE, - '--logging_level', 'DEBUG', - '-v'], - stdout=tmp_logfile, - stderr=subprocess.STDOUT) + tmp_logfile = open("/tmp/test_rqworker.log", "w") + subprocess.Popen( + [ + "rqworker", + config.RQ_WORKER_NAME, + "-P", + config.SECUREDROP_ROOT, + "--pid", + TEST_WORKER_PIDFILE, + "--logging_level", + "DEBUG", + "-v", + ], + stdout=tmp_logfile, + stderr=subprocess.STDOUT, + ) def _stop_test_rqworker() -> None: diff --git a/securedrop/tests/functional/app_navigators.py b/securedrop/tests/functional/app_navigators.py --- a/securedrop/tests/functional/app_navigators.py +++ b/securedrop/tests/functional/app_navigators.py @@ -2,24 +2,19 @@ import tempfile import time from contextlib import contextmanager - -from typing import Optional, Dict, Iterable, Generator, List +from typing import Dict, Generator, Iterable, List, Optional import pyotp import requests +from encryption import EncryptionManager +from selenium.common.exceptions import NoAlertPresentException, WebDriverException +from selenium.webdriver.common.by import By from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement - -from selenium.common.exceptions import NoAlertPresentException -from selenium.common.exceptions import WebDriverException -from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait - -from tests.functional.web_drivers import get_web_driver, WebDriverTypeEnum - -from encryption import EncryptionManager from tests.functional.tor_utils import proxies_for_url +from tests.functional.web_drivers import WebDriverTypeEnum, get_web_driver from tests.test_encryption import import_journalist_private_key diff --git a/securedrop/tests/functional/conftest.py b/securedrop/tests/functional/conftest.py --- a/securedrop/tests/functional/conftest.py +++ b/securedrop/tests/functional/conftest.py @@ -1,23 +1,22 @@ import multiprocessing +import socket +import time from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timezone from io import BytesIO from pathlib import Path -from typing import Generator, Tuple, Optional, Callable, Any +from typing import Any, Callable, Generator, Optional, Tuple from uuid import uuid4 -import requests -from selenium.webdriver.firefox.webdriver import WebDriver - import pytest +import requests from models import Journalist +from selenium.webdriver.firefox.webdriver import WebDriver from tests.functional.db_session import get_database_session from tests.functional.factories import SecureDropConfigFactory from tests.functional.sd_config_v2 import SecureDropConfig from tests.functional.web_drivers import WebDriverTypeEnum, get_web_driver -import socket -import time # Function-scoped so that tests can be run in parallel if needed @@ -268,12 +267,12 @@ def _create_source_and_submission(config_in_use: SecureDropConfig) -> Path: """ # This function will be called in a separate Process that runs the app # Hence the late imports - from store import Storage, add_checksum_for_file + from encryption import EncryptionManager + from models import Submission + from passphrases import PassphraseGenerator from source_user import create_source_user + from store import Storage, add_checksum_for_file from tests.functional.db_session import get_database_session - from passphrases import PassphraseGenerator - from models import Submission - from encryption import EncryptionManager # Create a source passphrase = PassphraseGenerator.get_default().generate_passphrase() diff --git a/securedrop/tests/functional/db_session.py b/securedrop/tests/functional/db_session.py --- a/securedrop/tests/functional/db_session.py +++ b/securedrop/tests/functional/db_session.py @@ -1,11 +1,10 @@ from contextlib import contextmanager from typing import Generator -from sqlalchemy.orm.session import Session - from db import db from flask import Flask from flask_sqlalchemy import SQLAlchemy +from sqlalchemy.orm.session import Session @contextmanager @@ -15,8 +14,8 @@ def _get_fake_db_module( # flask-sqlalchemy's API only allows DB access via a Flask app # So we create a fake Flask app just so we can get a connection to the DB app_for_db_connection = Flask("FakeAppForDbConnection") - app_for_db_connection.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app_for_db_connection.config['SQLALCHEMY_DATABASE_URI'] = database_uri + app_for_db_connection.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app_for_db_connection.config["SQLALCHEMY_DATABASE_URI"] = database_uri db.init_app(app_for_db_connection) with app_for_db_connection.app_context(): diff --git a/securedrop/tests/functional/factories.py b/securedrop/tests/functional/factories.py --- a/securedrop/tests/functional/factories.py +++ b/securedrop/tests/functional/factories.py @@ -1,11 +1,10 @@ -from pathlib import Path import secrets import shutil import subprocess -from tests.functional.sd_config_v2 import DEFAULT_SECUREDROP_ROOT, FlaskAppConfig -from tests.functional.sd_config_v2 import SecureDropConfig +from pathlib import Path from tests.functional.db_session import _get_fake_db_module +from tests.functional.sd_config_v2 import DEFAULT_SECUREDROP_ROOT, FlaskAppConfig, SecureDropConfig def _generate_random_token() -> str: @@ -54,7 +53,7 @@ def create( SOURCE_APP_FLASK_CONFIG_CLS=FlaskAppConfigFactory.create(SESSION_COOKIE_NAME="ss"), SCRYPT_GPG_PEPPER=_generate_random_token(), SCRYPT_ID_PEPPER=_generate_random_token(), - SCRYPT_PARAMS=dict(N=2 ** 14, r=8, p=1), + SCRYPT_PARAMS=dict(N=2**14, r=8, p=1), WORKER_PIDFILE="/tmp/securedrop_test_worker.pid", RQ_WORKER_NAME="test", NOUNS=str(NOUNS), diff --git a/securedrop/tests/functional/functional_test.py b/securedrop/tests/functional/functional_test.py --- a/securedrop/tests/functional/functional_test.py +++ b/securedrop/tests/functional/functional_test.py @@ -10,37 +10,29 @@ import traceback from datetime import datetime from multiprocessing import Process -from os.path import abspath -from os.path import dirname -from os.path import expanduser -from os.path import join -from os.path import realpath +from os.path import abspath, dirname, expanduser, join, realpath +import journalist_app import mock import pyotp import pytest import requests +import source_app import tbselenium.common as cm +import tests.utils.env as env +from db import db +from encryption import EncryptionManager +from models import Journalist from selenium import webdriver -from selenium.common.exceptions import NoAlertPresentException -from selenium.common.exceptions import WebDriverException +from selenium.common.exceptions import NoAlertPresentException, WebDriverException from selenium.webdriver.common.by import By from selenium.webdriver.remote.remote_connection import LOGGER from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait +from source_user import _SourceScryptManager from sqlalchemy.exc import IntegrityError from tbselenium.tbdriver import TorBrowserDriver -from tbselenium.utils import set_security_level -from tbselenium.utils import SECURITY_LOW, SECURITY_MEDIUM, SECURITY_HIGH - -import journalist_app -import source_app -import tests.utils.env as env -from db import db -from encryption import EncryptionManager -from models import Journalist -from source_user import _SourceScryptManager - +from tbselenium.utils import SECURITY_HIGH, SECURITY_LOW, SECURITY_MEDIUM, set_security_level LOGFILE_PATH = abspath(join(dirname(realpath(__file__)), "../log/driver.log")) FIREFOX_PATH = "/usr/bin/firefox/firefox" @@ -89,7 +81,7 @@ def set_tbb_securitylevel(self, level): if level not in {SECURITY_HIGH, SECURITY_MEDIUM, SECURITY_LOW}: raise ValueError("Invalid Tor Browser security setting: " + str(level)) - if hasattr(self, 'torbrowser_driver'): + if hasattr(self, "torbrowser_driver"): set_security_level(self.torbrowser_driver, level) def create_torbrowser_driver(self): @@ -169,6 +161,7 @@ def switch_to_torbrowser_driver(self): def start_source_server(self, source_port): from sdconfig import config + config.SESSION_EXPIRATION_MINUTES = self.session_expiration / 60.0 self.source_app.run(port=source_port, debug=True, use_reloader=False, threaded=True) @@ -214,6 +207,7 @@ def sd_servers(self, setup_journalist_key_and_gpg_folder): self.journalist_location = "http://127.0.0.1:%d" % journalist_port from sdconfig import config + self.source_app = source_app.create_app(config) self.journalist_app = journalist_app.create_app(config) self.journalist_app.config["WTF_CSRF_ENABLED"] = True @@ -227,9 +221,7 @@ def sd_servers(self, setup_journalist_key_and_gpg_folder): # Add our test user try: valid_password = "correct horse battery staple profanity oil chewy" - user = Journalist( - username="journalist", password=valid_password, is_admin=True - ) + user = Journalist(username="journalist", password=valid_password, is_admin=True) user.otp_secret = "JHCOGO7VCER3EJ4L" db.session.add(user) db.session.commit() @@ -249,9 +241,7 @@ def sd_servers(self, setup_journalist_key_and_gpg_folder): def start_journalist_server(app): app.run(port=journalist_port, debug=True, use_reloader=False, threaded=True) - self.source_process = Process( - target=lambda: self.start_source_server(source_port) - ) + self.source_process = Process(target=lambda: self.start_source_server(source_port)) self.journalist_process = Process( target=lambda: start_journalist_server(self.journalist_app) @@ -416,7 +406,7 @@ def alert_wait(self, timeout=None): def alert_accept(self): # adapted from https://stackoverflow.com/a/34795883/837471 def alert_is_not_present(object): - """ Expect an alert to not be present.""" + """Expect an alert to not be present.""" try: alert = self.driver.switch_to.alert alert.text diff --git a/securedrop/tests/functional/journalist_navigation_steps.py b/securedrop/tests/functional/journalist_navigation_steps.py --- a/securedrop/tests/functional/journalist_navigation_steps.py +++ b/securedrop/tests/functional/journalist_navigation_steps.py @@ -11,19 +11,17 @@ import pytest import requests -from selenium.common.exceptions import NoSuchElementException -from selenium.common.exceptions import TimeoutException + +# Number of times to try flaky clicks. +from encryption import EncryptionManager +from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait - - -# Number of times to try flaky clicks. -from encryption import EncryptionManager -from tests.functional.tor_utils import proxies_for_url from source_user import _SourceScryptManager +from tests.functional.tor_utils import proxies_for_url from tests.test_encryption import import_journalist_private_key CLICK_ATTEMPTS = 15 @@ -203,6 +201,7 @@ def _admin_disallows_document_uploads(self): def preferences_saved(): flash_msg = self.driver.find_element_by_css_selector(".flash") assert "Preferences saved." in flash_msg.text + self.wait_for(preferences_saved, timeout=self.timeout * 6) def _admin_allows_document_uploads(self): @@ -213,11 +212,12 @@ def _admin_allows_document_uploads(self): def preferences_saved(): flash_msg = self.driver.find_element_by_css_selector(".flash") assert "Preferences saved." in flash_msg.text + self.wait_for(preferences_saved, timeout=self.timeout * 6) def _admin_sets_organization_name(self): assert self.orgname_default == self.driver.title - self.driver.find_element_by_id('organization_name').clear() + self.driver.find_element_by_id("organization_name").clear() self.safe_send_keys_by_id("organization_name", self.orgname_new) self.safe_click_by_id("submit-update-org-name") @@ -258,7 +258,7 @@ def _admin_adds_a_user_with_invalid_username(self): btns = self.driver.find_elements_by_tag_name("button") assert "ADD USER" in [el.text for el in btns] - invalid_username = 'deleted' + invalid_username = "deleted" self.safe_send_keys_by_css_selector('input[name="username"]', invalid_username) @@ -267,8 +267,10 @@ def _admin_adds_a_user_with_invalid_username(self): self.wait_for(lambda: self.driver.find_element_by_css_selector(".form-validation-error")) error_msg = self.driver.find_element_by_css_selector(".form-validation-error") - assert "This username is invalid because it is reserved for internal use " \ - "by the software." in error_msg.text + assert ( + "This username is invalid because it is reserved for internal use " + "by the software." in error_msg.text + ) def _admin_adds_a_user(self, is_admin=False, new_username=""): self.safe_click_by_id("add-user") @@ -284,11 +286,13 @@ def _admin_adds_a_user(self, is_admin=False, new_username=""): if not new_username: new_username = next(journalist_usernames) - self.new_user = dict(username=new_username, first_name='', last_name='', password=password) - self._add_user(self.new_user["username"], - first_name=self.new_user['first_name'], - last_name=self.new_user['last_name'], - is_admin=is_admin) + self.new_user = dict(username=new_username, first_name="", last_name="", password=password) + self._add_user( + self.new_user["username"], + first_name=self.new_user["first_name"], + last_name=self.new_user["last_name"], + is_admin=is_admin, + ) if not self.accept_languages: # Clicking submit on the add user form should redirect to @@ -310,7 +314,7 @@ def user_token_added(): # Successfully verifying the code should redirect to the admin # interface, and flash a message indicating success flash_msg = self.driver.find_elements_by_css_selector(".flash") - assert "The two-factor code for user \"{}\" was verified successfully.".format( + assert 'The two-factor code for user "{}" was verified successfully.'.format( self.new_user["username"] ) in [el.text for el in flash_msg] @@ -685,13 +689,14 @@ def reply_stored(): def _visit_edit_account(self): self.safe_click_by_id("link-edit-account") - def _visit_edit_secret(self, otp_type, tooltip_text=''): + def _visit_edit_secret(self, otp_type, tooltip_text=""): reset_form = self.wait_for( lambda: self.driver.find_element_by_id("reset-two-factor-" + otp_type) ) assert "/account/reset-2fa-" + otp_type in reset_form.get_attribute("action") reset_button = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-" + otp_type)[0] + "#button-reset-two-factor-" + otp_type + )[0] # 2FA reset buttons show a tooltip with explanatory text on hover. # Also, confirm the text on the tooltip is the correct one. @@ -722,13 +727,12 @@ def _set_hotp_secret(self): def _visit_edit_hotp_secret(self): self._visit_edit_secret( - "hotp", - "Reset two-factor authentication for security keys, like a YubiKey") + "hotp", "Reset two-factor authentication for security keys, like a YubiKey" + ) def _visit_edit_totp_secret(self): self._visit_edit_secret( - "totp", - "Reset two-factor authentication for mobile apps, such as FreeOTP" + "totp", "Reset two-factor authentication for mobile apps, such as FreeOTP" ) def _admin_visits_add_user(self): @@ -757,8 +761,7 @@ def retry_2fa_pop_ups(self, navigation_step, button_to_click): try: try: # This is the button we click to trigger the alert. - self.wait_for(lambda: self.driver.find_elements_by_id( - button_to_click)[0]) + self.wait_for(lambda: self.driver.find_elements_by_id(button_to_click)[0]) except IndexError: # If the button isn't there, then the alert is up from the last # time we attempted to run this test. Switch to it and accept it. @@ -781,17 +784,18 @@ def _admin_visits_reset_2fa_hotp(self): def _admin_visits_reset_2fa_hotp_step(): # 2FA reset buttons show a tooltip with explanatory text on hover. # Also, confirm the text on the tooltip is the correct one. - hotp_reset_button = self.driver.find_elements_by_id( - "reset-two-factor-hotp")[0] + hotp_reset_button = self.driver.find_elements_by_id("reset-two-factor-hotp")[0] hotp_reset_button.location_once_scrolled_into_view ActionChains(self.driver).move_to_element(hotp_reset_button).perform() time.sleep(1) tip_opacity = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-hotp span.tooltip")[0].value_of_css_property('opacity') + "#button-reset-two-factor-hotp span.tooltip" + )[0].value_of_css_property("opacity") tip_text = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-hotp span.tooltip")[0].text + "#button-reset-two-factor-hotp span.tooltip" + )[0].text assert tip_opacity == "1" @@ -815,22 +819,23 @@ def _admin_visits_reset_2fa_totp_step(): # 2FA reset buttons show a tooltip with explanatory text on hover. # Also, confirm the text on the tooltip is the correct one. totp_reset_button = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-totp")[0] + "#button-reset-two-factor-totp" + )[0] totp_reset_button.location_once_scrolled_into_view ActionChains(self.driver).move_to_element(totp_reset_button).perform() time.sleep(1) tip_opacity = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-totp span.tooltip")[0].value_of_css_property('opacity') + "#button-reset-two-factor-totp span.tooltip" + )[0].value_of_css_property("opacity") tip_text = self.driver.find_elements_by_css_selector( - "#button-reset-two-factor-totp span.tooltip")[0].text + "#button-reset-two-factor-totp span.tooltip" + )[0].text assert tip_opacity == "1" if not self.accept_languages: - expected_text = ( - "Reset two-factor authentication for mobile apps, such as FreeOTP" - ) + expected_text = "Reset two-factor authentication for mobile apps, such as FreeOTP" assert tip_text == expected_text self.safe_click_by_id("button-reset-two-factor-totp") @@ -841,15 +846,16 @@ def _admin_visits_reset_2fa_totp_step(): def _admin_creates_a_user(self, hotp): self.safe_click_by_id("add-user") self.wait_for(lambda: self.driver.find_element_by_id("username")) - self.new_user = dict(username="dellsberg", - first_name='', - last_name='', - password="pentagonpapers") - self._add_user(self.new_user["username"], - first_name=self.new_user['first_name'], - last_name=self.new_user['last_name'], - is_admin=False, - hotp=hotp) + self.new_user = dict( + username="dellsberg", first_name="", last_name="", password="pentagonpapers" + ) + self._add_user( + self.new_user["username"], + first_name=self.new_user["first_name"], + last_name=self.new_user["last_name"], + is_admin=False, + hotp=hotp, + ) def _journalist_delete_all(self): for checkbox in self.driver.find_elements_by_name("doc_names_selected"): diff --git a/securedrop/tests/functional/pageslayout/functional_test.py b/securedrop/tests/functional/pageslayout/functional_test.py --- a/securedrop/tests/functional/pageslayout/functional_test.py +++ b/securedrop/tests/functional/pageslayout/functional_test.py @@ -18,15 +18,11 @@ import io import logging import os -from os.path import abspath -from os.path import dirname -from os.path import realpath +from os.path import abspath, dirname, realpath import pytest - -from tests.functional import functional_test - from PIL import Image +from tests.functional import functional_test def list_locales(): @@ -40,7 +36,7 @@ def list_locales(): def autocrop_btm(img, bottom_padding=12): """Automatically crop the bottom of a screenshot.""" # Get the grayscale of img - gray = img.convert('L') + gray = img.convert("L") # We start one row above the bottom since the "modal" windows screenshots # have a bottom line color different than the background btm = img.height - 2 @@ -71,9 +67,7 @@ def _screenshot(self, filename): # revert the HTTP Accept-Language format locale = self.accept_languages.replace("-", "_") - log_dir = abspath( - os.path.join(dirname(realpath(__file__)), "screenshots", locale) - ) + log_dir = abspath(os.path.join(dirname(realpath(__file__)), "screenshots", locale)) if not os.path.exists(log_dir): os.makedirs(log_dir) @@ -85,12 +79,10 @@ def _save_html(self, filename): # revert the HTTP Accept-Language format locale = self.accept_languages.replace("-", "_") - html_dir = abspath( - os.path.join(dirname(realpath(__file__)), "html", locale) - ) + html_dir = abspath(os.path.join(dirname(realpath(__file__)), "html", locale)) if not os.path.exists(html_dir): os.makedirs(html_dir) html = self.driver.page_source - with open(os.path.join(html_dir, filename), 'w') as f: + with open(os.path.join(html_dir, filename), "w") as f: f.write(html) diff --git a/securedrop/tests/functional/pageslayout/screenshot_utils.py b/securedrop/tests/functional/pageslayout/screenshot_utils.py --- a/securedrop/tests/functional/pageslayout/screenshot_utils.py +++ b/securedrop/tests/functional/pageslayout/screenshot_utils.py @@ -1,13 +1,10 @@ from io import BytesIO - from pathlib import Path -from selenium.webdriver.firefox.webdriver import WebDriver from PIL import Image - +from selenium.webdriver.firefox.webdriver import WebDriver from tests.functional.pageslayout.functional_test import autocrop_btm - _SCREENSHOTS_DIR = (Path(__file__).parent / "screenshots").absolute() _HTML_DIR = (Path(__file__).parent / "html").absolute() diff --git a/securedrop/tests/functional/pageslayout/test_journalist.py b/securedrop/tests/functional/pageslayout/test_journalist.py --- a/securedrop/tests/functional/pageslayout/test_journalist.py +++ b/securedrop/tests/functional/pageslayout/test_journalist.py @@ -16,22 +16,20 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import pytest - -from tests.functional import journalist_navigation_steps -from tests.functional import source_navigation_steps import tests.functional.pageslayout.functional_test as pft +from tests.functional import journalist_navigation_steps, source_navigation_steps @pytest.mark.pagelayout class TestJournalistLayout( - pft.FunctionalTest, - source_navigation_steps.SourceNavigationStepsMixin, - journalist_navigation_steps.JournalistNavigationStepsMixin): - + pft.FunctionalTest, + source_navigation_steps.SourceNavigationStepsMixin, + journalist_navigation_steps.JournalistNavigationStepsMixin, +): def test_login(self): self.driver.get(self.journalist_location + "/login") - self._screenshot('journalist-login.png') - self._save_html('journalist-login.html') + self._screenshot("journalist-login.png") + self._save_html("journalist-login.html") def test_journalist_composes_reply(self): self._source_visits_source_homepage() @@ -43,24 +41,24 @@ def test_journalist_composes_reply(self): self._journalist_checks_messages() self._journalist_downloads_message() self._journalist_composes_reply() - self._screenshot('journalist-composes_reply.png') - self._save_html('journalist-composes_reply.html') + self._screenshot("journalist-composes_reply.png") + self._save_html("journalist-composes_reply.html") def test_edit_account_user(self): self._journalist_logs_in() self._visit_edit_account() - self._screenshot('journalist-edit_account_user.png') - self._save_html('journalist-edit_account_user.html') + self._screenshot("journalist-edit_account_user.png") + self._save_html("journalist-edit_account_user.html") def test_index_no_documents_admin(self): self._admin_logs_in() - self._screenshot('journalist-admin_index_no_documents.png') - self._save_html('journalist-admin_index_no_documents.html') + self._screenshot("journalist-admin_index_no_documents.png") + self._save_html("journalist-admin_index_no_documents.html") def test_index_no_documents(self): self._journalist_logs_in() - self._screenshot('journalist-index_no_documents.png') - self._save_html('journalist-index_no_documents.html') + self._screenshot("journalist-index_no_documents.png") + self._save_html("journalist-index_no_documents.html") def test_index(self): self._source_visits_source_homepage() @@ -70,8 +68,8 @@ def test_index(self): self._source_submits_a_message() self._source_logs_out() self._journalist_logs_in() - self._screenshot('journalist-index.png') - self._save_html('journalist-index.html') + self._screenshot("journalist-index.png") + self._save_html("journalist-index.html") def test_index_javascript(self): self._source_visits_source_homepage() @@ -81,34 +79,29 @@ def test_index_javascript(self): self._source_submits_a_message() self._source_logs_out() self._journalist_logs_in() - self._screenshot('journalist-index_javascript.png') - self._save_html('journalist-index_javascript.html') + self._screenshot("journalist-index_javascript.png") + self._save_html("journalist-index_javascript.html") self._journalist_selects_the_first_source() self._journalist_selects_all_documents() - self._screenshot( - 'journalist-clicks_on_source_and_selects_documents.png' - ) - self._save_html( - 'journalist-clicks_on_source_and_selects_documents.html' - ) + self._screenshot("journalist-clicks_on_source_and_selects_documents.png") + self._save_html("journalist-clicks_on_source_and_selects_documents.html") def test_index_entered_text(self): - self._input_text_in_login_form('jane_doe', 'my password is long', - '117264') - self._screenshot('journalist-index_with_text.png') - self._save_html('journalist-index_with_text.html') + self._input_text_in_login_form("jane_doe", "my password is long", "117264") + self._screenshot("journalist-index_with_text.png") + self._save_html("journalist-index_with_text.html") def test_fail_to_visit_admin(self): self._journalist_visits_admin() - self._screenshot('journalist-code-fail_to_visit_admin.png') - self._save_html('journalist-code-fail_to_visit_admin.html') + self._screenshot("journalist-code-fail_to_visit_admin.png") + self._save_html("journalist-code-fail_to_visit_admin.html") def test_fail_login(self, hardening): self._journalist_fail_login() - self._screenshot('journalist-code-fail_login.png') - self._save_html('journalist-code-fail_login.html') + self._screenshot("journalist-code-fail_login.png") + self._save_html("journalist-code-fail_login.html") def test_fail_login_many(self, hardening): self._journalist_fail_login_many() - self._screenshot('journalist-code-fail_login_many.png') - self._save_html('journalist-code-fail_login_many.html') + self._screenshot("journalist-code-fail_login_many.png") + self._save_html("journalist-code-fail_login_many.html") diff --git a/securedrop/tests/functional/pageslayout/test_journalist_account.py b/securedrop/tests/functional/pageslayout/test_journalist_account.py --- a/securedrop/tests/functional/pageslayout/test_journalist_account.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_account.py @@ -16,34 +16,32 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import pytest - -from tests.functional import journalist_navigation_steps import tests.functional.pageslayout.functional_test as pft +from tests.functional import journalist_navigation_steps @pytest.mark.pagelayout class TestJournalistLayoutAccount( pft.FunctionalTest, journalist_navigation_steps.JournalistNavigationStepsMixin ): - def test_account_edit_hotp_secret(self): self._journalist_logs_in() self._visit_edit_account() self._visit_edit_hotp_secret() - self._screenshot('journalist-account_edit_hotp_secret.png') - self._save_html('journalist-account_edit_hotp_secret.html') + self._screenshot("journalist-account_edit_hotp_secret.png") + self._save_html("journalist-account_edit_hotp_secret.html") def test_account_new_two_factor_hotp(self): self._journalist_logs_in() self._visit_edit_account() self._visit_edit_hotp_secret() self._set_hotp_secret() - self._screenshot('journalist-account_new_two_factor_hotp.png') - self._save_html('journalist-account_new_two_factor_hotp.html') + self._screenshot("journalist-account_new_two_factor_hotp.png") + self._save_html("journalist-account_new_two_factor_hotp.html") def test_account_new_two_factor_totp(self): self._journalist_logs_in() self._visit_edit_account() self._visit_edit_totp_secret() - self._screenshot('journalist-account_new_two_factor_totp.png') - self._save_html('journalist-account_new_two_factor_totp.html') + self._screenshot("journalist-account_new_two_factor_totp.png") + self._save_html("journalist-account_new_two_factor_totp.html") diff --git a/securedrop/tests/functional/pageslayout/test_journalist_admin.py b/securedrop/tests/functional/pageslayout/test_journalist_admin.py --- a/securedrop/tests/functional/pageslayout/test_journalist_admin.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_admin.py @@ -16,33 +16,30 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import pytest - -from tests.functional import journalist_navigation_steps import tests.functional.pageslayout.functional_test as pft +from tests.functional import journalist_navigation_steps @pytest.mark.pagelayout class TestJournalistLayoutAdmin( pft.FunctionalTest, journalist_navigation_steps.JournalistNavigationStepsMixin ): - def test_admin_add_user_hotp(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_visits_add_user() self._admin_enters_journalist_account_details_hotp( - 'journalist2', - 'c4 26 43 52 69 13 02 49 9f 6a a5 33 96 46 d9 05 42 a3 4f ae' + "journalist2", "c4 26 43 52 69 13 02 49 9f 6a a5 33 96 46 d9 05 42 a3 4f ae" ) - self._screenshot('journalist-admin_add_user_hotp.png') - self._save_html('journalist-admin_add_user_hotp.html') + self._screenshot("journalist-admin_add_user_hotp.png") + self._save_html("journalist-admin_add_user_hotp.html") def test_admin_add_user_totp(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_visits_add_user() - self._screenshot('journalist-admin_add_user_totp.png') - self._save_html('journalist-admin_add_user_totp.html') + self._screenshot("journalist-admin_add_user_totp.png") + self._save_html("journalist-admin_add_user_totp.html") def test_admin_edit_hotp_secret(self): self._admin_logs_in() @@ -50,8 +47,8 @@ def test_admin_edit_hotp_secret(self): self._admin_adds_a_user() self._admin_visits_edit_user() self._admin_visits_reset_2fa_hotp() - self._screenshot('journalist-admin_edit_hotp_secret.png') - self._save_html('journalist-admin_edit_hotp_secret.html') + self._screenshot("journalist-admin_edit_hotp_secret.png") + self._save_html("journalist-admin_edit_hotp_secret.html") def test_admin_edit_totp_secret(self): self._admin_logs_in() @@ -59,59 +56,59 @@ def test_admin_edit_totp_secret(self): self._admin_adds_a_user() self._admin_visits_edit_user() self._admin_visits_reset_2fa_totp() - self._screenshot('journalist-admin_edit_totp_secret.png') - self._save_html('journalist-admin_edit_totp_secret.html') + self._screenshot("journalist-admin_edit_totp_secret.png") + self._save_html("journalist-admin_edit_totp_secret.html") def test_edit_account_admin(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_adds_a_user() self._admin_visits_edit_user() - self._screenshot('journalist-edit_account_admin.png') - self._save_html('journalist-edit_account_admin.html') + self._screenshot("journalist-edit_account_admin.png") + self._save_html("journalist-edit_account_admin.html") def test_admin(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_adds_a_user() - self._screenshot('journalist-admin.png') - self._save_html('journalist-admin.html') + self._screenshot("journalist-admin.png") + self._save_html("journalist-admin.html") def test_admin_new_user_two_factor_hotp(self): self._admin_logs_in() self._admin_visits_admin_interface() - valid_hotp = '1234567890123456789012345678901234567890' + valid_hotp = "1234567890123456789012345678901234567890" self._admin_creates_a_user(hotp=valid_hotp) - self._screenshot('journalist-admin_new_user_two_factor_hotp.png') - self._save_html('journalist-admin_new_user_two_factor_hotp.html') + self._screenshot("journalist-admin_new_user_two_factor_hotp.png") + self._save_html("journalist-admin_new_user_two_factor_hotp.html") def test_admin_new_user_two_factor_totp(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_creates_a_user(hotp=None) - self._screenshot('journalist-admin_new_user_two_factor_totp.png') - self._save_html('journalist-admin_new_user_two_factor_totp.html') + self._screenshot("journalist-admin_new_user_two_factor_totp.png") + self._save_html("journalist-admin_new_user_two_factor_totp.html") def test_admin_changes_logo(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_visits_system_config_page() - self._screenshot('journalist-admin_system_config_page.png') - self._save_html('journalist-admin_system_config_page.html') + self._screenshot("journalist-admin_system_config_page.png") + self._save_html("journalist-admin_system_config_page.html") self._admin_updates_logo_image() - self._screenshot('journalist-admin_changes_logo_image.png') - self._save_html('journalist-admin_changes_logo_image.html') + self._screenshot("journalist-admin_changes_logo_image.png") + self._save_html("journalist-admin_changes_logo_image.html") def test_admin_uses_ossec_alert_button(self): self._admin_logs_in() self._admin_visits_admin_interface() self._admin_visits_system_config_page() self._admin_can_send_test_alert() - self._screenshot('journalist-admin_ossec_alert_button.png') - self._save_html('journalist-admin_ossec_alert_button.html') + self._screenshot("journalist-admin_ossec_alert_button.png") + self._save_html("journalist-admin_ossec_alert_button.html") def test_admin_interface_index(self): self._admin_logs_in() self._admin_visits_admin_interface() - self._screenshot('journalist-admin_interface_index.png') - self._save_html('journalist-admin_interface_index.html') + self._screenshot("journalist-admin_interface_index.png") + self._save_html("journalist-admin_interface_index.html") diff --git a/securedrop/tests/functional/pageslayout/test_journalist_col.py b/securedrop/tests/functional/pageslayout/test_journalist_col.py --- a/securedrop/tests/functional/pageslayout/test_journalist_col.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_col.py @@ -16,18 +16,16 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import pytest - -from tests.functional import journalist_navigation_steps -from tests.functional import source_navigation_steps import tests.functional.pageslayout.functional_test as pft +from tests.functional import journalist_navigation_steps, source_navigation_steps @pytest.mark.pagelayout class TestJournalistLayoutCol( - pft.FunctionalTest, - source_navigation_steps.SourceNavigationStepsMixin, - journalist_navigation_steps.JournalistNavigationStepsMixin): - + pft.FunctionalTest, + source_navigation_steps.SourceNavigationStepsMixin, + journalist_navigation_steps.JournalistNavigationStepsMixin, +): def test_col_no_documents(self): self._source_visits_source_homepage() self._source_chooses_to_submit_documents() @@ -38,8 +36,8 @@ def test_col_no_documents(self): self._journalist_visits_col() self._journalist_delete_all() self._journalist_confirm_delete_selected() - self._screenshot('journalist-col_no_document.png') - self._save_html('journalist-col_no_document.html') + self._screenshot("journalist-col_no_document.png") + self._save_html("journalist-col_no_document.html") def test_col_has_no_key(self): self._source_visits_source_homepage() @@ -50,8 +48,8 @@ def test_col_has_no_key(self): self._journalist_logs_in() self._source_delete_key() self._journalist_visits_col() - self._screenshot('journalist-col_has_no_key.png') - self._save_html('journalist-col_has_no_key.html') + self._screenshot("journalist-col_has_no_key.png") + self._save_html("journalist-col_has_no_key.html") def test_col(self): self._source_visits_source_homepage() @@ -61,8 +59,8 @@ def test_col(self): self._source_logs_out() self._journalist_logs_in() self._journalist_visits_col() - self._screenshot('journalist-col.png') - self._save_html('journalist-col.html') + self._screenshot("journalist-col.png") + self._save_html("journalist-col.html") def test_col_javascript(self): self._source_visits_source_homepage() @@ -72,5 +70,5 @@ def test_col_javascript(self): self._source_logs_out() self._journalist_logs_in() self._journalist_visits_col() - self._screenshot('journalist-col_javascript.png') - self._save_html('journalist-col_javascript.html') + self._screenshot("journalist-col_javascript.png") + self._save_html("journalist-col_javascript.html") diff --git a/securedrop/tests/functional/pageslayout/test_journalist_delete.py b/securedrop/tests/functional/pageslayout/test_journalist_delete.py --- a/securedrop/tests/functional/pageslayout/test_journalist_delete.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_delete.py @@ -18,19 +18,17 @@ import time import pytest - -from tests.functional import journalist_navigation_steps -from tests.functional import source_navigation_steps import tests.functional.pageslayout.functional_test as pft +from tests.functional import journalist_navigation_steps, source_navigation_steps # TODO(AD): This should be merged with TestJournalist @pytest.mark.pagelayout class TestJournalistLayoutDelete( - pft.FunctionalTest, - source_navigation_steps.SourceNavigationStepsMixin, - journalist_navigation_steps.JournalistNavigationStepsMixin): - + pft.FunctionalTest, + source_navigation_steps.SourceNavigationStepsMixin, + journalist_navigation_steps.JournalistNavigationStepsMixin, +): def test_delete_none(self): self._source_visits_source_homepage() self._source_chooses_to_submit_documents() @@ -42,8 +40,8 @@ def test_delete_none(self): self._journalist_visits_col() self._journalist_clicks_delete_selected_link() self._journalist_confirm_delete_selected() - self._screenshot('journalist-delete_none.png') - self._save_html('journalist-delete_none.html') + self._screenshot("journalist-delete_none.png") + self._save_html("journalist-delete_none.html") # TODO(AD): This should be merged with # test_journalist_verifies_deletion_of_one_submission_modal() @@ -59,8 +57,8 @@ def test_delete_one_confirmation(self): self._journalist_selects_first_doc() self._journalist_clicks_delete_selected_link() time.sleep(1) - self._screenshot('journalist-delete_one_confirmation.png') - self._save_html('journalist-delete_one_confirmation.html') + self._screenshot("journalist-delete_one_confirmation.png") + self._save_html("journalist-delete_one_confirmation.html") # TODO(AD): This should be merged with test_journalist_interface_ui_with_modal() def test_delete_all_confirmation(self): @@ -74,8 +72,8 @@ def test_delete_all_confirmation(self): self._journalist_visits_col() self._journalist_delete_all_confirmation() time.sleep(1) - self._screenshot('journalist-delete_all_confirmation.png') - self._save_html('journalist-delete_all_confirmation.html') + self._screenshot("journalist-delete_all_confirmation.png") + self._save_html("journalist-delete_all_confirmation.html") def test_delete_one(self): self._source_visits_source_homepage() @@ -88,8 +86,8 @@ def test_delete_one(self): self._journalist_visits_col() self._journalist_delete_one() self._journalist_confirm_delete_selected() - self._screenshot('journalist-delete_one.png') - self._save_html('journalist-delete_one.html') + self._screenshot("journalist-delete_one.png") + self._save_html("journalist-delete_one.html") def test_delete_all(self): self._source_visits_source_homepage() @@ -102,5 +100,5 @@ def test_delete_all(self): self._journalist_visits_col() self._journalist_delete_all() self._journalist_confirm_delete_selected() - self._screenshot('journalist-delete_all.png') - self._save_html('journalist-delete_all.html') + self._screenshot("journalist-delete_all.png") + self._save_html("journalist-delete_all.html") diff --git a/securedrop/tests/functional/pageslayout/test_source.py b/securedrop/tests/functional/pageslayout/test_source.py --- a/securedrop/tests/functional/pageslayout/test_source.py +++ b/securedrop/tests/functional/pageslayout/test_source.py @@ -16,7 +16,6 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import pytest - from tests.functional.app_navigators import SourceAppNagivator from tests.functional.pageslayout.functional_test import list_locales from tests.functional.pageslayout.screenshot_utils import save_screenshot_and_html diff --git a/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py b/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py --- a/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py +++ b/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py @@ -17,7 +17,6 @@ # import pytest from tbselenium.utils import disable_js - from tests.functional.app_navigators import SourceAppNagivator from tests.functional.pageslayout.functional_test import list_locales from tests.functional.pageslayout.screenshot_utils import save_screenshot_and_html @@ -26,7 +25,6 @@ @pytest.mark.parametrize("locale", list_locales()) @pytest.mark.pagelayout class TestSourceLayoutTorBrowser: - def test_index_and_logout(self, locale, sd_servers_v2): # Given a source user accessing the app from their browser locale_with_commas = locale.replace("_", "-") diff --git a/securedrop/tests/functional/pageslayout/test_source_session_layout.py b/securedrop/tests/functional/pageslayout/test_source_session_layout.py --- a/securedrop/tests/functional/pageslayout/test_source_session_layout.py +++ b/securedrop/tests/functional/pageslayout/test_source_session_layout.py @@ -2,15 +2,12 @@ from pathlib import Path import pytest - -from tests.functional.conftest import spawn_sd_servers from tests.functional.app_navigators import SourceAppNagivator +from tests.functional.conftest import spawn_sd_servers from tests.functional.factories import SecureDropConfigFactory - from tests.functional.pageslayout.functional_test import list_locales from tests.functional.pageslayout.screenshot_utils import save_screenshot_and_html - # Very short session expiration time SESSION_EXPIRATION_SECONDS = 3 diff --git a/securedrop/tests/functional/pageslayout/test_source_static_pages.py b/securedrop/tests/functional/pageslayout/test_source_static_pages.py --- a/securedrop/tests/functional/pageslayout/test_source_static_pages.py +++ b/securedrop/tests/functional/pageslayout/test_source_static_pages.py @@ -1,11 +1,9 @@ import pytest import requests - from tests.functional import tor_utils from tests.functional.pageslayout.functional_test import list_locales from tests.functional.pageslayout.screenshot_utils import save_screenshot_and_html -from tests.functional.web_drivers import get_web_driver, WebDriverTypeEnum - +from tests.functional.web_drivers import WebDriverTypeEnum, get_web_driver from version import __version__ diff --git a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py --- a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py +++ b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py @@ -1,10 +1,9 @@ from pathlib import Path import pytest -from selenium.common.exceptions import NoSuchElementException - from encryption import EncryptionManager -from tests.functional.app_navigators import SourceAppNagivator, JournalistAppNavigator +from selenium.common.exceptions import NoSuchElementException +from tests.functional.app_navigators import JournalistAppNavigator, SourceAppNagivator from tests.functional.pageslayout.functional_test import list_locales from tests.functional.pageslayout.screenshot_utils import save_screenshot_and_html @@ -12,7 +11,6 @@ @pytest.mark.parametrize("locale", list_locales()) @pytest.mark.pagelayout class TestSubmitAndRetrieveFile: - def test_submit_and_retrieve_happy_path( self, locale, sd_servers_v2_with_clean_state, tor_browser_web_driver, firefox_web_driver ): @@ -68,11 +66,11 @@ def test_submit_and_retrieve_happy_path( source_app_nav.source_visits_source_homepage() source_app_nav.source_chooses_to_login() source_app_nav.source_proceeds_to_login(codename=source_codename) - save_screenshot_and_html(source_app_nav.driver, locale, 'source-checks_for_reply') + save_screenshot_and_html(source_app_nav.driver, locale, "source-checks_for_reply") # When they delete the journalist's reply, it succeeds self._source_deletes_journalist_reply(source_app_nav) - save_screenshot_and_html(source_app_nav.driver, locale, 'source-deletes_reply') + save_screenshot_and_html(source_app_nav.driver, locale, "source-deletes_reply") @staticmethod def _source_deletes_journalist_reply(navigator: SourceAppNagivator) -> None: diff --git a/securedrop/tests/functional/test_admin_interface.py b/securedrop/tests/functional/test_admin_interface.py --- a/securedrop/tests/functional/test_admin_interface.py +++ b/securedrop/tests/functional/test_admin_interface.py @@ -1,15 +1,14 @@ -from . import functional_test as ft -from . import journalist_navigation_steps -from . import source_navigation_steps - from tbselenium.utils import SECURITY_LOW +from . import functional_test as ft +from . import journalist_navigation_steps, source_navigation_steps -class TestAdminInterface( - ft.FunctionalTest, - journalist_navigation_steps.JournalistNavigationStepsMixin, - source_navigation_steps.SourceNavigationStepsMixin): +class TestAdminInterface( + ft.FunctionalTest, + journalist_navigation_steps.JournalistNavigationStepsMixin, + source_navigation_steps.SourceNavigationStepsMixin, +): def test_admin_interface(self): self._admin_logs_in() self._admin_visits_admin_interface() diff --git a/securedrop/tests/functional/test_journalist.py b/securedrop/tests/functional/test_journalist.py --- a/securedrop/tests/functional/test_journalist.py +++ b/securedrop/tests/functional/test_journalist.py @@ -20,14 +20,12 @@ from uuid import uuid4 import pytest - from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys - from tests.functional.app_navigators import JournalistAppNavigator from tests.functional.conftest import ( - _create_source_and_submission, SdServersFixtureResult, + _create_source_and_submission, spawn_sd_servers, ) from tests.functional.factories import SecureDropConfigFactory diff --git a/securedrop/tests/functional/test_make_account_changes.py b/securedrop/tests/functional/test_make_account_changes.py --- a/securedrop/tests/functional/test_make_account_changes.py +++ b/securedrop/tests/functional/test_make_account_changes.py @@ -1,12 +1,10 @@ # -*- coding: utf-8 -*- -from . import journalist_navigation_steps -from . import functional_test +from . import functional_test, journalist_navigation_steps class TestMakeAccountChanges( - functional_test.FunctionalTest, - journalist_navigation_steps.JournalistNavigationStepsMixin): - + functional_test.FunctionalTest, journalist_navigation_steps.JournalistNavigationStepsMixin +): def test_admin_edit_account_html_template_rendering(self): """The edit_account.html template is used both when an admin is editing a user's account, and when a user is editing their own account. While @@ -20,7 +18,7 @@ def test_admin_edit_account_html_template_rendering(self): self._admin_visits_admin_interface() self._admin_adds_a_user() # Admin view of non-admin user - self._edit_user(self.new_user['username']) + self._edit_user(self.new_user["username"]) # User view of self self._edit_account() self._logout() diff --git a/securedrop/tests/functional/test_sd_config_v2.py b/securedrop/tests/functional/test_sd_config_v2.py --- a/securedrop/tests/functional/test_sd_config_v2.py +++ b/securedrop/tests/functional/test_sd_config_v2.py @@ -1,16 +1,14 @@ from typing import Set + from tests.functional.factories import SecureDropConfigFactory def _get_public_attributes(obj: object) -> Set[str]: - attributes = set( - attr_name for attr_name in dir(obj) if not attr_name.startswith("_") - ) + attributes = set(attr_name for attr_name in dir(obj) if not attr_name.startswith("_")) return attributes class TestSecureDropConfigV2: - def test_v1_and_v2_have_the_same_attributes(self, config, tmp_path): sd_config_v1 = config sd_config_v2 = SecureDropConfigFactory.create(SECUREDROP_DATA_ROOT=tmp_path) diff --git a/securedrop/tests/functional/test_source.py b/securedrop/tests/functional/test_source.py --- a/securedrop/tests/functional/test_source.py +++ b/securedrop/tests/functional/test_source.py @@ -1,9 +1,9 @@ import requests import werkzeug - +from tests.functional import tor_utils from tests.functional.app_navigators import SourceAppNagivator + from ..test_journalist import VALID_PASSWORD -from tests.functional import tor_utils class TestSourceAppCodenameHints: diff --git a/securedrop/tests/functional/test_source_cancels.py b/securedrop/tests/functional/test_source_cancels.py --- a/securedrop/tests/functional/test_source_cancels.py +++ b/securedrop/tests/functional/test_source_cancels.py @@ -2,7 +2,6 @@ class TestSourceUserCancels: - def test_source_cancels_at_login_page(self, sd_servers_v2, tor_browser_web_driver): # Given a source user who goes to the login page source_app_nav = SourceAppNagivator( diff --git a/securedrop/tests/functional/test_source_warnings.py b/securedrop/tests/functional/test_source_warnings.py --- a/securedrop/tests/functional/test_source_warnings.py +++ b/securedrop/tests/functional/test_source_warnings.py @@ -1,8 +1,8 @@ import os import shutil + import pytest from selenium import webdriver - from tests.functional.app_navigators import SourceAppNagivator from . import functional_test diff --git a/securedrop/tests/functional/test_submit_and_retrieve_message.py b/securedrop/tests/functional/test_submit_and_retrieve_message.py --- a/securedrop/tests/functional/test_submit_and_retrieve_message.py +++ b/securedrop/tests/functional/test_submit_and_retrieve_message.py @@ -1,7 +1,7 @@ from pathlib import Path from encryption import EncryptionManager -from tests.functional.app_navigators import SourceAppNagivator, JournalistAppNavigator +from tests.functional.app_navigators import JournalistAppNavigator, SourceAppNagivator class TestSubmitAndRetrieveMessage: diff --git a/securedrop/tests/functional/web_drivers.py b/securedrop/tests/functional/web_drivers.py --- a/securedrop/tests/functional/web_drivers.py +++ b/securedrop/tests/functional/web_drivers.py @@ -1,25 +1,19 @@ -from contextlib import contextmanager import logging import os -from pathlib import Path -from enum import Enum import time +from contextlib import contextmanager from datetime import datetime -from os.path import abspath -from os.path import dirname -from os.path import expanduser -from os.path import join -from os.path import realpath +from enum import Enum +from os.path import abspath, dirname, expanduser, join, realpath +from pathlib import Path from typing import Generator, Optional -from selenium.webdriver.firefox.webdriver import WebDriver - import tbselenium.common as cm from selenium import webdriver +from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.remote.remote_connection import LOGGER from tbselenium.tbdriver import TorBrowserDriver - _LOGFILE_PATH = abspath(join(dirname(realpath(__file__)), "../log/driver.log")) _FIREFOX_PATH = "/usr/bin/firefox/firefox" diff --git a/securedrop/tests/i18n/code.py b/securedrop/tests/i18n/code.py --- a/securedrop/tests/i18n/code.py +++ b/securedrop/tests/i18n/code.py @@ -1,4 +1,4 @@ # -*- coding: utf-8 -*- from flask_babel import gettext -print(gettext('code hello i18n')) +print(gettext("code hello i18n")) diff --git a/securedrop/tests/migrations/helpers.py b/securedrop/tests/migrations/helpers.py --- a/securedrop/tests/migrations/helpers.py +++ b/securedrop/tests/migrations/helpers.py @@ -2,7 +2,6 @@ import random import string - from datetime import datetime @@ -33,11 +32,11 @@ def random_username(): def random_chars(len, chars=string.printable): - return ''.join([random.choice(chars) for _ in range(len)]) + return "".join([random.choice(chars) for _ in range(len)]) def random_ascii_chars(len, chars=string.ascii_lowercase): - return ''.join([random.choice(chars) for _ in range(len)]) + return "".join([random.choice(chars) for _ in range(len)]) def random_datetime(nullable): diff --git a/securedrop/tests/migrations/migration_15ac9509fc68.py b/securedrop/tests/migrations/migration_15ac9509fc68.py --- a/securedrop/tests/migrations/migration_15ac9509fc68.py +++ b/securedrop/tests/migrations/migration_15ac9509fc68.py @@ -3,21 +3,27 @@ import random import string -from sqlalchemy import text - from db import db from journalist_app import create_app -from .helpers import (random_bool, random_chars, random_username, random_bytes, - random_datetime, bool_or_none) +from sqlalchemy import text + +from .helpers import ( + bool_or_none, + random_bool, + random_bytes, + random_chars, + random_datetime, + random_username, +) -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") -class UpgradeTester(): +class UpgradeTester: - '''This migration has no upgrade because there are no tables in the - database prior to running, so there is no data to load or test. - ''' + """This migration has no upgrade because there are no tables in the + database prior to running, so there is no data to load or test. + """ def __init__(self, config): pass @@ -29,7 +35,7 @@ def check_upgrade(self): pass -class DowngradeTester(): +class DowngradeTester: JOURNO_NUM = 200 SOURCE_NUM = 200 @@ -70,7 +76,7 @@ def load_data(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -83,97 +89,97 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), + "username": random_username(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), } - sql = '''INSERT INTO journalists (username, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access) VALUES (:username, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access); - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'filesystem_id': filesystem_id, - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "filesystem_id": filesystem_id, + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (filesystem_id, journalist_designation, + sql = """INSERT INTO sources (filesystem_id, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:filesystem_id, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_journalist_login_attempt(journalist_id): params = { - 'timestamp': random_datetime(nullable=True), - 'journalist_id': journalist_id, + "timestamp": random_datetime(nullable=True), + "journalist_id": journalist_id, } - sql = '''INSERT INTO journalist_login_attempt (timestamp, + sql = """INSERT INTO journalist_login_attempt (timestamp, journalist_id) VALUES (:timestamp, :journalist_id) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_reply(journalist_id, source_id): params = { - 'journalist_id': journalist_id, - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), + "journalist_id": journalist_id, + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), } - sql = '''INSERT INTO replies (journalist_id, source_id, filename, + sql = """INSERT INTO replies (journalist_id, source_id, filename, size) VALUES (:journalist_id, :source_id, :filename, :size) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_source_star(source_id): params = { - 'source_id': source_id, - 'starred': bool_or_none(), + "source_id": source_id, + "starred": bool_or_none(), } - sql = '''INSERT INTO source_stars (source_id, starred) + sql = """INSERT INTO source_stars (source_id, starred) VALUES (:source_id, :starred) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_submission(source_id): params = { - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), - 'downloaded': bool_or_none(), + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "downloaded": bool_or_none(), } - sql = '''INSERT INTO submissions (source_id, filename, size, + sql = """INSERT INTO submissions (source_id, filename, size, downloaded) VALUES (:source_id, :filename, :size, :downloaded) - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''We don't need to check anything on this downgrade because the - migration drops all the tables. Thus, there is nothing to do. - ''' + """We don't need to check anything on this downgrade because the + migration drops all the tables. Thus, there is nothing to do. + """ pass diff --git a/securedrop/tests/migrations/migration_1ddb81fb88c2.py b/securedrop/tests/migrations/migration_1ddb81fb88c2.py --- a/securedrop/tests/migrations/migration_1ddb81fb88c2.py +++ b/securedrop/tests/migrations/migration_1ddb81fb88c2.py @@ -1,10 +1,8 @@ # -*- coding: utf-8 -*- -from sqlalchemy import text - from db import db from journalist_app import create_app - +from sqlalchemy import text index_definition = ( "index", diff --git a/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py b/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py --- a/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py +++ b/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py @@ -2,70 +2,75 @@ import random import string - -from sqlalchemy import text from uuid import uuid4 from db import db from journalist_app import create_app -from .helpers import (random_bool, random_chars, random_username, random_bytes, - random_datetime, bool_or_none) +from sqlalchemy import text -random.seed('ᕕ( ᐛ )ᕗ') +from .helpers import ( + bool_or_none, + random_bool, + random_bytes, + random_chars, + random_datetime, + random_username, +) +random.seed("ᕕ( ᐛ )ᕗ") -class Helper(): +class Helper: @staticmethod def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'uuid': str(uuid4()), - 'filesystem_id': filesystem_id, - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "uuid": str(uuid4()), + "filesystem_id": filesystem_id, + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (uuid, filesystem_id, + sql = """INSERT INTO sources (uuid, filesystem_id, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:uuid, :filesystem_id, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_journalist_login_attempt(journalist_id): params = { - 'timestamp': random_datetime(nullable=True), - 'journalist_id': journalist_id, + "timestamp": random_datetime(nullable=True), + "journalist_id": journalist_id, } - sql = '''INSERT INTO journalist_login_attempt (timestamp, + sql = """INSERT INTO journalist_login_attempt (timestamp, journalist_id) VALUES (:timestamp, :journalist_id) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def add_reply(journalist_id, source_id): params = { - 'journalist_id': journalist_id, - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), + "journalist_id": journalist_id, + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), } - sql = '''INSERT INTO replies (journalist_id, source_id, filename, + sql = """INSERT INTO replies (journalist_id, source_id, filename, size) VALUES (:journalist_id, :source_id, :filename, :size) - ''' + """ db.engine.execute(text(sql), **params) @staticmethod def extract(app): with app.app_context(): - sql = '''SELECT j.id, count(distinct a.id), count(distinct r.id) + sql = """SELECT j.id, count(distinct a.id), count(distinct r.id) FROM journalists AS j LEFT OUTER JOIN journalist_login_attempt AS a ON a.journalist_id = j.id @@ -73,7 +78,7 @@ def extract(app): ON r.journalist_id = j.id GROUP BY j.id ORDER BY j.id - ''' + """ res = list(db.session.execute(text(sql))) return res @@ -112,7 +117,7 @@ def check_upgrade(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -125,24 +130,24 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), + "username": random_username(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), } - sql = '''INSERT INTO journalists (username, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access) VALUES (:username, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access); - ''' + """ db.engine.execute(text(sql), **params) @@ -180,7 +185,7 @@ def check_downgrade(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -193,23 +198,23 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) diff --git a/securedrop/tests/migrations/migration_2e24fc7536e8.py b/securedrop/tests/migrations/migration_2e24fc7536e8.py --- a/securedrop/tests/migrations/migration_2e24fc7536e8.py +++ b/securedrop/tests/migrations/migration_2e24fc7536e8.py @@ -1,9 +1,9 @@ import uuid -from sqlalchemy import text - from db import db from journalist_app import create_app +from sqlalchemy import text + from .helpers import random_datetime @@ -15,25 +15,25 @@ class UpgradeTester: def __init__(self, config): """This function MUST accept an argument named `config`. - You will likely want to save a reference to the config in your - class, so you can access the database later. + You will likely want to save a reference to the config in your + class, so you can access the database later. """ self.config = config self.app = create_app(config) def load_data(self): """This function loads data into the database and filesystem. It is - executed before the upgrade. + executed before the upgrade. """ with self.app.app_context(): params = { - 'uuid': str(uuid.uuid4()), - 'journalist_id': None, - 'source_id': 0, - 'filename': 'dummy.txt', - 'size': 1, - 'checksum': '', - 'deleted_by_source': False, + "uuid": str(uuid.uuid4()), + "journalist_id": None, + "source_id": 0, + "filename": "dummy.txt", + "size": 1, + "checksum": "", + "deleted_by_source": False, } sql = """\ INSERT INTO replies (uuid, journalist_id, source_id, filename, @@ -44,46 +44,52 @@ def load_data(self): # Insert two SeenReplys corresponding to the just-inserted reply, which also # verifies our handling of duplicate keys. for _ in range(2): - db.engine.execute(text( - """\ + db.engine.execute( + text( + """\ INSERT INTO seen_replies (reply_id, journalist_id) VALUES (1, NULL); """ - )) + ) + ) # Insert a JournalistLoginAttempt - db.engine.execute(text( - """\ + db.engine.execute( + text( + """\ INSERT INTO journalist_login_attempt (timestamp, journalist_id) VALUES (:timestamp, NULL) """ - ), timestamp=random_datetime(nullable=False)) + ), + timestamp=random_datetime(nullable=False), + ) def check_upgrade(self): """This function is run after the upgrade and verifies the state - of the database or filesystem. It MUST raise an exception if the - check fails. + of the database or filesystem. It MUST raise an exception if the + check fails. """ with self.app.app_context(): deleted = db.engine.execute( 'SELECT id, passphrase_hash, otp_secret FROM journalists WHERE username="deleted"' ).first() # A passphrase_hash is set - assert deleted[1].startswith('$argon2') + assert deleted[1].startswith("$argon2") # And a TOTP secret is set assert len(deleted[2]) == 32 deleted_id = deleted[0] - replies = db.engine.execute( - text('SELECT journalist_id FROM replies')).fetchall() + replies = db.engine.execute(text("SELECT journalist_id FROM replies")).fetchall() assert len(replies) == 1 # And the journalist_id matches our "deleted" one assert replies[0][0] == deleted_id seen_replies = db.engine.execute( - text('SELECT journalist_id FROM seen_replies')).fetchall() + text("SELECT journalist_id FROM seen_replies") + ).fetchall() assert len(seen_replies) == 1 # And the journalist_id matches our "deleted" one assert seen_replies[0][0] == deleted_id login_attempts = db.engine.execute( - text('SELECT * FROM journalist_login_attempt')).fetchall() + text("SELECT * FROM journalist_login_attempt") + ).fetchall() # The NULL login attempt was deleted outright assert login_attempts == [] @@ -94,20 +100,20 @@ class DowngradeTester: def __init__(self, config): """This function MUST accept an argument named `config`. - You will likely want to save a reference to the config in your - class, so you can access the database later. + You will likely want to save a reference to the config in your + class, so you can access the database later. """ self.config = config def load_data(self): """This function loads data into the database and filesystem. It is - executed before the downgrade. + executed before the downgrade. """ pass def check_downgrade(self): """This function is run after the downgrade and verifies the state - of the database or filesystem. It MUST raise an exception if the - check fails. + of the database or filesystem. It MUST raise an exception if the + check fails. """ pass diff --git a/securedrop/tests/migrations/migration_35513370ba0d.py b/securedrop/tests/migrations/migration_35513370ba0d.py --- a/securedrop/tests/migrations/migration_35513370ba0d.py +++ b/securedrop/tests/migrations/migration_35513370ba0d.py @@ -3,10 +3,10 @@ import random from uuid import uuid4 +import pytest +import sqlalchemy from db import db from journalist_app import create_app -import sqlalchemy -import pytest from .helpers import bool_or_none, random_bool, random_chars, random_datetime @@ -76,8 +76,6 @@ def check_downgrade(self): with self.app.app_context(): with pytest.raises(sqlalchemy.exc.OperationalError): sources = db.engine.execute( - sqlalchemy.text( - "SELECT * FROM sources WHERE deleted_at IS NOT NULL" - ) + sqlalchemy.text("SELECT * FROM sources WHERE deleted_at IS NOT NULL") ).fetchall() assert len(sources) == 0 diff --git a/securedrop/tests/migrations/migration_3d91d6948753.py b/securedrop/tests/migrations/migration_3d91d6948753.py --- a/securedrop/tests/migrations/migration_3d91d6948753.py +++ b/securedrop/tests/migrations/migration_3d91d6948753.py @@ -3,21 +3,21 @@ import random import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app -from .helpers import random_bool, random_chars, random_datetime, bool_or_none +from .helpers import bool_or_none, random_bool, random_chars, random_datetime -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") -class UpgradeTester(): +class UpgradeTester: - '''This migration verifies that the UUID column now exists, and that + """This migration verifies that the UUID column now exists, and that the data migration completed successfully. - ''' + """ SOURCE_NUM = 200 @@ -37,31 +37,30 @@ def load_data(self): def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'filesystem_id': filesystem_id, - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "filesystem_id": filesystem_id, + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (filesystem_id, journalist_designation, + sql = """INSERT INTO sources (filesystem_id, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:filesystem_id, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) def check_upgrade(self): with self.app.app_context(): - sources = db.engine.execute( - text('SELECT * FROM sources')).fetchall() + sources = db.engine.execute(text("SELECT * FROM sources")).fetchall() assert len(sources) == self.SOURCE_NUM for source in sources: assert source.uuid is not None -class DowngradeTester(): +class DowngradeTester: SOURCE_NUM = 200 @@ -81,26 +80,26 @@ def load_data(self): def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'filesystem_id': filesystem_id, - 'uuid': str(uuid.uuid4()), - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "filesystem_id": filesystem_id, + "uuid": str(uuid.uuid4()), + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (filesystem_id, uuid, + sql = """INSERT INTO sources (filesystem_id, uuid, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:filesystem_id, :uuid, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''Verify that the UUID column is now gone, but otherwise the table + """Verify that the UUID column is now gone, but otherwise the table has the expected number of rows. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM sources" sources = db.engine.execute(text(sql)).fetchall() @@ -109,7 +108,7 @@ def check_downgrade(self): try: # This should produce an exception, as the column (should) # be gone. - assert source['uuid'] is None + assert source["uuid"] is None except NoSuchColumnError: pass diff --git a/securedrop/tests/migrations/migration_3da3fcab826a.py b/securedrop/tests/migrations/migration_3da3fcab826a.py --- a/securedrop/tests/migrations/migration_3da3fcab826a.py +++ b/securedrop/tests/migrations/migration_3da3fcab826a.py @@ -1,28 +1,27 @@ # -*- coding: utf-8 -*- -import random import os +import random from uuid import uuid4 -from sqlalchemy import text - from db import db from journalist_app import create_app -from .helpers import random_bool, random_chars, random_ascii_chars, random_datetime, bool_or_none +from sqlalchemy import text +from .helpers import bool_or_none, random_ascii_chars, random_bool, random_chars, random_datetime -TEST_DATA_DIR = '/tmp/securedrop/store' +TEST_DATA_DIR = "/tmp/securedrop/store" def create_file_in_dummy_source_dir(filename): - filesystem_id = 'dummy' + filesystem_id = "dummy" basedir = os.path.join(TEST_DATA_DIR, filesystem_id) if not os.path.exists(basedir): os.makedirs(basedir) path_to_file = os.path.join(basedir, filename) - with open(path_to_file, 'a'): + with open(path_to_file, "a"): os.utime(path_to_file, None) @@ -59,33 +58,29 @@ def load_data(self): def create_journalist(self): if self.journalist_id is not None: - raise RuntimeError('Journalist already created') + raise RuntimeError("Journalist already created") - params = { - 'uuid': str(uuid4()), - 'username': random_chars(50), - 'session_nonce': 0 - } - sql = '''INSERT INTO journalists (uuid, username, session_nonce) + params = {"uuid": str(uuid4()), "username": random_chars(50), "session_nonce": 0} + sql = """INSERT INTO journalists (uuid, username, session_nonce) VALUES (:uuid, :username, :session_nonce) - ''' + """ self.journalist_id = db.engine.execute(text(sql), **params).lastrowid def add_reply(self, journalist_id, source_id, with_file=True): - filename = '1-' + random_ascii_chars(5) + '-' + random_ascii_chars(5) + '-reply.gpg' + filename = "1-" + random_ascii_chars(5) + "-" + random_ascii_chars(5) + "-reply.gpg" params = { - 'uuid': str(uuid4()), - 'journalist_id': journalist_id, - 'source_id': source_id, - 'filename': filename, - 'size': random.randint(0, 1024 * 1024 * 500), - 'deleted_by_source': False, + "uuid": str(uuid4()), + "journalist_id": journalist_id, + "source_id": source_id, + "filename": filename, + "size": random.randint(0, 1024 * 1024 * 500), + "deleted_by_source": False, } - sql = '''INSERT INTO replies (journalist_id, uuid, source_id, filename, + sql = """INSERT INTO replies (journalist_id, uuid, source_id, filename, size, deleted_by_source) VALUES (:journalist_id, :uuid, :source_id, :filename, :size, :deleted_by_source) - ''' + """ db.engine.execute(text(sql), **params) if with_file: @@ -95,35 +90,35 @@ def add_reply(self, journalist_id, source_id, with_file=True): def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'uuid': str(uuid4()), - 'filesystem_id': filesystem_id, - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "uuid": str(uuid4()), + "filesystem_id": filesystem_id, + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (uuid, filesystem_id, + sql = """INSERT INTO sources (uuid, filesystem_id, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:uuid, :filesystem_id, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) def add_submission(self, source_id, with_file=True): - filename = '1-' + random_ascii_chars(5) + '-' + random_ascii_chars(5) + '-doc.gz.gpg' + filename = "1-" + random_ascii_chars(5) + "-" + random_ascii_chars(5) + "-doc.gz.gpg" params = { - 'uuid': str(uuid4()), - 'source_id': source_id, - 'filename': filename, - 'size': random.randint(0, 1024 * 1024 * 500), - 'downloaded': bool_or_none(), + "uuid": str(uuid4()), + "source_id": source_id, + "filename": filename, + "size": random.randint(0, 1024 * 1024 * 500), + "downloaded": bool_or_none(), } - sql = '''INSERT INTO submissions (uuid, source_id, filename, size, + sql = """INSERT INTO submissions (uuid, source_id, filename, size, downloaded) VALUES (:uuid, :source_id, :filename, :size, :downloaded) - ''' + """ db.engine.execute(text(sql), **params) if with_file: @@ -131,16 +126,14 @@ def add_submission(self, source_id, with_file=True): def check_upgrade(self): with self.app.app_context(): - submissions = db.engine.execute( - text('SELECT * FROM submissions')).fetchall() + submissions = db.engine.execute(text("SELECT * FROM submissions")).fetchall() # Submissions without a source should be deleted assert len(submissions) == 1 for submission in submissions: assert submission.source_id == self.valid_source_id - replies = db.engine.execute( - text('SELECT * FROM replies')).fetchall() + replies = db.engine.execute(text("SELECT * FROM replies")).fetchall() # Replies without a source should be deleted assert len(replies) == 1 diff --git a/securedrop/tests/migrations/migration_48a75abc0121.py b/securedrop/tests/migrations/migration_48a75abc0121.py --- a/securedrop/tests/migrations/migration_48a75abc0121.py +++ b/securedrop/tests/migrations/migration_48a75abc0121.py @@ -2,13 +2,13 @@ import random import string +from uuid import uuid4 import pytest from db import db from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import IntegrityError -from uuid import uuid4 from .helpers import ( bool_or_none, @@ -23,12 +23,11 @@ class Helper: - @staticmethod def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'uuid': str(uuid4()), + "uuid": str(uuid4()), "filesystem_id": filesystem_id, "journalist_designation": random_chars(50), "flagged": bool_or_none(), @@ -127,7 +126,7 @@ def add_reply(journalist_id, source_id): "source_id": source_id, "filename": random_chars(50), "size": random.randint(0, 1024 * 1024 * 500), - "deleted_by_source": 0 + "deleted_by_source": 0, } sql = """ INSERT INTO replies (uuid, journalist_id, source_id, filename, size, deleted_by_source) @@ -142,7 +141,7 @@ def add_message(source_id): "source_id": source_id, "filename": random_chars(50) + "-msg.gpg", "size": random.randint(0, 1024 * 1024 * 500), - "downloaded": random.choice([True, False]) + "downloaded": random.choice([True, False]), } sql = """ INSERT INTO submissions (uuid, source_id, filename, size, downloaded) @@ -158,7 +157,7 @@ def add_file(source_id): "filename": random_chars(50) + "-doc.gz.gpg", "size": random.randint(0, 1024 * 1024 * 500), "downloaded": random.choice([True, False]), - "checksum": "sha256:" + random_chars(64) + "checksum": "sha256:" + random_chars(64), } sql = """ INSERT INTO submissions (uuid, source_id, filename, size, downloaded, checksum) @@ -258,7 +257,7 @@ def check_upgrade(self): # Now seen tables exist, so you should be able to mark some files, messages, and replies # as seen for submission in submissions: - if submission.filename.endswith('-doc.gz.gpg') and random.choice([0, 1]): + if submission.filename.endswith("-doc.gz.gpg") and random.choice([0, 1]): selected_journo_id = random.randint(0, self.JOURNO_NUM) self.mark_file_as_seen(submission.id, selected_journo_id) elif random.choice([0, 1]): @@ -339,7 +338,7 @@ def load_data(self): sql = "SELECT * FROM submissions" submissions = db.engine.execute(text(sql)).fetchall() for submission in submissions: - if submission.filename.endswith('-doc.gz.gpg') and random.choice([0, 1]): + if submission.filename.endswith("-doc.gz.gpg") and random.choice([0, 1]): selected_journo_id = random.randint(0, self.JOURNO_NUM) self.mark_file_as_seen(submission.id, selected_journo_id) elif random.choice([0, 1]): @@ -355,7 +354,7 @@ def load_data(self): # Mark some files, messages, and replies as seen for submission in submissions: - if submission.filename.endswith('-doc.gz.gpg') and random.choice([0, 1]): + if submission.filename.endswith("-doc.gz.gpg") and random.choice([0, 1]): selected_journo_id = random.randint(0, self.JOURNO_NUM) self.mark_file_as_seen(submission.id, selected_journo_id) elif random.choice([0, 1]): diff --git a/securedrop/tests/migrations/migration_523fff3f969c.py b/securedrop/tests/migrations/migration_523fff3f969c.py --- a/securedrop/tests/migrations/migration_523fff3f969c.py +++ b/securedrop/tests/migrations/migration_523fff3f969c.py @@ -1,9 +1,7 @@ -from sqlalchemy import text -from sqlalchemy.exc import OperationalError - from db import db from journalist_app import create_app - +from sqlalchemy import text +from sqlalchemy.exc import OperationalError instance_config_sql = "SELECT * FROM instance_config" diff --git a/securedrop/tests/migrations/migration_60f41bb14d98.py b/securedrop/tests/migrations/migration_60f41bb14d98.py --- a/securedrop/tests/migrations/migration_60f41bb14d98.py +++ b/securedrop/tests/migrations/migration_60f41bb14d98.py @@ -4,22 +4,29 @@ import string import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app -from .helpers import (random_bool, random_bytes, random_chars, random_datetime, - random_username, random_name, bool_or_none) +from .helpers import ( + bool_or_none, + random_bool, + random_bytes, + random_chars, + random_datetime, + random_name, + random_username, +) -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") -class UpgradeTester(): +class UpgradeTester: - '''This migration verifies that the session_nonce column now exists, and + """This migration verifies that the session_nonce column now exists, and that the data migration completed successfully. - ''' + """ JOURNO_NUM = 20 @@ -36,7 +43,7 @@ def load_data(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -49,40 +56,39 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'uuid': str(uuid.uuid4()), - 'first_name': random_name(), - 'last_name': random_name(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "uuid": str(uuid.uuid4()), + "first_name": random_name(), + "last_name": random_name(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, uuid, first_name, last_name, + sql = """INSERT INTO journalists (username, uuid, first_name, last_name, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :uuid, :first_name, :last_name, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) def check_upgrade(self): with self.app.app_context(): - journalists = db.engine.execute( - text('SELECT * FROM journalists')).fetchall() + journalists = db.engine.execute(text("SELECT * FROM journalists")).fetchall() for journalist in journalists: assert journalist.session_nonce is not None -class DowngradeTester(): +class DowngradeTester: JOURNO_NUM = 20 @@ -99,7 +105,7 @@ def load_data(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -112,36 +118,36 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'uuid': str(uuid.uuid4()), - 'first_name': random_name(), - 'last_name': random_name(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'session_nonce': random.randint(0, 10000), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "uuid": str(uuid.uuid4()), + "first_name": random_name(), + "last_name": random_name(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "session_nonce": random.randint(0, 10000), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, uuid, first_name, last_name, + sql = """INSERT INTO journalists (username, uuid, first_name, last_name, pw_salt, pw_hash, is_admin, session_nonce, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :uuid, :first_name, :last_name, :pw_salt, :pw_hash, :is_admin, :session_nonce, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''Verify that the session_nonce column is now gone, but otherwise the + """Verify that the session_nonce column is now gone, but otherwise the table has the expected number of rows. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM journalists" journalists = db.engine.execute(text(sql)).fetchall() @@ -150,6 +156,6 @@ def check_downgrade(self): try: # This should produce an exception, as the column (should) # be gone. - assert journalist['session_nonce'] is None + assert journalist["session_nonce"] is None except NoSuchColumnError: pass diff --git a/securedrop/tests/migrations/migration_6db892e17271.py b/securedrop/tests/migrations/migration_6db892e17271.py --- a/securedrop/tests/migrations/migration_6db892e17271.py +++ b/securedrop/tests/migrations/migration_6db892e17271.py @@ -4,40 +4,46 @@ import string import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app -from .helpers import (random_bool, random_bytes, random_chars, random_datetime, - random_username, bool_or_none) +from .helpers import ( + bool_or_none, + random_bool, + random_bytes, + random_chars, + random_datetime, + random_username, +) -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'uuid': str(uuid.uuid4()), - 'filesystem_id': filesystem_id, - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "uuid": str(uuid.uuid4()), + "filesystem_id": filesystem_id, + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (uuid, filesystem_id, + sql = """INSERT INTO sources (uuid, filesystem_id, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:uuid, :filesystem_id, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -50,33 +56,33 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) -class UpgradeTester(): +class UpgradeTester: - '''This migration verifies that the deleted_by_source column now exists, + """This migration verifies that the deleted_by_source column now exists, and that the data migration completed successfully. - ''' + """ SOURCE_NUM = 200 JOURNO_NUM = 20 @@ -100,30 +106,29 @@ def load_data(self): @staticmethod def add_reply(journalist_id, source_id): params = { - 'journalist_id': journalist_id, - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), - 'deleted_by_source': False, + "journalist_id": journalist_id, + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "deleted_by_source": False, } - sql = '''INSERT INTO replies (journalist_id, source_id, filename, + sql = """INSERT INTO replies (journalist_id, source_id, filename, size, deleted_by_source) VALUES (:journalist_id, :source_id, :filename, :size, :deleted_by_source) - ''' + """ db.engine.execute(text(sql), **params) def check_upgrade(self): with self.app.app_context(): - replies = db.engine.execute( - text('SELECT * FROM replies')).fetchall() + replies = db.engine.execute(text("SELECT * FROM replies")).fetchall() assert len(replies) == self.JOURNO_NUM - 1 for reply in replies: assert reply.uuid is not None -class DowngradeTester(): +class DowngradeTester: SOURCE_NUM = 200 JOURNO_NUM = 20 @@ -147,24 +152,24 @@ def load_data(self): @staticmethod def add_reply(journalist_id, source_id): params = { - 'journalist_id': journalist_id, - 'source_id': source_id, - 'uuid': str(uuid.uuid4()), - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), - 'deleted_by_source': False, + "journalist_id": journalist_id, + "source_id": source_id, + "uuid": str(uuid.uuid4()), + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "deleted_by_source": False, } - sql = '''INSERT INTO replies (journalist_id, source_id, uuid, filename, + sql = """INSERT INTO replies (journalist_id, source_id, uuid, filename, size, deleted_by_source) VALUES (:journalist_id, :source_id, :uuid, :filename, :size, :deleted_by_source) - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''Verify that the deleted_by_source column is now gone, and + """Verify that the deleted_by_source column is now gone, and otherwise the table has the expected number of rows. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM replies" replies = db.engine.execute(text(sql)).fetchall() @@ -173,7 +178,7 @@ def check_downgrade(self): try: # This should produce an exception, as the column (should) # be gone. - assert reply['uuid'] is None + assert reply["uuid"] is None except NoSuchColumnError: pass diff --git a/securedrop/tests/migrations/migration_92fba0be98e9.py b/securedrop/tests/migrations/migration_92fba0be98e9.py --- a/securedrop/tests/migrations/migration_92fba0be98e9.py +++ b/securedrop/tests/migrations/migration_92fba0be98e9.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- +import pytest +import sqlalchemy from db import db from journalist_app import create_app -import sqlalchemy -import pytest from .helpers import random_bool, random_datetime diff --git a/securedrop/tests/migrations/migration_a9fe328b053a.py b/securedrop/tests/migrations/migration_a9fe328b053a.py --- a/securedrop/tests/migrations/migration_a9fe328b053a.py +++ b/securedrop/tests/migrations/migration_a9fe328b053a.py @@ -2,53 +2,51 @@ import random import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app from .helpers import random_chars -random.seed('⎦˚◡˚⎣') +random.seed("⎦˚◡˚⎣") class Helper: - def __init__(self): self.journalist_id = None def create_journalist(self): if self.journalist_id is not None: - raise RuntimeError('Journalist already created') + raise RuntimeError("Journalist already created") params = { - 'uuid': str(uuid.uuid4()), - 'username': random_chars(50), + "uuid": str(uuid.uuid4()), + "username": random_chars(50), } - sql = '''INSERT INTO journalists (uuid, username) + sql = """INSERT INTO journalists (uuid, username) VALUES (:uuid, :username) - ''' + """ self.journalist_id = db.engine.execute(text(sql), **params).lastrowid def create_journalist_after_migration(self): if self.journalist_id is not None: - raise RuntimeError('Journalist already created') + raise RuntimeError("Journalist already created") params = { - 'uuid': str(uuid.uuid4()), - 'username': random_chars(50), - 'first_name': random_chars(50), - 'last_name': random_chars(50) + "uuid": str(uuid.uuid4()), + "username": random_chars(50), + "first_name": random_chars(50), + "last_name": random_chars(50), } - sql = ''' + sql = """ INSERT INTO journalists (uuid, username, first_name, last_name) VALUES (:uuid, :username, :first_name, :last_name) - ''' + """ self.journalist_id = db.engine.execute(text(sql), **params).lastrowid class UpgradeTester(Helper): - def __init__(self, config): Helper.__init__(self) self.config = config @@ -59,19 +57,18 @@ def load_data(self): self.create_journalist() def check_upgrade(self): - ''' + """ - Verify that Journalist first and last names are present after upgrade. - ''' + """ with self.app.app_context(): journalists_sql = "SELECT * FROM journalists" journalists = db.engine.execute(text(journalists_sql)).fetchall() for journalist in journalists: - assert journalist['first_name'] is None - assert journalist['last_name'] is None + assert journalist["first_name"] is None + assert journalist["last_name"] is None class DowngradeTester(Helper): - def __init__(self, config): Helper.__init__(self) self.config = config @@ -82,18 +79,18 @@ def load_data(self): self.create_journalist_after_migration() def check_downgrade(self): - ''' + """ - Verify that Journalist first and last names are gone after downgrade. - ''' + """ with self.app.app_context(): journalists_sql = "SELECT * FROM journalists" journalists = db.engine.execute(text(journalists_sql)).fetchall() for journalist in journalists: try: - assert journalist['first_name'] + assert journalist["first_name"] except NoSuchColumnError: pass try: - assert journalist['last_name'] + assert journalist["last_name"] except NoSuchColumnError: pass diff --git a/securedrop/tests/migrations/migration_b060f38c0c31.py b/securedrop/tests/migrations/migration_b060f38c0c31.py --- a/securedrop/tests/migrations/migration_b060f38c0c31.py +++ b/securedrop/tests/migrations/migration_b060f38c0c31.py @@ -5,12 +5,12 @@ from typing import Any, Dict import pytest +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import OperationalError -from db import db -from journalist_app import create_app -from .helpers import random_chars, random_datetime, bool_or_none +from .helpers import bool_or_none, random_chars, random_datetime random.seed("ᕕ( ᐛ )ᕗ") @@ -22,7 +22,7 @@ def add_submission(source_id): "filename": random_chars(50), "size": random.randint(0, 1024 * 1024 * 500), "downloaded": bool_or_none(), - "checksum": random_chars(255, chars="0123456789abcdef") + "checksum": random_chars(255, chars="0123456789abcdef"), } sql = """ INSERT INTO submissions (uuid, source_id, filename, size, downloaded, checksum) diff --git a/securedrop/tests/migrations/migration_b58139cfdc8c.py b/securedrop/tests/migrations/migration_b58139cfdc8c.py --- a/securedrop/tests/migrations/migration_b58139cfdc8c.py +++ b/securedrop/tests/migrations/migration_b58139cfdc8c.py @@ -3,25 +3,24 @@ import os import random import uuid -import mock - from os import path -from sqlalchemy import text -from sqlalchemy.exc import NoSuchColumnError +import mock from db import db from journalist_app import create_app +from sqlalchemy import text +from sqlalchemy.exc import NoSuchColumnError from store import Storage + from .helpers import random_chars, random_datetime -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") -DATA = b'wat' -DATA_CHECKSUM = 'sha256:f00a787f7492a95e165b470702f4fe9373583fbdc025b2c8bdf0262cc48fcff4' +DATA = b"wat" +DATA_CHECKSUM = "sha256:f00a787f7492a95e165b470702f4fe9373583fbdc025b2c8bdf0262cc48fcff4" class Helper: - def __init__(self): self.journalist_id = None self.source_id = None @@ -34,92 +33,92 @@ def counter(self): def create_journalist(self): if self.journalist_id is not None: - raise RuntimeError('Journalist already created') + raise RuntimeError("Journalist already created") params = { - 'uuid': str(uuid.uuid4()), - 'username': random_chars(50), + "uuid": str(uuid.uuid4()), + "username": random_chars(50), } - sql = '''INSERT INTO journalists (uuid, username) + sql = """INSERT INTO journalists (uuid, username) VALUES (:uuid, :username) - ''' + """ self.journalist_id = db.engine.execute(text(sql), **params).lastrowid def create_source(self): if self.source_id is not None: - raise RuntimeError('Source already created') + raise RuntimeError("Source already created") - self.source_filesystem_id = 'aliruhglaiurhgliaurg-{}'.format(self.counter) + self.source_filesystem_id = "aliruhglaiurhgliaurg-{}".format(self.counter) params = { - 'filesystem_id': self.source_filesystem_id, - 'uuid': str(uuid.uuid4()), - 'journalist_designation': random_chars(50), - 'flagged': False, - 'last_updated': random_datetime(nullable=True), - 'pending': False, - 'interaction_count': 0, + "filesystem_id": self.source_filesystem_id, + "uuid": str(uuid.uuid4()), + "journalist_designation": random_chars(50), + "flagged": False, + "last_updated": random_datetime(nullable=True), + "pending": False, + "interaction_count": 0, } - sql = '''INSERT INTO sources (filesystem_id, uuid, journalist_designation, flagged, + sql = """INSERT INTO sources (filesystem_id, uuid, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:filesystem_id, :uuid, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ self.source_id = db.engine.execute(text(sql), **params).lastrowid def create_submission(self, checksum=False): filename = str(uuid.uuid4()) params = { - 'uuid': str(uuid.uuid4()), - 'source_id': self.source_id, - 'filename': filename, - 'size': random.randint(10, 1000), - 'downloaded': False, - + "uuid": str(uuid.uuid4()), + "source_id": self.source_id, + "filename": filename, + "size": random.randint(10, 1000), + "downloaded": False, } if checksum: - params['checksum'] = \ - 'sha256:f00a787f7492a95e165b470702f4fe9373583fbdc025b2c8bdf0262cc48fcff4' - sql = '''INSERT INTO submissions (uuid, source_id, filename, size, downloaded, checksum) + params[ + "checksum" + ] = "sha256:f00a787f7492a95e165b470702f4fe9373583fbdc025b2c8bdf0262cc48fcff4" + sql = """INSERT INTO submissions (uuid, source_id, filename, size, downloaded, checksum) VALUES (:uuid, :source_id, :filename, :size, :downloaded, :checksum) - ''' + """ else: - sql = '''INSERT INTO submissions (uuid, source_id, filename, size, downloaded) + sql = """INSERT INTO submissions (uuid, source_id, filename, size, downloaded) VALUES (:uuid, :source_id, :filename, :size, :downloaded) - ''' + """ return (db.engine.execute(text(sql), **params).lastrowid, filename) def create_reply(self, checksum=False): filename = str(uuid.uuid4()) params = { - 'uuid': str(uuid.uuid4()), - 'source_id': self.source_id, - 'journalist_id': self.journalist_id, - 'filename': filename, - 'size': random.randint(10, 1000), - 'deleted_by_source': False, + "uuid": str(uuid.uuid4()), + "source_id": self.source_id, + "journalist_id": self.journalist_id, + "filename": filename, + "size": random.randint(10, 1000), + "deleted_by_source": False, } if checksum: - params['checksum'] = \ - 'sha256:f00a787f7492a95e165b470702f4fe9373583fbdc025b2c8bdf0262cc48fcff4' - sql = '''INSERT INTO replies (uuid, source_id, journalist_id, filename, size, + params[ + "checksum" + ] = "sha256:f00a787f7492a95e165b470702f4fe9373583fbdc025b2c8bdf0262cc48fcff4" + sql = """INSERT INTO replies (uuid, source_id, journalist_id, filename, size, deleted_by_source, checksum) VALUES (:uuid, :source_id, :journalist_id, :filename, :size, :deleted_by_source, :checksum) - ''' + """ else: - sql = '''INSERT INTO replies (uuid, source_id, journalist_id, filename, size, + sql = """INSERT INTO replies (uuid, source_id, journalist_id, filename, size, deleted_by_source) VALUES (:uuid, :source_id, :journalist_id, :filename, :size, :deleted_by_source) - ''' + """ return (db.engine.execute(text(sql), **params).lastrowid, filename) class UpgradeTester(Helper): - def __init__(self, config): Helper.__init__(self) self.config = config @@ -149,11 +148,11 @@ def load_data(self): if not path.exists(dirname): os.mkdir(dirname) - with io.open(full_path, 'wb') as f: + with io.open(full_path, "wb") as f: f.write(DATA) def check_upgrade(self): - ''' + """ We cannot inject the `SDConfig` object provided by the fixture `config` into the alembic subprocess that actually performs the migration. This is needed to get both the value of the DB URL and access to the function `storage.path`. These values are passed to the `rqworker`, @@ -161,12 +160,11 @@ def check_upgrade(self): `load_data` function provides data that can be manually verified by checking the `rqworker` log file in `/tmp/`. The other part of the migration, creating a table, cannot be tested regardless. - ''' + """ pass class DowngradeTester(Helper): - def __init__(self, config): Helper.__init__(self) self.config = config @@ -189,18 +187,18 @@ def load_data(self): self.add_revoked_token() def check_downgrade(self): - ''' + """ Verify that the checksum column is now gone. The dropping of the revoked_tokens table cannot be checked. If the migration completes, then it wokred correctly. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM submissions" submissions = db.engine.execute(text(sql)).fetchall() for submission in submissions: try: # this should produce an exception since the column is gone - submission['checksum'] + submission["checksum"] except NoSuchColumnError: pass @@ -209,16 +207,16 @@ def check_downgrade(self): for reply in replies: try: # this should produce an exception since the column is gone - submission['checksum'] + submission["checksum"] except NoSuchColumnError: pass def add_revoked_token(self): params = { - 'journalist_id': self.journalist_id, - 'token': 'abc123', + "journalist_id": self.journalist_id, + "token": "abc123", } - sql = '''INSERT INTO revoked_tokens (journalist_id, token) + sql = """INSERT INTO revoked_tokens (journalist_id, token) VALUES (:journalist_id, :token) - ''' + """ db.engine.execute(text(sql), **params) diff --git a/securedrop/tests/migrations/migration_b7f98cfd6a70.py b/securedrop/tests/migrations/migration_b7f98cfd6a70.py --- a/securedrop/tests/migrations/migration_b7f98cfd6a70.py +++ b/securedrop/tests/migrations/migration_b7f98cfd6a70.py @@ -1,46 +1,45 @@ import uuid -from sqlalchemy import text - from db import db from journalist_app import create_app - +from sqlalchemy import text # Random, chosen by fair dice roll -FILESYSTEM_ID = 'FPLIUY3FWFROQ52YHDMXFYKOTIK2FT4GAFN6HTCPPG3TSNAHYOPDDT5C3TR' \ - 'JWDV2IL3JDOS4NFAJNEI73KRQ7HQEVNAF35UCCW5M7VI=' +FILESYSTEM_ID = ( + "FPLIUY3FWFROQ52YHDMXFYKOTIK2FT4GAFN6HTCPPG3TSNAHYOPDDT5C3TR" + "JWDV2IL3JDOS4NFAJNEI73KRQ7HQEVNAF35UCCW5M7VI=" +) class UpgradeTester: - """Insert a source, verify the filesystem_id makes it through untouched - """ + """Insert a source, verify the filesystem_id makes it through untouched""" def __init__(self, config): """This function MUST accept an argument named `config`. - You will likely want to save a reference to the config in your - class, so you can access the database later. + You will likely want to save a reference to the config in your + class, so you can access the database later. """ self.config = config self.app = create_app(config) def load_data(self): """This function loads data into the database and filesystem. It is - executed before the upgrade. + executed before the upgrade. """ with self.app.app_context(): sources = [ { - 'uuid': str(uuid.uuid4()), - 'filesystem_id': FILESYSTEM_ID, - 'journalist_designation': 'sunburned arraignment', - 'interaction_count': 0, + "uuid": str(uuid.uuid4()), + "filesystem_id": FILESYSTEM_ID, + "journalist_designation": "sunburned arraignment", + "interaction_count": 0, }, { - 'uuid': str(uuid.uuid4()), - 'filesystem_id': None, - 'journalist_designation': 'needy transponder', - 'interaction_count': 0, - } + "uuid": str(uuid.uuid4()), + "filesystem_id": None, + "journalist_designation": "needy transponder", + "interaction_count": 0, + }, ] sql = """\ INSERT INTO sources (uuid, filesystem_id, journalist_designation, interaction_count) @@ -50,25 +49,25 @@ def load_data(self): # Insert a source_stars row associated each source for source_id in (1, 2): db.engine.execute( - text("INSERT INTO source_stars (source_id, starred) " - "VALUES (:source_id, :starred)"), - {"source_id": source_id, "starred": True} + text( + "INSERT INTO source_stars (source_id, starred) " + "VALUES (:source_id, :starred)" + ), + {"source_id": source_id, "starred": True}, ) def check_upgrade(self): """This function is run after the upgrade and verifies the state - of the database or filesystem. It MUST raise an exception if the - check fails. + of the database or filesystem. It MUST raise an exception if the + check fails. """ with self.app.app_context(): # Verify remaining single source is the one with a non-NULL filesystem_id - sources = db.engine.execute( - 'SELECT filesystem_id FROM sources' - ).fetchall() + sources = db.engine.execute("SELECT filesystem_id FROM sources").fetchall() assert len(sources) == 1 assert sources[0][0] == FILESYSTEM_ID # Verify that the source_stars #2 row got deleted - stars = db.engine.execute('SELECT source_id FROM source_stars').fetchall() + stars = db.engine.execute("SELECT source_id FROM source_stars").fetchall() assert stars == [(1,)] @@ -78,20 +77,20 @@ class DowngradeTester: def __init__(self, config): """This function MUST accept an argument named `config`. - You will likely want to save a reference to the config in your - class, so you can access the database later. + You will likely want to save a reference to the config in your + class, so you can access the database later. """ self.config = config def load_data(self): """This function loads data into the database and filesystem. It is - executed before the downgrade. + executed before the downgrade. """ pass def check_downgrade(self): """This function is run after the downgrade and verifies the state - of the database or filesystem. It MUST raise an exception if the - check fails. + of the database or filesystem. It MUST raise an exception if the + check fails. """ pass diff --git a/securedrop/tests/migrations/migration_d9d36b6f4d1e.py b/securedrop/tests/migrations/migration_d9d36b6f4d1e.py --- a/securedrop/tests/migrations/migration_d9d36b6f4d1e.py +++ b/securedrop/tests/migrations/migration_d9d36b6f4d1e.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -from db import db -from journalist_app import create_app -import sqlalchemy -import pytest import secrets -from .helpers import random_bool, random_datetime, random_ascii_chars +import pytest +import sqlalchemy +from db import db +from journalist_app import create_app +from .helpers import random_ascii_chars, random_bool, random_datetime index_definition = ( "index", @@ -22,7 +22,9 @@ def get_schema(app): with app.app_context(): result = list( - db.engine.execute(sqlalchemy.text("SELECT type, name, tbl_name, sql FROM sqlite_master")) + db.engine.execute( + sqlalchemy.text("SELECT type, name, tbl_name, sql FROM sqlite_master") + ) ) return ((x[0], x[1], x[2], x[3]) for x in result) @@ -43,7 +45,7 @@ def update_config(): params = { "valid_until": random_datetime(nullable=False), "allow_document_uploads": random_bool(), - "organization_name": random_ascii_chars(secrets.randbelow(75)) + "organization_name": random_ascii_chars(secrets.randbelow(75)), } sql = """ INSERT INTO instance_config ( @@ -62,15 +64,14 @@ def check_upgrade(self): with self.app.app_context(): for query in [ - "SELECT * FROM instance_config WHERE initial_message_min_len != 0", - "SELECT * FROM instance_config WHERE reject_message_with_codename != 0" - ]: + "SELECT * FROM instance_config WHERE initial_message_min_len != 0", + "SELECT * FROM instance_config WHERE reject_message_with_codename != 0", + ]: result = db.engine.execute(sqlalchemy.text(query)).fetchall() assert len(result) == 0 class DowngradeTester: - def __init__(self, config): self.app = create_app(config) @@ -82,8 +83,8 @@ def check_downgrade(self): with self.app.app_context(): for query in [ - "SELECT * FROM instance_config WHERE initial_message_min_len IS NOT NULL", - "SELECT * FROM instance_config WHERE reject_message_with_codename IS NOT NULL" - ]: + "SELECT * FROM instance_config WHERE initial_message_min_len IS NOT NULL", + "SELECT * FROM instance_config WHERE reject_message_with_codename IS NOT NULL", + ]: with pytest.raises(sqlalchemy.exc.OperationalError): db.engine.execute(sqlalchemy.text(query)).fetchall() diff --git a/securedrop/tests/migrations/migration_de00920916bf.py b/securedrop/tests/migrations/migration_de00920916bf.py --- a/securedrop/tests/migrations/migration_de00920916bf.py +++ b/securedrop/tests/migrations/migration_de00920916bf.py @@ -2,33 +2,32 @@ import random import uuid -from sqlalchemy import text - from db import db from journalist_app import create_app +from sqlalchemy import text + from .helpers import random_chars -random.seed('くコ:彡') +random.seed("くコ:彡") class Helper: - def __init__(self): self.journalist_id = None def create_journalist(self, otp_secret="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"): if self.journalist_id is not None: - raise RuntimeError('Journalist already created') + raise RuntimeError("Journalist already created") params = { - 'uuid': str(uuid.uuid4()), - 'username': random_chars(50), - 'session_nonce': 0, - 'otp_secret': otp_secret + "uuid": str(uuid.uuid4()), + "username": random_chars(50), + "session_nonce": 0, + "otp_secret": otp_secret, } - sql = '''INSERT INTO journalists (uuid, username, otp_secret, session_nonce) + sql = """INSERT INTO journalists (uuid, username, otp_secret, session_nonce) VALUES (:uuid, :username, :otp_secret, :session_nonce) - ''' + """ self.journalist_id = db.engine.execute(text(sql), **params).lastrowid @@ -52,11 +51,10 @@ def check_upgrade(self): with self.app.app_context(): journalists_sql = "SELECT * FROM journalists" journalist = db.engine.execute(text(journalists_sql)).first() - assert len(journalist['otp_secret']) == 32 # Varchar ignores length + assert len(journalist["otp_secret"]) == 32 # Varchar ignores length class DowngradeTester(Helper): - def __init__(self, config): Helper.__init__(self) self.config = config @@ -70,4 +68,4 @@ def check_downgrade(self): with self.app.app_context(): journalists_sql = "SELECT * FROM journalists" journalist = db.engine.execute(text(journalists_sql)).first() - assert len(journalist['otp_secret']) == 32 # Varchar ignores length + assert len(journalist["otp_secret"]) == 32 # Varchar ignores length diff --git a/securedrop/tests/migrations/migration_e0a525cbab83.py b/securedrop/tests/migrations/migration_e0a525cbab83.py --- a/securedrop/tests/migrations/migration_e0a525cbab83.py +++ b/securedrop/tests/migrations/migration_e0a525cbab83.py @@ -4,40 +4,46 @@ import string import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app -from .helpers import (random_bool, random_bytes, random_chars, random_datetime, - random_username, bool_or_none) +from .helpers import ( + bool_or_none, + random_bool, + random_bytes, + random_chars, + random_datetime, + random_username, +) -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'uuid': str(uuid.uuid4()), - 'filesystem_id': filesystem_id, - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "uuid": str(uuid.uuid4()), + "filesystem_id": filesystem_id, + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (uuid, filesystem_id, + sql = """INSERT INTO sources (uuid, filesystem_id, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:uuid, :filesystem_id, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -50,33 +56,33 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) -class UpgradeTester(): +class UpgradeTester: - '''This migration verifies that the deleted_by_source column now exists, + """This migration verifies that the deleted_by_source column now exists, and that the data migration completed successfully. - ''' + """ SOURCE_NUM = 200 JOURNO_NUM = 20 @@ -100,28 +106,27 @@ def load_data(self): @staticmethod def add_reply(journalist_id, source_id): params = { - 'journalist_id': journalist_id, - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), + "journalist_id": journalist_id, + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), } - sql = '''INSERT INTO replies (journalist_id, source_id, filename, + sql = """INSERT INTO replies (journalist_id, source_id, filename, size) VALUES (:journalist_id, :source_id, :filename, :size) - ''' + """ db.engine.execute(text(sql), **params) def check_upgrade(self): with self.app.app_context(): - replies = db.engine.execute( - text('SELECT * FROM replies')).fetchall() + replies = db.engine.execute(text("SELECT * FROM replies")).fetchall() assert len(replies) == self.JOURNO_NUM - 1 for reply in replies: assert reply.deleted_by_source == False # noqa -class DowngradeTester(): +class DowngradeTester: SOURCE_NUM = 200 JOURNO_NUM = 20 @@ -145,23 +150,23 @@ def load_data(self): @staticmethod def add_reply(journalist_id, source_id): params = { - 'journalist_id': journalist_id, - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), - 'deleted_by_source': False, + "journalist_id": journalist_id, + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "deleted_by_source": False, } - sql = '''INSERT INTO replies (journalist_id, source_id, filename, + sql = """INSERT INTO replies (journalist_id, source_id, filename, size, deleted_by_source) VALUES (:journalist_id, :source_id, :filename, :size, :deleted_by_source) - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''Verify that the deleted_by_source column is now gone, and + """Verify that the deleted_by_source column is now gone, and otherwise the table has the expected number of rows. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM replies" replies = db.engine.execute(text(sql)).fetchall() @@ -170,7 +175,7 @@ def check_downgrade(self): try: # This should produce an exception, as the column (should) # be gone. - assert reply['deleted_by_source'] is None + assert reply["deleted_by_source"] is None except NoSuchColumnError: pass diff --git a/securedrop/tests/migrations/migration_f2833ac34bb6.py b/securedrop/tests/migrations/migration_f2833ac34bb6.py --- a/securedrop/tests/migrations/migration_f2833ac34bb6.py +++ b/securedrop/tests/migrations/migration_f2833ac34bb6.py @@ -4,22 +4,28 @@ import string import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app -from .helpers import (random_bool, random_bytes, random_chars, random_datetime, - random_username, bool_or_none) +from .helpers import ( + bool_or_none, + random_bool, + random_bytes, + random_chars, + random_datetime, + random_username, +) -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") -class UpgradeTester(): +class UpgradeTester: - '''This migration verifies that the UUID column now exists, and that + """This migration verifies that the UUID column now exists, and that the data migration completed successfully. - ''' + """ JOURNO_NUM = 20 @@ -36,7 +42,7 @@ def load_data(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -49,37 +55,36 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) def check_upgrade(self): with self.app.app_context(): - journalists = db.engine.execute( - text('SELECT * FROM journalists')).fetchall() + journalists = db.engine.execute(text("SELECT * FROM journalists")).fetchall() for journalist in journalists: assert journalist.uuid is not None -class DowngradeTester(): +class DowngradeTester: JOURNO_NUM = 20 @@ -96,7 +101,7 @@ def load_data(self): @staticmethod def add_journalist(): if random_bool(): - otp_secret = random_chars(16, string.ascii_uppercase + '234567') + otp_secret = random_chars(16, string.ascii_uppercase + "234567") else: otp_secret = None @@ -109,32 +114,32 @@ def add_journalist(): last_token = random_chars(6, string.digits) if random_bool() else None params = { - 'username': random_username(), - 'uuid': str(uuid.uuid4()), - 'pw_salt': random_bytes(1, 64, nullable=True), - 'pw_hash': random_bytes(32, 64, nullable=True), - 'is_admin': bool_or_none(), - 'otp_secret': otp_secret, - 'is_totp': is_totp, - 'hotp_counter': hotp_counter, - 'last_token': last_token, - 'created_on': random_datetime(nullable=True), - 'last_access': random_datetime(nullable=True), - 'passphrase_hash': random_bytes(32, 64, nullable=True) + "username": random_username(), + "uuid": str(uuid.uuid4()), + "pw_salt": random_bytes(1, 64, nullable=True), + "pw_hash": random_bytes(32, 64, nullable=True), + "is_admin": bool_or_none(), + "otp_secret": otp_secret, + "is_totp": is_totp, + "hotp_counter": hotp_counter, + "last_token": last_token, + "created_on": random_datetime(nullable=True), + "last_access": random_datetime(nullable=True), + "passphrase_hash": random_bytes(32, 64, nullable=True), } - sql = '''INSERT INTO journalists (username, uuid, pw_salt, pw_hash, + sql = """INSERT INTO journalists (username, uuid, pw_salt, pw_hash, is_admin, otp_secret, is_totp, hotp_counter, last_token, created_on, last_access, passphrase_hash) VALUES (:username, :uuid, :pw_salt, :pw_hash, :is_admin, :otp_secret, :is_totp, :hotp_counter, :last_token, :created_on, :last_access, :passphrase_hash); - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''Verify that the UUID column is now gone, but otherwise the table + """Verify that the UUID column is now gone, but otherwise the table has the expected number of rows. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM journalists" journalists = db.engine.execute(text(sql)).fetchall() @@ -143,6 +148,6 @@ def check_downgrade(self): try: # This should produce an exception, as the column (should) # be gone. - assert journalist['uuid'] is None + assert journalist["uuid"] is None except NoSuchColumnError: pass diff --git a/securedrop/tests/migrations/migration_faac8092c123.py b/securedrop/tests/migrations/migration_faac8092c123.py --- a/securedrop/tests/migrations/migration_faac8092c123.py +++ b/securedrop/tests/migrations/migration_faac8092c123.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- -class UpgradeTester(): - '''This migration has no upgrade because it is only the enabling of - pragmas which do not affect database contents. - ''' +class UpgradeTester: + """This migration has no upgrade because it is only the enabling of + pragmas which do not affect database contents. + """ def __init__(self, config): pass @@ -16,10 +16,10 @@ def check_upgrade(self): pass -class DowngradeTester(): - '''This migration has no downgrade because it is only the enabling of - pragmas, so we don't need to test the downgrade. - ''' +class DowngradeTester: + """This migration has no downgrade because it is only the enabling of + pragmas, so we don't need to test the downgrade. + """ def __init__(self, config): pass diff --git a/securedrop/tests/migrations/migration_fccf57ceef02.py b/securedrop/tests/migrations/migration_fccf57ceef02.py --- a/securedrop/tests/migrations/migration_fccf57ceef02.py +++ b/securedrop/tests/migrations/migration_fccf57ceef02.py @@ -3,41 +3,41 @@ import random import uuid +from db import db +from journalist_app import create_app from sqlalchemy import text from sqlalchemy.exc import NoSuchColumnError -from db import db -from journalist_app import create_app -from .helpers import random_bool, random_chars, random_datetime, bool_or_none +from .helpers import bool_or_none, random_bool, random_chars, random_datetime -random.seed('ᕕ( ᐛ )ᕗ') +random.seed("ᕕ( ᐛ )ᕗ") def add_source(): filesystem_id = random_chars(96) if random_bool() else None params = { - 'filesystem_id': filesystem_id, - 'uuid': str(uuid.uuid4()), - 'journalist_designation': random_chars(50), - 'flagged': bool_or_none(), - 'last_updated': random_datetime(nullable=True), - 'pending': bool_or_none(), - 'interaction_count': random.randint(0, 1000), + "filesystem_id": filesystem_id, + "uuid": str(uuid.uuid4()), + "journalist_designation": random_chars(50), + "flagged": bool_or_none(), + "last_updated": random_datetime(nullable=True), + "pending": bool_or_none(), + "interaction_count": random.randint(0, 1000), } - sql = '''INSERT INTO sources (filesystem_id, uuid, + sql = """INSERT INTO sources (filesystem_id, uuid, journalist_designation, flagged, last_updated, pending, interaction_count) VALUES (:filesystem_id, :uuid, :journalist_designation, :flagged, :last_updated, :pending, :interaction_count) - ''' + """ db.engine.execute(text(sql), **params) -class UpgradeTester(): +class UpgradeTester: - '''This migration verifies that the UUID column now exists, and that + """This migration verifies that the UUID column now exists, and that the data migration completed successfully. - ''' + """ SOURCE_NUM = 200 @@ -64,27 +64,26 @@ def load_data(self): @staticmethod def add_submission(source_id): params = { - 'source_id': source_id, - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), - 'downloaded': bool_or_none(), + "source_id": source_id, + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "downloaded": bool_or_none(), } - sql = '''INSERT INTO submissions (source_id, filename, size, + sql = """INSERT INTO submissions (source_id, filename, size, downloaded) VALUES (:source_id, :filename, :size, :downloaded) - ''' + """ db.engine.execute(text(sql), **params) def check_upgrade(self): with self.app.app_context(): - submissions = db.engine.execute( - text('SELECT * FROM submissions')).fetchall() + submissions = db.engine.execute(text("SELECT * FROM submissions")).fetchall() for submission in submissions: assert submission.uuid is not None -class DowngradeTester(): +class DowngradeTester: SOURCE_NUM = 200 @@ -111,22 +110,22 @@ def load_data(self): @staticmethod def add_submission(source_id): params = { - 'source_id': source_id, - 'uuid': str(uuid.uuid4()), - 'filename': random_chars(50), - 'size': random.randint(0, 1024 * 1024 * 500), - 'downloaded': bool_or_none(), + "source_id": source_id, + "uuid": str(uuid.uuid4()), + "filename": random_chars(50), + "size": random.randint(0, 1024 * 1024 * 500), + "downloaded": bool_or_none(), } - sql = '''INSERT INTO submissions (source_id, uuid, filename, size, + sql = """INSERT INTO submissions (source_id, uuid, filename, size, downloaded) VALUES (:source_id, :uuid, :filename, :size, :downloaded) - ''' + """ db.engine.execute(text(sql), **params) def check_downgrade(self): - '''Verify that the UUID column is now gone, but otherwise the table + """Verify that the UUID column is now gone, but otherwise the table has the expected number of rows. - ''' + """ with self.app.app_context(): sql = "SELECT * FROM submissions" submissions = db.engine.execute(text(sql)).fetchall() @@ -135,6 +134,6 @@ def check_downgrade(self): try: # This should produce an exception, as the column (should) # be gone. - assert submission['uuid'] is None + assert submission["uuid"] is None except NoSuchColumnError: pass diff --git a/securedrop/tests/test_2fa.py b/securedrop/tests/test_2fa.py --- a/securedrop/tests/test_2fa.py +++ b/securedrop/tests/test_2fa.py @@ -1,36 +1,34 @@ # -*- coding: utf-8 -*- -import pytest import time - from contextlib import contextmanager from datetime import datetime, timedelta + +import pytest from flask import url_for +from models import BadTokenException, Journalist from pyotp import TOTP -from models import Journalist, BadTokenException from .utils import login_user from .utils.instrument import InstrumentedApp @contextmanager def totp_window(): - '''To ensure we have enough time during a single TOTP window to do the - whole test, optionally sleep. - ''' + """To ensure we have enough time during a single TOTP window to do the + whole test, optionally sleep. + """ now = datetime.now() # `or 30` to ensure we don't have a zero-length window seconds_left_in_window = ((30 - now.second) % 30) or 30 - window_end = now.replace(microsecond=0) + \ - timedelta(seconds=seconds_left_in_window) + window_end = now.replace(microsecond=0) + timedelta(seconds=seconds_left_in_window) window_end_delta = window_end - now # if we have less than 5 seconds left in this window, sleep to wait for # the next window if window_end_delta < timedelta(seconds=5): - timeout = window_end_delta.seconds + \ - window_end_delta.microseconds / 1000000.0 + timeout = window_end_delta.seconds + window_end_delta.microseconds / 1000000.0 time.sleep(timeout) window_end = window_end + timedelta(seconds=30) @@ -45,144 +43,133 @@ def totp_window(): def test_totp_reuse_protections(journalist_app, test_journo, hardening): """Ensure that logging in twice with the same TOTP token fails. - Also, ensure that last_token is updated accordingly. + Also, ensure that last_token is updated accordingly. """ with totp_window(): - token = TOTP(test_journo['otp_secret']).now() + token = TOTP(test_journo["otp_secret"]).now() with journalist_app.test_client() as app: login_user(app, test_journo) - resp = app.get(url_for('main.logout'), follow_redirects=True) + resp = app.get(url_for("main.logout"), follow_redirects=True) assert resp.status_code == 200 with journalist_app.app_context(): - journo = Journalist.query.get(test_journo['id']) + journo = Journalist.query.get(test_journo["id"]) assert journo.last_token == token with journalist_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(username=test_journo['username'], - password=test_journo['password'], - token=token)) + resp = app.post( + url_for("main.login"), + data=dict( + username=test_journo["username"], password=test_journo["password"], token=token + ), + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Login failed" in text def test_totp_reuse_protections2(journalist_app, test_journo, hardening): """More granular than the preceeding test, we want to make sure the right - exception is being raised in the right place. + exception is being raised in the right place. """ with totp_window(): - token = TOTP(test_journo['otp_secret']).now() + token = TOTP(test_journo["otp_secret"]).now() with journalist_app.app_context(): - Journalist.login(test_journo['username'], - test_journo['password'], - token) + Journalist.login(test_journo["username"], test_journo["password"], token) with pytest.raises(BadTokenException): - Journalist.login(test_journo['username'], - test_journo['password'], - token) + Journalist.login(test_journo["username"], test_journo["password"], token) def test_totp_reuse_protections3(journalist_app, test_journo, hardening): """We want to ensure that padding has no effect on token reuse verification.""" with totp_window(): - token = TOTP(test_journo['otp_secret']).now() + token = TOTP(test_journo["otp_secret"]).now() with journalist_app.app_context(): - Journalist.login(test_journo['username'], - test_journo['password'], - token) + Journalist.login(test_journo["username"], test_journo["password"], token) with pytest.raises(BadTokenException): - Journalist.login(test_journo['username'], - test_journo['password'], - token + " ") + Journalist.login(test_journo["username"], test_journo["password"], token + " ") def test_totp_reuse_protections4(journalist_app, test_journo, hardening): """More granular than the preceeding test, we want to make sure the right - exception is being raised in the right place. + exception is being raised in the right place. """ - invalid_token = '000000' + invalid_token = "000000" with totp_window(): - token = TOTP(test_journo['otp_secret']).now() + token = TOTP(test_journo["otp_secret"]).now() with journalist_app.app_context(): - Journalist.login(test_journo['username'], - test_journo['password'], - token) + Journalist.login(test_journo["username"], test_journo["password"], token) with pytest.raises(BadTokenException): - Journalist.login(test_journo['username'], - test_journo['password'], - invalid_token) + Journalist.login(test_journo["username"], test_journo["password"], invalid_token) with pytest.raises(BadTokenException): - Journalist.login(test_journo['username'], - test_journo['password'], - token) + Journalist.login(test_journo["username"], test_journo["password"], token) def test_bad_token_fails_to_verify_on_admin_new_user_two_factor_page( - journalist_app, test_admin, hardening): - '''Regression test for - https://github.com/freedomofpress/securedrop/pull/1692 - ''' + journalist_app, test_admin, hardening +): + """Regression test for + https://github.com/freedomofpress/securedrop/pull/1692 + """ - invalid_token = '000000' + invalid_token = "000000" with totp_window(): with journalist_app.test_client() as app: login_user(app, test_admin) # Submit the token once with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.new_user_two_factor', - uid=test_admin['id']), - data=dict(token=invalid_token)) + resp = app.post( + url_for("admin.new_user_two_factor", uid=test_admin["id"]), + data=dict(token=invalid_token), + ) assert resp.status_code == 200 ins.assert_message_flashed( - 'There was a problem verifying the two-factor code. Please try again.', - 'error') + "There was a problem verifying the two-factor code. Please try again.", "error" + ) with journalist_app.test_client() as app: login_user(app, test_admin) # Submit the same invalid token again with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.new_user_two_factor', - uid=test_admin['id']), - data=dict(token=invalid_token)) + resp = app.post( + url_for("admin.new_user_two_factor", uid=test_admin["id"]), + data=dict(token=invalid_token), + ) ins.assert_message_flashed( - 'There was a problem verifying the two-factor code. Please try again.', - 'error' + "There was a problem verifying the two-factor code. Please try again.", "error" ) def test_bad_token_fails_to_verify_on_new_user_two_factor_page( - journalist_app, test_journo, hardening): - '''Regression test for - https://github.com/freedomofpress/securedrop/pull/1692 - ''' - invalid_token = '000000' + journalist_app, test_journo, hardening +): + """Regression test for + https://github.com/freedomofpress/securedrop/pull/1692 + """ + invalid_token = "000000" with totp_window(): with journalist_app.test_client() as app: login_user(app, test_journo) # Submit the token once with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('account.new_two_factor'), - data=dict(token=invalid_token)) + resp = app.post(url_for("account.new_two_factor"), data=dict(token=invalid_token)) assert resp.status_code == 200 ins.assert_message_flashed( - 'There was a problem verifying the two-factor code. Please try again.', - 'error' + "There was a problem verifying the two-factor code. Please try again.", "error" ) with journalist_app.test_client() as app: @@ -190,9 +177,7 @@ def test_bad_token_fails_to_verify_on_new_user_two_factor_page( # Submit the same invalid token again with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('account.new_two_factor'), - data=dict(token=invalid_token)) + resp = app.post(url_for("account.new_two_factor"), data=dict(token=invalid_token)) ins.assert_message_flashed( - 'There was a problem verifying the two-factor code. Please try again.', - 'error' + "There was a problem verifying the two-factor code. Please try again.", "error" ) diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -1,83 +1,84 @@ # -*- coding: utf-8 -*- import os -import pytest import re import subprocess from collections import OrderedDict +from os import path +import pytest from alembic.config import Config as AlembicConfig from alembic.script import ScriptDirectory -from os import path -from sqlalchemy import text - from db import db from journalist_app import create_app +from sqlalchemy import text +MIGRATION_PATH = path.join(path.dirname(__file__), "..", "alembic", "versions") -MIGRATION_PATH = path.join(path.dirname(__file__), '..', 'alembic', 'versions') - -ALL_MIGRATIONS = [x.split('.')[0].split('_')[0] - for x in os.listdir(MIGRATION_PATH) - if x.endswith('.py')] +ALL_MIGRATIONS = [ + x.split(".")[0].split("_")[0] for x in os.listdir(MIGRATION_PATH) if x.endswith(".py") +] -WHITESPACE_REGEX = re.compile(r'\s+') +WHITESPACE_REGEX = re.compile(r"\s+") def list_migrations(cfg_path, head): cfg = AlembicConfig(cfg_path) script = ScriptDirectory.from_config(cfg) - migrations = [x.revision - for x in script.walk_revisions(base='base', head=head)] + migrations = [x.revision for x in script.walk_revisions(base="base", head=head)] migrations.reverse() return migrations def upgrade(alembic_config, migration): - subprocess.check_call(['alembic', 'upgrade', migration], - cwd=path.dirname(alembic_config)) + subprocess.check_call(["alembic", "upgrade", migration], cwd=path.dirname(alembic_config)) def downgrade(alembic_config, migration): - subprocess.check_call(['alembic', 'downgrade', migration], - cwd=path.dirname(alembic_config)) + subprocess.check_call(["alembic", "downgrade", migration], cwd=path.dirname(alembic_config)) def get_schema(app): with app.app_context(): - result = list(db.engine.execute(text(''' + result = list( + db.engine.execute( + text( + """ SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name, tbl_name - '''))) + """ + ) + ) + ) return {(x[0], x[1], x[2]): x[3] for x in result} def assert_schemas_equal(left, right): - assert list(left) == list(right), 'Left and right do not contain same list of tables' + assert list(left) == list(right), "Left and right do not contain same list of tables" for (table, left_schema) in list(left.items()): assert_ddl_equal(left_schema, right[table]) def assert_ddl_equal(left, right): - '''Check the "tokenized" DDL is equivalent because, because sometimes - Alembic schemas append columns on the same line to the DDL comes out - like: + """Check the "tokenized" DDL is equivalent because, because sometimes + Alembic schemas append columns on the same line to the DDL comes out + like: - column1 TEXT NOT NULL, column2 TEXT NOT NULL + column1 TEXT NOT NULL, column2 TEXT NOT NULL - and SQLAlchemy comes out: + and SQLAlchemy comes out: - column1 TEXT NOT NULL, - column2 TEXT NOT NULL + column1 TEXT NOT NULL, + column2 TEXT NOT NULL - Also, sometimes CHECK constraints are duplicated by alembic, like: - CHECK (column IN (0, 1)), - CHECK (column IN (0, 1)), - So dedupe alembic's output as well + Also, sometimes CHECK constraints are duplicated by alembic, like: + CHECK (column IN (0, 1)), + CHECK (column IN (0, 1)), + So dedupe alembic's output as well - ''' + """ # ignore the autoindex cases if left is None and right is None: return @@ -93,27 +94,25 @@ def assert_ddl_equal(left, right): right = [x for x in WHITESPACE_REGEX.split(right) if x] # Strip commas and quotes - left = [x.replace("\"", "").replace(",", "") for x in left] + left = [x.replace('"', "").replace(",", "") for x in left] left.sort() - right = [x.replace("\"", "").replace(",", "") for x in right] + right = [x.replace('"', "").replace(",", "") for x in right] right.sort() assert left == right, f"Schemas don't match:\nLeft\n{left_schema}\nRight:\n{right_schema}" -def test_alembic_head_matches_db_models(journalist_app, - alembic_config, - config): - '''This test is to make sure that our database models in `models.py` are - always in sync with the schema generated by `alembic upgrade head`. - ''' +def test_alembic_head_matches_db_models(journalist_app, alembic_config, config): + """This test is to make sure that our database models in `models.py` are + always in sync with the schema generated by `alembic upgrade head`. + """ models_schema = get_schema(journalist_app) os.remove(config.DATABASE_FILE) # Create database file - subprocess.check_call(['sqlite3', config.DATABASE_FILE, '.databases']) - upgrade(alembic_config, 'head') + subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) + upgrade(alembic_config, "head") # Recreate the app to get a new SQLALCHEMY_DATABASE_URI app = create_app(config) @@ -121,22 +120,19 @@ def test_alembic_head_matches_db_models(journalist_app, # The initial migration creates the table 'alembic_version', but this is # not present in the schema created by `db.create_all()`. - alembic_schema = {k: v for k, v in list(alembic_schema.items()) - if k[2] != 'alembic_version'} + alembic_schema = {k: v for k, v in list(alembic_schema.items()) if k[2] != "alembic_version"} assert_schemas_equal(alembic_schema, models_schema) [email protected]('migration', ALL_MIGRATIONS) [email protected]("migration", ALL_MIGRATIONS) def test_alembic_migration_up_and_down(alembic_config, config, migration): upgrade(alembic_config, migration) downgrade(alembic_config, "base") [email protected]('migration', ALL_MIGRATIONS) -def test_schema_unchanged_after_up_then_downgrade(alembic_config, - config, - migration): [email protected]("migration", ALL_MIGRATIONS) +def test_schema_unchanged_after_up_then_downgrade(alembic_config, config, migration): # Create the app here. Using a fixture will init the database. app = create_app(config) @@ -152,21 +148,22 @@ def test_schema_unchanged_after_up_then_downgrade(alembic_config, original_schema = get_schema(app) - upgrade(alembic_config, '+1') - downgrade(alembic_config, '-1') + upgrade(alembic_config, "+1") + downgrade(alembic_config, "-1") reverted_schema = get_schema(app) # The initial migration is a degenerate case because it creates the table # 'alembic_version', but rolling back the migration doesn't clear it. if len(migrations) == 1: - reverted_schema = {k: v for k, v in list(reverted_schema.items()) - if k[2] != 'alembic_version'} + reverted_schema = { + k: v for k, v in list(reverted_schema.items()) if k[2] != "alembic_version" + } assert_schemas_equal(reverted_schema, original_schema) [email protected]('migration', ALL_MIGRATIONS) [email protected]("migration", ALL_MIGRATIONS) def test_upgrade_with_data(alembic_config, config, migration): migrations = list_migrations(alembic_config, migration) if len(migrations) == 1: @@ -178,8 +175,8 @@ def test_upgrade_with_data(alembic_config, config, migration): upgrade(alembic_config, last_migration) # Dynamic module import - mod_name = 'tests.migrations.migration_{}'.format(migration) - mod = __import__(mod_name, fromlist=['UpgradeTester']) + mod_name = "tests.migrations.migration_{}".format(migration) + mod = __import__(mod_name, fromlist=["UpgradeTester"]) # Load the test data upgrade_tester = mod.UpgradeTester(config=config) @@ -192,21 +189,21 @@ def test_upgrade_with_data(alembic_config, config, migration): upgrade_tester.check_upgrade() [email protected]('migration', ALL_MIGRATIONS) [email protected]("migration", ALL_MIGRATIONS) def test_downgrade_with_data(alembic_config, config, migration): # Upgrade to the target upgrade(alembic_config, migration) # Dynamic module import - mod_name = 'tests.migrations.migration_{}'.format(migration) - mod = __import__(mod_name, fromlist=['DowngradeTester']) + mod_name = "tests.migrations.migration_{}".format(migration) + mod = __import__(mod_name, fromlist=["DowngradeTester"]) # Load the test data downgrade_tester = mod.DowngradeTester(config=config) downgrade_tester.load_data() # Downgrade to previous migration - downgrade(alembic_config, '-1') + downgrade(alembic_config, "-1") # Make sure it applied "cleanly" for some definition of clean downgrade_tester.check_downgrade() diff --git a/securedrop/tests/test_db.py b/securedrop/tests/test_db.py --- a/securedrop/tests/test_db.py +++ b/securedrop/tests/test_db.py @@ -1,21 +1,19 @@ # -*- coding: utf-8 -*- import pytest - from mock import MagicMock - -from sqlalchemy import create_engine -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import sessionmaker - -from .utils import db_helper from models import ( InstanceConfig, Journalist, - Submission, - Reply, LoginThrottledException, - get_one_or_else + Reply, + Submission, + get_one_or_else, ) +from sqlalchemy import create_engine +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import sessionmaker + +from .utils import db_helper def test_get_one_or_else_returns_one(journalist_app, test_journo): @@ -23,15 +21,13 @@ def test_get_one_or_else_returns_one(journalist_app, test_journo): # precondition: there must be one journalist assert Journalist.query.count() == 1 - query = Journalist.query.filter_by(username=test_journo['username']) + query = Journalist.query.filter_by(username=test_journo["username"]) selected_journo = get_one_or_else(query, MagicMock(), MagicMock()) - assert selected_journo.id == test_journo['id'] + assert selected_journo.id == test_journo["id"] -def test_get_one_or_else_multiple_results(journalist_app, - test_admin, - test_journo): +def test_get_one_or_else_multiple_results(journalist_app, test_admin, test_journo): with journalist_app.app_context(): # precondition: there must be multiple journalists assert Journalist.query.count() == 2 @@ -52,22 +48,21 @@ def test_get_one_or_else_no_result_found(journalist_app, test_journo): # precondition: there must be one journalist assert Journalist.query.count() == 1 - bad_name = test_journo['username'] + 'aaaaaa' + bad_name = test_journo["username"] + "aaaaaa" query = Journalist.query.filter_by(username=bad_name) mock_logger = MagicMock() mock_abort = MagicMock() get_one_or_else(query, mock_logger, mock_abort) - log_line = ('Found none when one was expected: ' - 'No row was found for one()') + log_line = "Found none when one was expected: " "No row was found for one()" mock_logger.error.assert_called_with(log_line) mock_abort.assert_called_with(404) def test_throttle_login(journalist_app, test_journo): with journalist_app.app_context(): - journalist = test_journo['journalist'] + journalist = test_journo["journalist"] for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): Journalist.throttle_login(journalist) with pytest.raises(LoginThrottledException): @@ -76,31 +71,26 @@ def test_throttle_login(journalist_app, test_journo): def test_submission_string_representation(journalist_app, test_source, app_storage): with journalist_app.app_context(): - db_helper.submit(app_storage, test_source['source'], 2) + db_helper.submit(app_storage, test_source["source"], 2) test_submission = Submission.query.first() test_submission.__repr__() -def test_reply_string_representation(journalist_app, - test_journo, - test_source, - app_storage): +def test_reply_string_representation(journalist_app, test_journo, test_source, app_storage): with journalist_app.app_context(): - db_helper.reply(app_storage, test_journo['journalist'], - test_source['source'], - 2) + db_helper.reply(app_storage, test_journo["journalist"], test_source["source"], 2) test_reply = Reply.query.first() test_reply.__repr__() def test_journalist_string_representation(journalist_app, test_journo): with journalist_app.app_context(): - test_journo['journalist'].__repr__() + test_journo["journalist"].__repr__() def test_source_string_representation(journalist_app, test_source): with journalist_app.app_context(): - test_source['source'].__repr__() + test_source["source"].__repr__() def test_only_one_active_instance_config_can_exist(config, source_app): @@ -115,7 +105,7 @@ def test_only_one_active_instance_config_can_exist(config, source_app): in InstanceConfig.get_current. """ # create a separate session - engine = create_engine(source_app.config['SQLALCHEMY_DATABASE_URI']) + engine = create_engine(source_app.config["SQLALCHEMY_DATABASE_URI"]) session = sessionmaker(bind=engine)() # in the separate session, create an InstanceConfig with default diff --git a/securedrop/tests/test_encryption.py b/securedrop/tests/test_encryption.py --- a/securedrop/tests/test_encryption.py +++ b/securedrop/tests/test_encryption.py @@ -1,12 +1,11 @@ import typing from contextlib import contextmanager +from datetime import datetime from pathlib import Path import pytest as pytest - from db import db -from encryption import EncryptionManager, GpgKeyNotFoundError, GpgEncryptError, GpgDecryptError -from datetime import datetime +from encryption import EncryptionManager, GpgDecryptError, GpgEncryptError, GpgKeyNotFoundError from passphrases import PassphraseGenerator from source_user import create_source_user @@ -17,8 +16,9 @@ def test_get_default(self, config): assert encryption_mgr assert encryption_mgr.get_journalist_public_key() - def test_generate_source_key_pair(self, setup_journalist_key_and_gpg_folder, - source_app, app_storage): + def test_generate_source_key_pair( + self, setup_journalist_key_and_gpg_folder, source_app, app_storage + ): # Given a source user with source_app.app_context(): source_user = create_source_user( @@ -226,8 +226,9 @@ def test_encrypt_source_file(self, setup_journalist_key_and_gpg_folder, tmp_path # For GPG 2.1+, a non-null passphrase _must_ be passed to decrypt() assert not encryption_mgr._gpg.decrypt(encrypted_file, passphrase="test 123").ok - def test_encrypt_and_decrypt_journalist_reply(self, source_app, test_source, - tmp_path, app_storage): + def test_encrypt_and_decrypt_journalist_reply( + self, source_app, test_source, tmp_path, app_storage + ): # Given a source user with a key pair in the default encryption manager source_user1 = test_source["source_user"] encryption_mgr = EncryptionManager.get_default() diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -20,146 +20,161 @@ import re from pathlib import Path -from db import db import i18n import i18n_tool import journalist_app as journalist_app_module import pytest import source_app from babel.core import Locale, UnknownLocaleError -from flask import render_template -from flask import render_template_string -from flask import request -from flask import session +from db import db +from flask import render_template, render_template_string, request, session from flask_babel import gettext from i18n import parse_locale_set from sdconfig import FALLBACK_LOCALE, SDConfig -from sh import pybabel -from sh import sed -from .utils.env import TESTS_DIR +from sh import pybabel, sed from werkzeug.datastructures import Headers +from .utils.env import TESTS_DIR -NEVER_LOCALE = 'eo' # Esperanto +NEVER_LOCALE = "eo" # Esperanto def verify_i18n(app): - not_translated = 'code hello i18n' - translated_fr = 'code bonjour' + not_translated = "code hello i18n" + translated_fr = "code bonjour" - for accepted in ('unknown', 'en_US'): - headers = Headers([('Accept-Language', accepted)]) + for accepted in ("unknown", "en_US"): + headers = Headers([("Accept-Language", accepted)]) with app.test_request_context(headers=headers): - assert not hasattr(request, 'babel_locale') + assert not hasattr(request, "babel_locale") assert not_translated == gettext(not_translated) - assert hasattr(request, 'babel_locale') - assert render_template_string(''' + assert hasattr(request, "babel_locale") + assert ( + render_template_string( + """ {{ gettext('code hello i18n') }} - ''').strip() == not_translated + """ + ).strip() + == not_translated + ) - for lang in ('fr', 'fr-FR'): - headers = Headers([('Accept-Language', lang)]) + for lang in ("fr", "fr-FR"): + headers = Headers([("Accept-Language", lang)]) with app.test_request_context(headers=headers): - assert not hasattr(request, 'babel_locale') + assert not hasattr(request, "babel_locale") assert translated_fr == gettext(not_translated) - assert hasattr(request, 'babel_locale') - assert render_template_string(''' + assert hasattr(request, "babel_locale") + assert ( + render_template_string( + """ {{ gettext('code hello i18n') }} - ''').strip() == translated_fr + """ + ).strip() + == translated_fr + ) # https://github.com/freedomofpress/securedrop/issues/2379 - headers = Headers([('Accept-Language', - 'en-US;q=0.6,fr_FR;q=0.4,nb_NO;q=0.2')]) + headers = Headers([("Accept-Language", "en-US;q=0.6,fr_FR;q=0.4,nb_NO;q=0.2")]) with app.test_request_context(headers=headers): - assert not hasattr(request, 'babel_locale') + assert not hasattr(request, "babel_locale") assert not_translated == gettext(not_translated) - translated_cn = 'code chinese' + translated_cn = "code chinese" - for lang in ('zh-CN', 'zh-Hans-CN'): - headers = Headers([('Accept-Language', lang)]) + for lang in ("zh-CN", "zh-Hans-CN"): + headers = Headers([("Accept-Language", lang)]) with app.test_request_context(headers=headers): - assert not hasattr(request, 'babel_locale') + assert not hasattr(request, "babel_locale") assert translated_cn == gettext(not_translated) - assert hasattr(request, 'babel_locale') - assert render_template_string(''' + assert hasattr(request, "babel_locale") + assert ( + render_template_string( + """ {{ gettext('code hello i18n') }} - ''').strip() == translated_cn + """ + ).strip() + == translated_cn + ) - translated_ar = 'code arabic' + translated_ar = "code arabic" - for lang in ('ar', 'ar-kw'): - headers = Headers([('Accept-Language', lang)]) + for lang in ("ar", "ar-kw"): + headers = Headers([("Accept-Language", lang)]) with app.test_request_context(headers=headers): - assert not hasattr(request, 'babel_locale') + assert not hasattr(request, "babel_locale") assert translated_ar == gettext(not_translated) - assert hasattr(request, 'babel_locale') - assert render_template_string(''' + assert hasattr(request, "babel_locale") + assert ( + render_template_string( + """ {{ gettext('code hello i18n') }} - ''').strip() == translated_ar + """ + ).strip() + == translated_ar + ) with app.test_client() as c: # a request without Accept-Language or "l" argument gets the # default locale - page = c.get('/login') - assert session.get('locale') == 'en_US' + page = c.get("/login") + assert session.get("locale") == "en_US" assert not_translated == gettext(not_translated) - assert b'?l=fr_FR' in page.data - assert b'?l=en_US' not in page.data + assert b"?l=fr_FR" in page.data + assert b"?l=en_US" not in page.data # the session locale should change when the "l" request # argument is present and valid - page = c.get('/login?l=fr_FR', headers=Headers([('Accept-Language', 'en_US')])) - assert session.get('locale') == 'fr_FR' + page = c.get("/login?l=fr_FR", headers=Headers([("Accept-Language", "en_US")])) + assert session.get("locale") == "fr_FR" assert translated_fr == gettext(not_translated) - assert b'?l=fr_FR' not in page.data - assert b'?l=en_US' in page.data + assert b"?l=fr_FR" not in page.data + assert b"?l=en_US" in page.data # confirm that the chosen locale, now in the session, is used # despite not matching the client's Accept-Language header - c.get('/', headers=Headers([('Accept-Language', 'en_US')])) - assert session.get('locale') == 'fr_FR' + c.get("/", headers=Headers([("Accept-Language", "en_US")])) + assert session.get("locale") == "fr_FR" assert translated_fr == gettext(not_translated) # the session locale should not change if an empty "l" request # argument is sent - c.get('/?l=') - assert session.get('locale') == 'fr_FR' + c.get("/?l=") + assert session.get("locale") == "fr_FR" assert translated_fr == gettext(not_translated) # the session locale should not change if no "l" request # argument is sent - c.get('/') - assert session.get('locale') == 'fr_FR' + c.get("/") + assert session.get("locale") == "fr_FR" assert translated_fr == gettext(not_translated) # sending an invalid locale identifier should not change the # session locale - c.get('/?l=YY_ZZ') - assert session.get('locale') == 'fr_FR' + c.get("/?l=YY_ZZ") + assert session.get("locale") == "fr_FR" assert translated_fr == gettext(not_translated) # requesting a valid locale via the request argument "l" # should change the session locale - c.get('/?l=en_US', headers=Headers([('Accept-Language', 'fr_FR')])) - assert session.get('locale') == 'en_US' + c.get("/?l=en_US", headers=Headers([("Accept-Language", "fr_FR")])) + assert session.get("locale") == "en_US" assert not_translated == gettext(not_translated) # again, the session locale should stick even if not included # in the client's Accept-Language header - c.get('/', headers=Headers([('Accept-Language', 'fr_FR')])) - assert session.get('locale') == 'en_US' + c.get("/", headers=Headers([("Accept-Language", "fr_FR")])) + assert session.get("locale") == "en_US" assert not_translated == gettext(not_translated) with app.test_request_context(): - assert '' == render_template('locales.html') + assert "" == render_template("locales.html") with app.test_client() as c: - c.get('/') - locales = render_template('locales.html') - assert '?l=fr_FR' in locales - assert '?l=en_US' not in locales + c.get("/") + locales = render_template("locales.html") + assert "?l=fr_FR" in locales + assert "?l=en_US" not in locales # Test that A[lang,hreflang] attributes (if present) will validate as # BCP47/RFC5646 language tags from `i18n.RequestLocaleInfo.language_tag`. @@ -170,8 +185,8 @@ def verify_i18n(app): assert 'hreflang="en-US"' in locales assert 'hreflang="fr-FR"' in locales - c.get('/?l=ar') - base = render_template('base.html') + c.get("/?l=ar") + base = render_template("base.html") assert 'dir="rtl"' in base @@ -181,48 +196,55 @@ def test_i18n(journalist_app, config): del journalist_app sources = [ - os.path.join(TESTS_DIR, 'i18n/code.py'), - os.path.join(TESTS_DIR, 'i18n/template.html'), + os.path.join(TESTS_DIR, "i18n/code.py"), + os.path.join(TESTS_DIR, "i18n/template.html"), ] - i18n_tool.I18NTool().main([ - '--verbose', - 'translate-messages', - '--mapping', os.path.join(TESTS_DIR, 'i18n/babel.cfg'), - '--translations-dir', config.TEMP_DIR, - '--sources', ",".join(sources), - '--extract-update', - ]) - - pot = os.path.join(config.TEMP_DIR, 'messages.pot') - pybabel('init', '-i', pot, '-d', config.TEMP_DIR, '-l', 'en_US') - - for (l, s) in (('fr_FR', 'code bonjour'), - ('zh_Hans', 'code chinese'), - ('ar', 'code arabic'), - ('nb_NO', 'code norwegian'), - ('es_ES', 'code spanish')): - pybabel('init', '-i', pot, '-d', config.TEMP_DIR, '-l', l) - po = os.path.join(config.TEMP_DIR, l, 'LC_MESSAGES/messages.po') - sed('-i', '-e', - '/code hello i18n/,+1s/msgstr ""/msgstr "{}"/'.format(s), - po) - - i18n_tool.I18NTool().main([ - '--verbose', - 'translate-messages', - '--translations-dir', config.TEMP_DIR, - '--compile', - ]) + i18n_tool.I18NTool().main( + [ + "--verbose", + "translate-messages", + "--mapping", + os.path.join(TESTS_DIR, "i18n/babel.cfg"), + "--translations-dir", + config.TEMP_DIR, + "--sources", + ",".join(sources), + "--extract-update", + ] + ) + + pot = os.path.join(config.TEMP_DIR, "messages.pot") + pybabel("init", "-i", pot, "-d", config.TEMP_DIR, "-l", "en_US") + + for (l, s) in ( + ("fr_FR", "code bonjour"), + ("zh_Hans", "code chinese"), + ("ar", "code arabic"), + ("nb_NO", "code norwegian"), + ("es_ES", "code spanish"), + ): + pybabel("init", "-i", pot, "-d", config.TEMP_DIR, "-l", l) + po = os.path.join(config.TEMP_DIR, l, "LC_MESSAGES/messages.po") + sed("-i", "-e", '/code hello i18n/,+1s/msgstr ""/msgstr "{}"/'.format(s), po) + + i18n_tool.I18NTool().main( + [ + "--verbose", + "translate-messages", + "--translations-dir", + config.TEMP_DIR, + "--compile", + ] + ) fake_config = SDConfig() - fake_config.SUPPORTED_LOCALES = ['ar', 'en_US', 'fr_FR', 'nb_NO', 'zh_Hans'] + fake_config.SUPPORTED_LOCALES = ["ar", "en_US", "fr_FR", "nb_NO", "zh_Hans"] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) # Use our config (and not an app fixture) because the i18n module # grabs values at init time and we can't inject them later. - for app in (journalist_app_module.create_app(fake_config), - source_app.create_app(fake_config)): + for app in (journalist_app_module.create_app(fake_config), source_app.create_app(fake_config)): with app.app_context(): db.create_all() assert list(i18n.LOCALES.keys()) == fake_config.SUPPORTED_LOCALES @@ -244,10 +266,10 @@ def test_no_usable_fallback_locale(journalist_app, config): i18n.USABLE_LOCALES = set() - with pytest.raises(ValueError, match='in the set of usable locales'): + with pytest.raises(ValueError, match="in the set of usable locales"): journalist_app_module.create_app(fake_config) - with pytest.raises(ValueError, match='in the set of usable locales'): + with pytest.raises(ValueError, match="in the set of usable locales"): source_app.create_app(fake_config) @@ -261,11 +283,10 @@ def test_unusable_default_but_usable_fallback_locale(config, caplog): fake_config.SUPPORTED_LOCALES = [NEVER_LOCALE, FALLBACK_LOCALE] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) - for app in (journalist_app_module.create_app(fake_config), - source_app.create_app(fake_config)): + for app in (journalist_app_module.create_app(fake_config), source_app.create_app(fake_config)): with app.app_context(): assert NEVER_LOCALE in caplog.text - assert 'not in the set of usable locales' in caplog.text + assert "not in the set of usable locales" in caplog.text def test_invalid_locales(config): @@ -273,7 +294,7 @@ def test_invalid_locales(config): An invalid locale raises an error during app configuration. """ fake_config = SDConfig() - fake_config.SUPPORTED_LOCALES = [FALLBACK_LOCALE, 'yy_ZZ'] + fake_config.SUPPORTED_LOCALES = [FALLBACK_LOCALE, "yy_ZZ"] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) with pytest.raises(UnknownLocaleError): @@ -290,22 +311,21 @@ def test_valid_but_unusable_locales(config, caplog): """ fake_config = SDConfig() - fake_config.SUPPORTED_LOCALES = [FALLBACK_LOCALE, 'wae_CH'] + fake_config.SUPPORTED_LOCALES = [FALLBACK_LOCALE, "wae_CH"] fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR) - for app in (journalist_app_module.create_app(fake_config), - source_app.create_app(fake_config)): + for app in (journalist_app_module.create_app(fake_config), source_app.create_app(fake_config)): with app.app_context(): - assert 'wae' in caplog.text - assert 'not in the set of usable locales' in caplog.text + assert "wae" in caplog.text + assert "not in the set of usable locales" in caplog.text def test_language_tags(): - assert i18n.RequestLocaleInfo(Locale.parse('en')).language_tag == 'en' - assert i18n.RequestLocaleInfo(Locale.parse('en-US', sep="-")).language_tag == 'en-US' - assert i18n.RequestLocaleInfo(Locale.parse('en-us', sep="-")).language_tag == 'en-US' - assert i18n.RequestLocaleInfo(Locale.parse('en_US')).language_tag == 'en-US' - assert i18n.RequestLocaleInfo(Locale.parse('zh_Hant')).language_tag == 'zh-Hant' + assert i18n.RequestLocaleInfo(Locale.parse("en")).language_tag == "en" + assert i18n.RequestLocaleInfo(Locale.parse("en-US", sep="-")).language_tag == "en-US" + assert i18n.RequestLocaleInfo(Locale.parse("en-us", sep="-")).language_tag == "en-US" + assert i18n.RequestLocaleInfo(Locale.parse("en_US")).language_tag == "en-US" + assert i18n.RequestLocaleInfo(Locale.parse("zh_Hant")).language_tag == "zh-Hant" # Grab the journalist_app fixture to trigger creation of resources @@ -314,18 +334,18 @@ def test_html_en_lang_correct(journalist_app, config): del journalist_app app = journalist_app_module.create_app(config).test_client() - resp = app.get('/', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/", follow_redirects=True) + html = resp.data.decode("utf-8") assert re.compile('<html lang="en-US".*>').search(html), html app = source_app.create_app(config).test_client() - resp = app.get('/', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/", follow_redirects=True) + html = resp.data.decode("utf-8") assert re.compile('<html lang="en-US".*>').search(html), html # check '/generate' too because '/' uses a different template - resp = app.post('/generate', data={'tor2web_check': 'href="fake.onion"'}, follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.post("/generate", data={"tor2web_check": 'href="fake.onion"'}, follow_redirects=True) + html = resp.data.decode("utf-8") assert re.compile('<html lang="en-US".*>').search(html), html @@ -336,21 +356,22 @@ def test_html_fr_lang_correct(journalist_app, config): # Then delete it because using it won't test what we want del journalist_app - config.SUPPORTED_LOCALES = ['fr_FR', 'en_US'] + config.SUPPORTED_LOCALES = ["fr_FR", "en_US"] app = journalist_app_module.create_app(config).test_client() - resp = app.get('/?l=fr_FR', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/?l=fr_FR", follow_redirects=True) + html = resp.data.decode("utf-8") assert re.compile('<html lang="fr-FR".*>').search(html), html app = source_app.create_app(config).test_client() - resp = app.get('/?l=fr_FR', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/?l=fr_FR", follow_redirects=True) + html = resp.data.decode("utf-8") assert re.compile('<html lang="fr-FR".*>').search(html), html # check '/generate' too because '/' uses a different template - resp = app.post('/generate?l=fr_FR', data={'tor2web_check': 'href="fake.onion"'}, - follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.post( + "/generate?l=fr_FR", data={"tor2web_check": 'href="fake.onion"'}, follow_redirects=True + ) + html = resp.data.decode("utf-8") assert re.compile('<html lang="fr-FR".*>').search(html), html @@ -361,29 +382,31 @@ def test_html_attributes(journalist_app, config): # Then delete it because using it won't test what we want del journalist_app - config.SUPPORTED_LOCALES = ['ar', 'en_US'] + config.SUPPORTED_LOCALES = ["ar", "en_US"] app = journalist_app_module.create_app(config).test_client() - resp = app.get('/?l=ar', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/?l=ar", follow_redirects=True) + html = resp.data.decode("utf-8") assert '<html lang="ar" dir="rtl">' in html - resp = app.get('/?l=en_US', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/?l=en_US", follow_redirects=True) + html = resp.data.decode("utf-8") assert '<html lang="en-US" dir="ltr">' in html app = source_app.create_app(config).test_client() - resp = app.get('/?l=ar', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/?l=ar", follow_redirects=True) + html = resp.data.decode("utf-8") assert '<html lang="ar" dir="rtl">' in html - resp = app.get('/?l=en_US', follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.get("/?l=en_US", follow_redirects=True) + html = resp.data.decode("utf-8") assert '<html lang="en-US" dir="ltr">' in html # check '/generate' too because '/' uses a different template - resp = app.post('/generate?l=ar', data={'tor2web_check': 'href="fake.onion"'}, - follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.post( + "/generate?l=ar", data={"tor2web_check": 'href="fake.onion"'}, follow_redirects=True + ) + html = resp.data.decode("utf-8") assert '<html lang="ar" dir="rtl">' in html - resp = app.post('/generate?l=en_US', data={'tor2web_check': 'href="fake.onion"'}, - follow_redirects=True) - html = resp.data.decode('utf-8') + resp = app.post( + "/generate?l=en_US", data={"tor2web_check": 'href="fake.onion"'}, follow_redirects=True + ) + html = resp.data.decode("utf-8") assert '<html lang="en-US" dir="ltr">' in html diff --git a/securedrop/tests/test_i18n_tool.py b/securedrop/tests/test_i18n_tool.py --- a/securedrop/tests/test_i18n_tool.py +++ b/securedrop/tests/test_i18n_tool.py @@ -2,15 +2,15 @@ import io import os -from os.path import abspath, dirname, exists, getmtime, join, realpath -import i18n_tool -from mock import patch -import pytest import shutil import signal import time +from os.path import abspath, dirname, exists, getmtime, join, realpath -from sh import sed, msginit, pybabel, git, touch +import i18n_tool +import pytest +from mock import patch +from sh import git, msginit, pybabel, sed, touch def dummy_translate(po): @@ -32,186 +32,199 @@ def dummy_translate(po): class TestI18NTool(object): - def setup(self): self.dir = abspath(dirname(realpath(__file__))) def test_main(self, tmpdir, caplog): with pytest.raises(SystemExit): - i18n_tool.I18NTool().main(['--help']) + i18n_tool.I18NTool().main(["--help"]) tool = i18n_tool.I18NTool() - with patch.object(tool, - 'setup_verbosity', - side_effect=KeyboardInterrupt): - assert tool.main([ - 'translate-messages', - '--translations-dir', str(tmpdir) - ]) == signal.SIGINT + with patch.object(tool, "setup_verbosity", side_effect=KeyboardInterrupt): + assert ( + tool.main(["translate-messages", "--translations-dir", str(tmpdir)]) + == signal.SIGINT + ) def test_translate_desktop_l10n(self, tmpdir): in_files = {} - for what in ('source', 'journalist'): - in_files[what] = join(str(tmpdir), what + '.desktop.in') - shutil.copy(join(self.dir, 'i18n/' + what + '.desktop.in'), - in_files[what]) - i18n_tool.I18NTool().main([ - '--verbose', - 'translate-desktop', - '--translations-dir', str(tmpdir), - '--sources', in_files['source'], - '--extract-update', - ]) - messages_file = join(str(tmpdir), 'desktop.pot') + for what in ("source", "journalist"): + in_files[what] = join(str(tmpdir), what + ".desktop.in") + shutil.copy(join(self.dir, "i18n/" + what + ".desktop.in"), in_files[what]) + i18n_tool.I18NTool().main( + [ + "--verbose", + "translate-desktop", + "--translations-dir", + str(tmpdir), + "--sources", + in_files["source"], + "--extract-update", + ] + ) + messages_file = join(str(tmpdir), "desktop.pot") assert exists(messages_file) with io.open(messages_file) as fobj: pot = fobj.read() - assert 'SecureDrop Source Interfaces' in pot + assert "SecureDrop Source Interfaces" in pot # pretend this happened a few seconds ago few_seconds_ago = time.time() - 60 os.utime(messages_file, (few_seconds_ago, few_seconds_ago)) - i18n_file = join(str(tmpdir), 'source.desktop') + i18n_file = join(str(tmpdir), "source.desktop") # # Extract+update but do not compile # old_messages_mtime = getmtime(messages_file) assert not exists(i18n_file) - i18n_tool.I18NTool().main([ - '--verbose', - 'translate-desktop', - '--translations-dir', str(tmpdir), - '--sources', ",".join(list(in_files.values())), - '--extract-update', - ]) + i18n_tool.I18NTool().main( + [ + "--verbose", + "translate-desktop", + "--translations-dir", + str(tmpdir), + "--sources", + ",".join(list(in_files.values())), + "--extract-update", + ] + ) assert not exists(i18n_file) current_messages_mtime = getmtime(messages_file) assert old_messages_mtime < current_messages_mtime - locale = 'fr_FR' + locale = "fr_FR" po_file = join(str(tmpdir), locale + ".po") msginit( - '--no-translator', - '--locale', locale, - '--output', po_file, - '--input', messages_file) - source = 'SecureDrop Source Interfaces' - sed('-i', '-e', - '/{}/,+1s/msgstr ""/msgstr "SOURCE FR"/'.format(source), - po_file) + "--no-translator", "--locale", locale, "--output", po_file, "--input", messages_file + ) + source = "SecureDrop Source Interfaces" + sed("-i", "-e", '/{}/,+1s/msgstr ""/msgstr "SOURCE FR"/'.format(source), po_file) assert exists(po_file) # Regression test to trigger bug introduced when adding # Romanian as an accepted language. - locale = 'ro' + locale = "ro" po_file = join(str(tmpdir), locale + ".po") msginit( - '--no-translator', - '--locale', locale, - '--output', po_file, - '--input', messages_file) - source = 'SecureDrop Source Interfaces' - sed('-i', '-e', - '/{}/,+1s/msgstr ""/msgstr "SOURCE RO"/'.format(source), - po_file) + "--no-translator", "--locale", locale, "--output", po_file, "--input", messages_file + ) + source = "SecureDrop Source Interfaces" + sed("-i", "-e", '/{}/,+1s/msgstr ""/msgstr "SOURCE RO"/'.format(source), po_file) assert exists(po_file) # # Compile but do not extract+update # old_messages_mtime = current_messages_mtime - i18n_tool.I18NTool().main([ - '--verbose', - 'translate-desktop', - '--translations-dir', str(tmpdir), - '--sources', ",".join(list(in_files.values()) + ['BOOM']), - '--compile', - ]) + i18n_tool.I18NTool().main( + [ + "--verbose", + "translate-desktop", + "--translations-dir", + str(tmpdir), + "--sources", + ",".join(list(in_files.values()) + ["BOOM"]), + "--compile", + ] + ) assert old_messages_mtime == getmtime(messages_file) with io.open(po_file) as fobj: po = fobj.read() - assert 'SecureDrop Source Interfaces' in po - assert 'SecureDrop Journalist Interfaces' not in po + assert "SecureDrop Source Interfaces" in po + assert "SecureDrop Journalist Interfaces" not in po with io.open(i18n_file) as fobj: i18n = fobj.read() - assert 'SOURCE FR' in i18n + assert "SOURCE FR" in i18n def test_translate_messages_l10n(self, tmpdir): source = [ - join(self.dir, 'i18n/code.py'), - join(self.dir, 'i18n/template.html'), + join(self.dir, "i18n/code.py"), + join(self.dir, "i18n/template.html"), ] args = [ - '--verbose', - 'translate-messages', - '--translations-dir', str(tmpdir), - '--mapping', join(self.dir, 'i18n/babel.cfg'), - '--sources', ",".join(source), - '--extract-update', - '--compile', + "--verbose", + "translate-messages", + "--translations-dir", + str(tmpdir), + "--mapping", + join(self.dir, "i18n/babel.cfg"), + "--sources", + ",".join(source), + "--extract-update", + "--compile", ] i18n_tool.I18NTool().main(args) - messages_file = join(str(tmpdir), 'messages.pot') + messages_file = join(str(tmpdir), "messages.pot") assert exists(messages_file) - with io.open(messages_file, 'rb') as fobj: + with io.open(messages_file, "rb") as fobj: pot = fobj.read() - assert b'code hello i18n' in pot - assert b'template hello i18n' in pot + assert b"code hello i18n" in pot + assert b"template hello i18n" in pot - locale = 'en_US' + locale = "en_US" locale_dir = join(str(tmpdir), locale) - pybabel('init', '-i', messages_file, '-d', str(tmpdir), '-l', locale) + pybabel("init", "-i", messages_file, "-d", str(tmpdir), "-l", locale) - po_file = join(locale_dir, 'LC_MESSAGES/messages.po') + po_file = join(locale_dir, "LC_MESSAGES/messages.po") dummy_translate(po_file) - mo_file = join(locale_dir, 'LC_MESSAGES/messages.mo') + mo_file = join(locale_dir, "LC_MESSAGES/messages.mo") assert not exists(mo_file) i18n_tool.I18NTool().main(args) assert exists(mo_file) - with io.open(mo_file, mode='rb') as fobj: + with io.open(mo_file, mode="rb") as fobj: mo = fobj.read() - assert b'code hello i18n' in mo - assert b'template hello i18n' in mo + assert b"code hello i18n" in mo + assert b"template hello i18n" in mo def test_translate_messages_compile_arg(self, tmpdir): args = [ - '--verbose', - 'translate-messages', - '--translations-dir', str(tmpdir), - '--mapping', join(self.dir, 'i18n/babel.cfg'), + "--verbose", + "translate-messages", + "--translations-dir", + str(tmpdir), + "--mapping", + join(self.dir, "i18n/babel.cfg"), ] - i18n_tool.I18NTool().main(args + [ - '--sources', join(self.dir, 'i18n/code.py'), - '--extract-update', - ]) - messages_file = join(str(tmpdir), 'messages.pot') + i18n_tool.I18NTool().main( + args + + [ + "--sources", + join(self.dir, "i18n/code.py"), + "--extract-update", + ] + ) + messages_file = join(str(tmpdir), "messages.pot") assert exists(messages_file) with io.open(messages_file) as fobj: pot = fobj.read() - assert 'code hello i18n' in pot + assert "code hello i18n" in pot - locale = 'en_US' + locale = "en_US" locale_dir = join(str(tmpdir), locale) - po_file = join(locale_dir, 'LC_MESSAGES/messages.po') - pybabel(['init', '-i', messages_file, '-d', str(tmpdir), '-l', locale]) + po_file = join(locale_dir, "LC_MESSAGES/messages.po") + pybabel(["init", "-i", messages_file, "-d", str(tmpdir), "-l", locale]) assert exists(po_file) # pretend this happened a few seconds ago few_seconds_ago = time.time() - 60 os.utime(po_file, (few_seconds_ago, few_seconds_ago)) - mo_file = join(locale_dir, 'LC_MESSAGES/messages.mo') + mo_file = join(locale_dir, "LC_MESSAGES/messages.mo") # # Extract+update but do not compile # old_po_mtime = getmtime(po_file) assert not exists(mo_file) - i18n_tool.I18NTool().main(args + [ - '--sources', join(self.dir, 'i18n/code.py'), - '--extract-update', - ]) + i18n_tool.I18NTool().main( + args + + [ + "--sources", + join(self.dir, "i18n/code.py"), + "--extract-update", + ] + ) assert not exists(mo_file) current_po_mtime = getmtime(po_file) assert old_po_mtime < current_po_mtime @@ -224,74 +237,72 @@ def test_translate_messages_compile_arg(self, tmpdir): # Compile but do not extract+update # source = [ - join(self.dir, 'i18n/code.py'), - join(self.dir, 'i18n/template.html'), + join(self.dir, "i18n/code.py"), + join(self.dir, "i18n/template.html"), ] current_po_mtime = getmtime(po_file) - i18n_tool.I18NTool().main(args + [ - '--sources', ",".join(source), - '--compile', - ]) + i18n_tool.I18NTool().main( + args + + [ + "--sources", + ",".join(source), + "--compile", + ] + ) assert current_po_mtime == getmtime(po_file) - with io.open(mo_file, mode='rb') as fobj: + with io.open(mo_file, mode="rb") as fobj: mo = fobj.read() - assert b'code hello i18n' in mo - assert b'template hello i18n' not in mo + assert b"code hello i18n" in mo + assert b"template hello i18n" not in mo def test_require_git_email_name(self, tmpdir): - k = {'_cwd': str(tmpdir)} - git('init', **k) + k = {"_cwd": str(tmpdir)} + git("init", **k) with pytest.raises(Exception) as excinfo: i18n_tool.I18NTool.require_git_email_name(str(tmpdir)) - assert 'please set name' in str(excinfo.value) + assert "please set name" in str(excinfo.value) - git.config('user.email', "[email protected]", **k) - git.config('user.name', "Your Name", **k) + git.config("user.email", "[email protected]", **k) + git.config("user.name", "Your Name", **k) assert i18n_tool.I18NTool.require_git_email_name(str(tmpdir)) def test_update_docs(self, tmpdir, caplog): - k = {'_cwd': str(tmpdir)} + k = {"_cwd": str(tmpdir)} git.init(**k) - git.config('user.email', "[email protected]", **k) - git.config('user.name', "Your Name", **k) - os.makedirs(join(str(tmpdir), 'docs/includes')) - touch('docs/includes/l10n.txt', **k) - git.add('docs/includes/l10n.txt', **k) - git.commit('-m', 'init', **k) - - i18n_tool.I18NTool().main([ - '--verbose', - 'update-docs', - '--docs-repo-dir', str(tmpdir)]) - assert 'l10n.txt updated' in caplog.text + git.config("user.email", "[email protected]", **k) + git.config("user.name", "Your Name", **k) + os.makedirs(join(str(tmpdir), "docs/includes")) + touch("docs/includes/l10n.txt", **k) + git.add("docs/includes/l10n.txt", **k) + git.commit("-m", "init", **k) + + i18n_tool.I18NTool().main(["--verbose", "update-docs", "--docs-repo-dir", str(tmpdir)]) + assert "l10n.txt updated" in caplog.text caplog.clear() - i18n_tool.I18NTool().main([ - '--verbose', - 'update-docs', - '--docs-repo-dir', str(tmpdir)]) - assert 'l10n.txt already up to date' in caplog.text + i18n_tool.I18NTool().main(["--verbose", "update-docs", "--docs-repo-dir", str(tmpdir)]) + assert "l10n.txt already up to date" in caplog.text def test_update_from_weblate(self, tmpdir, caplog): d = str(tmpdir) - for repo in ('i18n', 'securedrop'): + for repo in ("i18n", "securedrop"): os.mkdir(join(d, repo)) - k = {'_cwd': join(d, repo)} + k = {"_cwd": join(d, repo)} git.init(**k) - git.config('user.email', '[email protected]', **k) - git.config('user.name', 'Loïc Nordhøy', **k) - touch('README.md', **k) - git.add('README.md', **k) - git.commit('-m', 'README', 'README.md', **k) - for o in os.listdir(join(self.dir, 'i18n')): - f = join(self.dir, 'i18n', o) + git.config("user.email", "[email protected]", **k) + git.config("user.name", "Loïc Nordhøy", **k) + touch("README.md", **k) + git.add("README.md", **k) + git.commit("-m", "README", "README.md", **k) + for o in os.listdir(join(self.dir, "i18n")): + f = join(self.dir, "i18n", o) if os.path.isfile(f): - shutil.copyfile(f, join(d, 'i18n', o)) + shutil.copyfile(f, join(d, "i18n", o)) else: - shutil.copytree(f, join(d, 'i18n', o)) - k = {'_cwd': join(d, 'i18n')} - git.add('securedrop', 'install_files', **k) - git.commit('-m', 'init', '-a', **k) - git.checkout('-b', 'i18n', 'master', **k) + shutil.copytree(f, join(d, "i18n", o)) + k = {"_cwd": join(d, "i18n")} + git.add("securedrop", "install_files", **k) + git.commit("-m", "init", "-a", **k) + git.checkout("-b", "i18n", "master", **k) def r(): return "".join([str(l) for l in caplog.records]) @@ -301,78 +312,96 @@ def r(): # into account despite the fact that it exists in weblate. # caplog.clear() - i18n_tool.I18NTool().main([ - '--verbose', - 'update-from-weblate', - '--root', join(str(tmpdir), 'securedrop'), - '--url', join(str(tmpdir), 'i18n'), - '--supported-languages', 'nl', - ]) - assert 'l10n: updated Dutch (nl)' in r() - assert 'l10n: updated German (de_DE)' not in r() + i18n_tool.I18NTool().main( + [ + "--verbose", + "update-from-weblate", + "--root", + join(str(tmpdir), "securedrop"), + "--url", + join(str(tmpdir), "i18n"), + "--supported-languages", + "nl", + ] + ) + assert "l10n: updated Dutch (nl)" in r() + assert "l10n: updated German (de_DE)" not in r() # # de_DE is added but there is no change in the nl translation # therefore nothing is done for nl # caplog.clear() - i18n_tool.I18NTool().main([ - '--verbose', - 'update-from-weblate', - '--root', join(str(tmpdir), 'securedrop'), - '--url', join(str(tmpdir), 'i18n'), - '--supported-languages', 'nl,de_DE', - ]) - assert 'l10n: updated Dutch (nl)' not in r() - assert 'l10n: updated German (de_DE)' in r() + i18n_tool.I18NTool().main( + [ + "--verbose", + "update-from-weblate", + "--root", + join(str(tmpdir), "securedrop"), + "--url", + join(str(tmpdir), "i18n"), + "--supported-languages", + "nl,de_DE", + ] + ) + assert "l10n: updated Dutch (nl)" not in r() + assert "l10n: updated German (de_DE)" in r() # # nothing new for nl or de_DE: nothing is done # caplog.clear() - i18n_tool.I18NTool().main([ - '--verbose', - 'update-from-weblate', - '--root', join(str(tmpdir), 'securedrop'), - '--url', join(str(tmpdir), 'i18n'), - '--supported-languages', 'nl,de_DE', - ]) - assert 'l10n: updated Dutch (nl)' not in r() - assert 'l10n: updated German (de_DE)' not in r() - message = str(git('--no-pager', '-C', 'securedrop', 'show', - _cwd=d, _encoding='utf-8')) + i18n_tool.I18NTool().main( + [ + "--verbose", + "update-from-weblate", + "--root", + join(str(tmpdir), "securedrop"), + "--url", + join(str(tmpdir), "i18n"), + "--supported-languages", + "nl,de_DE", + ] + ) + assert "l10n: updated Dutch (nl)" not in r() + assert "l10n: updated German (de_DE)" not in r() + message = str(git("--no-pager", "-C", "securedrop", "show", _cwd=d, _encoding="utf-8")) assert "Loïc" in message # # an update is done to nl in weblate # - k = {'_cwd': join(d, 'i18n')} - f = 'securedrop/translations/nl/LC_MESSAGES/messages.po' - sed('-i', '-e', 's/inactiviteit/INACTIVITEIT/', f, **k) + k = {"_cwd": join(d, "i18n")} + f = "securedrop/translations/nl/LC_MESSAGES/messages.po" + sed("-i", "-e", "s/inactiviteit/INACTIVITEIT/", f, **k) git.add(f, **k) - git.config('user.email', '[email protected]', **k) - git.config('user.name', 'Someone Else', **k) - git.commit('-m', 'translation change', f, **k) + git.config("user.email", "[email protected]", **k) + git.config("user.name", "Someone Else", **k) + git.commit("-m", "translation change", f, **k) - k = {'_cwd': join(d, 'securedrop')} - git.config('user.email', '[email protected]', **k) - git.config('user.name', 'Someone Else', **k) + k = {"_cwd": join(d, "securedrop")} + git.config("user.email", "[email protected]", **k) + git.config("user.name", "Someone Else", **k) # # the nl translation update from weblate is copied # over. # caplog.clear() - i18n_tool.I18NTool().main([ - '--verbose', - 'update-from-weblate', - '--root', join(str(tmpdir), 'securedrop'), - '--url', join(str(tmpdir), 'i18n'), - '--supported-languages', 'nl,de_DE', - ]) - assert 'l10n: updated Dutch (nl)' in r() - assert 'l10n: updated German (de_DE)' not in r() - message = str(git('--no-pager', '-C', 'securedrop', 'show', - _cwd=d)) + i18n_tool.I18NTool().main( + [ + "--verbose", + "update-from-weblate", + "--root", + join(str(tmpdir), "securedrop"), + "--url", + join(str(tmpdir), "i18n"), + "--supported-languages", + "nl,de_DE", + ] + ) + assert "l10n: updated Dutch (nl)" in r() + assert "l10n: updated German (de_DE)" not in r() + message = str(git("--no-pager", "-C", "securedrop", "show", _cwd=d)) assert "Someone Else" in message assert "Loïc" not in message diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -8,35 +8,38 @@ from base64 import b32encode from binascii import unhexlify from io import BytesIO -import mock - -from bs4 import BeautifulSoup -from flask import escape, g, session -from pyotp import HOTP, TOTP import journalist_app as journalist_app_module +import mock +from bs4 import BeautifulSoup from db import db from encryption import EncryptionManager -from store import Storage +from flask import escape, g, session +from pyotp import HOTP, TOTP from source_app.session_manager import SessionManager +from store import Storage + from . import utils from .test_encryption import import_journalist_private_key from .utils.instrument import InstrumentedApp - # Seed the RNG for deterministic testing -random.seed('ಠ_ಠ') -GENERATE_DATA = {'tor2web_check': 'href="fake.onion"'} +random.seed("ಠ_ಠ") +GENERATE_DATA = {"tor2web_check": 'href="fake.onion"'} def _login_user(app, user_dict): - resp = app.post('/login', - data={'username': user_dict['username'], - 'password': user_dict['password'], - 'token': TOTP(user_dict['otp_secret']).now()}, - follow_redirects=True) + resp = app.post( + "/login", + data={ + "username": user_dict["username"], + "password": user_dict["password"], + "token": TOTP(user_dict["otp_secret"]).now(), + }, + follow_redirects=True, + ) assert resp.status_code == 200 - assert hasattr(g, 'user') # ensure logged in + assert hasattr(g, "user") # ensure logged in def test_submit_message(journalist_app, source_app, test_journo, app_storage): @@ -45,44 +48,48 @@ def test_submit_message(journalist_app, source_app, test_journo, app_storage): test_msg = "This is a test message." with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + app.post("/create", data={"tab_id": tab_id}, follow_redirects=True) source_user = SessionManager.get_logged_in_user(db_session=db.session) filesystem_id = source_user.filesystem_id # redirected to submission form - resp = app.post('/submit', data=dict( - msg=test_msg, - fh=(BytesIO(b''), ''), - ), follow_redirects=True) + resp = app.post( + "/submit", + data=dict( + msg=test_msg, + fh=(BytesIO(b""), ""), + ), + follow_redirects=True, + ) assert resp.status_code == 200 - app.get('/logout') + app.get("/logout") # Request the Journalist Interface index with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') + resp = app.get("/") assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Sources" in text - soup = BeautifulSoup(text, 'html.parser') + soup = BeautifulSoup(text, "html.parser") # The source should have a "download unread" link that # says "1 unread" - col = soup.select('table#collections tr.source')[0] - unread_span = col.select('td.unread a')[0] + col = soup.select("table#collections tr.source")[0] + unread_span = col.select("td.unread a")[0] assert "1 unread" in unread_span.get_text() - col_url = soup.select('table#collections th.designation a')[0]['href'] + col_url = soup.select("table#collections th.designation a")[0]["href"] resp = app.get(col_url) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') - submission_url = soup.select('table#submissions th.filename a')[0]['href'] + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") + submission_url = soup.select("table#submissions th.filename a")[0]["href"] assert "-msg" in submission_url - size = soup.select('table#submissions td.info')[0] - assert re.compile(r'\d+ bytes').match(size['title']) + size = soup.select("table#submissions td.info")[0] + assert re.compile(r"\d+ bytes").match(size["title"]) resp = app.get(submission_url) assert resp.status_code == 200 @@ -91,39 +98,42 @@ def test_submit_message(journalist_app, source_app, test_journo, app_storage): with import_journalist_private_key(encryption_mgr): decryption_result = encryption_mgr._gpg.decrypt(resp.data) assert decryption_result.ok - assert decryption_result.data.decode('utf-8') == test_msg + assert decryption_result.data.decode("utf-8") == test_msg # delete submission resp = app.get(col_url) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") doc_name = soup.select( 'table#submissions > tr.submission > td.status input[name="doc_names_selected"]' - )[0]['value'] - resp = app.post('/bulk', data=dict( - action='delete', - filesystem_id=filesystem_id, - doc_names_selected=doc_name, - ), follow_redirects=True) + )[0]["value"] + resp = app.post( + "/bulk", + data=dict( + action="delete", + filesystem_id=filesystem_id, + doc_names_selected=doc_name, + ), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") assert "The item has been deleted." in text # confirm that submission deleted and absent in list of submissions resp = app.get(col_url) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "No submissions to display." in text # the file should be deleted from the filesystem # since file deletion is handled by a polling worker, this test # needs to wait for the worker to get the job and execute it def assertion(): - assert not ( - os.path.exists(app_storage.path(filesystem_id, - doc_name))) + assert not (os.path.exists(app_storage.path(filesystem_id, doc_name))) + utils.asynchronous.wait_for_assertion(assertion) @@ -134,43 +144,47 @@ def test_submit_file(journalist_app, source_app, test_journo, app_storage): test_filename = "test.txt" with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + app.post("/create", data={"tab_id": tab_id}, follow_redirects=True) source_user = SessionManager.get_logged_in_user(db_session=db.session) filesystem_id = source_user.filesystem_id # redirected to submission form - resp = app.post('/submit', data=dict( - msg="", - fh=(BytesIO(test_file_contents), test_filename), - ), follow_redirects=True) + resp = app.post( + "/submit", + data=dict( + msg="", + fh=(BytesIO(test_file_contents), test_filename), + ), + follow_redirects=True, + ) assert resp.status_code == 200 - app.get('/logout') + app.get("/logout") with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') + resp = app.get("/") assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Sources" in text - soup = BeautifulSoup(text, 'html.parser') + soup = BeautifulSoup(text, "html.parser") # The source should have a "download unread" link that says # "1 unread" - col = soup.select('table#collections tr.source')[0] - unread_span = col.select('td.unread a')[0] + col = soup.select("table#collections tr.source")[0] + unread_span = col.select("td.unread a")[0] assert "1 unread" in unread_span.get_text() - col_url = soup.select('table#collections th.designation a')[0]['href'] + col_url = soup.select("table#collections th.designation a")[0]["href"] resp = app.get(col_url) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') - submission_url = soup.select('table#submissions th.filename a')[0]['href'] + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") + submission_url = soup.select("table#submissions th.filename a")[0]["href"] assert "-doc" in submission_url - size = soup.select('table#submissions td.info')[0] - assert re.compile(r'\d+ bytes').match(size['title']) + size = soup.select("table#submissions td.info")[0] + assert re.compile(r"\d+ bytes").match(size["title"]) resp = app.get(submission_url) assert resp.status_code == 200 @@ -181,7 +195,7 @@ def test_submit_file(journalist_app, source_app, test_journo, app_storage): assert decrypted_data.ok sio = BytesIO(decrypted_data.data) - with gzip.GzipFile(mode='rb', fileobj=sio) as gzip_file: + with gzip.GzipFile(mode="rb", fileobj=sio) as gzip_file: unzipped_decrypted_data = gzip_file.read() mtime = gzip_file.mtime assert unzipped_decrypted_data == test_file_contents @@ -191,62 +205,71 @@ def test_submit_file(journalist_app, source_app, test_journo, app_storage): # delete submission resp = app.get(col_url) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") doc_name = soup.select( 'table#submissions > tr.submission > td.status input[name="doc_names_selected"]' - )[0]['value'] - resp = app.post('/bulk', data=dict( - action='delete', - filesystem_id=filesystem_id, - doc_names_selected=doc_name, - ), follow_redirects=True) + )[0]["value"] + resp = app.post( + "/bulk", + data=dict( + action="delete", + filesystem_id=filesystem_id, + doc_names_selected=doc_name, + ), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "The item has been deleted." in text - soup = BeautifulSoup(resp.data, 'html.parser') + soup = BeautifulSoup(resp.data, "html.parser") # confirm that submission deleted and absent in list of submissions resp = app.get(col_url) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "No submissions to display." in text # the file should be deleted from the filesystem # since file deletion is handled by a polling worker, this test # needs to wait for the worker to get the job and execute it def assertion(): - assert not ( - os.path.exists(app_storage.path(filesystem_id, doc_name))) + assert not (os.path.exists(app_storage.path(filesystem_id, doc_name))) + utils.asynchronous.wait_for_assertion(assertion) -def _helper_test_reply(journalist_app, source_app, config, test_journo, - test_reply, expected_success=True): +def _helper_test_reply( + journalist_app, source_app, config, test_journo, test_reply, expected_success=True +): test_msg = "This is a test message." with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id, codename = next(iter(session['codenames'].items())) - app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) + app.post("/generate", data=GENERATE_DATA) + tab_id, codename = next(iter(session["codenames"].items())) + app.post("/create", data={"tab_id": tab_id}, follow_redirects=True) # redirected to submission form - resp = app.post('/submit', data=dict( - msg=test_msg, - fh=(BytesIO(b''), ''), - ), follow_redirects=True) + resp = app.post( + "/submit", + data=dict( + msg=test_msg, + fh=(BytesIO(b""), ""), + ), + follow_redirects=True, + ) assert resp.status_code == 200 source_user = SessionManager.get_logged_in_user(db_session=db.session) filesystem_id = source_user.filesystem_id - app.get('/logout') + app.get("/logout") with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') + resp = app.get("/") assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Sources" in text - soup = BeautifulSoup(resp.data, 'html.parser') - col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] + soup = BeautifulSoup(resp.data, "html.parser") + col_url = soup.select("table#collections tr.source > th.designation a")[0]["href"] resp = app.get(col_url) assert resp.status_code == 200 @@ -257,94 +280,96 @@ def _helper_test_reply(journalist_app, source_app, config, test_journo, with journalist_app.test_client() as app: _login_user(app, test_journo) for i in range(2): - resp = app.post('/reply', data=dict( - filesystem_id=filesystem_id, - message=test_reply - ), follow_redirects=True) + resp = app.post( + "/reply", + data=dict(filesystem_id=filesystem_id, message=test_reply), + follow_redirects=True, + ) assert resp.status_code == 200 if not expected_success: pass else: - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "The source will receive your reply" in text resp = app.get(col_url) - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "reply-" in text - soup = BeautifulSoup(text, 'html.parser') + soup = BeautifulSoup(text, "html.parser") # Download the reply and verify that it can be decrypted with the # journalist's key as well as the source's reply key - filesystem_id = soup.select('input[name="filesystem_id"]')[0]['value'] - checkbox_values = [ - soup.select('input[name="doc_names_selected"]')[1]['value']] - resp = app.post('/bulk', data=dict( - filesystem_id=filesystem_id, - action='download', - doc_names_selected=checkbox_values - ), follow_redirects=True) + filesystem_id = soup.select('input[name="filesystem_id"]')[0]["value"] + checkbox_values = [soup.select('input[name="doc_names_selected"]')[1]["value"]] + resp = app.post( + "/bulk", + data=dict( + filesystem_id=filesystem_id, action="download", doc_names_selected=checkbox_values + ), + follow_redirects=True, + ) assert resp.status_code == 200 - zf = zipfile.ZipFile(BytesIO(resp.data), 'r') + zf = zipfile.ZipFile(BytesIO(resp.data), "r") data = zf.read(zf.namelist()[0]) _can_decrypt_with_journalist_secret_key(data) _can_decrypt_with_source_secret_key(data, source_user.gpg_secret) # Test deleting reply on the journalist interface - last_reply_number = len( - soup.select('input[name="doc_names_selected"]')) - 1 + last_reply_number = len(soup.select('input[name="doc_names_selected"]')) - 1 _helper_filenames_delete(app, soup, last_reply_number) with source_app.test_client() as app: - resp = app.post('/login', data=dict(codename=codename), - follow_redirects=True) + resp = app.post("/login", data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 - resp = app.get('/lookup') + resp = app.get("/lookup") assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") if not expected_success: # there should be no reply assert "You have received a reply." not in text else: - assert ("You have received a reply. To protect your identity" - in text) + assert "You have received a reply. To protect your identity" in text assert test_reply in text, text - soup = BeautifulSoup(text, 'html.parser') - msgid = soup.select( - 'form > input[name="reply_filename"]')[0]['value'] - resp = app.post('/delete', data=dict( - filesystem_id=filesystem_id, - reply_filename=msgid - ), follow_redirects=True) + soup = BeautifulSoup(text, "html.parser") + msgid = soup.select('form > input[name="reply_filename"]')[0]["value"] + resp = app.post( + "/delete", + data=dict(filesystem_id=filesystem_id, reply_filename=msgid), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Reply deleted" in text - app.get('/logout') + app.get("/logout") def _helper_filenames_delete(journalist_app, soup, i): - filesystem_id = soup.select('input[name="filesystem_id"]')[0]['value'] - checkbox_values = [ - soup.select('input[name="doc_names_selected"]')[i]['value']] + filesystem_id = soup.select('input[name="filesystem_id"]')[0]["value"] + checkbox_values = [soup.select('input[name="doc_names_selected"]')[i]["value"]] # delete - resp = journalist_app.post('/bulk', data=dict( - filesystem_id=filesystem_id, - action='delete', - doc_names_selected=checkbox_values - ), follow_redirects=True) + resp = journalist_app.post( + "/bulk", + data=dict(filesystem_id=filesystem_id, action="delete", doc_names_selected=checkbox_values), + follow_redirects=True, + ) assert resp.status_code == 200 - assert "The item has been deleted." in resp.data.decode('utf-8') + assert "The item has been deleted." in resp.data.decode("utf-8") # Make sure the files were deleted from the filesystem def assertion(): - assert not any([os.path.exists(Storage.get_default().path(filesystem_id, - doc_name)) - for doc_name in checkbox_values]) + assert not any( + [ + os.path.exists(Storage.get_default().path(filesystem_id, doc_name)) + for doc_name in checkbox_values + ] + ) + utils.asynchronous.wait_for_assertion(assertion) @@ -354,27 +379,24 @@ def _can_decrypt_with_journalist_secret_key(msg: bytes) -> None: # For GPG 2.1+, a non null passphrase _must_ be passed to decrypt() decryption_result = encryption_mgr._gpg.decrypt(msg, passphrase="dummy passphrase") - assert decryption_result.ok, \ - "Could not decrypt msg with key, gpg says: {}" \ - .format(decryption_result.stderr) + assert decryption_result.ok, "Could not decrypt msg with key, gpg says: {}".format( + decryption_result.stderr + ) def _can_decrypt_with_source_secret_key(msg: bytes, source_gpg_secret: str) -> None: encryption_mgr = EncryptionManager.get_default() decryption_result = encryption_mgr._gpg.decrypt(msg, passphrase=source_gpg_secret) - assert decryption_result.ok, \ - "Could not decrypt msg with key, gpg says: {}" \ - .format(decryption_result.stderr) + assert decryption_result.ok, "Could not decrypt msg with key, gpg says: {}".format( + decryption_result.stderr + ) -def test_reply_normal(journalist_app, - source_app, - test_journo, - config): - '''Test for regression on #1360 (failure to encode bytes before calling - gpg functions). - ''' +def test_reply_normal(journalist_app, source_app, test_journo, config): + """Test for regression on #1360 (failure to encode bytes before calling + gpg functions). + """ encryption_mgr = EncryptionManager.get_default() with mock.patch.object(encryption_mgr._gpg, "_encoding", "ansi_x3.4_1968"): _helper_test_reply( @@ -382,10 +404,7 @@ def test_reply_normal(journalist_app, ) -def test_unicode_reply_with_ansi_env(journalist_app, - source_app, - test_journo, - config): +def test_unicode_reply_with_ansi_env(journalist_app, source_app, test_journo, config): # This makes python-gnupg handle encoding equivalent to if we were # running SD in an environment where os.getenv("LANG") == "C". # Unfortunately, with the way our test suite is set up simply setting @@ -406,38 +425,42 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): # first, add a source with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - app.post('/create', data={'tab_id': tab_id}) - resp = app.post('/submit', data=dict( - msg="This is a test.", - fh=(BytesIO(b''), ''), - ), follow_redirects=True) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + app.post("/create", data={"tab_id": tab_id}) + resp = app.post( + "/submit", + data=dict( + msg="This is a test.", + fh=(BytesIO(b""), ""), + ), + follow_redirects=True, + ) assert resp.status_code == 200 with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') + resp = app.get("/") # navigate to the collection page - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - first_col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") + first_col_url = soup.select("table#collections tr.source > th.designation a")[0]["href"] resp = app.get(first_col_url) assert resp.status_code == 200 # find the delete form and extract the post parameters - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - delete_form_inputs = soup.select( - 'form#delete-collection')[0]('input') - filesystem_id = delete_form_inputs[1]['value'] - col_name = delete_form_inputs[2]['value'] - - resp = app.post('/col/delete/' + filesystem_id, - follow_redirects=True) + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") + delete_form_inputs = soup.select("form#delete-collection")[0]("input") + filesystem_id = delete_form_inputs[1]["value"] + col_name = delete_form_inputs[2]["value"] + + resp = app.post("/col/delete/" + filesystem_id, follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert escape( - "The account and data for the source {} have been deleted.".format(col_name)) in text + text = resp.data.decode("utf-8") + assert ( + escape("The account and data for the source {} have been deleted.".format(col_name)) + in text + ) assert "No documents have been submitted!" in text @@ -456,29 +479,35 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): with source_app.test_client() as app: num_sources = 2 for i in range(num_sources): - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - app.post('/create', data={'tab_id': tab_id}) - app.post('/submit', data=dict( - msg="This is a test " + str(i) + ".", - fh=(BytesIO(b''), ''), - ), follow_redirects=True) - app.get('/logout') + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + app.post("/create", data={"tab_id": tab_id}) + app.post( + "/submit", + data=dict( + msg="This is a test " + str(i) + ".", + fh=(BytesIO(b""), ""), + ), + follow_redirects=True, + ) + app.get("/logout") with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') + resp = app.get("/") # get all the checkbox values - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - checkbox_values = [checkbox['value'] for checkbox in - soup.select('input[name="cols_selected"]')] - - resp = app.post('/col/process', data=dict( - action='delete', - cols_selected=checkbox_values - ), follow_redirects=True) + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") + checkbox_values = [ + checkbox["value"] for checkbox in soup.select('input[name="cols_selected"]') + ] + + resp = app.post( + "/col/process", + data=dict(action="delete", cols_selected=checkbox_values), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "The accounts and all data for {} sources".format(num_sources) in text # simulate the source_deleter's work @@ -487,25 +516,42 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): # Make sure the collections are deleted from the filesystem def assertion(): assert not ( - any([os.path.exists(Storage.get_default().path(filesystem_id)) - for filesystem_id in checkbox_values])) + any( + [ + os.path.exists(Storage.get_default().path(filesystem_id)) + for filesystem_id in checkbox_values + ] + ) + ) utils.asynchronous.wait_for_assertion(assertion) def _helper_filenames_submit(app): - app.post('/submit', data=dict( - msg="This is a test.", - fh=(BytesIO(b''), ''), - ), follow_redirects=True) - app.post('/submit', data=dict( - msg="This is a test.", - fh=(BytesIO(b'This is a test'), 'test.txt'), - ), follow_redirects=True) - app.post('/submit', data=dict( - msg="", - fh=(BytesIO(b'This is a test'), 'test.txt'), - ), follow_redirects=True) + app.post( + "/submit", + data=dict( + msg="This is a test.", + fh=(BytesIO(b""), ""), + ), + follow_redirects=True, + ) + app.post( + "/submit", + data=dict( + msg="This is a test.", + fh=(BytesIO(b"This is a test"), "test.txt"), + ), + follow_redirects=True, + ) + app.post( + "/submit", + data=dict( + msg="", + fh=(BytesIO(b"This is a test"), "test.txt"), + ), + follow_redirects=True, + ) def test_filenames(source_app, journalist_app, test_journo): @@ -513,25 +559,26 @@ def test_filenames(source_app, journalist_app, test_journo): and files""" # add a source and submit stuff with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - app.post('/create', data={'tab_id': tab_id}) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + app.post("/create", data={"tab_id": tab_id}) _helper_filenames_submit(app) # navigate to the collection page with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - first_col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] + resp = app.get("/") + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") + first_col_url = soup.select("table#collections tr.source > th.designation a")[0]["href"] resp = app.get(first_col_url) assert resp.status_code == 200 # test filenames and sort order - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - submission_filename_re = r'^{0}-[a-z0-9-_]+(-msg|-doc\.gz)\.gpg$' + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") + submission_filename_re = r"^{0}-[a-z0-9-_]+(-msg|-doc\.gz)\.gpg$" for i, submission_link in enumerate( - soup.select('table#submissions tr.submission > th.filename a')): + soup.select("table#submissions tr.submission > th.filename a") + ): filename = str(submission_link.contents[0]) assert re.match(submission_filename_re.format(i + 1), filename) @@ -540,36 +587,39 @@ def test_filenames_delete(journalist_app, source_app, test_journo): """Test pretty, sequential filenames when journalist deletes files""" # add a source and submit stuff with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - app.post('/create', data={'tab_id': tab_id}) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + app.post("/create", data={"tab_id": tab_id}) _helper_filenames_submit(app) # navigate to the collection page with journalist_app.test_client() as app: _login_user(app, test_journo) - resp = app.get('/') - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') - first_col_url = soup.select('table#collections tr.source > th.designation a')[0]['href'] + resp = app.get("/") + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") + first_col_url = soup.select("table#collections tr.source > th.designation a")[0]["href"] resp = app.get(first_col_url) assert resp.status_code == 200 - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") # delete file #2 _helper_filenames_delete(app, soup, 1) resp = app.get(first_col_url) - soup = BeautifulSoup(resp.data.decode('utf-8'), 'html.parser') + soup = BeautifulSoup(resp.data.decode("utf-8"), "html.parser") # test filenames and sort order - submission_filename_re = r'^{0}-[a-z0-9-_]+(-msg|-doc\.gz)\.gpg$' + submission_filename_re = r"^{0}-[a-z0-9-_]+(-msg|-doc\.gz)\.gpg$" filename = str( - soup.select('table#submissions tr.submission > th.filename a')[0].contents[0]) + soup.select("table#submissions tr.submission > th.filename a")[0].contents[0] + ) assert re.match(submission_filename_re.format(1), filename) filename = str( - soup.select('table#submissions tr.submission > th.filename a')[1].contents[0]) + soup.select("table#submissions tr.submission > th.filename a")[1].contents[0] + ) assert re.match(submission_filename_re.format(3), filename) filename = str( - soup.select('table#submissions tr.submission > th.filename a')[2].contents[0]) + soup.select("table#submissions tr.submission > th.filename a")[2].contents[0] + ) assert re.match(submission_filename_re.format(4), filename) @@ -580,115 +630,125 @@ def test_user_change_password(journalist_app, test_journo): with journalist_app.test_client() as app: _login_user(app, test_journo) # change password - new_pw = 'another correct horse battery staply long password' - assert new_pw != test_journo['password'] # precondition - app.post('/account/new-password', - data=dict(password=new_pw, - current_password=test_journo['password'], - token=TOTP(test_journo['otp_secret']).now())) + new_pw = "another correct horse battery staply long password" + assert new_pw != test_journo["password"] # precondition + app.post( + "/account/new-password", + data=dict( + password=new_pw, + current_password=test_journo["password"], + token=TOTP(test_journo["otp_secret"]).now(), + ), + ) # logout - app.get('/logout') + app.get("/logout") # start a new client/context to be sure we've cleared the session with journalist_app.test_client() as app: # login with new credentials should redirect to index page with InstrumentedApp(journalist_app) as ins: - resp = app.post('/login', data=dict( - username=test_journo['username'], - password=new_pw, - token=TOTP(test_journo['otp_secret']).now())) - ins.assert_redirects(resp, '/') + resp = app.post( + "/login", + data=dict( + username=test_journo["username"], + password=new_pw, + token=TOTP(test_journo["otp_secret"]).now(), + ), + ) + ins.assert_redirects(resp, "/") def test_login_after_regenerate_hotp(journalist_app, test_journo): """Test that journalists can login after resetting their HOTP 2fa""" - otp_secret = '0123456789abcdef0123456789abcdef01234567' + otp_secret = "0123456789abcdef0123456789abcdef01234567" b32_otp_secret = b32encode(unhexlify(otp_secret)) # edit hotp with journalist_app.test_client() as app: _login_user(app, test_journo) with InstrumentedApp(journalist_app) as ins: - resp = app.post('/account/reset-2fa-hotp', - data=dict(otp_secret=otp_secret)) + resp = app.post("/account/reset-2fa-hotp", data=dict(otp_secret=otp_secret)) # valid otp secrets should redirect - ins.assert_redirects(resp, '/account/2fa') + ins.assert_redirects(resp, "/account/2fa") - resp = app.post('/account/2fa', - data=dict(token=HOTP(b32_otp_secret).at(0))) + resp = app.post("/account/2fa", data=dict(token=HOTP(b32_otp_secret).at(0))) # successful verificaton should redirect to /account/account - ins.assert_redirects(resp, '/account/account') + ins.assert_redirects(resp, "/account/account") # log out - app.get('/logout') + app.get("/logout") # start a new client/context to be sure we've cleared the session with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: # login with new 2fa secret should redirect to index page - resp = app.post('/login', data=dict( - username=test_journo['username'], - password=test_journo['password'], - token=HOTP(b32_otp_secret).at(1))) - ins.assert_redirects(resp, '/') + resp = app.post( + "/login", + data=dict( + username=test_journo["username"], + password=test_journo["password"], + token=HOTP(b32_otp_secret).at(1), + ), + ) + ins.assert_redirects(resp, "/") def test_prevent_document_uploads(source_app, journalist_app, test_admin): - '''Test that the source interface accepts only messages when + """Test that the source interface accepts only messages when allow_document_uploads == False. - ''' + """ # Set allow_document_uploads = False: with journalist_app.test_client() as app: _login_user(app, test_admin) form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=True, - min_message_length=0) - resp = app.post('/admin/update-submission-preferences', - data=form.data, - follow_redirects=True) + prevent_document_uploads=True, min_message_length=0 + ) + resp = app.post( + "/admin/update-submission-preferences", data=form.data, follow_redirects=True + ) assert resp.status_code == 200 # Check that the source interface accepts only messages: with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - resp = app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + resp = app.post("/create", data={"tab_id": tab_id}, follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') - assert 'Submit Messages' in text + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") + assert "Submit Messages" in text assert len(soup.select('input[type="file"]')) == 0 def test_no_prevent_document_uploads(source_app, journalist_app, test_admin): - '''Test that the source interface accepts both files and messages when + """Test that the source interface accepts both files and messages when allow_document_uploads == True. - ''' + """ # Set allow_document_uploads = True: with journalist_app.test_client() as app: _login_user(app, test_admin) form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=False, - min_message_length=0) - resp = app.post('/admin/update-submission-preferences', - data=form.data, - follow_redirects=True) + prevent_document_uploads=False, min_message_length=0 + ) + resp = app.post( + "/admin/update-submission-preferences", data=form.data, follow_redirects=True + ) assert resp.status_code == 200 # Check that the source interface accepts both files and messages: with source_app.test_client() as app: - app.post('/generate', data=GENERATE_DATA) - tab_id = next(iter(session['codenames'].keys())) - resp = app.post('/create', data={'tab_id': tab_id}, follow_redirects=True) + app.post("/generate", data=GENERATE_DATA) + tab_id = next(iter(session["codenames"].keys())) + resp = app.post("/create", data={"tab_id": tab_id}, follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - soup = BeautifulSoup(text, 'html.parser') - assert 'Submit Files or Messages' in text + text = resp.data.decode("utf-8") + soup = BeautifulSoup(text, "html.parser") + assert "Submit Files or Messages" in text assert len(soup.select('input[type="file"]')) == 1 diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -3,33 +3,28 @@ import base64 import binascii import io -from mock import call import os -from pathlib import Path -import pytest import random import zipfile from base64 import b64decode +from html import escape as htmlescape from io import BytesIO +from pathlib import Path +import journalist_app as journalist_app_module +import models +import pytest +from db import db +from encryption import EncryptionManager, GpgKeyNotFoundError from flaky import flaky from flask import current_app, escape, g, session, url_for from flask_babel import gettext, ngettext -from mock import patch -from pyotp import TOTP -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm.exc import StaleDataError -from sqlalchemy.sql.expression import func -from html import escape as htmlescape - -import journalist_app as journalist_app_module -from encryption import EncryptionManager, GpgKeyNotFoundError from journalist_app.utils import mark_seen -import models -from db import db +from mock import call, patch from models import ( - InvalidPasswordLength, InstanceConfig, + InvalidPasswordLength, + InvalidUsernameException, Journalist, JournalistLoginAttempt, Reply, @@ -37,39 +32,47 @@ SeenMessage, SeenReply, Source, - InvalidUsernameException, - Submission + Submission, ) from passphrases import PassphraseGenerator +from pyotp import TOTP from sdconfig import config +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm.exc import StaleDataError +from sqlalchemy.sql.expression import func -from .utils.instrument import InstrumentedApp -from .utils.i18n import get_plural_tests, get_test_locales, language_tag, page_language, xfail_untranslated_messages from . import utils - +from .utils.i18n import ( + get_plural_tests, + get_test_locales, + language_tag, + page_language, + xfail_untranslated_messages, +) +from .utils.instrument import InstrumentedApp # Smugly seed the RNG for deterministic testing -random.seed(r'¯\_(ツ)_/¯') +random.seed(r"¯\_(ツ)_/¯") -VALID_PASSWORD = 'correct horse battery staple generic passphrase hooray' -VALID_PASSWORD_2 = 'another correct horse battery staple generic passphrase' +VALID_PASSWORD = "correct horse battery staple generic passphrase hooray" +VALID_PASSWORD_2 = "another correct horse battery staple generic passphrase" def _login_user(app, username, password, otp_secret, success=True): - resp = app.post(url_for('main.login'), - data={'username': username, - 'password': password, - 'token': TOTP(otp_secret).now()}, - follow_redirects=True) + resp = app.post( + url_for("main.login"), + data={"username": username, "password": password, "token": TOTP(otp_secret).now()}, + follow_redirects=True, + ) assert resp.status_code == 200 - assert (success == hasattr(g, 'user')) # check logged-in vs expected + assert success == hasattr(g, "user") # check logged-in vs expected [email protected]("otp_secret", ['', 'GA','GARBAGE','JHCOGO7VCER3EJ4']) [email protected]("otp_secret", ["", "GA", "GARBAGE", "JHCOGO7VCER3EJ4"]) def test_user_with_invalid_otp_secret_cannot_login(journalist_app, otp_secret): # Create a user with whitespace at the end of the username with journalist_app.app_context(): - new_username = 'badotp' + otp_secret + new_username = "badotp" + otp_secret user, password = utils.db_helper.init_journalist(is_admin=False) user.otp_secret = otp_secret user.username = new_username @@ -78,14 +81,13 @@ def test_user_with_invalid_otp_secret_cannot_login(journalist_app, otp_secret): # Verify that user is *not* able to login successfully with journalist_app.test_client() as app: - _login_user(app, new_username, password, - otp_secret, success=False) + _login_user(app, new_username, password, otp_secret, success=False) def test_user_with_whitespace_in_username_can_login(journalist_app): # Create a user with whitespace at the end of the username with journalist_app.app_context(): - username_with_whitespace = 'journalist ' + username_with_whitespace = "journalist " user, password = utils.db_helper.init_journalist(is_admin=False) otp_secret = user.otp_secret user.username = username_with_whitespace @@ -94,35 +96,33 @@ def test_user_with_whitespace_in_username_can_login(journalist_app): # Verify that user is able to login successfully with journalist_app.test_client() as app: - _login_user(app, username_with_whitespace, password, - otp_secret) + _login_user(app, username_with_whitespace, password, otp_secret) def test_reply_error_logging(journalist_app, test_journo, test_source): exception_class = StaleDataError - exception_msg = 'Potentially sensitive content!' + exception_msg = "Potentially sensitive content!" with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], - test_journo['password'], test_journo['otp_secret']) - with patch.object(journalist_app.logger, 'error') \ - as mocked_error_logger: - with patch.object(db.session, 'commit', - side_effect=exception_class(exception_msg)): + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + with patch.object(journalist_app.logger, "error") as mocked_error_logger: + with patch.object(db.session, "commit", side_effect=exception_class(exception_msg)): resp = app.post( - url_for('main.reply'), - data={'filesystem_id': test_source['filesystem_id'], - 'message': '_'}, - follow_redirects=True) + url_for("main.reply"), + data={"filesystem_id": test_source["filesystem_id"], "message": "_"}, + follow_redirects=True, + ) assert resp.status_code == 200 # Notice the "potentially sensitive" exception_msg is not present in # the log event. mocked_error_logger.assert_called_once_with( "Reply from '{}' (ID {}) failed: {}!".format( - test_journo['username'], - test_journo['id'], - exception_class)) + test_journo["username"], test_journo["id"], exception_class + ) + ) @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -131,57 +131,60 @@ def test_reply_error_flashed_message(config, journalist_app, test_journo, test_s exception_class = StaleDataError with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], - test_journo['password'], test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(app) as ins: - with patch.object(db.session, 'commit', - side_effect=exception_class()): + with patch.object(db.session, "commit", side_effect=exception_class()): resp = app.post( - url_for('main.reply', l=locale), - data={'filesystem_id': test_source['filesystem_id'], 'message': '_'}, - follow_redirects=True + url_for("main.reply", l=locale), + data={"filesystem_id": test_source["filesystem_id"], "message": "_"}, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['An unexpected error occurred! Please inform your admin.'] + msgids = ["An unexpected error occurred! Please inform your admin."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'error') + ins.assert_message_flashed(gettext(msgids[0]), "error") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_empty_replies_are_rejected(config, journalist_app, test_journo, test_source, locale): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], - test_journo['password'], test_journo['otp_secret']) - resp = app.post(url_for('main.reply', l=locale), - data={'filesystem_id': test_source['filesystem_id'], - 'message': ''}, - follow_redirects=True) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + resp = app.post( + url_for("main.reply", l=locale), + data={"filesystem_id": test_source["filesystem_id"], "message": ""}, + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) - msgids = ['You cannot send an empty reply.'] + msgids = ["You cannot send an empty reply."] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_nonempty_replies_are_accepted(config, journalist_app, test_journo, test_source, locale): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], - test_journo['password'], test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) resp = app.post( - url_for('main.reply', l=locale), - data={'filesystem_id': test_source['filesystem_id'], 'message': '_'}, - follow_redirects=True + url_for("main.reply", l=locale), + data={"filesystem_id": test_source["filesystem_id"], "message": "_"}, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['You cannot send an empty reply.'] + msgids = ["You cannot send an empty reply."] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) not in resp.data.decode('utf-8') + assert gettext(msgids[0]) not in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -190,22 +193,22 @@ def test_successful_reply_marked_as_seen_by_sender( config, journalist_app, test_journo, test_source, locale ): with journalist_app.test_client() as app: - journo = test_journo['journalist'] - _login_user(app, journo.username, test_journo['password'], test_journo['otp_secret']) + journo = test_journo["journalist"] + _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) seen_reply = SeenReply.query.filter_by(journalist_id=journo.id).one_or_none() assert not seen_reply resp = app.post( - url_for('main.reply', l=locale), - data={'filesystem_id': test_source['filesystem_id'], 'message': '_'}, - follow_redirects=True + url_for("main.reply", l=locale), + data={"filesystem_id": test_source["filesystem_id"], "message": "_"}, + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['You cannot send an empty reply.'] + msgids = ["You cannot send an empty reply."] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) not in resp.data.decode('utf-8') + assert gettext(msgids[0]) not in resp.data.decode("utf-8") seen_reply = SeenReply.query.filter_by(journalist_id=journo.id).one_or_none() assert seen_reply @@ -213,8 +216,8 @@ def test_successful_reply_marked_as_seen_by_sender( def test_unauthorized_access_redirects_to_login(journalist_app): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: - resp = app.get(url_for('main.index')) - ins.assert_redirects(resp, url_for('main.login')) + resp = app.get(url_for("main.index")) + ins.assert_redirects(resp, url_for("main.login")) @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -228,29 +231,25 @@ def test_login_throttle(config, journalist_app, test_journo, locale): with InstrumentedApp(app) as ins: for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): resp = app.post( - url_for('main.login'), + url_for("main.login"), data=dict( - username=test_journo['username'], - password='invalid', - token='invalid' - ) + username=test_journo["username"], password="invalid", token="invalid" + ), ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Login failed" in text resp = app.post( - url_for('main.login', l=locale), + url_for("main.login", l=locale), data=dict( - username=test_journo['username'], - password='invalid', - token='invalid' - ) + username=test_journo["username"], password="invalid", token="invalid" + ), ) assert page_language(resp.data) == language_tag(locale) msgids = [ "Login failed.", - "Please wait at least {num} second before logging in again." + "Please wait at least {num} second before logging in again.", ] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( @@ -259,10 +258,10 @@ def test_login_throttle(config, journalist_app, test_journo, locale): ngettext( msgids[1], "Please wait at least {num} seconds before logging in again.", - Journalist._LOGIN_ATTEMPT_PERIOD - ).format(num=Journalist._LOGIN_ATTEMPT_PERIOD) + Journalist._LOGIN_ATTEMPT_PERIOD, + ).format(num=Journalist._LOGIN_ATTEMPT_PERIOD), ), - 'error' + "error", ) finally: models.LOGIN_HARDENING = original_hardening @@ -283,30 +282,26 @@ def test_login_throttle_is_not_global(config, journalist_app, test_journo, test_ with InstrumentedApp(app) as ins: for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD): resp = app.post( - url_for('main.login', l=locale), + url_for("main.login", l=locale), data=dict( - username=test_journo['username'], - password='invalid', - token='invalid' - ) + username=test_journo["username"], password="invalid", token="invalid" + ), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Login failed.'] + msgids = ["Login failed."] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") resp = app.post( - url_for('main.login', l=locale), + url_for("main.login", l=locale), data=dict( - username=test_journo['username'], - password='invalid', - token='invalid' - ) + username=test_journo["username"], password="invalid", token="invalid" + ), ) assert page_language(resp.data) == language_tag(locale) msgids = [ "Login failed.", - "Please wait at least {num} second before logging in again." + "Please wait at least {num} second before logging in again.", ] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( @@ -315,23 +310,26 @@ def test_login_throttle_is_not_global(config, journalist_app, test_journo, test_ ngettext( msgids[1], "Please wait at least {num} seconds before logging in again.", - Journalist._LOGIN_ATTEMPT_PERIOD - ).format(num=Journalist._LOGIN_ATTEMPT_PERIOD) + Journalist._LOGIN_ATTEMPT_PERIOD, + ).format(num=Journalist._LOGIN_ATTEMPT_PERIOD), ), - 'error' + "error", ) # A different user should be able to login resp = app.post( - url_for('main.login', l=locale), - data=dict(username=test_admin['username'], - password=test_admin['password'], - token=TOTP(test_admin['otp_secret']).now()), - follow_redirects=True) + url_for("main.login", l=locale), + data=dict( + username=test_admin["username"], + password=test_admin["password"], + token=TOTP(test_admin["otp_secret"]).now(), + ), + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) - msgids = ['All Sources'] + msgids = ["All Sources"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") finally: models.LOGIN_HARDENING = original_hardening @@ -340,25 +338,25 @@ def test_login_throttle_is_not_global(config, journalist_app, test_journo, test_ @pytest.mark.parametrize("locale", get_test_locales()) def test_login_invalid_credentials(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: - resp = app.post(url_for('main.login', l=locale), - data=dict(username=test_journo['username'], - password='invalid', - token='mocked')) + resp = app.post( + url_for("main.login", l=locale), + data=dict(username=test_journo["username"], password="invalid", token="mocked"), + ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Login failed.'] + msgids = ["Login failed."] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_validate_redirect(config, journalist_app, locale): with journalist_app.test_client() as app: - resp = app.post(url_for('main.index', l=locale), follow_redirects=True) + resp = app.post(url_for("main.index", l=locale), follow_redirects=True) assert page_language(resp.data) == language_tag(locale) - msgids = ['Login to access the journalist interface'] + msgids = ["Login to access the journalist interface"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -366,18 +364,18 @@ def test_validate_redirect(config, journalist_app, locale): def test_login_valid_credentials(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: resp = app.post( - url_for('main.login', l=locale), - data=dict(username=test_journo['username'], - password=test_journo['password'], - token=TOTP(test_journo['otp_secret']).now()), - follow_redirects=True) + url_for("main.login", l=locale), + data=dict( + username=test_journo["username"], + password=test_journo["password"], + token=TOTP(test_journo["otp_secret"]).now(), + ), + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) - msgids = [ - 'All Sources', - 'No documents have been submitted!' - ] + msgids = ["All Sources", "No documents have been submitted!"] with xfail_untranslated_messages(config, locale, msgids): - resp_text = resp.data.decode('utf-8') + resp_text = resp.data.decode("utf-8") for msgid in msgids: assert gettext(msgid) in resp_text @@ -386,113 +384,124 @@ def test_admin_login_redirects_to_index(journalist_app, test_admin): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('main.login'), - data=dict(username=test_admin['username'], - password=test_admin['password'], - token=TOTP(test_admin['otp_secret']).now()), - follow_redirects=False) - ins.assert_redirects(resp, url_for('main.index')) + url_for("main.login"), + data=dict( + username=test_admin["username"], + password=test_admin["password"], + token=TOTP(test_admin["otp_secret"]).now(), + ), + follow_redirects=False, + ) + ins.assert_redirects(resp, url_for("main.index")) def test_user_login_redirects_to_index(journalist_app, test_journo): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password=test_journo['password'], - token=TOTP(test_journo['otp_secret']).now()), - follow_redirects=False) - ins.assert_redirects(resp, url_for('main.index')) + url_for("main.login"), + data=dict( + username=test_journo["username"], + password=test_journo["password"], + token=TOTP(test_journo["otp_secret"]).now(), + ), + follow_redirects=False, + ) + ins.assert_redirects(resp, url_for("main.index")) -def test_admin_has_link_to_edit_account_page_in_index_page(journalist_app, - test_admin): +def test_admin_has_link_to_edit_account_page_in_index_page(journalist_app, test_admin): with journalist_app.test_client() as app: resp = app.post( - url_for('main.login'), - data=dict(username=test_admin['username'], - password=test_admin['password'], - token=TOTP(test_admin['otp_secret']).now()), - follow_redirects=True) - edit_account_link = ('<a href="/account/account" ' - 'id="link-edit-account">') - text = resp.data.decode('utf-8') + url_for("main.login"), + data=dict( + username=test_admin["username"], + password=test_admin["password"], + token=TOTP(test_admin["otp_secret"]).now(), + ), + follow_redirects=True, + ) + edit_account_link = '<a href="/account/account" ' 'id="link-edit-account">' + text = resp.data.decode("utf-8") assert edit_account_link in text -def test_user_has_link_to_edit_account_page_in_index_page(journalist_app, - test_journo): +def test_user_has_link_to_edit_account_page_in_index_page(journalist_app, test_journo): with journalist_app.test_client() as app: resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password=test_journo['password'], - token=TOTP(test_journo['otp_secret']).now()), - follow_redirects=True) - edit_account_link = ('<a href="/account/account" ' - 'id="link-edit-account">') - text = resp.data.decode('utf-8') + url_for("main.login"), + data=dict( + username=test_journo["username"], + password=test_journo["password"], + token=TOTP(test_journo["otp_secret"]).now(), + ), + follow_redirects=True, + ) + edit_account_link = '<a href="/account/account" ' 'id="link-edit-account">' + text = resp.data.decode("utf-8") assert edit_account_link in text -def test_admin_has_link_to_admin_index_page_in_index_page(journalist_app, - test_admin): +def test_admin_has_link_to_admin_index_page_in_index_page(journalist_app, test_admin): with journalist_app.test_client() as app: resp = app.post( - url_for('main.login'), - data=dict(username=test_admin['username'], - password=test_admin['password'], - token=TOTP(test_admin['otp_secret']).now()), - follow_redirects=True) - text = resp.data.decode('utf-8') + url_for("main.login"), + data=dict( + username=test_admin["username"], + password=test_admin["password"], + token=TOTP(test_admin["otp_secret"]).now(), + ), + follow_redirects=True, + ) + text = resp.data.decode("utf-8") assert '<a href="/admin/" id="link-admin-index">' in text -def test_user_lacks_link_to_admin_index_page_in_index_page(journalist_app, - test_journo): +def test_user_lacks_link_to_admin_index_page_in_index_page(journalist_app, test_journo): with journalist_app.test_client() as app: resp = app.post( - url_for('main.login'), - data=dict(username=test_journo['username'], - password=test_journo['password'], - token=TOTP(test_journo['otp_secret']).now()), - follow_redirects=True) - text = resp.data.decode('utf-8') + url_for("main.login"), + data=dict( + username=test_journo["username"], + password=test_journo["password"], + token=TOTP(test_journo["otp_secret"]).now(), + ), + follow_redirects=True, + ) + text = resp.data.decode("utf-8") assert '<a href="/admin/" id="link-admin-index">' not in text def test_admin_logout_redirects_to_index(journalist_app, test_admin): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: - _login_user(app, test_admin['username'], - test_admin['password'], - test_admin['otp_secret']) - resp = app.get(url_for('main.logout')) - ins.assert_redirects(resp, url_for('main.index')) + _login_user( + app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + ) + resp = app.get(url_for("main.logout")) + ins.assert_redirects(resp, url_for("main.index")) def test_user_logout_redirects_to_index(journalist_app, test_journo): with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: - _login_user(app, test_journo['username'], - test_journo['password'], - test_journo['otp_secret']) - resp = app.get(url_for('main.logout')) - ins.assert_redirects(resp, url_for('main.index')) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + resp = app.get(url_for("main.logout")) + ins.assert_redirects(resp, url_for("main.index")) @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_index(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - resp = app.get(url_for('admin.index', l=locale)) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + resp = app.get(url_for("admin.index", l=locale)) assert page_language(resp.data) == language_tag(locale) - msgids = ['Admin Interface'] + msgids = ["Admin Interface"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -500,28 +509,26 @@ def test_admin_index(config, journalist_app, test_admin, locale): def test_admin_delete_user(config, journalist_app, test_admin, test_journo, locale): # Verify journalist is in the database with journalist_app.app_context(): - assert Journalist.query.get(test_journo['id']) is not None + assert Journalist.query.get(test_journo["id"]) is not None with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.delete_user', user_id=test_journo['id'], l=locale), - follow_redirects=True + url_for("admin.delete_user", user_id=test_journo["id"], l=locale), + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = ["Deleted user '{user}'."] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(user=test_journo['username']), - 'notification' + gettext(msgids[0]).format(user=test_journo["username"]), "notification" ) # Verify journalist is no longer in the database with journalist_app.app_context(): - assert Journalist.query.get(test_journo['id']) is None + assert Journalist.query.get(test_journo["id"]) is None @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -529,45 +536,43 @@ def test_admin_delete_user(config, journalist_app, test_admin, test_journo, loca def test_admin_cannot_delete_self(config, journalist_app, test_admin, test_journo, locale): # Verify journalist is in the database with journalist_app.app_context(): - assert Journalist.query.get(test_journo['id']) is not None + assert Journalist.query.get(test_journo["id"]) is not None with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.delete_user', user_id=test_admin['id'], l=locale), - follow_redirects=True + url_for("admin.delete_user", user_id=test_admin["id"], l=locale), follow_redirects=True ) # Assert correct interface behavior assert resp.status_code == 403 - resp = app.get(url_for('admin.index', l=locale), follow_redirects=True) + resp = app.get(url_for("admin.index", l=locale), follow_redirects=True) assert resp.status_code == 200 assert page_language(resp.data) == language_tag(locale) - msgids = [ - "Admin Interface", - "Edit user {username}", - "Delete user {username}" - ] + msgids = ["Admin Interface", "Edit user {username}", "Delete user {username}"] with xfail_untranslated_messages(config, locale, msgids): - resp_text = resp.data.decode('utf-8') + resp_text = resp.data.decode("utf-8") assert gettext(msgids[0]) in resp_text # The user can be edited and deleted - assert escape( - gettext("Edit user {username}").format(username=test_journo['username']) - ) in resp_text - assert escape( - gettext("Delete user {username}").format(username=test_journo['username']) - ) in resp_text + assert ( + escape(gettext("Edit user {username}").format(username=test_journo["username"])) + in resp_text + ) + assert ( + escape(gettext("Delete user {username}").format(username=test_journo["username"])) + in resp_text + ) # The admin can be edited but cannot deleted - assert escape( - gettext("Edit user {username}").format(username=test_admin['username']) - ) in resp_text - assert escape( - gettext("Delete user {username}").format(username=test_admin['username']) - ) not in resp_text + assert ( + escape(gettext("Edit user {username}").format(username=test_admin["username"])) + in resp_text + ) + assert ( + escape(gettext("Delete user {username}").format(username=test_admin["username"])) + not in resp_text + ) @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -576,19 +581,20 @@ def test_admin_edits_user_password_success_response( config, journalist_app, test_admin, test_journo, locale ): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - resp = app.post(url_for('admin.new_password', user_id=test_journo['id'], l=locale), - data=dict(password=VALID_PASSWORD_2), - follow_redirects=True) + resp = app.post( + url_for("admin.new_password", user_id=test_journo["id"], l=locale), + data=dict(password=VALID_PASSWORD_2), + follow_redirects=True, + ) assert resp.status_code == 200 assert page_language(resp.data) == language_tag(locale) msgids = [ "Password updated. Don't forget to save it in your KeePassX database. New password:" ] with xfail_untranslated_messages(config, locale, msgids): - resp_text = resp.data.decode('utf-8') + resp_text = resp.data.decode("utf-8") assert escape(gettext(msgids[0])) in resp_text assert VALID_PASSWORD_2 in resp_text @@ -600,18 +606,20 @@ def test_admin_edits_user_password_session_invalidate( ): # Start the journalist session. with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) # Change the journalist password via an admin session. with journalist_app.test_client() as admin_app: - _login_user(admin_app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user( + admin_app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + ) resp = admin_app.post( - url_for('admin.new_password', user_id=test_journo['id'], l=locale), + url_for("admin.new_password", user_id=test_journo["id"], l=locale), data=dict(password=VALID_PASSWORD_2), - follow_redirects=True + follow_redirects=True, ) assert resp.status_code == 200 assert page_language(resp.data) == language_tag(locale) @@ -619,22 +627,22 @@ def test_admin_edits_user_password_session_invalidate( "Password updated. Don't forget to save it in your KeePassX database. New password:" ] with xfail_untranslated_messages(config, locale, msgids): - resp_text = resp.data.decode('utf-8') + resp_text = resp.data.decode("utf-8") assert escape(gettext(msgids[0])) in resp_text assert VALID_PASSWORD_2 in resp_text # Now verify the password change error is flashed. with InstrumentedApp(journalist_app) as ins: - resp = app.get(url_for('main.index', l=locale), follow_redirects=True) - msgids = ['You have been logged out due to password change'] + resp = app.get(url_for("main.index", l=locale), follow_redirects=True) + msgids = ["You have been logged out due to password change"] assert page_language(resp.data) == language_tag(locale) with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'error') + ins.assert_message_flashed(gettext(msgids[0]), "error") # Also ensure that session is now invalid. - session.pop('expires', None) - session.pop('csrf_token', None) - session.pop('locale', None) + session.pop("expires", None) + session.pop("csrf_token", None) + session.pop("locale", None) assert not session, session @@ -643,9 +651,8 @@ def test_admin_deletes_invalid_user_404(journalist_app, test_admin): invalid_id = db.session.query(func.max(Journalist.id)).scalar() + 1 with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - resp = app.post(url_for('admin.delete_user', user_id=invalid_id)) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + resp = app.post(url_for("admin.delete_user", user_id=invalid_id)) assert resp.status_code == 404 @@ -656,9 +663,8 @@ def test_admin_deletes_deleted_user_403(journalist_app, test_admin): deleted_id = deleted.id with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - resp = app.post(url_for('admin.delete_user', user_id=deleted_id)) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + resp = app.post(url_for("admin.delete_user", user_id=deleted_id)) assert resp.status_code == 403 @@ -668,25 +674,23 @@ def test_admin_edits_user_password_error_response( config, journalist_app, test_admin, test_journo, locale ): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - with patch('sqlalchemy.orm.scoping.scoped_session.commit', - side_effect=Exception()): + with patch("sqlalchemy.orm.scoping.scoped_session.commit", side_effect=Exception()): with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.new_password', user_id=test_journo['id'], l=locale), + url_for("admin.new_password", user_id=test_journo["id"], l=locale), data=dict(password=VALID_PASSWORD_2), - follow_redirects=True + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = [ - 'There was an error, and the new password might not have been ' - 'saved correctly. To prevent you from getting locked ' - 'out of your account, you should reset your password again.' + "There was an error, and the new password might not have been " + "saved correctly. To prevent you from getting locked " + "out of your account, you should reset your password again." ] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'error') + ins.assert_message_flashed(gettext(msgids[0]), "error") @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -700,21 +704,24 @@ def test_user_edits_password_success_response(config, journalist_app, test_journ models.LOGIN_HARDENING = False with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) - token = TOTP(test_journo['otp_secret']).now() - resp = app.post(url_for('account.new_password', l=locale), - data=dict(current_password=test_journo['password'], - token=token, - password=VALID_PASSWORD_2), - follow_redirects=True) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + token = TOTP(test_journo["otp_secret"]).now() + resp = app.post( + url_for("account.new_password", l=locale), + data=dict( + current_password=test_journo["password"], token=token, password=VALID_PASSWORD_2 + ), + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) msgids = [ "Password updated. Don't forget to save it in your KeePassX database. New password:" ] with xfail_untranslated_messages(config, locale, msgids): - resp_text = resp.data.decode('utf-8') + resp_text = resp.data.decode("utf-8") assert escape(gettext(msgids[0])) in resp_text assert VALID_PASSWORD_2 in resp_text finally: @@ -729,22 +736,26 @@ def test_user_edits_password_expires_session(journalist_app, test_journo): # hardening measures. models.LOGIN_HARDENING = False with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) - assert 'uid' in session + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + assert "uid" in session with InstrumentedApp(journalist_app) as ins: - token = TOTP(test_journo['otp_secret']).now() - resp = app.post(url_for('account.new_password'), - data=dict( - current_password=test_journo['password'], - token=token, - password=VALID_PASSWORD_2)) + token = TOTP(test_journo["otp_secret"]).now() + resp = app.post( + url_for("account.new_password"), + data=dict( + current_password=test_journo["password"], + token=token, + password=VALID_PASSWORD_2, + ), + ) - ins.assert_redirects(resp, url_for('main.login')) + ins.assert_redirects(resp, url_for("main.login")) # verify the session was expired after the password was changed - assert 'uid' not in session + assert "uid" not in session finally: models.LOGIN_HARDENING = original_hardening @@ -760,35 +771,35 @@ def test_user_edits_password_error_response(config, journalist_app, test_journo, models.LOGIN_HARDENING = False with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) # patch token verification because there are multiple commits # to the database and this isolates the one we want to fail - with patch.object(Journalist, 'verify_token', return_value=True): - with patch.object(db.session, 'commit', - side_effect=[None, Exception()]): + with patch.object(Journalist, "verify_token", return_value=True): + with patch.object(db.session, "commit", side_effect=[None, Exception()]): with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('account.new_password', l=locale), + url_for("account.new_password", l=locale), data=dict( - current_password=test_journo['password'], - token='mocked', - password=VALID_PASSWORD_2 + current_password=test_journo["password"], + token="mocked", + password=VALID_PASSWORD_2, ), - follow_redirects=True + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = [ ( - 'There was an error, and the new password might not have been ' - 'saved correctly. To prevent you from getting locked ' - 'out of your account, you should reset your password again.' + "There was an error, and the new password might not have been " + "saved correctly. To prevent you from getting locked " + "out of your account, you should reset your password again." ) ] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'error') + ins.assert_message_flashed(gettext(msgids[0]), "error") finally: models.LOGIN_HARDENING = original_hardening @@ -798,18 +809,18 @@ def test_user_edits_password_error_response(config, journalist_app, test_journo, def test_admin_add_user_when_username_already_taken(config, journalist_app, test_admin, locale): with journalist_app.test_client() as client: _login_user( - client, test_admin['username'], test_admin['password'], test_admin['otp_secret'] + client, test_admin["username"], test_admin["password"], test_admin["otp_secret"] ) with InstrumentedApp(journalist_app) as ins: resp = client.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username=test_admin['username'], - first_name='', - last_name='', + username=test_admin["username"], + first_name="", + last_name="", password=VALID_PASSWORD, - otp_secret='', - is_admin=None + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) @@ -817,187 +828,191 @@ def test_admin_add_user_when_username_already_taken(config, journalist_app, test msgids = ['Username "{username}" already taken.'] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(username=test_admin["username"]), - 'error' + gettext(msgids[0]).format(username=test_admin["username"]), "error" ) def test_max_password_length(): """Creating a Journalist with a password that is greater than the maximum password length should raise an exception""" - overly_long_password = VALID_PASSWORD + \ - 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) + overly_long_password = VALID_PASSWORD + "a" * ( + Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1 + ) with pytest.raises(InvalidPasswordLength): - Journalist(username="My Password is Too Big!", - password=overly_long_password) + Journalist(username="My Password is Too Big!", password=overly_long_password) def test_login_password_too_long(journalist_app, test_journo, mocker): - mocked_error_logger = mocker.patch('journalist.app.logger.error') + mocked_error_logger = mocker.patch("journalist.app.logger.error") with journalist_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(username=test_journo['username'], - password='a' * (Journalist.MAX_PASSWORD_LEN + 1), - token=TOTP(test_journo['otp_secret']).now())) + resp = app.post( + url_for("main.login"), + data=dict( + username=test_journo["username"], + password="a" * (Journalist.MAX_PASSWORD_LEN + 1), + token=TOTP(test_journo["otp_secret"]).now(), + ), + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Login failed" in text mocked_error_logger.assert_called_once_with( - "Login for '{}' failed: Password is too long.".format(test_journo['username']) + "Login for '{}' failed: Password is too long.".format(test_journo["username"]) ) def test_min_password_length(): """Creating a Journalist with a password that is smaller than the - minimum password length should raise an exception. This uses the - magic number 7 below to get around the "diceware-like" requirement - that may cause a failure before the length check. + minimum password length should raise an exception. This uses the + magic number 7 below to get around the "diceware-like" requirement + that may cause a failure before the length check. """ - password = ('a ' * 7)[0:(Journalist.MIN_PASSWORD_LEN - 1)] + password = ("a " * 7)[0 : (Journalist.MIN_PASSWORD_LEN - 1)] with pytest.raises(InvalidPasswordLength): - Journalist(username="My Password is Too Small!", - password=password) + Journalist(username="My Password is Too Small!", password=password) -def test_admin_edits_user_password_too_long_warning(journalist_app, - test_admin, - test_journo): +def test_admin_edits_user_password_too_long_warning(journalist_app, test_admin, test_journo): # append a bunch of a's to a diceware password to keep it "diceware-like" - overly_long_password = VALID_PASSWORD + \ - 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) + overly_long_password = VALID_PASSWORD + "a" * ( + Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1 + ) with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: app.post( - url_for('admin.new_password', user_id=test_journo['id']), - data=dict(username=test_journo['username'], - first_name='', - last_name='', - is_admin=None, - password=overly_long_password), - follow_redirects=True) + url_for("admin.new_password", user_id=test_journo["id"]), + data=dict( + username=test_journo["username"], + first_name="", + last_name="", + is_admin=None, + password=overly_long_password, + ), + follow_redirects=True, + ) - ins.assert_message_flashed('The password you submitted is invalid. ' - 'Password not changed.', 'error') + ins.assert_message_flashed( + "The password you submitted is invalid. " "Password not changed.", "error" + ) def test_user_edits_password_too_long_warning(journalist_app, test_journo): - overly_long_password = VALID_PASSWORD + \ - 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) + overly_long_password = VALID_PASSWORD + "a" * ( + Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1 + ) with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: app.post( - url_for('account.new_password'), - data=dict(username=test_journo['username'], - first_name='', - last_name='', - is_admin=None, - token=TOTP(test_journo['otp_secret']).now(), - current_password=test_journo['password'], - password=overly_long_password), - follow_redirects=True) + url_for("account.new_password"), + data=dict( + username=test_journo["username"], + first_name="", + last_name="", + is_admin=None, + token=TOTP(test_journo["otp_secret"]).now(), + current_password=test_journo["password"], + password=overly_long_password, + ), + follow_redirects=True, + ) - ins.assert_message_flashed('The password you submitted is invalid. ' - 'Password not changed.', 'error') + ins.assert_message_flashed( + "The password you submitted is invalid. " "Password not changed.", "error" + ) @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_password_too_long_warning(config, journalist_app, test_admin, locale): - overly_long_password = VALID_PASSWORD + \ - 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) + overly_long_password = VALID_PASSWORD + "a" * ( + Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1 + ) with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='dellsberg', - first_name='', - last_name='', + username="dellsberg", + first_name="", + last_name="", password=overly_long_password, - otp_secret='', - is_admin=None + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) msgids = [ - 'There was an error with the autogenerated password. User not ' - 'created. Please try again.' + "There was an error with the autogenerated password. User not " + "created. Please try again." ] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'error') + ins.assert_message_flashed(gettext(msgids[0]), "error") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_first_name_too_long_warning(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) - _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username=test_admin['username'], + username=test_admin["username"], first_name=overly_long_name, - last_name='', + last_name="", password=VALID_PASSWORD, - otp_secret='', - is_admin=None + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Cannot be longer than {num} character.'] + msgids = ["Cannot be longer than {num} character."] with xfail_untranslated_messages(config, locale, msgids): - assert ( - ngettext( - 'Cannot be longer than {num} character.', - 'Cannot be longer than {num} characters.', - Journalist.MAX_NAME_LEN - ).format(num=Journalist.MAX_NAME_LEN) - in resp.data.decode('utf-8') - ) + assert ngettext( + "Cannot be longer than {num} character.", + "Cannot be longer than {num} characters.", + Journalist.MAX_NAME_LEN, + ).format(num=Journalist.MAX_NAME_LEN) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_last_name_too_long_warning(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) - _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username=test_admin['username'], - first_name='', + username=test_admin["username"], + first_name="", last_name=overly_long_name, password=VALID_PASSWORD, - otp_secret='', - is_admin=None + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Cannot be longer than {num} character.'] + msgids = ["Cannot be longer than {num} character."] with xfail_untranslated_messages(config, locale, msgids): - assert ( - ngettext( - 'Cannot be longer than {num} character.', - 'Cannot be longer than {num} characters.', - Journalist.MAX_NAME_LEN - ).format(num=Journalist.MAX_NAME_LEN) - in resp.data.decode('utf-8') - ) + assert ngettext( + "Cannot be longer than {num} character.", + "Cannot be longer than {num} characters.", + Journalist.MAX_NAME_LEN, + ).format(num=Journalist.MAX_NAME_LEN) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -1009,50 +1024,43 @@ def test_admin_edits_user_invalid_username_deleted( username to deleted""" new_username = "deleted" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.edit_user', user_id=test_admin['id'], l=locale), - data=dict( - username=new_username, - first_name='', - last_name='', - is_admin=None - ), - follow_redirects=True + url_for("admin.edit_user", user_id=test_admin["id"], l=locale), + data=dict(username=new_username, first_name="", last_name="", is_admin=None), + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) msgids = [ - 'Invalid username: {message}', - 'This username is invalid because it is reserved for internal use by the software.' + "Invalid username: {message}", + "This username is invalid because it is reserved for internal use by the software.", ] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(message=gettext(msgids[1])), - 'error' + gettext(msgids[0]).format(message=gettext(msgids[1])), "error" ) -def test_admin_resets_user_hotp_format_non_hexa( - journalist_app, test_admin, test_journo): +def test_admin_resets_user_hotp_format_non_hexa(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - journo = test_journo['journalist'] + journo = test_journo["journalist"] # guard to ensure check below tests the correct condition assert journo.is_totp old_secret = journo.otp_secret - non_hexa_secret='0123456789ABCDZZ0123456789ABCDEF01234567' + non_hexa_secret = "0123456789ABCDZZ0123456789ABCDEF01234567" with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret=non_hexa_secret)) + app.post( + url_for("admin.reset_two_factor_hotp"), + data=dict(uid=test_journo["id"], otp_secret=non_hexa_secret), + ) # fetch altered DB object journo = Journalist.query.get(journo.id) @@ -1064,27 +1072,30 @@ def test_admin_resets_user_hotp_format_non_hexa( assert journo.is_totp ins.assert_message_flashed( - "Invalid HOTP secret format: please only submit letters A-F and " - "numbers 0-9.", "error") + "Invalid HOTP secret format: please only submit letters A-F and " "numbers 0-9.", + "error", + ) [email protected]("the_secret", [' ', ' ', '0123456789ABCDEF0123456789ABCDE']) [email protected]("the_secret", [" ", " ", "0123456789ABCDEF0123456789ABCDE"]) def test_admin_resets_user_hotp_format_too_short( - journalist_app, test_admin, test_journo, the_secret): + journalist_app, test_admin, test_journo, the_secret +): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - journo = test_journo['journalist'] + journo = test_journo["journalist"] # guard to ensure check below tests the correct condition assert journo.is_totp old_secret = journo.otp_secret with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret=the_secret)) + app.post( + url_for("admin.reset_two_factor_hotp"), + data=dict(uid=test_journo["id"], otp_secret=the_secret), + ) # fetch altered DB object journo = Journalist.query.get(journo.id) @@ -1097,22 +1108,24 @@ def test_admin_resets_user_hotp_format_too_short( ins.assert_message_flashed( "HOTP secrets are 40 characters long" - " - you have entered {num}.".format(num=len(the_secret.replace(' ', ''))), "error") + " - you have entered {num}.".format(num=len(the_secret.replace(" ", ""))), + "error", + ) def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - journo = test_journo['journalist'] + journo = test_journo["journalist"] old_secret = journo.otp_secret - valid_secret="DEADBEEF01234567DEADBEEF01234567DEADBEEF" + valid_secret = "DEADBEEF01234567DEADBEEF01234567DEADBEEF" with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], - otp_secret=valid_secret)) + resp = app.post( + url_for("admin.reset_two_factor_hotp"), + data=dict(uid=test_journo["id"], otp_secret=valid_secret), + ) # fetch altered DB object journo = Journalist.query.get(journo.id) @@ -1122,263 +1135,260 @@ def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo): assert not journo.is_totp # Redirect to admin 2FA view - ins.assert_redirects(resp, url_for('admin.new_user_two_factor', - uid=journo.id)) + ins.assert_redirects(resp, url_for("admin.new_user_two_factor", uid=journo.id)) -def test_admin_resets_user_hotp_error(mocker, - journalist_app, - test_admin, - test_journo): +def test_admin_resets_user_hotp_error(mocker, journalist_app, test_admin, test_journo): - bad_secret = '0123456789ABCDZZ0123456789ABCDZZ01234567' - error_message = 'SOMETHING WRONG!' - mocked_error_logger = mocker.patch('journalist.app.logger.error') - old_secret = test_journo['otp_secret'] + bad_secret = "0123456789ABCDZZ0123456789ABCDZZ01234567" + error_message = "SOMETHING WRONG!" + mocked_error_logger = mocker.patch("journalist.app.logger.error") + old_secret = test_journo["otp_secret"] with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - mocker.patch('models.Journalist.set_hotp_secret', - side_effect=binascii.Error(error_message)) + mocker.patch("models.Journalist.set_hotp_secret", side_effect=binascii.Error(error_message)) with InstrumentedApp(journalist_app) as ins: - app.post(url_for('admin.reset_two_factor_hotp'), - data=dict(uid=test_journo['id'], otp_secret=bad_secret)) - ins.assert_message_flashed("An unexpected error occurred! " - "Please inform your admin.", - "error") + app.post( + url_for("admin.reset_two_factor_hotp"), + data=dict(uid=test_journo["id"], otp_secret=bad_secret), + ) + ins.assert_message_flashed( + "An unexpected error occurred! " "Please inform your admin.", "error" + ) # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) + user = Journalist.query.get(test_journo["id"]) new_secret = user.otp_secret assert new_secret == old_secret mocked_error_logger.assert_called_once_with( "set_hotp_secret '{}' (id {}) failed: {}".format( - bad_secret, test_journo['id'], error_message)) + bad_secret, test_journo["id"], error_message + ) + ) def test_user_resets_hotp(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] - new_secret = '0123456789ABCDEF0123456789ABCDEF01234567' + old_secret = test_journo["otp_secret"] + new_secret = "0123456789ABCDEF0123456789ABCDEF01234567" # Precondition assert new_secret != old_secret with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret=new_secret)) + resp = app.post( + url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=new_secret) + ) # should redirect to verification page - ins.assert_redirects(resp, url_for('account.new_two_factor')) + ins.assert_redirects(resp, url_for("account.new_two_factor")) # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) + user = Journalist.query.get(test_journo["id"]) new_secret = user.otp_secret assert old_secret != new_secret def test_user_resets_user_hotp_format_non_hexa(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] + old_secret = test_journo["otp_secret"] - non_hexa_secret='0123456789ABCDZZ0123456789ABCDEF01234567' + non_hexa_secret = "0123456789ABCDZZ0123456789ABCDEF01234567" with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: - app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret=non_hexa_secret)) + app.post( + url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=non_hexa_secret) + ) ins.assert_message_flashed( - "Invalid HOTP secret format: " - "please only submit letters A-F and numbers 0-9.", "error") + "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9.", + "error", + ) # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) + user = Journalist.query.get(test_journo["id"]) new_secret = user.otp_secret assert old_secret == new_secret -def test_user_resets_user_hotp_error(mocker, - journalist_app, - test_journo): - bad_secret = '0123456789ABCDZZ0123456789ABCDZZ01234567' - old_secret = test_journo['otp_secret'] - error_message = 'SOMETHING WRONG!' - mocked_error_logger = mocker.patch('journalist.app.logger.error') +def test_user_resets_user_hotp_error(mocker, journalist_app, test_journo): + bad_secret = "0123456789ABCDZZ0123456789ABCDZZ01234567" + old_secret = test_journo["otp_secret"] + error_message = "SOMETHING WRONG!" + mocked_error_logger = mocker.patch("journalist.app.logger.error") with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) - mocker.patch('models.Journalist.set_hotp_secret', - side_effect=binascii.Error(error_message)) + mocker.patch("models.Journalist.set_hotp_secret", side_effect=binascii.Error(error_message)) with InstrumentedApp(journalist_app) as ins: - app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret=bad_secret)) + app.post(url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=bad_secret)) ins.assert_message_flashed( - "An unexpected error occurred! Please inform your " - "admin.", "error") + "An unexpected error occurred! Please inform your " "admin.", "error" + ) # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) + user = Journalist.query.get(test_journo["id"]) new_secret = user.otp_secret assert old_secret == new_secret mocked_error_logger.assert_called_once_with( "set_hotp_secret '{}' (id {}) failed: {}".format( - bad_secret, test_journo['id'], error_message)) + bad_secret, test_journo["id"], error_message + ) + ) def test_admin_resets_user_totp(journalist_app, test_admin, test_journo): - old_secret = test_journo['otp_secret'] + old_secret = test_journo["otp_secret"] with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.reset_two_factor_totp'), - data=dict(uid=test_journo['id'])) - ins.assert_redirects( - resp, - url_for('admin.new_user_two_factor', uid=test_journo['id'])) + url_for("admin.reset_two_factor_totp"), data=dict(uid=test_journo["id"]) + ) + ins.assert_redirects(resp, url_for("admin.new_user_two_factor", uid=test_journo["id"])) # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) + user = Journalist.query.get(test_journo["id"]) new_secret = user.otp_secret assert new_secret != old_secret def test_user_resets_totp(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] + old_secret = test_journo["otp_secret"] with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('account.reset_two_factor_totp')) + resp = app.post(url_for("account.reset_two_factor_totp")) # should redirect to verification page - ins.assert_redirects(resp, url_for('account.new_two_factor')) + ins.assert_redirects(resp, url_for("account.new_two_factor")) # Re-fetch journalist to get fresh DB instance - user = Journalist.query.get(test_journo['id']) + user = Journalist.query.get(test_journo["id"]) new_secret = user.otp_secret assert new_secret != old_secret + @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_resets_hotp_with_missing_otp_secret_key(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.reset_two_factor_hotp', l=locale), - data=dict(uid=test_admin['id']), + url_for("admin.reset_two_factor_hotp", l=locale), + data=dict(uid=test_admin["id"]), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Change HOTP Secret'] + msgids = ["Change HOTP Secret"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") def test_admin_new_user_2fa_redirect(journalist_app, test_admin, test_journo): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.new_user_two_factor', uid=test_journo['id']), - data=dict(token=TOTP(test_journo['otp_secret']).now())) - ins.assert_redirects(resp, url_for('admin.index')) + url_for("admin.new_user_two_factor", uid=test_journo["id"]), + data=dict(token=TOTP(test_journo["otp_secret"]).now()), + ) + ins.assert_redirects(resp, url_for("admin.index")) @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_http_get_on_admin_new_user_two_factor_page( - config, - journalist_app, - test_admin, - test_journo, - locale + config, journalist_app, test_admin, test_journo, locale ): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.get( - url_for('admin.new_user_two_factor', uid=test_journo['id'], l=locale), + url_for("admin.new_user_two_factor", uid=test_journo["id"], l=locale), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Enable FreeOTP'] + msgids = ["Enable FreeOTP"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_http_get_on_admin_add_user_page(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - resp = app.get(url_for('admin.add_user', l=locale)) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + resp = app.get(url_for("admin.add_user", l=locale)) assert page_language(resp.data) == language_tag(locale) - msgids = ['ADD USER'] + msgids = ["ADD USER"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") def test_admin_add_user(journalist_app, test_admin): - username = 'dellsberg' + username = "dellsberg" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('admin.add_user'), - data=dict(username=username, - first_name='', - last_name='', - password=VALID_PASSWORD, - otp_secret='', - is_admin=None)) + resp = app.post( + url_for("admin.add_user"), + data=dict( + username=username, + first_name="", + last_name="", + password=VALID_PASSWORD, + otp_secret="", + is_admin=None, + ), + ) new_user = Journalist.query.filter_by(username=username).one() - ins.assert_redirects(resp, url_for('admin.new_user_two_factor', - uid=new_user.id)) + ins.assert_redirects(resp, url_for("admin.new_user_two_factor", uid=new_user.id)) @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_with_invalid_username(config, journalist_app, test_admin, locale): - username = 'deleted' + username = "deleted" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( username=username, - first_name='', - last_name='', + first_name="", + last_name="", password=VALID_PASSWORD, - otp_secret='', - is_admin=None + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) @@ -1403,12 +1413,8 @@ def test_deleted_user_cannot_login(config, journalist_app, locale): # Verify that deleted user is not able to login with journalist_app.test_client() as app: resp = app.post( - url_for('main.login', l=locale), - data=dict( - username="deleted", - password=password, - token=TOTP(otp_secret).now() - ), + url_for("main.login", l=locale), + data=dict(username="deleted", password=password, token=TOTP(otp_secret).now()), ) assert page_language(resp.data) == language_tag(locale) msgids = [ @@ -1416,7 +1422,7 @@ def test_deleted_user_cannot_login(config, journalist_app, locale): ( "Please wait for a new code from your two-factor mobile" " app or security key before trying again." - ) + ), ] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( @@ -1424,7 +1430,7 @@ def test_deleted_user_cannot_login(config, journalist_app, locale): gettext(msgids[0]), gettext(msgids[1]), ), - 'error' + "error", ) @@ -1438,7 +1444,7 @@ def test_deleted_user_cannot_login_exception(journalist_app, locale): db.session.commit() otp_secret = user.otp_secret - with journalist_app.test_request_context('/'): + with journalist_app.test_request_context("/"): with pytest.raises(InvalidUsernameException): Journalist.login("deleted", password, TOTP(otp_secret).now()) @@ -1447,58 +1453,54 @@ def test_deleted_user_cannot_login_exception(journalist_app, locale): @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_without_username(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='', - first_name='', - last_name='', + username="", + first_name="", + last_name="", password=VALID_PASSWORD, - otp_secret='', - is_admin=None), + otp_secret="", + is_admin=None, + ), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['This field is required.'] + msgids = ["This field is required."] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_too_short_username(config, journalist_app, test_admin, locale): - username = 'a' * (Journalist.MIN_USERNAME_LEN - 1) + username = "a" * (Journalist.MIN_USERNAME_LEN - 1) with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( username=username, - first_name='', - last_name='', - password='pentagonpapers', - password_again='pentagonpapers', - otp_secret='', - is_admin=None + first_name="", + last_name="", + password="pentagonpapers", + password_again="pentagonpapers", + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Must be at least {num} character long.'] + msgids = ["Must be at least {num} character long."] with xfail_untranslated_messages(config, locale, msgids): - assert( - ngettext( - 'Must be at least {num} character long.', - 'Must be at least {num} characters long.', - Journalist.MIN_USERNAME_LEN - ).format(num=Journalist.MIN_USERNAME_LEN) - in resp.data.decode('utf-8') - ) + assert ngettext( + "Must be at least {num} character long.", + "Must be at least {num} characters long.", + Journalist.MIN_USERNAME_LEN, + ).format(num=Journalist.MIN_USERNAME_LEN) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -1507,65 +1509,57 @@ def test_admin_add_user_too_short_username(config, journalist_app, test_admin, l ( (locale, "a" * i) for locale in get_test_locales() - for i in get_plural_tests()[locale] if i != 0 # pylint: disable=undefined-variable - ) + for i in get_plural_tests()[locale] # pylint: disable=undefined-variable + if i != 0 + ), ) def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='dellsberg', - first_name='', - last_name='', + username="dellsberg", + first_name="", + last_name="", password=VALID_PASSWORD, password_again=VALID_PASSWORD, is_admin=None, is_hotp=True, - otp_secret=secret + otp_secret=secret, ), ) journalist_app.logger.critical("response: %s", resp.data) assert page_language(resp.data) == language_tag(locale) - msgids = ['HOTP secrets are 40 characters long - you have entered {num}.'] + msgids = ["HOTP secrets are 40 characters long - you have entered {num}."] with xfail_untranslated_messages(config, locale, msgids): - assert ( - ngettext( - 'HOTP secrets are 40 characters long - you have entered {num}.', - 'HOTP secrets are 40 characters long - you have entered {num}.', - len(secret) - ).format(num=len(secret)) - in resp.data.decode("utf-8") - ) + assert ngettext( + "HOTP secrets are 40 characters long - you have entered {num}.", + "HOTP secrets are 40 characters long - you have entered {num}.", + len(secret), + ).format(num=len(secret)) in resp.data.decode("utf-8") + @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize( - "locale, secret", - ( - (locale, ' ' *i) - for locale in get_test_locales() - for i in range(3) - ) + "locale, secret", ((locale, " " * i) for locale in get_test_locales() for i in range(3)) ) def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='dellsberg', - first_name='', - last_name='', + username="dellsberg", + first_name="", + last_name="", password=VALID_PASSWORD, password_again=VALID_PASSWORD, is_admin=None, is_hotp=True, - otp_secret=secret + otp_secret=secret, ), ) @@ -1573,90 +1567,94 @@ def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, msgids = ['The "otp_secret" field is required when "is_hotp" is set.'] with xfail_untranslated_messages(config, locale, msgids): # Should redirect to the token verification page - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_yubikey_valid_length(journalist_app, test_admin, locale): - otp = '1234567890123456789012345678901234567890' + otp = "1234567890123456789012345678901234567890" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='dellsberg', - first_name='', - last_name='', + username="dellsberg", + first_name="", + last_name="", password=VALID_PASSWORD, password_again=VALID_PASSWORD, is_admin=None, is_hotp=True, - otp_secret=otp + otp_secret=otp, ), - follow_redirects=True + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Enable YubiKey (OATH-HOTP)'] + msgids = ["Enable YubiKey (OATH-HOTP)"] with xfail_untranslated_messages(config, locale, msgids): # Should redirect to the token verification page - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_yubikey_correct_length_with_whitespace(journalist_app, test_admin, locale): - otp = '12 34 56 78 90 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90' + otp = "12 34 56 78 90 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='dellsberg', - first_name='', - last_name='', + username="dellsberg", + first_name="", + last_name="", password=VALID_PASSWORD, password_again=VALID_PASSWORD, is_admin=None, is_hotp=True, - otp_secret=otp + otp_secret=otp, ), - follow_redirects=True + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Enable YubiKey (OATH-HOTP)'] + msgids = ["Enable YubiKey (OATH-HOTP)"] with xfail_untranslated_messages(config, locale, msgids): # Should redirect to the token verification page - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") def test_admin_sets_user_to_admin(journalist_app, test_admin): - new_user = 'admin-set-user-to-admin-test' + new_user = "admin-set-user-to-admin-test" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - resp = app.post(url_for('admin.add_user'), - data=dict(username=new_user, - first_name='', - last_name='', - otp_secret='', - password=VALID_PASSWORD, - is_admin=None)) + resp = app.post( + url_for("admin.add_user"), + data=dict( + username=new_user, + first_name="", + last_name="", + otp_secret="", + password=VALID_PASSWORD, + is_admin=None, + ), + ) assert resp.status_code in (200, 302) journo = Journalist.query.filter_by(username=new_user).one() # precondition check assert journo.is_admin is False - resp = app.post(url_for('admin.edit_user', user_id=journo.id), - data=dict(first_name='', last_name='', is_admin=True)) + resp = app.post( + url_for("admin.edit_user", user_id=journo.id), + data=dict(first_name="", last_name="", is_admin=True), + ) assert resp.status_code in (200, 302) journo = Journalist.query.filter_by(username=new_user).one() @@ -1664,28 +1662,31 @@ def test_admin_sets_user_to_admin(journalist_app, test_admin): def test_admin_renames_user(journalist_app, test_admin): - new_user = 'admin-renames-user-test' + new_user = "admin-renames-user-test" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - resp = app.post(url_for('admin.add_user'), - data=dict(username=new_user, - first_name='', - last_name='', - password=VALID_PASSWORD, - otp_secret='', - is_admin=None)) + resp = app.post( + url_for("admin.add_user"), + data=dict( + username=new_user, + first_name="", + last_name="", + password=VALID_PASSWORD, + otp_secret="", + is_admin=None, + ), + ) assert resp.status_code in (200, 302) journo = Journalist.query.filter(Journalist.username == new_user).one() - new_user = new_user + 'a' - resp = app.post(url_for('admin.edit_user', user_id=journo.id), - data=dict(username=new_user, - first_name='', - last_name='')) - assert resp.status_code in (200, 302), resp.data.decode('utf-8') + new_user = new_user + "a" + resp = app.post( + url_for("admin.edit_user", user_id=journo.id), + data=dict(username=new_user, first_name="", last_name=""), + ) + assert resp.status_code in (200, 302), resp.data.decode("utf-8") # the following will throw an exception if new_user is not found # therefore asserting it has been created @@ -1693,26 +1694,29 @@ def test_admin_renames_user(journalist_app, test_admin): def test_admin_adds_first_name_last_name_to_user(journalist_app, test_admin): - new_user = 'admin-first-name-last-name-user-test' + new_user = "admin-first-name-last-name-user-test" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - resp = app.post(url_for('admin.add_user'), - data=dict(username=new_user, - first_name='', - last_name='', - password=VALID_PASSWORD, - otp_secret='', - is_admin=None)) + resp = app.post( + url_for("admin.add_user"), + data=dict( + username=new_user, + first_name="", + last_name="", + password=VALID_PASSWORD, + otp_secret="", + is_admin=None, + ), + ) assert resp.status_code in (200, 302) journo = Journalist.query.filter(Journalist.username == new_user).one() - resp = app.post(url_for('admin.edit_user', user_id=journo.id), - data=dict(username=new_user, - first_name='test name', - last_name='test name')) + resp = app.post( + url_for("admin.edit_user", user_id=journo.id), + data=dict(username=new_user, first_name="test name", last_name="test name"), + ) assert resp.status_code in (200, 302) # the following will throw an exception if new_user is not found @@ -1724,224 +1728,219 @@ def test_admin_adds_first_name_last_name_to_user(journalist_app, test_admin): @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_adds_invalid_first_last_name_to_user(config, journalist_app, test_admin, locale): with journalist_app.test_client() as client: - new_user = 'admin-invalid-first-name-last-name-user-test' + new_user = "admin-invalid-first-name-last-name-user-test" _login_user( - client, test_admin['username'], test_admin['password'], test_admin['otp_secret'] + client, test_admin["username"], test_admin["password"], test_admin["otp_secret"] ) resp = client.post( - url_for('admin.add_user'), + url_for("admin.add_user"), data=dict( username=new_user, - first_name='', - last_name='', + first_name="", + last_name="", password=VALID_PASSWORD, - otp_secret='', - is_admin=None - ) + otp_secret="", + is_admin=None, + ), ) assert resp.status_code == 302 journo = Journalist.query.filter(Journalist.username == new_user).one() - overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) + overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) with InstrumentedApp(journalist_app) as ins: resp = client.post( - url_for('admin.edit_user', user_id=journo.id, l=locale), - data=dict( - username=new_user, - first_name=overly_long_name, - last_name='test name' - ), + url_for("admin.edit_user", user_id=journo.id, l=locale), + data=dict(username=new_user, first_name=overly_long_name, last_name="test name"), follow_redirects=True, ) assert resp.status_code == 200 assert page_language(resp.data) == language_tag(locale) - msgids = [ - "Name not updated: {message}", - "Name too long" - ] + msgids = ["Name not updated: {message}", "Name too long"] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(message=gettext("Name too long")), - 'error' + gettext(msgids[0]).format(message=gettext("Name too long")), "error" ) @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_admin_add_user_integrity_error(config, journalist_app, test_admin, mocker, locale): - mocked_error_logger = mocker.patch('journalist_app.admin.current_app.logger.error') - mocker.patch('journalist_app.admin.Journalist', - side_effect=IntegrityError('STATEMENT', 'PARAMETERS', None)) + mocked_error_logger = mocker.patch("journalist_app.admin.current_app.logger.error") + mocker.patch( + "journalist_app.admin.Journalist", + side_effect=IntegrityError("STATEMENT", "PARAMETERS", None), + ) with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.add_user', l=locale), + url_for("admin.add_user", l=locale), data=dict( - username='username', - first_name='', - last_name='', + username="username", + first_name="", + last_name="", password=VALID_PASSWORD, - otp_secret='', - is_admin=None + otp_secret="", + is_admin=None, ), ) assert page_language(resp.data) == language_tag(locale) msgids = [ - "An error occurred saving this user to the database. " - "Please inform your admin." + "An error occurred saving this user to the database. " "Please inform your admin." ] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed(gettext(msgids[0]), "error") log_event = mocked_error_logger.call_args[0][0] - assert ("Adding user 'username' failed: (builtins.NoneType) " - "None\n[SQL: STATEMENT]\n[parameters: 'PARAMETERS']") in log_event + assert ( + "Adding user 'username' failed: (builtins.NoneType) " + "None\n[SQL: STATEMENT]\n[parameters: 'PARAMETERS']" + ) in log_event @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_prevent_document_uploads(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=True, - min_message_length=0) - app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) + prevent_document_uploads=True, min_message_length=0 + ) + app.post( + url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + ) assert InstanceConfig.get_current().allow_document_uploads is False with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.update_submission_preferences', l=locale), + url_for("admin.update_submission_preferences", l=locale), data=form.data, - follow_redirects=True + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Preferences saved.'] + msgids = ["Preferences saved."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'submission-preferences-success') + ins.assert_message_flashed(gettext(msgids[0]), "submission-preferences-success") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_no_prevent_document_uploads(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - form = journalist_app_module.forms.SubmissionPreferencesForm( - min_message_length=0) - app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + form = journalist_app_module.forms.SubmissionPreferencesForm(min_message_length=0) + app.post( + url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + ) assert InstanceConfig.get_current().allow_document_uploads is True with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.update_submission_preferences', l=locale), + url_for("admin.update_submission_preferences", l=locale), data=form.data, - follow_redirects=True + follow_redirects=True, ) assert InstanceConfig.get_current().allow_document_uploads is True assert page_language(resp.data) == language_tag(locale) - msgids = ['Preferences saved.'] + msgids = ["Preferences saved."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'submission-preferences-success') + ins.assert_message_flashed(gettext(msgids[0]), "submission-preferences-success") def test_prevent_document_uploads_invalid(journalist_app, test_admin): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) form_true = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=True, - min_message_length=0) - app.post(url_for('admin.update_submission_preferences'), - data=form_true.data, - follow_redirects=True) + prevent_document_uploads=True, min_message_length=0 + ) + app.post( + url_for("admin.update_submission_preferences"), + data=form_true.data, + follow_redirects=True, + ) assert InstanceConfig.get_current().allow_document_uploads is False - with patch('flask_wtf.FlaskForm.validate_on_submit') as fMock: + with patch("flask_wtf.FlaskForm.validate_on_submit") as fMock: fMock.return_value = False form_false = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_document_uploads=False) - app.post(url_for('admin.update_submission_preferences'), - data=form_false.data, - follow_redirects=True) + prevent_document_uploads=False + ) + app.post( + url_for("admin.update_submission_preferences"), + data=form_false.data, + follow_redirects=True, + ) assert InstanceConfig.get_current().allow_document_uploads is False def test_message_filtering(config, journalist_app, test_admin): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) # Assert status quo assert InstanceConfig.get_current().initial_message_min_len == 0 # Try to set min length to 10, but don't tick the "prevent short messages" checkbox form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_short_messages=False, - min_message_length=10) - app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) + prevent_short_messages=False, min_message_length=10 + ) + app.post( + url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + ) # Still 0 assert InstanceConfig.get_current().initial_message_min_len == 0 # Inverse, tick the "prevent short messages" checkbox but leave min length at 0 form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_short_messages=True, - min_message_length=0) - resp = app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) + prevent_short_messages=True, min_message_length=0 + ) + resp = app.post( + url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + ) # Still 0 assert InstanceConfig.get_current().initial_message_min_len == 0 - html = resp.data.decode('utf-8') - assert 'To configure a minimum message length, you must set the required' in html + html = resp.data.decode("utf-8") + assert "To configure a minimum message length, you must set the required" in html # Now tick the "prevent short messages" checkbox form = journalist_app_module.forms.SubmissionPreferencesForm( - prevent_short_messages=True, - min_message_length=10) - app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) + prevent_short_messages=True, min_message_length=10 + ) + app.post( + url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + ) assert InstanceConfig.get_current().initial_message_min_len == 10 # Submit junk data for min_message_length - resp = app.post(url_for('admin.update_submission_preferences'), - data={**form.data, 'min_message_length': 'abcdef'}, - follow_redirects=True) - html = resp.data.decode('utf-8') - assert 'To configure a minimum message length, you must set the required' in html + resp = app.post( + url_for("admin.update_submission_preferences"), + data={**form.data, "min_message_length": "abcdef"}, + follow_redirects=True, + ) + html = resp.data.decode("utf-8") + assert "To configure a minimum message length, you must set the required" in html # Now rejecting codenames assert InstanceConfig.get_current().reject_message_with_codename is False - form = journalist_app_module.forms.SubmissionPreferencesForm( - reject_codename_messages=True) - app.post(url_for('admin.update_submission_preferences'), - data=form.data, - follow_redirects=True) + form = journalist_app_module.forms.SubmissionPreferencesForm(reject_codename_messages=True) + app.post( + url_for("admin.update_submission_preferences"), data=form.data, follow_redirects=True + ) assert InstanceConfig.get_current().reject_message_with_codename is True def test_orgname_default_set(journalist_app, test_admin): - - class dummy_current(): + class dummy_current: organization_name = None - with patch.object(InstanceConfig, 'get_current') as iMock: + with patch.object(InstanceConfig, "get_current") as iMock: with journalist_app.test_client() as app: iMock.return_value = dummy_current() - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user( + app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + ) assert g.organization_name == "SecureDrop" @@ -1950,21 +1949,17 @@ class dummy_current(): def test_orgname_valid_succeeds(config, journalist_app, test_admin, locale): test_name = "Walden Inquirer" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - form = journalist_app_module.forms.OrgNameForm( - organization_name=test_name) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + form = journalist_app_module.forms.OrgNameForm(organization_name=test_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.update_org_name', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Preferences saved.'] + msgids = ["Preferences saved."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'org-name-success') + ins.assert_message_flashed(gettext(msgids[0]), "org-name-success") assert InstanceConfig.get_current().organization_name == test_name @@ -1972,21 +1967,17 @@ def test_orgname_valid_succeeds(config, journalist_app, test_admin, locale): @pytest.mark.parametrize("locale", get_test_locales()) def test_orgname_null_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - form = journalist_app_module.forms.OrgNameForm( - organization_name=None) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + form = journalist_app_module.forms.OrgNameForm(organization_name=None) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.update_org_name', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) - msgids = ['This field is required.'] + msgids = ["This field is required."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'org-name-error') + ins.assert_message_flashed(gettext(msgids[0]), "org-name-error") assert InstanceConfig.get_current().organization_name == "SecureDrop" @@ -1995,27 +1986,20 @@ def test_orgname_null_fails(config, journalist_app, test_admin, locale): def test_orgname_oversized_fails(config, journalist_app, test_admin, locale): test_name = "1234567812345678123456781234567812345678123456781234567812345678a" with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - form = journalist_app_module.forms.OrgNameForm( - organization_name=test_name) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + form = journalist_app_module.forms.OrgNameForm(organization_name=test_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" resp = app.post( - url_for('admin.update_org_name', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Cannot be longer than {num} character.'] + msgids = ["Cannot be longer than {num} character."] with xfail_untranslated_messages(config, locale, msgids): - assert ( - ngettext( - 'Cannot be longer than {num} character.', - 'Cannot be longer than {num} characters.', - InstanceConfig.MAX_ORG_NAME_LEN - ).format(num=InstanceConfig.MAX_ORG_NAME_LEN) - in resp.data.decode('utf-8') - ) + assert ngettext( + "Cannot be longer than {num} character.", + "Cannot be longer than {num} characters.", + InstanceConfig.MAX_ORG_NAME_LEN, + ).format(num=InstanceConfig.MAX_ORG_NAME_LEN) in resp.data.decode("utf-8") assert InstanceConfig.get_current().organization_name == "SecureDrop" @@ -2024,21 +2008,17 @@ def test_orgname_oversized_fails(config, journalist_app, test_admin, locale): def test_orgname_html_escaped(config, journalist_app, test_admin, locale): t_name = '"> <a href=foo>' with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - form = journalist_app_module.forms.OrgNameForm( - organization_name=t_name) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + form = journalist_app_module.forms.OrgNameForm(organization_name=t_name) assert InstanceConfig.get_current().organization_name == "SecureDrop" with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.update_org_name', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Preferences saved.'] + msgids = ["Preferences saved."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'org-name-success') + ins.assert_message_flashed(gettext(msgids[0]), "org-name-success") assert InstanceConfig.get_current().organization_name == htmlescape(t_name, quote=True) @@ -2059,9 +2039,8 @@ def test_logo_default_available(journalist_app): @pytest.mark.parametrize("locale", get_test_locales()) def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admin, locale): # Save original logo to restore after test run - logo_image_location = os.path.join(config.SECUREDROP_ROOT, - "static/i/logo.png") - with io.open(logo_image_location, 'rb') as logo_file: + logo_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") + with io.open(logo_image_location, "rb") as logo_file: original_image = logo_file.read() try: @@ -2071,22 +2050,19 @@ def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admi ) with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - # Create 1px * 1px 'white' PNG file from its base64 string - form = journalist_app_module.forms.LogoForm( - logo=(BytesIO(logo_bytes), 'test.png') + _login_user( + app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] ) + # Create 1px * 1px 'white' PNG file from its base64 string + form = journalist_app_module.forms.LogoForm(logo=(BytesIO(logo_bytes), "test.png")) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.manage_config', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.manage_config", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) - msgids = ['Image updated.'] + msgids = ["Image updated."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'logo-success') + ins.assert_message_flashed(gettext(msgids[0]), "logo-success") with journalist_app.test_client() as app: logo_url = journalist_app_module.get_logo_url(journalist_app) @@ -2096,7 +2072,7 @@ def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admi assert response.data == logo_bytes finally: # Restore original image to logo location for subsequent tests - with io.open(logo_image_location, 'wb') as logo_file: + with io.open(logo_image_location, "wb") as logo_file: logo_file.write(original_image) @@ -2104,17 +2080,12 @@ def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admi @pytest.mark.parametrize("locale", get_test_locales()) def test_logo_upload_with_invalid_filetype_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - form = journalist_app_module.forms.LogoForm( - logo=(BytesIO(b'filedata'), 'bad.exe') - ) + form = journalist_app_module.forms.LogoForm(logo=(BytesIO(b"filedata"), "bad.exe")) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.manage_config', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.manage_config", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) @@ -2127,28 +2098,34 @@ def test_logo_upload_with_invalid_filetype_fails(config, journalist_app, test_ad @pytest.mark.parametrize("locale", get_test_locales()) def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): # Save original logo to restore after test run - logo_image_location = os.path.join(config.SECUREDROP_ROOT, - "static/i/logo.png") - with io.open(logo_image_location, 'rb') as logo_file: + logo_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") + with io.open(logo_image_location, "rb") as logo_file: original_image = logo_file.read() try: with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user( + app, test_admin["username"], test_admin["password"], test_admin["otp_secret"] + ) # Create 1px * 1px 'white' PNG file from its base64 string form = journalist_app_module.forms.LogoForm( - logo=(BytesIO(base64.decodebytes - (b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQ" - b"VR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=")), 'test.png') + logo=( + BytesIO( + base64.decodebytes( + b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQ" + b"VR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=" + ) + ), + "test.png", + ) ) with InstrumentedApp(journalist_app) as ins: - with patch('werkzeug.datastructures.FileStorage.save') as sMock: + with patch("werkzeug.datastructures.FileStorage.save") as sMock: sMock.side_effect = Exception resp = app.post( - url_for('admin.manage_config', l=locale), + url_for("admin.manage_config", l=locale), data=form.data, - follow_redirects=True + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) @@ -2157,38 +2134,30 @@ def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): ins.assert_message_flashed(gettext(msgids[0]), "logo-error") finally: # Restore original image to logo location for subsequent tests - with io.open(logo_image_location, 'wb') as logo_file: + with io.open(logo_image_location, "wb") as logo_file: logo_file.write(original_image) def test_creation_of_ossec_test_log_event(journalist_app, test_admin, mocker): - mocked_error_logger = mocker.patch('journalist.app.logger.error') + mocked_error_logger = mocker.patch("journalist.app.logger.error") with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) - app.post(url_for('admin.ossec_test')) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) + app.post(url_for("admin.ossec_test")) - mocked_error_logger.assert_called_once_with( - "This is a test OSSEC alert" - ) + mocked_error_logger.assert_called_once_with("This is a test OSSEC alert") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_logo_upload_with_empty_input_field_fails(config, journalist_app, test_admin, locale): with journalist_app.test_client() as app: - _login_user(app, test_admin['username'], test_admin['password'], - test_admin['otp_secret']) + _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - form = journalist_app_module.forms.LogoForm( - logo=(BytesIO(b''), '') - ) + form = journalist_app_module.forms.LogoForm(logo=(BytesIO(b""), "")) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('admin.manage_config', l=locale), - data=form.data, - follow_redirects=True + url_for("admin.manage_config", l=locale), data=form.data, follow_redirects=True ) assert page_language(resp.data) == language_tag(locale) @@ -2198,39 +2167,48 @@ def test_logo_upload_with_empty_input_field_fails(config, journalist_app, test_a def test_admin_page_restriction_http_gets(journalist_app, test_journo): - admin_urls = [url_for('admin.index'), url_for('admin.add_user'), - url_for('admin.edit_user', user_id=test_journo['id'])] + admin_urls = [ + url_for("admin.index"), + url_for("admin.add_user"), + url_for("admin.edit_user", user_id=test_journo["id"]), + ] with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) for admin_url in admin_urls: resp = app.get(admin_url) assert resp.status_code == 302 def test_admin_page_restriction_http_posts(journalist_app, test_journo): - admin_urls = [url_for('admin.reset_two_factor_totp'), - url_for('admin.reset_two_factor_hotp'), - url_for('admin.add_user', user_id=test_journo['id']), - url_for('admin.new_user_two_factor'), - url_for('admin.reset_two_factor_totp'), - url_for('admin.reset_two_factor_hotp'), - url_for('admin.edit_user', user_id=test_journo['id']), - url_for('admin.delete_user', user_id=test_journo['id'])] - with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + admin_urls = [ + url_for("admin.reset_two_factor_totp"), + url_for("admin.reset_two_factor_hotp"), + url_for("admin.add_user", user_id=test_journo["id"]), + url_for("admin.new_user_two_factor"), + url_for("admin.reset_two_factor_totp"), + url_for("admin.reset_two_factor_hotp"), + url_for("admin.edit_user", user_id=test_journo["id"]), + url_for("admin.delete_user", user_id=test_journo["id"]), + ] + with journalist_app.test_client() as app: + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) for admin_url in admin_urls: resp = app.post(admin_url) assert resp.status_code == 302 def test_user_authorization_for_gets(journalist_app): - urls = [url_for('main.index'), url_for('col.col', filesystem_id='1'), - url_for('col.download_single_file', - filesystem_id='1', fn='1'), - url_for('account.edit')] + urls = [ + url_for("main.index"), + url_for("col.col", filesystem_id="1"), + url_for("col.download_single_file", filesystem_id="1", fn="1"), + url_for("account.edit"), + ] with journalist_app.test_client() as app: for url in urls: @@ -2239,16 +2217,18 @@ def test_user_authorization_for_gets(journalist_app): def test_user_authorization_for_posts(journalist_app): - urls = [url_for('col.add_star', filesystem_id='1'), - url_for('col.remove_star', filesystem_id='1'), - url_for('col.process'), - url_for('col.delete_single', filesystem_id='1'), - url_for('main.reply'), - url_for('main.bulk'), - url_for('account.new_two_factor'), - url_for('account.reset_two_factor_totp'), - url_for('account.reset_two_factor_hotp'), - url_for('account.change_name')] + urls = [ + url_for("col.add_star", filesystem_id="1"), + url_for("col.remove_star", filesystem_id="1"), + url_for("col.process"), + url_for("col.delete_single", filesystem_id="1"), + url_for("main.reply"), + url_for("main.bulk"), + url_for("account.new_two_factor"), + url_for("account.reset_two_factor_totp"), + url_for("account.reset_two_factor_hotp"), + url_for("account.change_name"), + ] with journalist_app.test_client() as app: for url in urls: resp = app.post(url) @@ -2259,24 +2239,22 @@ def test_user_authorization_for_posts(journalist_app): @pytest.mark.parametrize("locale", get_test_locales()) def test_incorrect_current_password_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('account.new_password', l=locale), - data=dict( - password=VALID_PASSWORD, - token='mocked', - current_password='badpw' - ), - follow_redirects=True) + url_for("account.new_password", l=locale), + data=dict(password=VALID_PASSWORD, token="mocked", current_password="badpw"), + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) msgids = [ - 'Incorrect password or two-factor code.', + "Incorrect password or two-factor code.", ( "Please wait for a new code from your two-factor mobile" " app or security key before trying again." - ) + ), ] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed(gettext(msgids[0]) + " " + gettext(msgids[1]), "error") @@ -2284,8 +2262,8 @@ def test_incorrect_current_password_change(config, journalist_app, test_journo, # need a journalist app for the app context def test_passphrase_migration_on_verification(journalist_app): - salt = b64decode('+mGOQmD5Nnb+mH9gwBoxKRhKZmmJ6BzpmD5YArPHZsY=') - journalist = Journalist('test', VALID_PASSWORD) + salt = b64decode("+mGOQmD5Nnb+mH9gwBoxKRhKZmmJ6BzpmD5YArPHZsY=") + journalist = Journalist("test", VALID_PASSWORD) # manually set the params hash = journalist._scrypt_hash(VALID_PASSWORD, salt) @@ -2306,8 +2284,8 @@ def test_passphrase_migration_on_verification(journalist_app): # need a journalist app for the app context def test_passphrase_migration_on_reset(journalist_app): - salt = b64decode('+mGOQmD5Nnb+mH9gwBoxKRhKZmmJ6BzpmD5YArPHZsY=') - journalist = Journalist('test', VALID_PASSWORD) + salt = b64decode("+mGOQmD5Nnb+mH9gwBoxKRhKZmmJ6BzpmD5YArPHZsY=") + journalist = Journalist("test", VALID_PASSWORD) # manually set the params hash = journalist._scrypt_hash(VALID_PASSWORD, salt) @@ -2332,12 +2310,16 @@ def test_journalist_reply_view(journalist_app, test_source, test_journo, app_sto submissions = utils.db_helper.submit(app_storage, source, 1) replies = utils.db_helper.reply(app_storage, journalist, source, 1) - subm_url = url_for('col.download_single_file', - filesystem_id=submissions[0].source.filesystem_id, - fn=submissions[0].filename) - reply_url = url_for('col.download_single_file', - filesystem_id=replies[0].source.filesystem_id, - fn=replies[0].filename) + subm_url = url_for( + "col.download_single_file", + filesystem_id=submissions[0].source.filesystem_id, + fn=submissions[0].filename, + ) + reply_url = url_for( + "col.download_single_file", + filesystem_id=replies[0].source.filesystem_id, + fn=replies[0].filename, + ) with journalist_app.test_client() as app: resp = app.get(subm_url) @@ -2349,74 +2331,78 @@ def test_journalist_reply_view(journalist_app, test_source, test_journo, app_sto @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_too_long_user_password_change(config, journalist_app, test_journo, locale): - overly_long_password = VALID_PASSWORD + \ - 'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1) + overly_long_password = VALID_PASSWORD + "a" * ( + Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1 + ) with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('account.new_password', l=locale), + url_for("account.new_password", l=locale), data=dict( password=overly_long_password, - token=TOTP(test_journo['otp_secret']).now(), - current_password=test_journo['password'] + token=TOTP(test_journo["otp_secret"]).now(), + current_password=test_journo["password"], ), - follow_redirects=True) + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) - msgids = ['The password you submitted is invalid. Password not changed.'] + msgids = ["The password you submitted is invalid. Password not changed."] with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), 'error') + ins.assert_message_flashed(gettext(msgids[0]), "error") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_valid_user_password_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) - resp = app.post(url_for('account.new_password', l=locale), - data=dict(password=VALID_PASSWORD_2, - token=TOTP(test_journo['otp_secret']).now(), - current_password=test_journo['password']), - follow_redirects=True) + resp = app.post( + url_for("account.new_password", l=locale), + data=dict( + password=VALID_PASSWORD_2, + token=TOTP(test_journo["otp_secret"]).now(), + current_password=test_journo["password"], + ), + follow_redirects=True, + ) assert page_language(resp.data) == language_tag(locale) msgids = [ "Password updated. Don't forget to save it in your KeePassX database. New password:" ] with xfail_untranslated_messages(config, locale, msgids): - assert escape(gettext(msgids[0])) in resp.data.decode('utf-8') - + assert escape(gettext(msgids[0])) in resp.data.decode("utf-8") @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) def test_valid_user_first_last_name_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('account.change_name', l=locale), - data=dict(first_name='test', last_name='test'), - follow_redirects=True + url_for("account.change_name", l=locale), + data=dict(first_name="test", last_name="test"), + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = [ - "Name updated.", - "Name too long" - ] + msgids = ["Name updated.", "Name too long"] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(gettext("Name too long")), - 'success' + gettext(msgids[0]).format(gettext("Name too long")), "success" ) @@ -2424,114 +2410,105 @@ def test_valid_user_first_last_name_change(config, journalist_app, test_journo, @pytest.mark.parametrize("locale", get_test_locales()) def test_valid_user_invalid_first_last_name_change(journalist_app, test_journo, locale): with journalist_app.test_client() as app: - overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1) - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: resp = app.post( - url_for('account.change_name', l=locale), - data=dict( - first_name=overly_long_name, - last_name=overly_long_name - ), - follow_redirects=True + url_for("account.change_name", l=locale), + data=dict(first_name=overly_long_name, last_name=overly_long_name), + follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = [ - "Name not updated: {message}", - "Name too long" - ] + msgids = ["Name not updated: {message}", "Name too long"] with xfail_untranslated_messages(config, locale, msgids): ins.assert_message_flashed( - gettext(msgids[0]).format(message=gettext("Name too long")), - 'error' + gettext(msgids[0]).format(message=gettext("Name too long")), "error" ) def test_regenerate_totp(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] + old_secret = test_journo["otp_secret"] with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('account.reset_two_factor_totp')) + resp = app.post(url_for("account.reset_two_factor_totp")) - new_secret = Journalist.query.get(test_journo['id']).otp_secret + new_secret = Journalist.query.get(test_journo["id"]).otp_secret # check that totp is different assert new_secret != old_secret # should redirect to verification page - ins.assert_redirects(resp, url_for('account.new_two_factor')) + ins.assert_redirects(resp, url_for("account.new_two_factor")) def test_edit_hotp(journalist_app, test_journo): - old_secret = test_journo['otp_secret'] - valid_secret="DEADBEEF01234567DEADBEEF01234567DADEFEEB" + old_secret = test_journo["otp_secret"] + valid_secret = "DEADBEEF01234567DEADBEEF01234567DADEFEEB" with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('account.reset_two_factor_hotp'), - data=dict(otp_secret=valid_secret)) + resp = app.post( + url_for("account.reset_two_factor_hotp"), data=dict(otp_secret=valid_secret) + ) - new_secret = Journalist.query.get(test_journo['id']).otp_secret + new_secret = Journalist.query.get(test_journo["id"]).otp_secret # check that totp is different assert new_secret != old_secret # should redirect to verification page - ins.assert_redirects(resp, url_for('account.new_two_factor')) + ins.assert_redirects(resp, url_for("account.new_two_factor")) -def test_delete_data_deletes_submissions_retaining_source(journalist_app, - test_journo, - test_source, - app_storage): +def test_delete_data_deletes_submissions_retaining_source( + journalist_app, test_journo, test_source, app_storage +): """Verify that when only a source's data is deleted, the submissions are deleted but the source is not.""" with journalist_app.app_context(): - source = Source.query.get(test_source['id']) - journo = Journalist.query.get(test_journo['id']) + source = Source.query.get(test_source["id"]) + journo = Journalist.query.get(test_journo["id"]) utils.db_helper.submit(app_storage, source, 2) utils.db_helper.reply(app_storage, journo, source, 2) assert len(source.collection) == 4 - journalist_app_module.utils.delete_source_files( - test_source['filesystem_id']) + journalist_app_module.utils.delete_source_files(test_source["filesystem_id"]) - res = Source.query.filter_by(id=test_source['id']).one_or_none() + res = Source.query.filter_by(id=test_source["id"]).one_or_none() assert res is not None assert len(source.collection) == 0 -def test_delete_source_deletes_submissions(journalist_app, - test_journo, - test_source, - app_storage): +def test_delete_source_deletes_submissions(journalist_app, test_journo, test_source, app_storage): """Verify that when a source is deleted, the submissions that correspond to them are also deleted.""" with journalist_app.app_context(): - source = Source.query.get(test_source['id']) - journo = Journalist.query.get(test_journo['id']) + source = Source.query.get(test_source["id"]) + journo = Journalist.query.get(test_journo["id"]) utils.db_helper.submit(app_storage, source, 2) utils.db_helper.reply(app_storage, journo, source, 2) - journalist_app_module.utils.delete_collection( - test_source['filesystem_id']) + journalist_app_module.utils.delete_collection(test_source["filesystem_id"]) - res = Source.query.filter_by(id=test_source['id']).one_or_none() + res = Source.query.filter_by(id=test_source["id"]).one_or_none() assert res is None @@ -2585,51 +2562,45 @@ def test_delete_collection_updates_db(journalist_app, test_journo, test_source, assert not seen_reply -def test_delete_source_deletes_source_key(journalist_app, - test_source, - test_journo, - app_storage): +def test_delete_source_deletes_source_key(journalist_app, test_source, test_journo, app_storage): """Verify that when a source is deleted, the PGP key that corresponds to them is also deleted.""" with journalist_app.app_context(): - source = Source.query.get(test_source['id']) - journo = Journalist.query.get(test_journo['id']) + source = Source.query.get(test_source["id"]) + journo = Journalist.query.get(test_journo["id"]) utils.db_helper.submit(app_storage, source, 2) utils.db_helper.reply(app_storage, journo, source, 2) # Source key exists encryption_mgr = EncryptionManager.get_default() - assert encryption_mgr.get_source_key_fingerprint(test_source['filesystem_id']) + assert encryption_mgr.get_source_key_fingerprint(test_source["filesystem_id"]) - journalist_app_module.utils.delete_collection( - test_source['filesystem_id']) + journalist_app_module.utils.delete_collection(test_source["filesystem_id"]) # Source key no longer exists with pytest.raises(GpgKeyNotFoundError): - encryption_mgr.get_source_key_fingerprint(test_source['filesystem_id']) + encryption_mgr.get_source_key_fingerprint(test_source["filesystem_id"]) -def test_delete_source_deletes_docs_on_disk(journalist_app, - test_source, - test_journo, - config, - app_storage): +def test_delete_source_deletes_docs_on_disk( + journalist_app, test_source, test_journo, config, app_storage +): """Verify that when a source is deleted, the encrypted documents that exist on disk is also deleted.""" with journalist_app.app_context(): - source = Source.query.get(test_source['id']) - journo = Journalist.query.get(test_journo['id']) + source = Source.query.get(test_source["id"]) + journo = Journalist.query.get(test_journo["id"]) utils.db_helper.submit(app_storage, source, 2) utils.db_helper.reply(app_storage, journo, source, 2) - dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) + dir_source_docs = os.path.join(config.STORE_DIR, test_source["filesystem_id"]) assert os.path.exists(dir_source_docs) - journalist_app_module.utils.delete_collection(test_source['filesystem_id']) + journalist_app_module.utils.delete_collection(test_source["filesystem_id"]) def assertion(): assert not os.path.exists(dir_source_docs) @@ -2637,24 +2608,22 @@ def assertion(): utils.asynchronous.wait_for_assertion(assertion) -def test_bulk_delete_deletes_db_entries(journalist_app, - test_source, - test_journo, - config, - app_storage): +def test_bulk_delete_deletes_db_entries( + journalist_app, test_source, test_journo, config, app_storage +): """ Verify that when files are deleted, the corresponding db entries are also deleted. """ with journalist_app.app_context(): - source = Source.query.get(test_source['id']) - journo = Journalist.query.get(test_journo['id']) + source = Source.query.get(test_source["id"]) + journo = Journalist.query.get(test_journo["id"]) utils.db_helper.submit(app_storage, source, 2) utils.db_helper.reply(app_storage, journo, source, 2) - dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) + dir_source_docs = os.path.join(config.STORE_DIR, test_source["filesystem_id"]) assert os.path.exists(dir_source_docs) subs = Submission.query.filter_by(source_id=source.id).all() @@ -2667,9 +2636,8 @@ def test_bulk_delete_deletes_db_entries(journalist_app, file_list.extend(subs) file_list.extend(replies) - with journalist_app.test_request_context('/'): - journalist_app_module.utils.bulk_delete(test_source['filesystem_id'], - file_list) + with journalist_app.test_request_context("/"): + journalist_app_module.utils.bulk_delete(test_source["filesystem_id"], file_list) def db_assertion(): subs = Submission.query.filter_by(source_id=source.id).all() @@ -2681,24 +2649,22 @@ def db_assertion(): utils.asynchronous.wait_for_assertion(db_assertion) -def test_bulk_delete_works_when_files_absent(journalist_app, - test_source, - test_journo, - config, - app_storage): +def test_bulk_delete_works_when_files_absent( + journalist_app, test_source, test_journo, config, app_storage +): """ Verify that when files are deleted but are already missing, the corresponding db entries are still deleted """ with journalist_app.app_context(): - source = Source.query.get(test_source['id']) - journo = Journalist.query.get(test_journo['id']) + source = Source.query.get(test_source["id"]) + journo = Journalist.query.get(test_journo["id"]) utils.db_helper.submit(app_storage, source, 2) utils.db_helper.reply(app_storage, journo, source, 2) - dir_source_docs = os.path.join(config.STORE_DIR, test_source['filesystem_id']) + dir_source_docs = os.path.join(config.STORE_DIR, test_source["filesystem_id"]) assert os.path.exists(dir_source_docs) subs = Submission.query.filter_by(source_id=source.id).all() @@ -2711,11 +2677,10 @@ def test_bulk_delete_works_when_files_absent(journalist_app, file_list.extend(subs) file_list.extend(replies) - with journalist_app.test_request_context('/'): + with journalist_app.test_request_context("/"): with patch("store.Storage.move_to_shredder") as delMock: delMock.side_effect = ValueError - journalist_app_module.utils.bulk_delete(test_source['filesystem_id'], - file_list) + journalist_app_module.utils.bulk_delete(test_source["filesystem_id"], file_list) def db_assertion(): subs = Submission.query.filter_by(source_id=source.id).all() @@ -2728,51 +2693,50 @@ def db_assertion(): def test_login_with_invalid_password_doesnt_call_argon2(mocker, test_journo): - mock_argon2 = mocker.patch('models.argon2.verify') - invalid_pw = 'a'*(Journalist.MAX_PASSWORD_LEN + 1) + mock_argon2 = mocker.patch("models.argon2.verify") + invalid_pw = "a" * (Journalist.MAX_PASSWORD_LEN + 1) with pytest.raises(InvalidPasswordLength): - Journalist.login(test_journo['username'], - invalid_pw, - TOTP(test_journo['otp_secret']).now()) + Journalist.login(test_journo["username"], invalid_pw, TOTP(test_journo["otp_secret"]).now()) assert not mock_argon2.called def test_valid_login_calls_argon2(mocker, test_journo): - mock_argon2 = mocker.patch('models.argon2.verify') - Journalist.login(test_journo['username'], - test_journo['password'], - TOTP(test_journo['otp_secret']).now()) + mock_argon2 = mocker.patch("models.argon2.verify") + Journalist.login( + test_journo["username"], test_journo["password"], TOTP(test_journo["otp_secret"]).now() + ) assert mock_argon2.called def test_render_locales(config, journalist_app, test_journo, test_source): """the locales.html template must collect both request.args (l=XX) and - request.view_args (/<filesystem_id>) to build the URL to - change the locale + request.view_args (/<filesystem_id>) to build the URL to + change the locale """ # We use the `journalist_app` fixture to generate all our tables, but we # don't use it during the test because we need to inject the i18n settings # (which are only triggered during `create_app` - config.SUPPORTED_LOCALES = ['en_US', 'fr_FR'] + config.SUPPORTED_LOCALES = ["en_US", "fr_FR"] app = journalist_app_module.create_app(config) - app.config['SERVER_NAME'] = 'localhost.localdomain' # needed for url_for - url = url_for('col.col', filesystem_id=test_source['filesystem_id']) + app.config["SERVER_NAME"] = "localhost.localdomain" # needed for url_for + url = url_for("col.col", filesystem_id=test_source["filesystem_id"]) # we need the relative URL, not the full url including proto / localhost - url_end = url.replace('http://', '') - url_end = url_end[url_end.index('/') + 1:] + url_end = url.replace("http://", "") + url_end = url_end[url_end.index("/") + 1 :] with app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) - resp = app.get(url + '?l=fr_FR') + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + resp = app.get(url + "?l=fr_FR") # check that links to i18n URLs are/aren't present - text = resp.data.decode('utf-8') - assert '?l=fr_FR' not in text, text - assert url_end + '?l=en_US' in text, text + text = resp.data.decode("utf-8") + assert "?l=fr_FR" not in text, text + assert url_end + "?l=en_US" in text, text def test_download_selected_submissions_and_replies( @@ -2788,9 +2752,7 @@ def test_download_selected_submissions_and_replies( selected.sort() with journalist_app.test_client() as app: - _login_user( - app, journo.username, test_journo["password"], test_journo["otp_secret"] - ) + _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) resp = app.post( "/bulk", data=dict( @@ -2816,9 +2778,7 @@ def test_download_selected_submissions_and_replies( ) assert zipinfo - seen_file = SeenFile.query.filter_by( - file_id=item.id, journalist_id=journo.id - ).one_or_none() + seen_file = SeenFile.query.filter_by(file_id=item.id, journalist_id=journo.id).one_or_none() seen_message = SeenMessage.query.filter_by( message_id=item.id, journalist_id=journo.id ).one_or_none() @@ -2866,9 +2826,7 @@ def test_download_selected_submissions_and_replies_previously_seen( db.session.commit() with journalist_app.test_client() as app: - _login_user( - app, journo.username, test_journo["password"], test_journo["otp_secret"] - ) + _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) resp = app.post( "/bulk", data=dict( @@ -2894,9 +2852,7 @@ def test_download_selected_submissions_and_replies_previously_seen( ) assert zipinfo - seen_file = SeenFile.query.filter_by( - file_id=item.id, journalist_id=journo.id - ).one_or_none() + seen_file = SeenFile.query.filter_by(file_id=item.id, journalist_id=journo.id).one_or_none() seen_message = SeenMessage.query.filter_by( message_id=item.id, journalist_id=journo.id ).one_or_none() @@ -2941,9 +2897,7 @@ def test_download_selected_submissions_previously_downloaded( db.session.commit() with journalist_app.test_client() as app: - _login_user( - app, journo.username, test_journo["password"], test_journo["otp_secret"] - ) + _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) resp = app.post( "/bulk", data=dict( @@ -3005,23 +2959,18 @@ def test_download_selected_submissions_missing_files( journalist_app, test_journo, test_source, mocker, selected_missing_files, app_storage ): """Tests download of selected submissions with missing files in storage.""" - mocked_error_logger = mocker.patch('journalist.app.logger.error') + mocked_error_logger = mocker.patch("journalist.app.logger.error") journo = Journalist.query.get(test_journo["id"]) with journalist_app.test_client() as app: - _login_user( - app, - journo.username, - test_journo["password"], - test_journo["otp_secret"] - ) + _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) resp = app.post( url_for("main.bulk"), data=dict( action="download", filesystem_id=test_source["filesystem_id"], doc_names_selected=selected_missing_files, - ) + ), ) assert resp.status_code == 302 @@ -3043,17 +2992,12 @@ def test_download_single_submission_missing_file( journalist_app, test_journo, test_source, mocker, selected_missing_files, app_storage ): """Tests download of single submissions with missing files in storage.""" - mocked_error_logger = mocker.patch('journalist.app.logger.error') + mocked_error_logger = mocker.patch("journalist.app.logger.error") journo = Journalist.query.get(test_journo["id"]) missing_file = selected_missing_files[0] with journalist_app.test_client() as app: - _login_user( - app, - journo.username, - test_journo["password"], - test_journo["otp_secret"] - ) + _login_user(app, journo.username, test_journo["password"], test_journo["otp_secret"]) resp = app.get( url_for( "col.download_single_file", @@ -3071,9 +3015,7 @@ def test_download_single_submission_missing_file( .as_posix() ) - mocked_error_logger.assert_called_once_with( - "File {} not found".format(missing_file) - ) + mocked_error_logger.assert_called_once_with("File {} not found".format(missing_file)) def test_download_unread_all_sources(journalist_app, test_journo, app_storage): @@ -3227,41 +3169,35 @@ def test_download_all_selected_sources(journalist_app, test_journo, app_storage) assert zipinfo -def test_single_source_is_successfully_starred(journalist_app, - test_journo, - test_source): +def test_single_source_is_successfully_starred(journalist_app, test_journo, test_source): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('col.add_star', - filesystem_id=test_source['filesystem_id'])) + resp = app.post(url_for("col.add_star", filesystem_id=test_source["filesystem_id"])) - ins.assert_redirects(resp, url_for('main.index')) + ins.assert_redirects(resp, url_for("main.index")) - source = Source.query.get(test_source['id']) + source = Source.query.get(test_source["id"]) assert source.star.starred -def test_single_source_is_successfully_unstarred(journalist_app, - test_journo, - test_source): +def test_single_source_is_successfully_unstarred(journalist_app, test_journo, test_source): with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) # First star the source - app.post(url_for('col.add_star', - filesystem_id=test_source['filesystem_id'])) + app.post(url_for("col.add_star", filesystem_id=test_source["filesystem_id"])) with InstrumentedApp(journalist_app) as ins: # Now unstar the source - resp = app.post( - url_for('col.remove_star', - filesystem_id=test_source['filesystem_id'])) + resp = app.post(url_for("col.remove_star", filesystem_id=test_source["filesystem_id"])) - ins.assert_redirects(resp, url_for('main.index')) + ins.assert_redirects(resp, url_for("main.index")) - source = Source.query.get(test_source['id']) + source = Source.query.get(test_source["id"]) assert not source.star.starred @@ -3273,25 +3209,25 @@ def test_journalist_session_expiration(config, journalist_app, test_journo, loca with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: login_data = { - 'username': test_journo['username'], - 'password': test_journo['password'], - 'token': TOTP(test_journo['otp_secret']).now(), + "username": test_journo["username"], + "password": test_journo["password"], + "token": TOTP(test_journo["otp_secret"]).now(), } - resp = app.post(url_for('main.login'), data=login_data) - ins.assert_redirects(resp, url_for('main.index')) - assert 'uid' in session + resp = app.post(url_for("main.login"), data=login_data) + ins.assert_redirects(resp, url_for("main.index")) + assert "uid" in session - resp = app.get(url_for('account.edit', l=locale), follow_redirects=True) + resp = app.get(url_for("account.edit", l=locale), follow_redirects=True) # because the session is being cleared when it expires, the # response should always be in English. - assert page_language(resp.data) == 'en-US' - assert 'You have been logged out due to inactivity.' in resp.data.decode('utf-8') + assert page_language(resp.data) == "en-US" + assert "You have been logged out due to inactivity." in resp.data.decode("utf-8") # check that the session was cleared (apart from 'expires' # which is always present and 'csrf_token' which leaks no info) - session.pop('expires', None) - session.pop('csrf_token', None) - session.pop('locale', None) + session.pop("expires", None) + session.pop("csrf_token", None) + session.pop("locale", None) assert not session, session @@ -3300,41 +3236,42 @@ def test_journalist_session_expiration(config, journalist_app, test_journo, loca def test_csrf_error_page(config, journalist_app, locale): # get the locale into the session with journalist_app.test_client() as app: - resp = app.get(url_for('main.login', l=locale)) + resp = app.get(url_for("main.login", l=locale)) assert page_language(resp.data) == language_tag(locale) - msgids = ['Show password'] + msgids = ["Show password"] with xfail_untranslated_messages(config, locale, msgids): - assert gettext(msgids[0]) in resp.data.decode('utf-8') + assert gettext(msgids[0]) in resp.data.decode("utf-8") - journalist_app.config['WTF_CSRF_ENABLED'] = True + journalist_app.config["WTF_CSRF_ENABLED"] = True with journalist_app.test_client() as app: with InstrumentedApp(journalist_app) as ins: - resp = app.post(url_for('main.login')) - ins.assert_redirects(resp, url_for('main.login')) + resp = app.post(url_for("main.login")) + ins.assert_redirects(resp, url_for("main.login")) - resp = app.post(url_for('main.login'), follow_redirects=True) + resp = app.post(url_for("main.login"), follow_redirects=True) # because the session is being cleared when it expires, the # response should always be in English. - assert page_language(resp.data) == 'en-US' - assert 'You have been logged out due to inactivity.' in resp.data.decode('utf-8') + assert page_language(resp.data) == "en-US" + assert "You have been logged out due to inactivity." in resp.data.decode("utf-8") def test_col_process_aborts_with_bad_action(journalist_app, test_journo): """If the action is not a valid choice, a 500 should occur""" with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) - form_data = {'cols_selected': 'does not matter', - 'action': 'this action does not exist'} + form_data = {"cols_selected": "does not matter", "action": "this action does not exist"} - resp = app.post(url_for('col.process'), data=form_data) + resp = app.post(url_for("col.process"), data=form_data) assert resp.status_code == 500 -def test_col_process_successfully_deletes_multiple_sources(journalist_app, - test_journo, app_storage): +def test_col_process_successfully_deletes_multiple_sources( + journalist_app, test_journo, app_storage +): # Create two sources with one submission each source_1, _ = utils.db_helper.init_source(app_storage) utils.db_helper.submit(app_storage, source_1, 1) @@ -3344,15 +3281,16 @@ def test_col_process_successfully_deletes_multiple_sources(journalist_app, utils.db_helper.submit(app_storage, source_3, 1) with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) - form_data = {'cols_selected': [source_1.filesystem_id, - source_2.filesystem_id], - 'action': 'delete'} + form_data = { + "cols_selected": [source_1.filesystem_id, source_2.filesystem_id], + "action": "delete", + } - resp = app.post(url_for('col.process'), data=form_data, - follow_redirects=True) + resp = app.post(url_for("col.process"), data=form_data, follow_redirects=True) assert resp.status_code == 200 @@ -3365,79 +3303,72 @@ def test_col_process_successfully_deletes_multiple_sources(journalist_app, assert remaining_sources[0].uuid == source_3.uuid -def test_col_process_successfully_stars_sources(journalist_app, - test_journo, - test_source, - app_storage): - utils.db_helper.submit(app_storage, test_source['source'], 1) +def test_col_process_successfully_stars_sources( + journalist_app, test_journo, test_source, app_storage +): + utils.db_helper.submit(app_storage, test_source["source"], 1) with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) - form_data = {'cols_selected': [test_source['filesystem_id']], - 'action': 'star'} + form_data = {"cols_selected": [test_source["filesystem_id"]], "action": "star"} - resp = app.post(url_for('col.process'), data=form_data, - follow_redirects=True) + resp = app.post(url_for("col.process"), data=form_data, follow_redirects=True) assert resp.status_code == 200 - source = Source.query.get(test_source['id']) + source = Source.query.get(test_source["id"]) assert source.star.starred -def test_col_process_successfully_unstars_sources(journalist_app, - test_journo, - test_source, - app_storage): - utils.db_helper.submit(app_storage, test_source['source'], 1) +def test_col_process_successfully_unstars_sources( + journalist_app, test_journo, test_source, app_storage +): + utils.db_helper.submit(app_storage, test_source["source"], 1) with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) # First star the source - form_data = {'cols_selected': [test_source['filesystem_id']], - 'action': 'star'} - app.post(url_for('col.process'), data=form_data, - follow_redirects=True) + form_data = {"cols_selected": [test_source["filesystem_id"]], "action": "star"} + app.post(url_for("col.process"), data=form_data, follow_redirects=True) # Now unstar the source - form_data = {'cols_selected': [test_source['filesystem_id']], - 'action': 'un-star'} - resp = app.post(url_for('col.process'), data=form_data, - follow_redirects=True) + form_data = {"cols_selected": [test_source["filesystem_id"]], "action": "un-star"} + resp = app.post(url_for("col.process"), data=form_data, follow_redirects=True) assert resp.status_code == 200 - source = Source.query.get(test_source['id']) + source = Source.query.get(test_source["id"]) assert not source.star.starred -def test_source_with_null_last_updated(journalist_app, - test_journo, - test_files): - '''Regression test for issues #3862''' +def test_source_with_null_last_updated(journalist_app, test_journo, test_files): + """Regression test for issues #3862""" - source = test_files['source'] + source = test_files["source"] source.last_updated = None db.session.add(source) db.session.commit() with journalist_app.test_client() as app: - _login_user(app, test_journo['username'], test_journo['password'], - test_journo['otp_secret']) - resp = app.get(url_for('main.index')) + _login_user( + app, test_journo["username"], test_journo["password"], test_journo["otp_secret"] + ) + resp = app.get(url_for("main.index")) assert resp.status_code == 200 def test_does_set_cookie_headers(journalist_app, test_journo): with journalist_app.test_client() as app: - response = app.get(url_for('main.login')) + response = app.get(url_for("main.login")) observed_headers = response.headers - assert 'Set-Cookie' in list(observed_headers.keys()) - assert 'Cookie' in observed_headers['Vary'] + assert "Set-Cookie" in list(observed_headers.keys()) + assert "Cookie" in observed_headers["Vary"] def test_app_error_handlers_defined(journalist_app): @@ -3448,12 +3379,12 @@ def test_app_error_handlers_defined(journalist_app): def test_lazy_deleted_journalist_creation(journalist_app): """test lazy creation of "deleted" jousrnalist works""" - not_found = Journalist.query.filter_by(username='deleted').one_or_none() + not_found = Journalist.query.filter_by(username="deleted").one_or_none() assert not_found is None, "deleted journalist doesn't exist yet" deleted = Journalist.get_deleted() db.session.commit() # Can be found as a normal Journalist object - found = Journalist.query.filter_by(username='deleted').one() + found = Journalist.query.filter_by(username="deleted").one() assert deleted.uuid == found.uuid assert found.is_deleted_user() is True # And get_deleted() now returns the same instance diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -1,27 +1,19 @@ # -*- coding: utf-8 -*- import json import random - from datetime import datetime -from flask import url_for -from itsdangerous import TimedJSONWebSignatureSerializer -from pyotp import TOTP from uuid import UUID, uuid4 from db import db from encryption import EncryptionManager -from models import ( - Journalist, - Reply, - Source, - SourceStar, - Submission, - RevokedToken, -) +from flask import url_for +from itsdangerous import TimedJSONWebSignatureSerializer +from models import Journalist, Reply, RevokedToken, Source, SourceStar, Submission +from pyotp import TOTP from .utils.api_helper import get_api_headers -random.seed('◔ ⌣ ◔') +random.seed("◔ ⌣ ◔") def assert_valid_timestamp(timestamp: str) -> None: @@ -32,11 +24,17 @@ def assert_valid_timestamp(timestamp: str) -> None: def test_unauthenticated_user_gets_all_endpoints(journalist_app): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_endpoints')) - - expected_endpoints = ['current_user_url', 'all_users_url', - 'submissions_url', 'sources_url', - 'auth_token_url', 'replies_url', 'seen_url'] + response = app.get(url_for("api.get_endpoints")) + + expected_endpoints = [ + "current_user_url", + "all_users_url", + "submissions_url", + "sources_url", + "auth_token_url", + "replies_url", + "seen_url", + ] expected_endpoints.sort() sorted_observed_endpoints = list(response.json.keys()) sorted_observed_endpoints.sort() @@ -45,522 +43,533 @@ def test_unauthenticated_user_gets_all_endpoints(journalist_app): def test_valid_user_can_get_an_api_token(journalist_app, test_journo): with journalist_app.test_client() as app: - valid_token = TOTP(test_journo['otp_secret']).now() - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'username': test_journo['username'], - 'passphrase': test_journo['password'], - 'one_time_code': valid_token}), - headers=get_api_headers()) - - assert response.json['journalist_uuid'] == test_journo['uuid'] - assert isinstance(Journalist.validate_api_token_and_get_user( - response.json['token']), Journalist) is True + valid_token = TOTP(test_journo["otp_secret"]).now() + response = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + "one_time_code": valid_token, + } + ), + headers=get_api_headers(), + ) + + assert response.json["journalist_uuid"] == test_journo["uuid"] + assert ( + isinstance( + Journalist.validate_api_token_and_get_user(response.json["token"]), Journalist + ) + is True + ) assert response.status_code == 200 - assert response.json['journalist_first_name'] == test_journo['first_name'] - assert response.json['journalist_last_name'] == test_journo['last_name'] + assert response.json["journalist_first_name"] == test_journo["first_name"] + assert response.json["journalist_last_name"] == test_journo["last_name"] - assert_valid_timestamp(response.json['expiration']) + assert_valid_timestamp(response.json["expiration"]) -def test_user_cannot_get_an_api_token_with_wrong_password(journalist_app, - test_journo): +def test_user_cannot_get_an_api_token_with_wrong_password(journalist_app, test_journo): with journalist_app.test_client() as app: - valid_token = TOTP(test_journo['otp_secret']).now() - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'username': test_journo['username'], - 'passphrase': 'wrong password', - 'one_time_code': valid_token}), - headers=get_api_headers()) + valid_token = TOTP(test_journo["otp_secret"]).now() + response = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": "wrong password", + "one_time_code": valid_token, + } + ), + headers=get_api_headers(), + ) assert response.status_code == 403 - assert response.json['error'] == 'Forbidden' + assert response.json["error"] == "Forbidden" -def test_user_cannot_get_an_api_token_with_wrong_2fa_token(journalist_app, - test_journo, - hardening): +def test_user_cannot_get_an_api_token_with_wrong_2fa_token(journalist_app, test_journo, hardening): with journalist_app.test_client() as app: - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'username': test_journo['username'], - 'passphrase': test_journo['password'], - 'one_time_code': '123456'}), - headers=get_api_headers()) + response = app.post( + url_for("api.get_token"), + data=json.dumps( + { + "username": test_journo["username"], + "passphrase": test_journo["password"], + "one_time_code": "123456", + } + ), + headers=get_api_headers(), + ) assert response.status_code == 403 - assert response.json['error'] == 'Forbidden' + assert response.json["error"] == "Forbidden" -def test_user_cannot_get_an_api_token_with_no_passphase_field(journalist_app, - test_journo): +def test_user_cannot_get_an_api_token_with_no_passphase_field(journalist_app, test_journo): with journalist_app.test_client() as app: - valid_token = TOTP(test_journo['otp_secret']).now() - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'username': test_journo['username'], - 'one_time_code': valid_token}), - headers=get_api_headers()) + valid_token = TOTP(test_journo["otp_secret"]).now() + response = app.post( + url_for("api.get_token"), + data=json.dumps({"username": test_journo["username"], "one_time_code": valid_token}), + headers=get_api_headers(), + ) assert response.status_code == 400 - assert response.json['error'] == 'Bad Request' - assert response.json['message'] == 'passphrase field is missing' + assert response.json["error"] == "Bad Request" + assert response.json["message"] == "passphrase field is missing" -def test_user_cannot_get_an_api_token_with_no_username_field(journalist_app, - test_journo): +def test_user_cannot_get_an_api_token_with_no_username_field(journalist_app, test_journo): with journalist_app.test_client() as app: - valid_token = TOTP(test_journo['otp_secret']).now() - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'passphrase': test_journo['password'], - 'one_time_code': valid_token}), - headers=get_api_headers()) + valid_token = TOTP(test_journo["otp_secret"]).now() + response = app.post( + url_for("api.get_token"), + data=json.dumps({"passphrase": test_journo["password"], "one_time_code": valid_token}), + headers=get_api_headers(), + ) assert response.status_code == 400 - assert response.json['error'] == 'Bad Request' - assert response.json['message'] == 'username field is missing' + assert response.json["error"] == "Bad Request" + assert response.json["message"] == "username field is missing" -def test_user_cannot_get_an_api_token_with_no_otp_field(journalist_app, - test_journo): +def test_user_cannot_get_an_api_token_with_no_otp_field(journalist_app, test_journo): with journalist_app.test_client() as app: - response = app.post(url_for('api.get_token'), - data=json.dumps( - {'username': test_journo['username'], - 'passphrase': test_journo['password']}), - headers=get_api_headers()) + response = app.post( + url_for("api.get_token"), + data=json.dumps( + {"username": test_journo["username"], "passphrase": test_journo["password"]} + ), + headers=get_api_headers(), + ) assert response.status_code == 400 - assert response.json['error'] == 'Bad Request' - assert response.json['message'] == 'one_time_code field is missing' + assert response.json["error"] == "Bad Request" + assert response.json["message"] == "one_time_code field is missing" -def test_authorized_user_gets_all_sources(journalist_app, test_submissions, - journalist_api_token): +def test_authorized_user_gets_all_sources(journalist_app, test_submissions, journalist_api_token): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_all_sources'), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.get_all_sources"), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 200 # We expect to see our test source in the response - assert test_submissions['source'].journalist_designation == \ - response.json['sources'][0]['journalist_designation'] - for source in response.json['sources']: - assert_valid_timestamp(source['last_updated']) + assert ( + test_submissions["source"].journalist_designation + == response.json["sources"][0]["journalist_designation"] + ) + for source in response.json["sources"]: + assert_valid_timestamp(source["last_updated"]) -def test_user_without_token_cannot_get_protected_endpoints(journalist_app, - test_files): +def test_user_without_token_cannot_get_protected_endpoints(journalist_app, test_files): with journalist_app.app_context(): - uuid = test_files['source'].uuid + uuid = test_files["source"].uuid protected_routes = [ - url_for('api.get_all_sources'), - url_for('api.single_source', source_uuid=uuid), - url_for('api.all_source_submissions', source_uuid=uuid), - url_for('api.single_submission', source_uuid=uuid, - submission_uuid=test_files['submissions'][0].uuid), - url_for('api.download_submission', source_uuid=uuid, - submission_uuid=test_files['submissions'][0].uuid), - url_for('api.get_all_submissions'), - url_for('api.get_all_replies'), - url_for('api.single_reply', source_uuid=uuid, - reply_uuid=test_files['replies'][0].uuid), - url_for('api.all_source_replies', source_uuid=uuid), - url_for('api.get_current_user'), - url_for('api.get_all_users'), - ] + url_for("api.get_all_sources"), + url_for("api.single_source", source_uuid=uuid), + url_for("api.all_source_submissions", source_uuid=uuid), + url_for( + "api.single_submission", + source_uuid=uuid, + submission_uuid=test_files["submissions"][0].uuid, + ), + url_for( + "api.download_submission", + source_uuid=uuid, + submission_uuid=test_files["submissions"][0].uuid, + ), + url_for("api.get_all_submissions"), + url_for("api.get_all_replies"), + url_for("api.single_reply", source_uuid=uuid, reply_uuid=test_files["replies"][0].uuid), + url_for("api.all_source_replies", source_uuid=uuid), + url_for("api.get_current_user"), + url_for("api.get_all_users"), + ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.get(protected_route, - headers=get_api_headers('')) + response = app.get(protected_route, headers=get_api_headers("")) assert response.status_code == 403 -def test_user_without_token_cannot_del_protected_endpoints(journalist_app, - test_submissions): +def test_user_without_token_cannot_del_protected_endpoints(journalist_app, test_submissions): with journalist_app.app_context(): - uuid = test_submissions['source'].uuid + uuid = test_submissions["source"].uuid protected_routes = [ - url_for('api.single_source', source_uuid=uuid), - url_for('api.single_submission', source_uuid=uuid, - submission_uuid=test_submissions['submissions'][0].uuid), - url_for('api.remove_star', source_uuid=uuid), - url_for('api.source_conversation', source_uuid=uuid), - ] + url_for("api.single_source", source_uuid=uuid), + url_for( + "api.single_submission", + source_uuid=uuid, + submission_uuid=test_submissions["submissions"][0].uuid, + ), + url_for("api.remove_star", source_uuid=uuid), + url_for("api.source_conversation", source_uuid=uuid), + ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.delete(protected_route, - headers=get_api_headers('')) + response = app.delete(protected_route, headers=get_api_headers("")) assert response.status_code == 403 -def test_attacker_cannot_create_valid_token_with_none_alg(journalist_app, - test_source, - test_journo): +def test_attacker_cannot_create_valid_token_with_none_alg(journalist_app, test_source, test_journo): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - s = TimedJSONWebSignatureSerializer('not the secret key', - algorithm_name='none') - attacker_token = s.dumps({'id': test_journo['id']}).decode('ascii') + uuid = test_source["source"].uuid + s = TimedJSONWebSignatureSerializer("not the secret key", algorithm_name="none") + attacker_token = s.dumps({"id": test_journo["id"]}).decode("ascii") - response = app.delete(url_for('api.single_source', source_uuid=uuid), - headers=get_api_headers(attacker_token)) + response = app.delete( + url_for("api.single_source", source_uuid=uuid), headers=get_api_headers(attacker_token) + ) assert response.status_code == 403 -def test_attacker_cannot_use_token_after_admin_deletes(journalist_app, - test_source, - journalist_api_token): +def test_attacker_cannot_use_token_after_admin_deletes( + journalist_app, test_source, journalist_api_token +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid + uuid = test_source["source"].uuid # In a scenario where an attacker compromises a journalist workstation # the admin should be able to delete the user and their token should # no longer be valid. - attacker = Journalist.validate_api_token_and_get_user( - journalist_api_token) + attacker = Journalist.validate_api_token_and_get_user(journalist_api_token) db.session.delete(attacker) db.session.commit() # Now this token should not be valid. - response = app.delete(url_for('api.single_source', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + response = app.delete( + url_for("api.single_source", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 403 -def test_user_without_token_cannot_post_protected_endpoints(journalist_app, - test_source): +def test_user_without_token_cannot_post_protected_endpoints(journalist_app, test_source): with journalist_app.app_context(): - uuid = test_source['source'].uuid + uuid = test_source["source"].uuid protected_routes = [ - url_for('api.all_source_replies', source_uuid=uuid), - url_for('api.add_star', source_uuid=uuid), - url_for('api.flag', source_uuid=uuid) + url_for("api.all_source_replies", source_uuid=uuid), + url_for("api.add_star", source_uuid=uuid), + url_for("api.flag", source_uuid=uuid), ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post(protected_route, - headers=get_api_headers(''), - data=json.dumps({'some': 'stuff'})) + response = app.post( + protected_route, headers=get_api_headers(""), data=json.dumps({"some": "stuff"}) + ) assert response.status_code == 403 def test_api_error_handlers_defined(journalist_app): """Ensure the expected error handler is defined in the API blueprint""" for status_code in [400, 401, 403, 404, 500]: - result = journalist_app.error_handler_spec['api'][status_code] + result = journalist_app.error_handler_spec["api"][status_code] - expected_error_handler = '_handle_api_http_exception' + expected_error_handler = "_handle_api_http_exception" assert list(result.values())[0].__name__ == expected_error_handler def test_api_error_handler_404(journalist_app, journalist_api_token): with journalist_app.test_client() as app: - response = app.get('/api/v1/invalidendpoint', - headers=get_api_headers(journalist_api_token)) + response = app.get("/api/v1/invalidendpoint", headers=get_api_headers(journalist_api_token)) assert response.status_code == 404 - assert response.json['error'] == 'Not Found' + assert response.json["error"] == "Not Found" -def test_trailing_slash_cleanly_404s(journalist_app, test_source, - journalist_api_token): +def test_trailing_slash_cleanly_404s(journalist_app, test_source, journalist_api_token): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.get(url_for('api.single_source', - source_uuid=uuid) + '/', - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.get( + url_for("api.single_source", source_uuid=uuid) + "/", + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 404 - assert response.json['error'] == 'Not Found' + assert response.json["error"] == "Not Found" -def test_authorized_user_gets_single_source(journalist_app, test_source, - journalist_api_token): +def test_authorized_user_gets_single_source(journalist_app, test_source, journalist_api_token): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.get(url_for('api.single_source', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.get( + url_for("api.single_source", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - assert response.json['uuid'] == test_source['source'].uuid - assert response.json['key']['fingerprint'] == \ - test_source['source'].fingerprint - assert 'BEGIN PGP PUBLIC KEY' in response.json['key']['public'] + assert response.json["uuid"] == test_source["source"].uuid + assert response.json["key"]["fingerprint"] == test_source["source"].fingerprint + assert "BEGIN PGP PUBLIC KEY" in response.json["key"]["public"] def test_get_non_existant_source_404s(journalist_app, journalist_api_token): with journalist_app.test_client() as app: - response = app.get(url_for('api.single_source', source_uuid=1), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.single_source", source_uuid=1), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 404 -def test_authorized_user_can_star_a_source(journalist_app, test_source, - journalist_api_token): +def test_authorized_user_can_star_a_source(journalist_app, test_source, journalist_api_token): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - source_id = test_source['source'].id - response = app.post(url_for('api.add_star', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + source_id = test_source["source"].id + response = app.post( + url_for("api.add_star", source_uuid=uuid), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 201 # Verify that the source was starred. - assert SourceStar.query.filter( - SourceStar.source_id == source_id).one().starred + assert SourceStar.query.filter(SourceStar.source_id == source_id).one().starred # API should also report is_starred is true - response = app.get(url_for('api.single_source', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) - assert response.json['is_starred'] is True + response = app.get( + url_for("api.single_source", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) + assert response.json["is_starred"] is True -def test_authorized_user_can_unstar_a_source(journalist_app, test_source, - journalist_api_token): +def test_authorized_user_can_unstar_a_source(journalist_app, test_source, journalist_api_token): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - source_id = test_source['source'].id - response = app.post(url_for('api.add_star', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + source_id = test_source["source"].id + response = app.post( + url_for("api.add_star", source_uuid=uuid), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 201 - response = app.delete(url_for('api.remove_star', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + response = app.delete( + url_for("api.remove_star", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 # Verify that the source is gone. - assert SourceStar.query.filter( - SourceStar.source_id == source_id).one().starred is False + assert SourceStar.query.filter(SourceStar.source_id == source_id).one().starred is False # API should also report is_starred is false - response = app.get(url_for('api.single_source', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) - assert response.json['is_starred'] is False + response = app.get( + url_for("api.single_source", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) + assert response.json["is_starred"] is False -def test_disallowed_methods_produces_405(journalist_app, test_source, - journalist_api_token): +def test_disallowed_methods_produces_405(journalist_app, test_source, journalist_api_token): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.delete(url_for('api.add_star', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.delete( + url_for("api.add_star", source_uuid=uuid), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 405 - assert response.json['error'] == 'Method Not Allowed' + assert response.json["error"] == "Method Not Allowed" -def test_authorized_user_can_get_all_submissions(journalist_app, - test_submissions, - journalist_api_token): +def test_authorized_user_can_get_all_submissions( + journalist_app, test_submissions, journalist_api_token +): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_all_submissions'), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.get_all_submissions"), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 200 - observed_submissions = [submission['filename'] for - submission in response.json['submissions']] + observed_submissions = [ + submission["filename"] for submission in response.json["submissions"] + ] - expected_submissions = [submission.filename for - submission in Submission.query.all()] + expected_submissions = [submission.filename for submission in Submission.query.all()] assert observed_submissions == expected_submissions -def test_authorized_user_get_all_submissions_with_disconnected_submissions(journalist_app, - test_submissions, - journalist_api_token): +def test_authorized_user_get_all_submissions_with_disconnected_submissions( + journalist_app, test_submissions, journalist_api_token +): with journalist_app.test_client() as app: db.session.execute( - "DELETE FROM sources WHERE id = :id", - {"id": test_submissions["source"].id} + "DELETE FROM sources WHERE id = :id", {"id": test_submissions["source"].id} + ) + response = app.get( + url_for("api.get_all_submissions"), headers=get_api_headers(journalist_api_token) ) - response = app.get(url_for('api.get_all_submissions'), - headers=get_api_headers(journalist_api_token)) assert response.status_code == 200 -def test_authorized_user_get_source_submissions(journalist_app, - test_submissions, - journalist_api_token): +def test_authorized_user_get_source_submissions( + journalist_app, test_submissions, journalist_api_token +): with journalist_app.test_client() as app: - uuid = test_submissions['source'].uuid - response = app.get(url_for('api.all_source_submissions', - source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_submissions["source"].uuid + response = app.get( + url_for("api.all_source_submissions", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - observed_submissions = [submission['filename'] for - submission in response.json['submissions']] + observed_submissions = [ + submission["filename"] for submission in response.json["submissions"] + ] - expected_submissions = [submission.filename for submission in - test_submissions['source'].submissions] + expected_submissions = [ + submission.filename for submission in test_submissions["source"].submissions + ] assert observed_submissions == expected_submissions -def test_authorized_user_can_get_single_submission(journalist_app, - test_submissions, - journalist_api_token): +def test_authorized_user_can_get_single_submission( + journalist_app, test_submissions, journalist_api_token +): with journalist_app.test_client() as app: - submission_uuid = test_submissions['source'].submissions[0].uuid - uuid = test_submissions['source'].uuid - response = app.get(url_for('api.single_submission', - source_uuid=uuid, - submission_uuid=submission_uuid), - headers=get_api_headers(journalist_api_token)) + submission_uuid = test_submissions["source"].submissions[0].uuid + uuid = test_submissions["source"].uuid + response = app.get( + url_for("api.single_submission", source_uuid=uuid, submission_uuid=submission_uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - assert response.json['uuid'] == submission_uuid - assert response.json['is_read'] is False - assert response.json['filename'] == \ - test_submissions['source'].submissions[0].filename - assert response.json['size'] == \ - test_submissions['source'].submissions[0].size + assert response.json["uuid"] == submission_uuid + assert response.json["is_read"] is False + assert response.json["filename"] == test_submissions["source"].submissions[0].filename + assert response.json["size"] == test_submissions["source"].submissions[0].size -def test_authorized_user_can_get_all_replies_with_disconnected_replies(journalist_app, - test_files, - journalist_api_token): +def test_authorized_user_can_get_all_replies_with_disconnected_replies( + journalist_app, test_files, journalist_api_token +): with journalist_app.test_client() as app: - db.session.execute( - "DELETE FROM sources WHERE id = :id", - {"id": test_files["source"].id} + db.session.execute("DELETE FROM sources WHERE id = :id", {"id": test_files["source"].id}) + response = app.get( + url_for("api.get_all_replies"), headers=get_api_headers(journalist_api_token) ) - response = app.get(url_for('api.get_all_replies'), - headers=get_api_headers(journalist_api_token)) assert response.status_code == 200 -def test_authorized_user_can_get_all_replies(journalist_app, test_files, - journalist_api_token): +def test_authorized_user_can_get_all_replies(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_all_replies'), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.get_all_replies"), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 200 - observed_replies = [reply['filename'] for - reply in response.json['replies']] + observed_replies = [reply["filename"] for reply in response.json["replies"]] - expected_replies = [reply.filename for - reply in Reply.query.all()] + expected_replies = [reply.filename for reply in Reply.query.all()] assert observed_replies == expected_replies -def test_authorized_user_get_source_replies(journalist_app, test_files, - journalist_api_token): +def test_authorized_user_get_source_replies(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app: - uuid = test_files['source'].uuid - response = app.get(url_for('api.all_source_replies', - source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_files["source"].uuid + response = app.get( + url_for("api.all_source_replies", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - observed_replies = [reply['filename'] for - reply in response.json['replies']] + observed_replies = [reply["filename"] for reply in response.json["replies"]] - expected_replies = [reply.filename for - reply in test_files['source'].replies] + expected_replies = [reply.filename for reply in test_files["source"].replies] assert observed_replies == expected_replies -def test_authorized_user_can_get_single_reply(journalist_app, test_files, - journalist_api_token): +def test_authorized_user_can_get_single_reply(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app: - reply_uuid = test_files['source'].replies[0].uuid - uuid = test_files['source'].uuid - response = app.get(url_for('api.single_reply', - source_uuid=uuid, - reply_uuid=reply_uuid), - headers=get_api_headers(journalist_api_token)) + reply_uuid = test_files["source"].replies[0].uuid + uuid = test_files["source"].uuid + response = app.get( + url_for("api.single_reply", source_uuid=uuid, reply_uuid=reply_uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 reply = Reply.query.filter(Reply.uuid == reply_uuid).one() - assert response.json['uuid'] == reply_uuid - assert response.json['journalist_username'] == \ - reply.journalist.username - assert response.json['journalist_uuid'] == \ - reply.journalist.uuid - assert response.json['journalist_first_name'] == \ - (reply.journalist.first_name or '') - assert response.json['journalist_last_name'] == \ - (reply.journalist.last_name or '') - assert response.json['is_deleted_by_source'] is False - assert response.json['filename'] == \ - test_files['source'].replies[0].filename - assert response.json['size'] == \ - test_files['source'].replies[0].size - - -def test_reply_of_deleted_journalist(journalist_app, - test_files_deleted_journalist, - journalist_api_token): + assert response.json["uuid"] == reply_uuid + assert response.json["journalist_username"] == reply.journalist.username + assert response.json["journalist_uuid"] == reply.journalist.uuid + assert response.json["journalist_first_name"] == (reply.journalist.first_name or "") + assert response.json["journalist_last_name"] == (reply.journalist.last_name or "") + assert response.json["is_deleted_by_source"] is False + assert response.json["filename"] == test_files["source"].replies[0].filename + assert response.json["size"] == test_files["source"].replies[0].size + + +def test_reply_of_deleted_journalist( + journalist_app, test_files_deleted_journalist, journalist_api_token +): with journalist_app.test_client() as app: - reply_uuid = test_files_deleted_journalist['source'].replies[0].uuid - uuid = test_files_deleted_journalist['source'].uuid - response = app.get(url_for('api.single_reply', - source_uuid=uuid, - reply_uuid=reply_uuid), - headers=get_api_headers(journalist_api_token)) + reply_uuid = test_files_deleted_journalist["source"].replies[0].uuid + uuid = test_files_deleted_journalist["source"].uuid + response = app.get( + url_for("api.single_reply", source_uuid=uuid, reply_uuid=reply_uuid), + headers=get_api_headers(journalist_api_token), + ) deleted_uuid = Journalist.get_deleted().uuid assert response.status_code == 200 - assert response.json['uuid'] == reply_uuid - assert response.json['journalist_username'] == "deleted" - assert response.json['journalist_uuid'] == deleted_uuid - assert response.json['journalist_first_name'] == "" - assert response.json['journalist_last_name'] == "" - assert response.json['is_deleted_by_source'] is False - assert response.json['filename'] == \ - test_files_deleted_journalist['source'].replies[0].filename - assert response.json['size'] == \ - test_files_deleted_journalist['source'].replies[0].size - - -def test_authorized_user_can_delete_single_submission(journalist_app, - test_submissions, - journalist_api_token): + assert response.json["uuid"] == reply_uuid + assert response.json["journalist_username"] == "deleted" + assert response.json["journalist_uuid"] == deleted_uuid + assert response.json["journalist_first_name"] == "" + assert response.json["journalist_last_name"] == "" + assert response.json["is_deleted_by_source"] is False + assert ( + response.json["filename"] == test_files_deleted_journalist["source"].replies[0].filename + ) + assert response.json["size"] == test_files_deleted_journalist["source"].replies[0].size + + +def test_authorized_user_can_delete_single_submission( + journalist_app, test_submissions, journalist_api_token +): with journalist_app.test_client() as app: - submission_uuid = test_submissions['source'].submissions[0].uuid - uuid = test_submissions['source'].uuid - response = app.delete(url_for('api.single_submission', - source_uuid=uuid, - submission_uuid=submission_uuid), - headers=get_api_headers(journalist_api_token)) + submission_uuid = test_submissions["source"].submissions[0].uuid + uuid = test_submissions["source"].uuid + response = app.delete( + url_for("api.single_submission", source_uuid=uuid, submission_uuid=submission_uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 # Submission now should be gone. - assert Submission.query.filter( - Submission.uuid == submission_uuid).all() == [] + assert Submission.query.filter(Submission.uuid == submission_uuid).all() == [] -def test_authorized_user_can_delete_single_reply(journalist_app, test_files, - journalist_api_token): +def test_authorized_user_can_delete_single_reply(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app: - reply_uuid = test_files['source'].replies[0].uuid - uuid = test_files['source'].uuid - response = app.delete(url_for('api.single_reply', - source_uuid=uuid, - reply_uuid=reply_uuid), - headers=get_api_headers(journalist_api_token)) + reply_uuid = test_files["source"].replies[0].uuid + uuid = test_files["source"].uuid + response = app.delete( + url_for("api.single_reply", source_uuid=uuid, reply_uuid=reply_uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 @@ -568,19 +577,21 @@ def test_authorized_user_can_delete_single_reply(journalist_app, test_files, assert Reply.query.filter(Reply.uuid == reply_uuid).all() == [] -def test_authorized_user_can_delete_source_conversation(journalist_app, - test_files, - journalist_api_token): +def test_authorized_user_can_delete_source_conversation( + journalist_app, test_files, journalist_api_token +): with journalist_app.test_client() as app: - uuid = test_files['source'].uuid - source_id = test_files['source'].id + uuid = test_files["source"].uuid + source_id = test_files["source"].id # Submissions and Replies both exist assert not Submission.query.filter(source_id == source_id).all() == [] assert not Reply.query.filter(source_id == source_id).all() == [] - response = app.delete(url_for('api.source_conversation', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + response = app.delete( + url_for("api.source_conversation", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 @@ -592,23 +603,28 @@ def test_authorized_user_can_delete_source_conversation(journalist_app, assert not Source.query.filter(uuid == uuid).all() == [] -def test_source_conversation_does_not_support_get(journalist_app, test_source, - journalist_api_token): +def test_source_conversation_does_not_support_get( + journalist_app, test_source, journalist_api_token +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.get(url_for('api.source_conversation', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.get( + url_for("api.source_conversation", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 405 -def test_authorized_user_can_delete_source_collection(journalist_app, - test_source, - journalist_api_token): +def test_authorized_user_can_delete_source_collection( + journalist_app, test_source, journalist_api_token +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.delete(url_for('api.single_source', source_uuid=uuid), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.delete( + url_for("api.single_source", source_uuid=uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 @@ -616,12 +632,12 @@ def test_authorized_user_can_delete_source_collection(journalist_app, assert Source.query.all() == [] -def test_authorized_user_can_download_submission(journalist_app, - test_submissions, - journalist_api_token): +def test_authorized_user_can_download_submission( + journalist_app, test_submissions, journalist_api_token +): with journalist_app.test_client() as app: - submission_uuid = test_submissions['source'].submissions[0].uuid - uuid = test_submissions['source'].uuid + submission_uuid = test_submissions["source"].submissions[0].uuid + uuid = test_submissions["source"].uuid response = app.get( url_for( @@ -635,384 +651,404 @@ def test_authorized_user_can_download_submission(journalist_app, assert response.status_code == 200 # Response should be a PGP encrypted download - assert response.mimetype == 'application/pgp-encrypted' + assert response.mimetype == "application/pgp-encrypted" # Response should have Etag field with hash - assert response.headers['ETag'].startswith('sha256:') + assert response.headers["ETag"].startswith("sha256:") -def test_authorized_user_can_download_reply(journalist_app, test_files, - journalist_api_token): +def test_authorized_user_can_download_reply(journalist_app, test_files, journalist_api_token): with journalist_app.test_client() as app: - reply_uuid = test_files['source'].replies[0].uuid - uuid = test_files['source'].uuid + reply_uuid = test_files["source"].replies[0].uuid + uuid = test_files["source"].uuid - response = app.get(url_for('api.download_reply', - source_uuid=uuid, - reply_uuid=reply_uuid), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.download_reply", source_uuid=uuid, reply_uuid=reply_uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 # Response should be a PGP encrypted download - assert response.mimetype == 'application/pgp-encrypted' + assert response.mimetype == "application/pgp-encrypted" # Response should have Etag field with hash - assert response.headers['ETag'].startswith('sha256:') + assert response.headers["ETag"].startswith("sha256:") -def test_authorized_user_can_get_current_user_endpoint(journalist_app, - test_journo, - journalist_api_token): +def test_authorized_user_can_get_current_user_endpoint( + journalist_app, test_journo, journalist_api_token +): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_current_user'), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.get_current_user"), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 200 - assert response.json['is_admin'] is False - assert response.json['username'] == test_journo['username'] - assert response.json['uuid'] == test_journo['journalist'].uuid - assert response.json['first_name'] == test_journo['journalist'].first_name - assert response.json['last_name'] == test_journo['journalist'].last_name + assert response.json["is_admin"] is False + assert response.json["username"] == test_journo["username"] + assert response.json["uuid"] == test_journo["journalist"].uuid + assert response.json["first_name"] == test_journo["journalist"].first_name + assert response.json["last_name"] == test_journo["journalist"].last_name -def test_authorized_user_can_get_all_users(journalist_app, test_journo, test_admin, - journalist_api_token): +def test_authorized_user_can_get_all_users( + journalist_app, test_journo, test_admin, journalist_api_token +): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_all_users'), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.get_all_users"), headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 200 # Ensure that all the users in the database are returned - observed_users = [user['uuid'] for user in response.json['users']] + observed_users = [user["uuid"] for user in response.json["users"]] expected_users = [user.uuid for user in Journalist.query.all()] assert observed_users == expected_users # Ensure that no fields other than the expected ones are returned - expected_fields = ['first_name', 'last_name', 'username', 'uuid'] - for user in response.json['users']: + expected_fields = ["first_name", "last_name", "username", "uuid"] + for user in response.json["users"]: assert sorted(user.keys()) == expected_fields def test_request_with_missing_auth_header_triggers_403(journalist_app): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_current_user'), - headers={ - 'Accept': 'application/json', - 'Content-Type': 'application/json' - }) + response = app.get( + url_for("api.get_current_user"), + headers={"Accept": "application/json", "Content-Type": "application/json"}, + ) assert response.status_code == 403 def test_request_with_auth_header_but_no_token_triggers_403(journalist_app): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_current_user'), - headers={ - 'Authorization': '', - 'Accept': 'application/json', - 'Content-Type': 'application/json' - }) + response = app.get( + url_for("api.get_current_user"), + headers={ + "Authorization": "", + "Accept": "application/json", + "Content-Type": "application/json", + }, + ) assert response.status_code == 403 -def test_unencrypted_replies_get_rejected(journalist_app, journalist_api_token, - test_source, test_journo): +def test_unencrypted_replies_get_rejected( + journalist_app, journalist_api_token, test_source, test_journo +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - reply_content = 'This is a plaintext reply' - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data=json.dumps({'reply': reply_content}), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + reply_content = "This is a plaintext reply" + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data=json.dumps({"reply": reply_content}), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 -def test_authorized_user_can_add_reply(journalist_app, journalist_api_token, - test_source, test_journo, app_storage): +def test_authorized_user_can_add_reply( + journalist_app, journalist_api_token, test_source, test_journo, app_storage +): with journalist_app.test_client() as app: - source_id = test_source['source'].id - uuid = test_source['source'].uuid + source_id = test_source["source"].id + uuid = test_source["source"].uuid # First we must encrypt the reply, or it will get rejected # by the server. encryption_mgr = EncryptionManager.get_default() - source_key = encryption_mgr.get_source_key_fingerprint( - test_source['source'].filesystem_id - ) - reply_content = encryption_mgr._gpg.encrypt( - 'This is a plaintext reply', source_key).data + source_key = encryption_mgr.get_source_key_fingerprint(test_source["source"].filesystem_id) + reply_content = encryption_mgr._gpg.encrypt("This is a plaintext reply", source_key).data - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data=json.dumps({'reply': reply_content.decode('utf-8')}), - headers=get_api_headers(journalist_api_token)) + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data=json.dumps({"reply": reply_content.decode("utf-8")}), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 201 # ensure the uuid is present and valid - reply_uuid = UUID(response.json['uuid']) + reply_uuid = UUID(response.json["uuid"]) # check that the uuid has a matching db object reply = Reply.query.filter_by(uuid=str(reply_uuid)).one_or_none() assert reply is not None # check that the filename is present and correct (#4047) - assert response.json['filename'] == reply.filename + assert response.json["filename"] == reply.filename with journalist_app.app_context(): # Now verify everything was saved. - assert reply.journalist_id == test_journo['id'] + assert reply.journalist_id == test_journo["id"] assert reply.source_id == source_id # regression test for #3918 - assert '/' not in reply.filename + assert "/" not in reply.filename source = Source.query.get(source_id) - expected_filename = '{}-{}-reply.gpg'.format( - source.interaction_count, source.journalist_filename) + expected_filename = "{}-{}-reply.gpg".format( + source.interaction_count, source.journalist_filename + ) expected_filepath = app_storage.path(source.filesystem_id, expected_filename) - with open(expected_filepath, 'rb') as fh: + with open(expected_filepath, "rb") as fh: saved_content = fh.read() assert reply_content == saved_content -def test_reply_without_content_400(journalist_app, journalist_api_token, - test_source, test_journo): +def test_reply_without_content_400(journalist_app, journalist_api_token, test_source, test_journo): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data=json.dumps({'reply': ''}), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data=json.dumps({"reply": ""}), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 -def test_reply_without_reply_field_400(journalist_app, journalist_api_token, - test_source, test_journo): +def test_reply_without_reply_field_400( + journalist_app, journalist_api_token, test_source, test_journo +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data=json.dumps({'other': 'stuff'}), - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data=json.dumps({"other": "stuff"}), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 -def test_reply_without_json_400(journalist_app, journalist_api_token, - test_source, test_journo): +def test_reply_without_json_400(journalist_app, journalist_api_token, test_source, test_journo): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data='invalid', - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data="invalid", + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 -def test_reply_with_valid_curly_json_400(journalist_app, journalist_api_token, - test_source, test_journo): +def test_reply_with_valid_curly_json_400( + journalist_app, journalist_api_token, test_source, test_journo +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data='{}', - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data="{}", + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 - assert response.json['message'] == 'reply not found in request body' + assert response.json["message"] == "reply not found in request body" -def test_reply_with_valid_square_json_400(journalist_app, journalist_api_token, - test_source, test_journo): +def test_reply_with_valid_square_json_400( + journalist_app, journalist_api_token, test_source, test_journo +): with journalist_app.test_client() as app: - uuid = test_source['source'].uuid - response = app.post(url_for('api.all_source_replies', - source_uuid=uuid), - data='[]', - headers=get_api_headers(journalist_api_token)) + uuid = test_source["source"].uuid + response = app.post( + url_for("api.all_source_replies", source_uuid=uuid), + data="[]", + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 - assert response.json['message'] == 'reply not found in request body' + assert response.json["message"] == "reply not found in request body" -def test_malformed_json_400(journalist_app, journalist_api_token, test_journo, - test_source): +def test_malformed_json_400(journalist_app, journalist_api_token, test_journo, test_source): with journalist_app.app_context(): - uuid = test_source['source'].uuid + uuid = test_source["source"].uuid protected_routes = [ - url_for('api.get_token'), - url_for('api.all_source_replies', source_uuid=uuid), - url_for('api.add_star', source_uuid=uuid), - url_for('api.flag', source_uuid=uuid), + url_for("api.get_token"), + url_for("api.all_source_replies", source_uuid=uuid), + url_for("api.add_star", source_uuid=uuid), + url_for("api.flag", source_uuid=uuid), ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post(protected_route, - data="{this is invalid {json!", - headers=get_api_headers(journalist_api_token)) + response = app.post( + protected_route, + data="{this is invalid {json!", + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 400 - assert response.json['error'] == 'Bad Request' + assert response.json["error"] == "Bad Request" -def test_empty_json_400(journalist_app, journalist_api_token, test_journo, - test_source): +def test_empty_json_400(journalist_app, journalist_api_token, test_journo, test_source): with journalist_app.app_context(): - uuid = test_source['source'].uuid + uuid = test_source["source"].uuid protected_routes = [ - url_for('api.get_token'), - url_for('api.all_source_replies', source_uuid=uuid), + url_for("api.get_token"), + url_for("api.all_source_replies", source_uuid=uuid), ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post(protected_route, - data="", - headers=get_api_headers(journalist_api_token)) + response = app.post( + protected_route, data="", headers=get_api_headers(journalist_api_token) + ) assert response.status_code == 400 - assert response.json['error'] == 'Bad Request' + assert response.json["error"] == "Bad Request" -def test_empty_json_20X(journalist_app, journalist_api_token, test_journo, - test_source): +def test_empty_json_20X(journalist_app, journalist_api_token, test_journo, test_source): with journalist_app.app_context(): - uuid = test_source['source'].uuid + uuid = test_source["source"].uuid protected_routes = [ - url_for('api.add_star', source_uuid=uuid), - url_for('api.flag', source_uuid=uuid), + url_for("api.add_star", source_uuid=uuid), + url_for("api.flag", source_uuid=uuid), ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post(protected_route, - data="", - headers=get_api_headers(journalist_api_token)) + response = app.post( + protected_route, data="", headers=get_api_headers(journalist_api_token) + ) assert response.status_code in (200, 201) def test_set_reply_uuid(journalist_app, journalist_api_token, test_source): - msg = '-----BEGIN PGP MESSAGE-----\nwat\n-----END PGP MESSAGE-----' + msg = "-----BEGIN PGP MESSAGE-----\nwat\n-----END PGP MESSAGE-----" reply_uuid = str(uuid4()) - req_data = {'uuid': reply_uuid, 'reply': msg} + req_data = {"uuid": reply_uuid, "reply": msg} with journalist_app.test_client() as app: # first check that we can set a valid UUID - source_uuid = test_source['uuid'] - resp = app.post(url_for('api.all_source_replies', - source_uuid=source_uuid), - data=json.dumps(req_data), - headers=get_api_headers(journalist_api_token)) + source_uuid = test_source["uuid"] + resp = app.post( + url_for("api.all_source_replies", source_uuid=source_uuid), + data=json.dumps(req_data), + headers=get_api_headers(journalist_api_token), + ) assert resp.status_code == 201 - assert resp.json['uuid'] == reply_uuid + assert resp.json["uuid"] == reply_uuid reply = Reply.query.filter_by(uuid=reply_uuid).one_or_none() assert reply is not None - len_of_replies = len(Source.query.get(test_source['id']).replies) + len_of_replies = len(Source.query.get(test_source["id"]).replies) # next check that requesting with the same UUID does not succeed - source_uuid = test_source['uuid'] - resp = app.post(url_for('api.all_source_replies', - source_uuid=source_uuid), - data=json.dumps(req_data), - headers=get_api_headers(journalist_api_token)) + source_uuid = test_source["uuid"] + resp = app.post( + url_for("api.all_source_replies", source_uuid=source_uuid), + data=json.dumps(req_data), + headers=get_api_headers(journalist_api_token), + ) assert resp.status_code == 409 - new_len_of_replies = len(Source.query.get(test_source['id']).replies) + new_len_of_replies = len(Source.query.get(test_source["id"]).replies) assert new_len_of_replies == len_of_replies # check setting null for the uuid field doesn't break - req_data['uuid'] = None - source_uuid = test_source['uuid'] - resp = app.post(url_for('api.all_source_replies', - source_uuid=source_uuid), - data=json.dumps(req_data), - headers=get_api_headers(journalist_api_token)) + req_data["uuid"] = None + source_uuid = test_source["uuid"] + resp = app.post( + url_for("api.all_source_replies", source_uuid=source_uuid), + data=json.dumps(req_data), + headers=get_api_headers(journalist_api_token), + ) assert resp.status_code == 201 - new_uuid = resp.json['uuid'] + new_uuid = resp.json["uuid"] reply = Reply.query.filter_by(uuid=new_uuid).one_or_none() assert reply is not None # check setting invalid values for the uuid field doesn't break - req_data['uuid'] = 'not a uuid' - source_uuid = test_source['uuid'] - resp = app.post(url_for('api.all_source_replies', - source_uuid=source_uuid), - data=json.dumps(req_data), - headers=get_api_headers(journalist_api_token)) + req_data["uuid"] = "not a uuid" + source_uuid = test_source["uuid"] + resp = app.post( + url_for("api.all_source_replies", source_uuid=source_uuid), + data=json.dumps(req_data), + headers=get_api_headers(journalist_api_token), + ) assert resp.status_code == 400 def test_api_does_not_set_cookie_headers(journalist_app, test_journo): with journalist_app.test_client() as app: - response = app.get(url_for('api.get_endpoints')) + response = app.get(url_for("api.get_endpoints")) observed_headers = response.headers - assert 'Set-Cookie' not in list(observed_headers.keys()) - if 'Vary' in list(observed_headers.keys()): - assert 'Cookie' not in observed_headers['Vary'] + assert "Set-Cookie" not in list(observed_headers.keys()) + if "Vary" in list(observed_headers.keys()): + assert "Cookie" not in observed_headers["Vary"] # regression test for #4053 def test_malformed_auth_token(journalist_app, journalist_api_token): with journalist_app.app_context(): # we know this endpoint requires an auth header - url = url_for('api.get_all_sources') + url = url_for("api.get_all_sources") with journalist_app.test_client() as app: # precondition to ensure token is even valid - resp = app.get(url, headers={'Authorization': 'Token {}'.format(journalist_api_token)}) + resp = app.get(url, headers={"Authorization": "Token {}".format(journalist_api_token)}) assert resp.status_code == 200 - resp = app.get(url, headers={'Authorization': 'not-token {}'.format(journalist_api_token)}) + resp = app.get(url, headers={"Authorization": "not-token {}".format(journalist_api_token)}) assert resp.status_code == 403 - resp = app.get(url, headers={'Authorization': journalist_api_token}) + resp = app.get(url, headers={"Authorization": journalist_api_token}) assert resp.status_code == 403 - resp = app.get(url, headers={'Authorization': 'too many {}'.format(journalist_api_token)}) + resp = app.get(url, headers={"Authorization": "too many {}".format(journalist_api_token)}) assert resp.status_code == 403 -def test_submission_download_generates_checksum(journalist_app, - journalist_api_token, - test_source, - test_submissions, - mocker): - submission = test_submissions['submissions'][0] +def test_submission_download_generates_checksum( + journalist_app, journalist_api_token, test_source, test_submissions, mocker +): + submission = test_submissions["submissions"][0] assert submission.checksum is None # precondition with journalist_app.test_client() as app: - response = app.get(url_for('api.download_submission', - source_uuid=test_source['uuid'], - submission_uuid=submission.uuid), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for( + "api.download_submission", + source_uuid=test_source["uuid"], + submission_uuid=submission.uuid, + ), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - assert response.headers['ETag'] + assert response.headers["ETag"] # check that the submission checksum was added fetched_submission = Submission.query.get(submission.id) assert fetched_submission.checksum - mock_add_checksum = mocker.patch('journalist_app.utils.add_checksum_for_file') + mock_add_checksum = mocker.patch("journalist_app.utils.add_checksum_for_file") with journalist_app.test_client() as app: - response = app.get(url_for('api.download_submission', - source_uuid=test_source['uuid'], - submission_uuid=submission.uuid), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for( + "api.download_submission", + source_uuid=test_source["uuid"], + submission_uuid=submission.uuid, + ), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - assert response.headers['ETag'] + assert response.headers["ETag"] fetched_submission = Submission.query.get(submission.id) assert fetched_submission.checksum @@ -1020,34 +1056,32 @@ def test_submission_download_generates_checksum(journalist_app, assert not mock_add_checksum.called -def test_reply_download_generates_checksum(journalist_app, - journalist_api_token, - test_source, - test_files, - mocker): - reply = test_files['replies'][0] +def test_reply_download_generates_checksum( + journalist_app, journalist_api_token, test_source, test_files, mocker +): + reply = test_files["replies"][0] assert reply.checksum is None # precondition with journalist_app.test_client() as app: - response = app.get(url_for('api.download_reply', - source_uuid=test_source['uuid'], - reply_uuid=reply.uuid), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.download_reply", source_uuid=test_source["uuid"], reply_uuid=reply.uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - assert response.headers['ETag'] + assert response.headers["ETag"] # check that the reply checksum was added fetched_reply = Reply.query.get(reply.id) assert fetched_reply.checksum - mock_add_checksum = mocker.patch('journalist_app.utils.add_checksum_for_file') + mock_add_checksum = mocker.patch("journalist_app.utils.add_checksum_for_file") with journalist_app.test_client() as app: - response = app.get(url_for('api.download_reply', - source_uuid=test_source['uuid'], - reply_uuid=reply.uuid), - headers=get_api_headers(journalist_api_token)) + response = app.get( + url_for("api.download_reply", source_uuid=test_source["uuid"], reply_uuid=reply.uuid), + headers=get_api_headers(journalist_api_token), + ) assert response.status_code == 200 - assert response.headers['ETag'] + assert response.headers["ETag"] fetched_reply = Reply.query.get(reply.id) assert fetched_reply.checksum @@ -1058,17 +1092,18 @@ def test_reply_download_generates_checksum(journalist_app, def test_revoke_token(journalist_app, test_journo, journalist_api_token): with journalist_app.test_client() as app: # without token 403's - resp = app.post(url_for('api.logout')) + resp = app.post(url_for("api.logout")) assert resp.status_code == 403 - resp = app.post(url_for('api.logout'), headers=get_api_headers(journalist_api_token)) + resp = app.post(url_for("api.logout"), headers=get_api_headers(journalist_api_token)) assert resp.status_code == 200 revoked_token = RevokedToken.query.filter_by(token=journalist_api_token).one() - assert revoked_token.journalist_id == test_journo['id'] + assert revoked_token.journalist_id == test_journo["id"] - resp = app.get(url_for('api.get_all_sources'), - headers=get_api_headers(journalist_api_token)) + resp = app.get( + url_for("api.get_all_sources"), headers=get_api_headers(journalist_api_token) + ) assert resp.status_code == 403 @@ -1077,9 +1112,9 @@ def test_seen(journalist_app, journalist_api_token, test_files, test_journo, tes Happy path for seen: marking things seen works. """ with journalist_app.test_client() as app: - replies_url = url_for('api.get_all_replies') - seen_url = url_for('api.seen') - submissions_url = url_for('api.get_all_submissions') + replies_url = url_for("api.get_all_replies") + seen_url = url_for("api.seen") + submissions_url = url_for("api.get_all_submissions") headers = get_api_headers(journalist_api_token) # check that /submissions contains no seen items @@ -1093,9 +1128,9 @@ def test_seen(journalist_app, journalist_api_token, test_files, test_journo, tes assert all([r["seen_by"] for r in response.json["replies"]]) # now mark one of each type of conversation item seen - file_uuid = test_files['submissions'][0].uuid - msg_uuid = test_submissions['submissions'][0].uuid - reply_uuid = test_files['replies'][0].uuid + file_uuid = test_files["submissions"][0].uuid + msg_uuid = test_submissions["submissions"][0].uuid + reply_uuid = test_files["replies"][0].uuid data = { "files": [file_uuid], "messages": [msg_uuid], @@ -1109,14 +1144,14 @@ def test_seen(journalist_app, journalist_api_token, test_files, test_journo, tes response = app.get(submissions_url, headers=headers) assert response.status_code == 200 assert [ - s for s in response.json["submissions"] - if s["is_file"] and s["uuid"] == file_uuid - and test_journo["uuid"] in s["seen_by"] + s + for s in response.json["submissions"] + if s["is_file"] and s["uuid"] == file_uuid and test_journo["uuid"] in s["seen_by"] ] assert [ - s for s in response.json["submissions"] - if s["is_message"] and s["uuid"] == msg_uuid - and test_journo["uuid"] in s["seen_by"] + s + for s in response.json["submissions"] + if s["is_message"] and s["uuid"] == msg_uuid and test_journo["uuid"] in s["seen_by"] ] # check that /replies still only contains one seen reply @@ -1135,9 +1170,9 @@ def test_seen(journalist_app, journalist_api_token, test_files, test_journo, tes response = app.get(submissions_url, headers=headers) assert response.status_code == 200 assert [ - s for s in response.json["submissions"] - if s["uuid"] in [file_uuid, msg_uuid] - and s["seen_by"] == [test_journo["uuid"]] + s + for s in response.json["submissions"] + if s["uuid"] in [file_uuid, msg_uuid] and s["seen_by"] == [test_journo["uuid"]] ] # check that /replies still only contains one seen reply @@ -1152,7 +1187,7 @@ def test_seen_bad_requests(journalist_app, journalist_api_token): Check that /seen rejects invalid requests. """ with journalist_app.test_client() as app: - seen_url = url_for('api.seen') + seen_url = url_for("api.seen") headers = get_api_headers(journalist_api_token) # invalid JSON diff --git a/securedrop/tests/test_journalist_utils.py b/securedrop/tests/test_journalist_utils.py --- a/securedrop/tests/test_journalist_utils.py +++ b/securedrop/tests/test_journalist_utils.py @@ -1,39 +1,42 @@ # -*- coding: utf-8 -*- -from flask import url_for -import pytest import random +import pytest +from flask import url_for +from journalist_app.utils import cleanup_expired_revoked_tokens from models import RevokedToken from sqlalchemy.orm.exc import NoResultFound -from journalist_app.utils import cleanup_expired_revoked_tokens - from .utils.api_helper import get_api_headers -random.seed('◔ ⌣ ◔') +random.seed("◔ ⌣ ◔") -def test_revoke_token_cleanup_does_not_delete_tokens_if_not_expired(journalist_app, test_journo, - journalist_api_token): +def test_revoke_token_cleanup_does_not_delete_tokens_if_not_expired( + journalist_app, test_journo, journalist_api_token +): with journalist_app.test_client() as app: - resp = app.post(url_for('api.logout'), headers=get_api_headers(journalist_api_token)) + resp = app.post(url_for("api.logout"), headers=get_api_headers(journalist_api_token)) assert resp.status_code == 200 cleanup_expired_revoked_tokens() revoked_token = RevokedToken.query.filter_by(token=journalist_api_token).one() - assert revoked_token.journalist_id == test_journo['id'] + assert revoked_token.journalist_id == test_journo["id"] -def test_revoke_token_cleanup_does_deletes_tokens_that_are_expired(journalist_app, test_journo, - journalist_api_token, mocker): +def test_revoke_token_cleanup_does_deletes_tokens_that_are_expired( + journalist_app, test_journo, journalist_api_token, mocker +): with journalist_app.test_client() as app: - resp = app.post(url_for('api.logout'), headers=get_api_headers(journalist_api_token)) + resp = app.post(url_for("api.logout"), headers=get_api_headers(journalist_api_token)) assert resp.status_code == 200 # Mock response from expired token method when token is expired - mocker.patch('journalist_app.admin.Journalist.validate_token_is_not_expired_or_invalid', - return_value=None) + mocker.patch( + "journalist_app.admin.Journalist.validate_token_is_not_expired_or_invalid", + return_value=None, + ) cleanup_expired_revoked_tokens() with pytest.raises(NoResultFound): diff --git a/securedrop/tests/test_manage.py b/securedrop/tests/test_manage.py --- a/securedrop/tests/test_manage.py +++ b/securedrop/tests/test_manage.py @@ -14,9 +14,10 @@ from passphrases import PassphraseGenerator from source_user import create_source_user - -YUBIKEY_HOTP = ['cb a0 5f ad 41 a2 ff 4e eb 53 56 3a 1b f7 23 2e ce fc dc', - 'cb a0 5f ad 41 a2 ff 4e eb 53 56 3a 1b f7 23 2e ce fc dc d7'] +YUBIKEY_HOTP = [ + "cb a0 5f ad 41 a2 ff 4e eb 53 56 3a 1b f7 23 2e ce fc dc", + "cb a0 5f ad 41 a2 ff 4e eb 53 56 3a 1b f7 23 2e ce fc dc d7", +] def test_parse_args(): @@ -25,38 +26,37 @@ def test_parse_args(): def test_not_verbose(caplog): - args = manage.get_args().parse_args(['run']) + args = manage.get_args().parse_args(["run"]) manage.setup_verbosity(args) - manage.log.debug('INVISIBLE') - assert 'INVISIBLE' not in caplog.text + manage.log.debug("INVISIBLE") + assert "INVISIBLE" not in caplog.text def test_verbose(caplog): - args = manage.get_args().parse_args(['--verbose', 'run']) + args = manage.get_args().parse_args(["--verbose", "run"]) manage.setup_verbosity(args) - manage.log.debug('VISIBLE') - assert 'VISIBLE' in caplog.text + manage.log.debug("VISIBLE") + assert "VISIBLE" in caplog.text def test_get_username_success(): - with mock.patch("manage.obtain_input", return_value='jen'): - assert manage._get_username() == 'jen' + with mock.patch("manage.obtain_input", return_value="jen"): + assert manage._get_username() == "jen" def test_get_username_fail(): - bad_username = 'a' * (Journalist.MIN_USERNAME_LEN - 1) - with mock.patch("manage.obtain_input", - side_effect=[bad_username, 'jen']): - assert manage._get_username() == 'jen' + bad_username = "a" * (Journalist.MIN_USERNAME_LEN - 1) + with mock.patch("manage.obtain_input", side_effect=[bad_username, "jen"]): + assert manage._get_username() == "jen" def test_get_yubikey_usage_yes(): - with mock.patch("manage.obtain_input", return_value='y'): + with mock.patch("manage.obtain_input", return_value="y"): assert manage._get_yubikey_usage() def test_get_yubikey_usage_no(): - with mock.patch("manage.obtain_input", return_value='n'): + with mock.patch("manage.obtain_input", return_value="n"): assert not manage._get_yubikey_usage() @@ -64,9 +64,9 @@ def test_get_yubikey_usage_no(): def test_handle_invalid_secret(journalist_app, config, mocker, capsys): """Regression test for bad secret logic in manage.py""" - mocker.patch("manage._get_username", return_value='ntoll'), - mocker.patch("manage._get_first_name", return_value=''), - mocker.patch("manage._get_last_name", return_value=''), + mocker.patch("manage._get_username", return_value="ntoll"), + mocker.patch("manage._get_first_name", return_value=""), + mocker.patch("manage._get_last_name", return_value=""), mocker.patch("manage._get_yubikey_usage", return_value=True), mocker.patch("manage.obtain_input", side_effect=YUBIKEY_HOTP), @@ -76,19 +76,17 @@ def test_handle_invalid_secret(journalist_app, config, mocker, capsys): out, err = capsys.readouterr() assert return_value == 0 - assert 'Try again.' in out - assert 'successfully added' in out + assert "Try again." in out + assert "successfully added" in out # Note: we use the `journalist_app` fixture because it creates the DB -def test_exception_handling_when_duplicate_username(journalist_app, - config, - mocker, capsys): +def test_exception_handling_when_duplicate_username(journalist_app, config, mocker, capsys): """Regression test for duplicate username logic in manage.py""" - mocker.patch("manage._get_username", return_value='foo-bar-baz') - mocker.patch("manage._get_first_name", return_value='') - mocker.patch("manage._get_last_name", return_value='') + mocker.patch("manage._get_username", return_value="foo-bar-baz") + mocker.patch("manage._get_first_name", return_value="") + mocker.patch("manage._get_last_name", return_value="") mocker.patch("manage._get_yubikey_usage", return_value=False) with journalist_app.app_context() as context: @@ -97,24 +95,23 @@ def test_exception_handling_when_duplicate_username(journalist_app, out, err = capsys.readouterr() assert return_value == 0 - assert 'successfully added' in out + assert "successfully added" in out # Inserting the user for a second time should fail return_value = manage._add_user(context=context) out, err = capsys.readouterr() assert return_value == 1 - assert 'ERROR: That username is already taken!' in out + assert "ERROR: That username is already taken!" in out # Note: we use the `journalist_app` fixture because it creates the DB def test_delete_user(journalist_app, config, mocker): - mocker.patch("manage._get_username", return_value='test-user-56789') - mocker.patch("manage._get_first_name", return_value='') - mocker.patch("manage._get_last_name", return_value='') + mocker.patch("manage._get_username", return_value="test-user-56789") + mocker.patch("manage._get_first_name", return_value="") + mocker.patch("manage._get_last_name", return_value="") mocker.patch("manage._get_yubikey_usage", return_value=False) - mocker.patch("manage._get_username_to_delete", - return_value='test-user-56789') - mocker.patch('manage._get_delete_confirmation', return_value=True) + mocker.patch("manage._get_username_to_delete", return_value="test-user-56789") + mocker.patch("manage._get_delete_confirmation", return_value=True) with journalist_app.app_context() as context: return_value = manage._add_user(context=context) @@ -126,21 +123,20 @@ def test_delete_user(journalist_app, config, mocker): # Note: we use the `journalist_app` fixture because it creates the DB def test_delete_non_existent_user(journalist_app, config, mocker, capsys): - mocker.patch("manage._get_username_to_delete", - return_value='does-not-exist') - mocker.patch('manage._get_delete_confirmation', return_value=True) + mocker.patch("manage._get_username_to_delete", return_value="does-not-exist") + mocker.patch("manage._get_delete_confirmation", return_value=True) with journalist_app.app_context() as context: return_value = manage.delete_user(args=None, context=context) out, err = capsys.readouterr() assert return_value == 0 - assert 'ERROR: That user was not found!' in out + assert "ERROR: That user was not found!" in out def test_get_username_to_delete(mocker): - mocker.patch("manage.obtain_input", return_value='test-user-12345') + mocker.patch("manage.obtain_input", return_value="test-user-12345") return_value = manage._get_username_to_delete() - assert return_value == 'test-user-12345' + assert return_value == "test-user-12345" def test_reset(journalist_app, test_journo, alembic_config, config): @@ -160,59 +156,55 @@ def test_reset(journalist_app, test_journo, alembic_config, config): assert os.path.exists(config.STORE_DIR) # Verify journalist user present in the database is gone - res = Journalist.query.filter_by(username=test_journo['username']).one_or_none() + res = Journalist.query.filter_by(username=test_journo["username"]).one_or_none() assert res is None finally: manage.config = original_config def test_get_username(mocker): - mocker.patch("manage.obtain_input", return_value='foo-bar-baz') - assert manage._get_username() == 'foo-bar-baz' + mocker.patch("manage.obtain_input", return_value="foo-bar-baz") + assert manage._get_username() == "foo-bar-baz" def test_get_first_name(mocker): - mocker.patch("manage.obtain_input", return_value='foo-bar-baz') - assert manage._get_first_name() == 'foo-bar-baz' + mocker.patch("manage.obtain_input", return_value="foo-bar-baz") + assert manage._get_first_name() == "foo-bar-baz" def test_get_last_name(mocker): - mocker.patch("manage.obtain_input", return_value='foo-bar-baz') - assert manage._get_last_name() == 'foo-bar-baz' + mocker.patch("manage.obtain_input", return_value="foo-bar-baz") + assert manage._get_last_name() == "foo-bar-baz" def test_clean_tmp_do_nothing(caplog): - args = argparse.Namespace(days=0, - directory=' UNLIKELY::::::::::::::::: ', - verbose=logging.DEBUG) + args = argparse.Namespace( + days=0, directory=" UNLIKELY::::::::::::::::: ", verbose=logging.DEBUG + ) manage.setup_verbosity(args) manage.clean_tmp(args) - assert 'does not exist, do nothing' in caplog.text + assert "does not exist, do nothing" in caplog.text def test_clean_tmp_too_young(config, caplog): - args = argparse.Namespace(days=24*60*60, - directory=config.TEMP_DIR, - verbose=logging.DEBUG) + args = argparse.Namespace(days=24 * 60 * 60, directory=config.TEMP_DIR, verbose=logging.DEBUG) # create a file - io.open(os.path.join(config.TEMP_DIR, 'FILE'), 'a').close() + io.open(os.path.join(config.TEMP_DIR, "FILE"), "a").close() manage.setup_verbosity(args) manage.clean_tmp(args) - assert 'modified less than' in caplog.text + assert "modified less than" in caplog.text def test_clean_tmp_removed(config, caplog): - args = argparse.Namespace(days=0, - directory=config.TEMP_DIR, - verbose=logging.DEBUG) - fname = os.path.join(config.TEMP_DIR, 'FILE') - with io.open(fname, 'a'): - old = time.time() - 24*60*60 + args = argparse.Namespace(days=0, directory=config.TEMP_DIR, verbose=logging.DEBUG) + fname = os.path.join(config.TEMP_DIR, "FILE") + with io.open(fname, "a"): + old = time.time() - 24 * 60 * 60 os.utime(fname, (old, old)) manage.setup_verbosity(args) manage.clean_tmp(args) - assert 'FILE removed' in caplog.text + assert "FILE removed" in caplog.text def test_were_there_submissions_today(source_app, config, app_storage): @@ -221,14 +213,14 @@ def test_were_there_submissions_today(source_app, config, app_storage): data_root = config.SECUREDROP_DATA_ROOT args = argparse.Namespace(data_root=data_root, verbose=logging.DEBUG) - count_file = os.path.join(data_root, 'submissions_today.txt') + count_file = os.path.join(data_root, "submissions_today.txt") source_user = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), source_app_storage=app_storage, ) source = source_user.get_db_record() - source.last_updated = (datetime.datetime.utcnow() - datetime.timedelta(hours=24*2)) + source.last_updated = datetime.datetime.utcnow() - datetime.timedelta(hours=24 * 2) db.session.commit() submissions.were_there_submissions_today(args, context) assert io.open(count_file).read() == "0" diff --git a/securedrop/tests/test_passphrases.py b/securedrop/tests/test_passphrases.py --- a/securedrop/tests/test_passphrases.py +++ b/securedrop/tests/test_passphrases.py @@ -1,8 +1,7 @@ from unittest import mock import pytest - -from passphrases import PassphraseGenerator, InvalidWordListError +from passphrases import InvalidWordListError, PassphraseGenerator # pylint: disable=unsupported-membership-test # False positive https://github.com/PyCQA/pylint/issues/3045 diff --git a/securedrop/tests/test_rm.py b/securedrop/tests/test_rm.py --- a/securedrop/tests/test_rm.py +++ b/securedrop/tests/test_rm.py @@ -4,7 +4,6 @@ import os import pytest - import rm diff --git a/securedrop/tests/test_secure_tempfile.py b/securedrop/tests/test_secure_tempfile.py --- a/securedrop/tests/test_secure_tempfile.py +++ b/securedrop/tests/test_secure_tempfile.py @@ -1,79 +1,78 @@ # -*- coding: utf-8 -*- import io import os -import pytest +import pytest from pretty_bad_protocol._util import _is_stream - from secure_tempfile import SecureTemporaryFile -MESSAGE = '410,757,864,530' +MESSAGE = "410,757,864,530" def test_read_before_writing(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") with pytest.raises(AssertionError) as err: f.read() - assert 'You must write before reading!' in str(err) + assert "You must write before reading!" in str(err) def test_write_then_read_once(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) - assert f.read().decode('utf-8') == MESSAGE + assert f.read().decode("utf-8") == MESSAGE def test_write_twice_then_read_once(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) f.write(MESSAGE) - assert f.read().decode('utf-8') == MESSAGE * 2 + assert f.read().decode("utf-8") == MESSAGE * 2 def test_write_then_read_twice(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) - assert f.read().decode('utf-8') == MESSAGE - assert f.read() == b'' + assert f.read().decode("utf-8") == MESSAGE + assert f.read() == b"" def test_write_then_read_then_write(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) f.read() with pytest.raises(AssertionError) as err: - f.write('be gentle to each other so we can be dangerous together') - assert 'You cannot write after reading!' in str(err) + f.write("be gentle to each other so we can be dangerous together") + assert "You cannot write after reading!" in str(err) def test_read_write_unicode(): - f = SecureTemporaryFile('/tmp') - unicode_msg = '鬼神 Kill Em All 1989' + f = SecureTemporaryFile("/tmp") + unicode_msg = "鬼神 Kill Em All 1989" f.write(unicode_msg) - assert f.read().decode('utf-8') == unicode_msg + assert f.read().decode("utf-8") == unicode_msg def test_file_seems_encrypted(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) - with io.open(f.filepath, 'rb') as fh: + with io.open(f.filepath, "rb") as fh: contents = fh.read() - assert MESSAGE.encode('utf-8') not in contents + assert MESSAGE.encode("utf-8") not in contents assert MESSAGE not in contents.decode() def test_file_is_removed_from_disk(): # once without reading the contents - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) assert os.path.exists(f.filepath) f.close() assert not os.path.exists(f.filepath) # once with reading the contents - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") f.write(MESSAGE) f.read() assert os.path.exists(f.filepath) @@ -82,14 +81,14 @@ def test_file_is_removed_from_disk(): def test_SecureTemporaryFile_is_a_STREAMLIKE_TYPE(): - assert _is_stream(SecureTemporaryFile('/tmp')) + assert _is_stream(SecureTemporaryFile("/tmp")) def test_buffered_read(): - f = SecureTemporaryFile('/tmp') + f = SecureTemporaryFile("/tmp") msg = MESSAGE * 1000 f.write(msg) - out = b'' + out = b"" while True: chars = f.read(1024) if chars: @@ -97,13 +96,13 @@ def test_buffered_read(): else: break - assert out.decode('utf-8') == msg + assert out.decode("utf-8") == msg def test_tmp_file_id_omits_invalid_chars(): """The `SecureTempFile.tmp_file_id` instance attribute is used as the filename for the secure temporary file. This attribute should not contain invalid characters such as '/' and '\0' (null).""" - f = SecureTemporaryFile('/tmp') - assert '/' not in f.tmp_file_id - assert '\0' not in f.tmp_file_id + f = SecureTemporaryFile("/tmp") + assert "/" not in f.tmp_file_id + assert "\0" not in f.tmp_file_id diff --git a/securedrop/tests/test_session_manager.py b/securedrop/tests/test_session_manager.py --- a/securedrop/tests/test_session_manager.py +++ b/securedrop/tests/test_session_manager.py @@ -2,14 +2,13 @@ from unittest import mock import pytest - from db import db from passphrases import PassphraseGenerator from source_app.session_manager import ( SessionManager, + UserHasBeenDeleted, UserNotLoggedIn, UserSessionExpired, - UserHasBeenDeleted, ) from source_user import create_source_user diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -1,50 +1,47 @@ # -*- coding: utf-8 -*- # flake8: noqa: E741 import gzip +import os import re +import shutil import subprocess import time -import os -import shutil from datetime import datetime, timedelta, timezone from io import BytesIO, StringIO from pathlib import Path from unittest import mock +import pytest +import version +from db import db from flaky import flaky -from flask import session, escape, url_for, g, request +from flask import escape, g, request, session, url_for from flask_babel import gettext -from mock import patch, ANY -import pytest - +from journalist_app.utils import delete_collection +from mock import ANY, patch +from models import InstanceConfig, Reply, Source from passphrases import PassphraseGenerator +from source_app import api as source_app_api +from source_app import get_logo_url, session_manager from source_app.session_manager import SessionManager -from . import utils -import version -from db import db -from journalist_app.utils import delete_collection -from models import InstanceConfig, Source, Reply -from source_app import api as source_app_api, session_manager -from source_app import get_logo_url +from . import utils from .utils.db_helper import new_codename, submit from .utils.i18n import get_test_locales, language_tag, page_language, xfail_untranslated_messages from .utils.instrument import InstrumentedApp -GENERATE_DATA = {'tor2web_check': 'href="fake.onion"'} +GENERATE_DATA = {"tor2web_check": 'href="fake.onion"'} def test_logo_default_available(config, source_app): # if the custom image is available, this test will fail - custom_image_location = os.path.join( - config.SECUREDROP_ROOT, "static/i/custom_logo.png" - ) + custom_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png") if os.path.exists(custom_image_location): os.remove(custom_image_location) with source_app.test_client() as app: logo_url = get_logo_url(source_app) - assert logo_url.endswith('i/logo.png') + assert logo_url.endswith("i/logo.png") response = app.get(logo_url, follow_redirects=False) assert response.status_code == 200 @@ -58,7 +55,7 @@ def test_logo_custom_available(config, source_app): with source_app.test_client() as app: logo_url = get_logo_url(source_app) - assert logo_url.endswith('i/custom_logo.png') + assert logo_url.endswith("i/custom_logo.png") response = app.get(logo_url, follow_redirects=False) assert response.status_code == 200 @@ -67,20 +64,19 @@ def test_page_not_found(source_app): """Verify the page not found condition returns the intended template""" with InstrumentedApp(source_app) as ins: with source_app.test_client() as app: - resp = app.get('UNKNOWN') + resp = app.get("UNKNOWN") assert resp.status_code == 404 - ins.assert_template_used('notfound.html') + ins.assert_template_used("notfound.html") def test_orgname_default_set(source_app): - - class dummy_current(): + class dummy_current: organization_name = None - with patch.object(InstanceConfig, 'get_current') as iMock: + with patch.object(InstanceConfig, "get_current") as iMock: with source_app.test_client() as app: iMock.return_value = dummy_current() - resp = app.get(url_for('main.index')) + resp = app.get(url_for("main.index")) assert resp.status_code == 200 assert g.organization_name == "SecureDrop" @@ -88,98 +84,100 @@ class dummy_current(): def test_index(source_app): """Test that the landing page loads and looks how we expect""" with source_app.test_client() as app: - resp = app.get(url_for('main.index')) + resp = app.get(url_for("main.index")) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert 'First submission' in text - assert 'Return visit' in text + text = resp.data.decode("utf-8") + assert "First submission" in text + assert "Return visit" in text def _find_codename(html): """Find a source codename (diceware passphrase) in HTML""" # Codenames may contain HTML escape characters, and the wordlist # contains various symbols. - codename_re = (r'<mark [^>]*id="codename"[^>]*>[^<]*<span>' - r'(?P<codename>[a-z0-9 &#;?:=@_.*+()\'"$%!-]+)</span>[^<]*</mark>') + codename_re = ( + r'<mark [^>]*id="codename"[^>]*>[^<]*<span>' + r'(?P<codename>[a-z0-9 &#;?:=@_.*+()\'"$%!-]+)</span>[^<]*</mark>' + ) codename_match = re.search(codename_re, html) assert codename_match is not None - return codename_match.group('codename') + return codename_match.group("codename") def test_generate_already_logged_in(source_app): with source_app.test_client() as app: new_codename(app, session) # Make sure it redirects to /lookup when logged in - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 302 # Make sure it flashes the message on the lookup page - resp = app.post(url_for('main.generate'), data=GENERATE_DATA, follow_redirects=True) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA, follow_redirects=True) # Should redirect to /lookup assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "because you are already logged in." in text def test_create_new_source(source_app): with source_app.test_client() as app: - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 200 - tab_id = next(iter(session['codenames'].keys())) - resp = app.post(url_for('main.create'), data={'tab_id': tab_id}, follow_redirects=True) + tab_id = next(iter(session["codenames"].keys())) + resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) assert SessionManager.is_user_logged_in(db_session=db.session) # should be redirected to /lookup - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Submit Files" in text - assert 'codenames' not in session + assert "codenames" not in session def test_generate_as_post(source_app): with source_app.test_client() as app: - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 200 - session_codename = next(iter(session['codenames'].values())) + session_codename = next(iter(session["codenames"].values())) - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "functions as both your username and your password" in text - codename = _find_codename(resp.data.decode('utf-8')) + codename = _find_codename(resp.data.decode("utf-8")) # codename is also stored in the session - make sure it matches the # codename displayed to the source assert codename == escape(session_codename) + def test_generate_as_get(source_app): with source_app.test_client() as app: - resp = app.get(url_for('main.generate')) + resp = app.get(url_for("main.generate")) assert resp.status_code == 200 - session_codename = next(iter(session['codenames'].values())) + session_codename = next(iter(session["codenames"].values())) - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "functions as both your username and your password" in text - codename = _find_codename(resp.data.decode('utf-8')) + codename = _find_codename(resp.data.decode("utf-8")) # codename is also stored in the session - make sure it matches the # codename displayed to the source assert codename == escape(session_codename) - def test_create_duplicate_codename_logged_in_not_in_session(source_app): - with patch.object(source_app.logger, 'error') as logger: + with patch.object(source_app.logger, "error") as logger: with source_app.test_client() as app: - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 200 - tab_id, codename = next(iter(session['codenames'].items())) + tab_id, codename = next(iter(session["codenames"].items())) # Create a source the first time - resp = app.post(url_for('main.create'), data={'tab_id': tab_id}, follow_redirects=True) + resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) assert resp.status_code == 200 with source_app.test_client() as app: # Attempt to add the same source with app.session_transaction() as sess: - sess['codenames'] = {tab_id: codename} + sess["codenames"] = {tab_id: codename} sess["codenames_expire"] = datetime.utcnow() + timedelta(hours=1) - resp = app.post(url_for('main.create'), data={'tab_id': tab_id}, follow_redirects=True) + resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) logger.assert_called_once() assert "Could not create a source" in logger.call_args[0][0] assert resp.status_code == 200 @@ -189,31 +187,31 @@ def test_create_duplicate_codename_logged_in_not_in_session(source_app): def test_create_duplicate_codename_logged_in_in_session(source_app): with source_app.test_client() as app: # Given a user who generated a codename in a browser tab - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 200 - first_tab_id, first_codename = list(session['codenames'].items())[0] + first_tab_id, first_codename = list(session["codenames"].items())[0] # And then they opened a new browser tab to generate a second codename - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 200 - second_tab_id, second_codename = list(session['codenames'].items())[1] + second_tab_id, second_codename = list(session["codenames"].items())[1] assert first_codename != second_codename # And the user then completed the account creation flow in the first tab resp = app.post( - url_for('main.create'), data={'tab_id': first_tab_id}, follow_redirects=True + url_for("main.create"), data={"tab_id": first_tab_id}, follow_redirects=True ) assert resp.status_code == 200 first_tab_account = SessionManager.get_logged_in_user(db_session=db.session) # When the user tries to complete the account creation flow again, in the second tab resp = app.post( - url_for('main.create'), data={'tab_id': second_tab_id}, follow_redirects=True + url_for("main.create"), data={"tab_id": second_tab_id}, follow_redirects=True ) # Then the user is shown the "already logged in" message assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "You are already logged in." in text # And no new account was created @@ -225,81 +223,70 @@ def test_lookup(source_app): """Test various elements on the /lookup page.""" with source_app.test_client() as app: codename = new_codename(app, session) - resp = app.post(url_for('main.login'), data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) # redirects to /lookup - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "public key" in text # download the public key - resp = app.get(url_for('info.download_public_key')) - text = resp.data.decode('utf-8') + resp = app.get(url_for("info.download_public_key")) + text = resp.data.decode("utf-8") assert "BEGIN PGP PUBLIC KEY BLOCK" in text def test_journalist_key_redirects_to_public_key(source_app): """Test that the /journalist-key route redirects to /public-key.""" with source_app.test_client() as app: - resp = app.get(url_for('info.download_journalist_key')) + resp = app.get(url_for("info.download_journalist_key")) assert resp.status_code == 301 - resp = app.get(url_for('info.download_journalist_key'), follow_redirects=True) - assert request.path == url_for('info.download_public_key') - assert "BEGIN PGP PUBLIC KEY BLOCK" in resp.data.decode('utf-8') + resp = app.get(url_for("info.download_journalist_key"), follow_redirects=True) + assert request.path == url_for("info.download_public_key") + assert "BEGIN PGP PUBLIC KEY BLOCK" in resp.data.decode("utf-8") def test_login_and_logout(source_app): with source_app.test_client() as app: - resp = app.get(url_for('main.login')) + resp = app.get(url_for("main.login")) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Enter Codename" in text codename = new_codename(app, session) - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Submit Files" in text assert SessionManager.is_user_logged_in(db_session=db.session) with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(codename='invalid'), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename="invalid"), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert 'Sorry, that is not a recognized codename.' in text + text = resp.data.decode("utf-8") + assert "Sorry, that is not a recognized codename." in text assert not SessionManager.is_user_logged_in(db_session=db.session) with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 assert SessionManager.is_user_logged_in(db_session=db.session) - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 assert SessionManager.is_user_logged_in(db_session=db.session) - resp = app.get(url_for('main.logout'), - follow_redirects=True) + resp = app.get(url_for("main.logout"), follow_redirects=True) assert not SessionManager.is_user_logged_in(db_session=db.session) - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") # This is part of the logout page message instructing users # to click the 'New Identity' icon - assert 'This will clear your Tor Browser activity data' in text + assert "This will clear your Tor Browser activity data" in text def test_user_must_log_in_for_protected_views(source_app): with source_app.test_client() as app: - resp = app.get(url_for('main.lookup'), - follow_redirects=True) + resp = app.get(url_for("main.lookup"), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Enter Codename" in text @@ -309,16 +296,14 @@ def test_login_with_whitespace(source_app): """ def login_test(app, codename): - resp = app.get(url_for('main.login')) + resp = app.get(url_for("main.login")) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Enter Codename" in text - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Submit Files" in text assert SessionManager.is_user_logged_in(db_session=db.session) @@ -326,9 +311,9 @@ def login_test(app, codename): codename = new_codename(app, session) codenames = [ - codename + ' ', - ' ' + codename + ' ', - ' ' + codename, + codename + " ", + " " + codename + " ", + " " + codename, ] for codename_ in codenames: @@ -351,16 +336,14 @@ def test_login_with_missing_reply_files(source_app, app_storage): assert not reply_file_path.exists() with source_app.test_client() as app: - resp = app.get(url_for('main.login')) + resp = app.get(url_for("main.login")) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Enter Codename" in text - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Submit Files" in text assert SessionManager.is_user_logged_in(db_session=db.session) @@ -372,10 +355,10 @@ def _dummy_submission(app): subsequent submissions """ return app.post( - url_for('main.submit'), - data=dict(msg="Pay no attention to the man behind the curtain.", - fh=(BytesIO(b''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="Pay no attention to the man behind the curtain.", fh=(BytesIO(b""), "")), + follow_redirects=True, + ) def test_initial_submission_notification(source_app): @@ -388,7 +371,7 @@ def test_initial_submission_notification(source_app): new_codename(app, session) resp = _dummy_submission(app) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thank you for sending this information to us." in text @@ -397,11 +380,12 @@ def test_submit_message(source_app): new_codename(app, session) _dummy_submission(app) resp = app.post( - url_for('main.submit'), - data=dict(msg="This is a test.", fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="This is a test.", fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message" in text @@ -409,13 +393,11 @@ def test_submit_empty_message(source_app): with source_app.test_client() as app: new_codename(app, session) resp = app.post( - url_for('main.submit'), - data=dict(msg="", fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), data=dict(msg="", fh=(StringIO(""), "")), follow_redirects=True + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert "You must enter a message or choose a file to submit." \ - in text + text = resp.data.decode("utf-8") + assert "You must enter a message or choose a file to submit." in text def test_submit_big_message(source_app): @@ -426,11 +408,12 @@ def test_submit_big_message(source_app): new_codename(app, session) _dummy_submission(app) resp = app.post( - url_for('main.submit'), - data=dict(msg="AA" * (1024 * 512), fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="AA" * (1024 * 512), fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Message text too long." in text @@ -440,31 +423,33 @@ def test_submit_initial_short_message(source_app): """ with source_app.test_client() as app: InstanceConfig.get_default().update_submission_prefs( - allow_uploads=True, min_length=10, reject_codenames=False) + allow_uploads=True, min_length=10, reject_codenames=False + ) new_codename(app, session) resp = app.post( - url_for('main.submit'), - data=dict(msg="A" * 5, fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="A" * 5, fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Your first message must be at least 10 characters long." in text # Now retry with a longer message resp = app.post( - url_for('main.submit'), - data=dict(msg="A" * 25, fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="A" * 25, fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thank you for sending this information to us." in text # Now send another short message, that should still be accepted since # it's no longer the initial one resp = app.post( - url_for('main.submit'), - data=dict(msg="A", fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), data=dict(msg="A", fh=(StringIO(""), "")), follow_redirects=True + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message." in text @@ -473,12 +458,13 @@ def test_submit_file(source_app): new_codename(app, session) _dummy_submission(app) resp = app.post( - url_for('main.submit'), - data=dict(msg="", fh=(BytesIO(b'This is a test'), 'test.txt')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="", fh=(BytesIO(b"This is a test"), "test.txt")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert 'Thanks! We received your document' in text + text = resp.data.decode("utf-8") + assert "Thanks! We received your document" in text def test_submit_both(source_app): @@ -486,13 +472,12 @@ def test_submit_both(source_app): new_codename(app, session) _dummy_submission(app) resp = app.post( - url_for('main.submit'), - data=dict( - msg="This is a test", - fh=(BytesIO(b'This is a test'), 'test.txt')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="This is a test", fh=(BytesIO(b"This is a test"), "test.txt")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message and document" in text @@ -504,9 +489,10 @@ def test_submit_antispam(source_app): new_codename(app, session) _dummy_submission(app) resp = app.post( - url_for('main.submit'), - data=dict(msg="Test", fh=(StringIO(''), ''), text="blah"), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="Test", fh=(StringIO(""), ""), text="blah"), + follow_redirects=True, + ) assert resp.status_code == 403 @@ -516,34 +502,34 @@ def test_submit_codename_second_login(source_app): """ with source_app.test_client() as app: InstanceConfig.get_default().update_submission_prefs( - allow_uploads=True, min_length=0, reject_codenames=True) + allow_uploads=True, min_length=0, reject_codenames=True + ) codename = new_codename(app, session) resp = app.post( - url_for('main.submit'), - data=dict(msg=codename, fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg=codename, fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Please do not submit your codename!" in text - resp = app.get(url_for('main.logout'), - follow_redirects=True) + resp = app.get(url_for("main.logout"), follow_redirects=True) assert not SessionManager.is_user_logged_in(db_session=db.session) - text = resp.data.decode('utf-8') - assert 'This will clear your Tor Browser activity data' in text + text = resp.data.decode("utf-8") + assert "This will clear your Tor Browser activity data" in text - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 assert SessionManager.is_user_logged_in(db_session=db.session) resp = app.post( - url_for('main.submit'), - data=dict(msg=codename, fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg=codename, fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thank you for sending this information" in text @@ -553,24 +539,27 @@ def test_submit_codename(source_app): """ with source_app.test_client() as app: InstanceConfig.get_default().update_submission_prefs( - allow_uploads=True, min_length=0, reject_codenames=True) + allow_uploads=True, min_length=0, reject_codenames=True + ) codename = new_codename(app, session) resp = app.post( - url_for('main.submit'), - data=dict(msg=codename, fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg=codename, fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Please do not submit your codename!" in text # Do a dummy submission _dummy_submission(app) # Now resubmit the codename, should be accepted. resp = app.post( - url_for('main.submit'), - data=dict(msg=codename, fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg=codename, fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message" in text @@ -582,13 +571,11 @@ def test_delete_all_successfully_deletes_replies(source_app, app_storage): utils.db_helper.reply(app_storage, journalist, source, 1) with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 - resp = app.post(url_for('main.batch_delete'), follow_redirects=True) + resp = app.post(url_for("main.batch_delete"), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "All replies have been deleted" in text with source_app.app_context(): @@ -612,17 +599,14 @@ def test_delete_all_replies_deleted_by_source_but_not_journalist(source_app, app db.session.commit() with source_app.test_client() as app: - with patch.object(source_app.logger, 'error') as logger: - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + with patch.object(source_app.logger, "error") as logger: + resp = app.post( + url_for("main.login"), data=dict(codename=codename), follow_redirects=True + ) assert resp.status_code == 200 - resp = app.post(url_for('main.batch_delete'), - follow_redirects=True) + resp = app.post(url_for("main.batch_delete"), follow_redirects=True) assert resp.status_code == 200 - logger.assert_called_once_with( - "Found no replies when at least one was expected" - ) + logger.assert_called_once_with("Found no replies when at least one was expected") def test_delete_all_replies_already_deleted_by_journalists(source_app, app_storage): @@ -632,114 +616,110 @@ def test_delete_all_replies_already_deleted_by_journalists(source_app, app_stora # Note that we are creating the source and no replies with source_app.test_client() as app: - with patch.object(source_app.logger, 'error') as logger: - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + with patch.object(source_app.logger, "error") as logger: + resp = app.post( + url_for("main.login"), data=dict(codename=codename), follow_redirects=True + ) assert resp.status_code == 200 - resp = app.post(url_for('main.batch_delete'), - follow_redirects=True) + resp = app.post(url_for("main.batch_delete"), follow_redirects=True) assert resp.status_code == 200 - logger.assert_called_once_with( - "Found no replies when at least one was expected" - ) + logger.assert_called_once_with("Found no replies when at least one was expected") def test_submit_sanitizes_filename(source_app): """Test that upload file name is sanitized""" - insecure_filename = '../../bin/gpg' - sanitized_filename = 'bin_gpg' + insecure_filename = "../../bin/gpg" + sanitized_filename = "bin_gpg" - with patch.object(gzip, 'GzipFile', wraps=gzip.GzipFile) as gzipfile: + with patch.object(gzip, "GzipFile", wraps=gzip.GzipFile) as gzipfile: with source_app.test_client() as app: new_codename(app, session) resp = app.post( - url_for('main.submit'), - data=dict( - msg="", - fh=(BytesIO(b'This is a test'), insecure_filename)), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="", fh=(BytesIO(b"This is a test"), insecure_filename)), + follow_redirects=True, + ) assert resp.status_code == 200 - gzipfile.assert_called_with(filename=sanitized_filename, - mode=ANY, - fileobj=ANY, - mtime=0) + gzipfile.assert_called_with(filename=sanitized_filename, mode=ANY, fileobj=ANY, mtime=0) [email protected]("test_url", ['main.index', 'main.create', 'main.submit']) [email protected]("test_url", ["main.index", "main.create", "main.submit"]) def test_redirect_when_tor2web(config, source_app, test_url): with source_app.test_client() as app: resp = app.get( - url_for(test_url), - headers=[('X-tor2web', 'encrypted')], - follow_redirects=True) - text = resp.data.decode('utf-8') + url_for(test_url), headers=[("X-tor2web", "encrypted")], follow_redirects=True + ) + text = resp.data.decode("utf-8") assert resp.status_code == 403 assert "Proxy Service Detected" in text + def test_tor2web_warning(source_app): with source_app.test_client() as app: - resp = app.get(url_for('info.tor2web_warning')) + resp = app.get(url_for("info.tor2web_warning")) assert resp.status_code == 403 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Proxy Service Detected" in text - def test_why_use_tor_browser(source_app): with source_app.test_client() as app: - resp = app.get(url_for('info.recommend_tor_browser')) + resp = app.get(url_for("info.recommend_tor_browser")) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "You Should Use Tor Browser" in text def test_why_journalist_key(source_app): with source_app.test_client() as app: - resp = app.get(url_for('info.why_download_public_key')) + resp = app.get(url_for("info.why_download_public_key")) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Why download the team's public key?" in text def test_metadata_route(config, source_app): with patch("server_os.get_os_release", return_value="20.04"): with source_app.test_client() as app: - resp = app.get(url_for('api.metadata')) + resp = app.get(url_for("api.metadata")) assert resp.status_code == 200 - assert resp.headers.get('Content-Type') == 'application/json' - assert resp.json.get('allow_document_uploads') ==\ - InstanceConfig.get_current().allow_document_uploads - assert resp.json.get('sd_version') == version.__version__ - assert resp.json.get('server_os') == '20.04' - assert resp.json.get('supported_languages') ==\ - config.SUPPORTED_LOCALES - assert resp.json.get('v3_source_url') is None + assert resp.headers.get("Content-Type") == "application/json" + assert ( + resp.json.get("allow_document_uploads") + == InstanceConfig.get_current().allow_document_uploads + ) + assert resp.json.get("sd_version") == version.__version__ + assert resp.json.get("server_os") == "20.04" + assert resp.json.get("supported_languages") == config.SUPPORTED_LOCALES + assert resp.json.get("v3_source_url") is None def test_metadata_v3_url(source_app): onion_test_url = "abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh.onion" with patch.object(source_app_api, "get_sourcev3_url") as mocked_v3_url: - mocked_v3_url.return_value = (onion_test_url) + mocked_v3_url.return_value = onion_test_url with source_app.test_client() as app: - resp = app.get(url_for('api.metadata')) + resp = app.get(url_for("api.metadata")) assert resp.status_code == 200 - assert resp.headers.get('Content-Type') == 'application/json' - assert resp.json.get('v3_source_url') == onion_test_url + assert resp.headers.get("Content-Type") == "application/json" + assert resp.json.get("v3_source_url") == onion_test_url def test_login_with_overly_long_codename(source_app): """Attempting to login with an overly long codename should result in an error to avoid DoS.""" - overly_long_codename = 'a' * (PassphraseGenerator.MAX_PASSPHRASE_LENGTH + 1) + overly_long_codename = "a" * (PassphraseGenerator.MAX_PASSPHRASE_LENGTH + 1) with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(codename=overly_long_codename), - follow_redirects=True) + resp = app.post( + url_for("main.login"), data=dict(codename=overly_long_codename), follow_redirects=True + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert ("Field must be between 1 and {} characters long." - .format(PassphraseGenerator.MAX_PASSPHRASE_LENGTH)) in text + text = resp.data.decode("utf-8") + assert ( + "Field must be between 1 and {} characters long.".format( + PassphraseGenerator.MAX_PASSPHRASE_LENGTH + ) + ) in text def test_normalize_timestamps(source_app, app_storage): @@ -765,18 +745,16 @@ def test_normalize_timestamps(source_app, app_storage): assert not first_submission_path.exists() # log in as the source - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Submit Files" in text assert SessionManager.is_user_logged_in(db_session=db.session) # submit another message resp = _dummy_submission(app) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message" in text # sleep to ensure timestamps would differ @@ -785,14 +763,13 @@ def test_normalize_timestamps(source_app, app_storage): # submit another message resp = _dummy_submission(app) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message" in text # only two of the source's three submissions should have files in the store assert 3 == len(source.submissions) submission_paths = [ - Path(app_storage.path(source.filesystem_id, s.filename)) - for s in source.submissions + Path(app_storage.path(source.filesystem_id, s.filename)) for s in source.submissions ] extant_paths = [p for p in submission_paths if p.exists()] assert 2 == len(extant_paths) @@ -813,24 +790,22 @@ def test_failed_normalize_timestamps_logs_warning(source_app): still occur, but a warning should be logged (this will trigger an OSSEC alert).""" - with patch.object(source_app.logger, 'warning') as logger: - with patch.object(subprocess, 'call', return_value=1): + with patch.object(source_app.logger, "warning") as logger: + with patch.object(subprocess, "call", return_value=1): with source_app.test_client() as app: new_codename(app, session) _dummy_submission(app) resp = app.post( - url_for('main.submit'), - data=dict( - msg="This is a test.", - fh=(StringIO(''), '')), - follow_redirects=True) + url_for("main.submit"), + data=dict(msg="This is a test.", fh=(StringIO(""), "")), + follow_redirects=True, + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Thanks! We received your message" in text logger.assert_called_once_with( - "Couldn't normalize submission " - "timestamps (touch exited with 1)" + "Couldn't normalize submission " "timestamps (touch exited with 1)" ) @@ -840,18 +815,18 @@ def test_source_is_deleted_while_logged_in(source_app): index when this happens, and a warning logged.""" with source_app.test_client() as app: codename = new_codename(app, session) - app.post('login', data=dict(codename=codename), follow_redirects=True) + app.post("login", data=dict(codename=codename), follow_redirects=True) # Now that the source is logged in, the journalist deletes the source source_user = SessionManager.get_logged_in_user(db_session=db.session) delete_collection(source_user.filesystem_id) # Source attempts to continue to navigate - resp = app.get(url_for('main.lookup'), follow_redirects=True) + resp = app.get(url_for("main.lookup"), follow_redirects=True) assert resp.status_code == 200 assert not SessionManager.is_user_logged_in(db_session=db.session) - text = resp.data.decode('utf-8') - assert 'First submission' in text + text = resp.data.decode("utf-8") + assert "First submission" in text assert not SessionManager.is_user_logged_in(db_session=db.session) @@ -859,14 +834,14 @@ def test_login_with_invalid_codename(source_app): """Logging in with a codename with invalid characters should return an informative message to the user.""" - invalid_codename = '[]' + invalid_codename = "[]" with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data=dict(codename=invalid_codename), - follow_redirects=True) + resp = app.post( + url_for("main.login"), data=dict(codename=invalid_codename), follow_redirects=True + ) assert resp.status_code == 200 - text = resp.data.decode('utf-8') + text = resp.data.decode("utf-8") assert "Invalid input." in text @@ -874,9 +849,7 @@ def test_source_session_expiration(source_app): with source_app.test_client() as app: # Given a source user who logs in codename = new_codename(app, session) - resp = app.post(url_for('main.login'), - data=dict(codename=codename), - follow_redirects=True) + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) assert resp.status_code == 200 # But we're now 6 hours later hence their session expired @@ -885,17 +858,17 @@ def test_source_session_expiration(source_app): mock_datetime.now.return_value = six_hours_later # When they browse to an authenticated page - resp = app.get(url_for('main.lookup'), follow_redirects=True) + resp = app.get(url_for("main.lookup"), follow_redirects=True) # They get redirected to the index page with the "logged out" message - text = resp.data.decode('utf-8') - assert 'You were logged out due to inactivity' in text + text = resp.data.decode("utf-8") + assert "You were logged out due to inactivity" in text def test_source_session_expiration_create(source_app): with source_app.test_client() as app: # Given a source user who is in the middle of the account creation flow - resp = app.post(url_for('main.generate'), data=GENERATE_DATA) + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) assert resp.status_code == 200 # But we're now 6 hours later hence they did not finish the account creation flow in time @@ -904,17 +877,17 @@ def test_source_session_expiration_create(source_app): mock_datetime.now.return_value = six_hours_later # When the user tries to complete the create flow - resp = app.post(url_for('main.create'), follow_redirects=True) + resp = app.post(url_for("main.create"), follow_redirects=True) # They get redirected to the index page with the "logged out" message - text = resp.data.decode('utf-8') - assert 'You were logged out due to inactivity' in text + text = resp.data.decode("utf-8") + assert "You were logged out due to inactivity" in text def test_source_no_session_expiration_message_when_not_logged_in(source_app): with source_app.test_client() as app: # Given an unauthenticated source user - resp = app.get(url_for('main.index')) + resp = app.get(url_for("main.index")) assert resp.status_code == 200 # And their session expired @@ -923,64 +896,60 @@ def test_source_no_session_expiration_message_when_not_logged_in(source_app): mock_datetime.now.return_value = six_hours_later # When they browse again the index page - refreshed_resp = app.get(url_for('main.index'), follow_redirects=True) + refreshed_resp = app.get(url_for("main.index"), follow_redirects=True) # The session expiration message is NOT displayed - text = refreshed_resp.data.decode('utf-8') - assert 'You were logged out due to inactivity' not in text + text = refreshed_resp.data.decode("utf-8") + assert "You were logged out due to inactivity" not in text def test_csrf_error_page(source_app): - source_app.config['WTF_CSRF_ENABLED'] = True + source_app.config["WTF_CSRF_ENABLED"] = True with source_app.test_client() as app: with InstrumentedApp(source_app) as ins: - resp = app.post(url_for('main.create')) - ins.assert_redirects(resp, url_for('main.index')) + resp = app.post(url_for("main.create")) + ins.assert_redirects(resp, url_for("main.index")) - resp = app.post(url_for('main.create'), follow_redirects=True) - text = resp.data.decode('utf-8') - assert 'You were logged out due to inactivity' in text + resp = app.post(url_for("main.create"), follow_redirects=True) + text = resp.data.decode("utf-8") + assert "You were logged out due to inactivity" in text def test_source_can_only_delete_own_replies(source_app, app_storage): - '''This test checks for a bug an authenticated source A could delete - replies send to source B by "guessing" the filename. - ''' + """This test checks for a bug an authenticated source A could delete + replies send to source B by "guessing" the filename. + """ source0, codename0 = utils.db_helper.init_source(app_storage) source1, codename1 = utils.db_helper.init_source(app_storage) journalist, _ = utils.db_helper.init_journalist() replies = utils.db_helper.reply(app_storage, journalist, source0, 1) filename = replies[0].filename - confirmation_msg = 'Reply deleted' + confirmation_msg = "Reply deleted" with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data={'codename': codename1}, - follow_redirects=True) + resp = app.post(url_for("main.login"), data={"codename": codename1}, follow_redirects=True) assert resp.status_code == 200 assert SessionManager.get_logged_in_user(db_session=db.session).db_record_id == source1.id - resp = app.post(url_for('main.delete'), - data={'reply_filename': filename}, - follow_redirects=True) + resp = app.post( + url_for("main.delete"), data={"reply_filename": filename}, follow_redirects=True + ) assert resp.status_code == 404 - assert confirmation_msg not in resp.data.decode('utf-8') + assert confirmation_msg not in resp.data.decode("utf-8") reply = Reply.query.filter_by(filename=filename).one() assert not reply.deleted_by_source with source_app.test_client() as app: - resp = app.post(url_for('main.login'), - data={'codename': codename0}, - follow_redirects=True) + resp = app.post(url_for("main.login"), data={"codename": codename0}, follow_redirects=True) assert resp.status_code == 200 assert SessionManager.get_logged_in_user(db_session=db.session).db_record_id == source0.id - resp = app.post(url_for('main.delete'), - data={'reply_filename': filename}, - follow_redirects=True) + resp = app.post( + url_for("main.delete"), data={"reply_filename": filename}, follow_redirects=True + ) assert resp.status_code == 200 - assert confirmation_msg in resp.data.decode('utf-8') + assert confirmation_msg in resp.data.decode("utf-8") reply = Reply.query.filter_by(filename=filename).one() assert reply.deleted_by_source @@ -990,7 +959,7 @@ def test_robots_txt(source_app): """Test that robots.txt works""" with source_app.test_client() as app: # Not using url_for here because we care about the actual URL path - resp = app.get('/robots.txt') + resp = app.get("/robots.txt") assert resp.status_code == 200 - text = resp.data.decode('utf-8') - assert 'Disallow: /' in text + text = resp.data.decode("utf-8") + assert "Disallow: /" in text diff --git a/securedrop/tests/test_source_user.py b/securedrop/tests/test_source_user.py --- a/securedrop/tests/test_source_user.py +++ b/securedrop/tests/test_source_user.py @@ -1,18 +1,18 @@ from unittest import mock import pytest - import source_user from db import db from passphrases import PassphraseGenerator - -from source_user import InvalidPassphraseError, _DesignationGenerator -from source_user import SourceDesignationCollisionError -from source_user import SourcePassphraseCollisionError -from source_user import _SourceScryptManager -from source_user import authenticate_source_user -from source_user import create_source_user - +from source_user import ( + InvalidPassphraseError, + SourceDesignationCollisionError, + SourcePassphraseCollisionError, + _DesignationGenerator, + _SourceScryptManager, + authenticate_source_user, + create_source_user, +) TEST_SALT_GPG_SECRET = "YrPAwKMyWN66Y2WNSt+FS1KwfysMHwPISG0wmpb717k=" TEST_SALT_FOR_FILESYSTEM_ID = "mEFXIwvxoBqjyxc/JypLdvgMRNRjApoaM0OBNrxJM2E=" @@ -62,7 +62,7 @@ def test_create_source_user_designation_collision(self, source_app, app_storage) with mock.patch.object( source_user._DesignationGenerator, "generate_journalist_designation", - return_value=existing_designation + return_value=existing_designation, ): # When trying to create another source, it fails, because the designation is the same with pytest.raises(SourceDesignationCollisionError): @@ -113,7 +113,7 @@ def test(self): scrypt_mgr = _SourceScryptManager( salt_for_gpg_secret=TEST_SALT_GPG_SECRET.encode(), salt_for_filesystem_id=TEST_SALT_FOR_FILESYSTEM_ID.encode(), - scrypt_n=2 ** 1, + scrypt_n=2**1, scrypt_r=1, scrypt_p=1, ) @@ -133,7 +133,6 @@ def test_get_default(self): class TestDesignationGenerator: - def test(self): # Given a designation generator nouns = ["ability", "accent", "academia"] diff --git a/securedrop/tests/test_source_utils.py b/securedrop/tests/test_source_utils.py --- a/securedrop/tests/test_source_utils.py +++ b/securedrop/tests/test_source_utils.py @@ -4,8 +4,8 @@ import pytest import werkzeug - from source_app.utils import check_url_file, codename_detected, fit_codenames_into_cookie + from .test_journalist import VALID_PASSWORD @@ -14,6 +14,7 @@ def test_check_url_file(config): assert check_url_file("nosuchfile", "whatever") is None try: + def write_url_file(path, content): url_file = open(path, "w") url_file.write("{}\n".format(content)) @@ -37,38 +38,41 @@ def write_url_file(path, content): def test_fit_codenames_into_cookie(config): # A single codename should never be truncated. - codenames = {'a': VALID_PASSWORD} - assert(fit_codenames_into_cookie(codenames) == codenames) + codenames = {"a": VALID_PASSWORD} + assert fit_codenames_into_cookie(codenames) == codenames # A reasonable number of codenames should never be truncated. codenames = { - 'a': VALID_PASSWORD, - 'b': VALID_PASSWORD, - 'c': VALID_PASSWORD, + "a": VALID_PASSWORD, + "b": VALID_PASSWORD, + "c": VALID_PASSWORD, } - assert(fit_codenames_into_cookie(codenames) == codenames) + assert fit_codenames_into_cookie(codenames) == codenames # A single gargantuan codename is undefined behavior---but also should not # be truncated. - codenames = {'a': werkzeug.Response.max_cookie_size*VALID_PASSWORD} - assert(fit_codenames_into_cookie(codenames) == codenames) + codenames = {"a": werkzeug.Response.max_cookie_size * VALID_PASSWORD} + assert fit_codenames_into_cookie(codenames) == codenames # Too many codenames of the expected length should be truncated. codenames = {} - too_many = 2*(werkzeug.Response.max_cookie_size // len(VALID_PASSWORD)) + too_many = 2 * (werkzeug.Response.max_cookie_size // len(VALID_PASSWORD)) for i in range(too_many): codenames[i] = VALID_PASSWORD serialized = json.dumps(codenames).encode() - assert(len(serialized) > werkzeug.Response.max_cookie_size) + assert len(serialized) > werkzeug.Response.max_cookie_size serialized = json.dumps(fit_codenames_into_cookie(codenames)).encode() - assert(len(serialized) < werkzeug.Response.max_cookie_size) - - [email protected]('message,expected', ( - ('Foo', False), - ('codename', True), - (' codename ', True), - ('foocodenamebar', False), -)) + assert len(serialized) < werkzeug.Response.max_cookie_size + + [email protected]( + "message,expected", + ( + ("Foo", False), + ("codename", True), + (" codename ", True), + ("foocodenamebar", False), + ), +) def test_codename_detected(message, expected): - assert codename_detected(message, 'codename') is expected + assert codename_detected(message, "codename") is expected diff --git a/securedrop/tests/test_store.py b/securedrop/tests/test_store.py --- a/securedrop/tests/test_store.py +++ b/securedrop/tests/test_store.py @@ -1,8 +1,7 @@ # -*- coding: utf-8 -*- +import io import logging import os -import io -import pytest import re import stat import zipfile @@ -10,21 +9,20 @@ from tempfile import TemporaryDirectory from typing import Generator +import pytest +import store +from db import db +from journalist_app import create_app +from models import Reply, Submission from passphrases import PassphraseGenerator from source_user import create_source_user +from store import Storage, async_add_checksum_for_file, queued_add_checksum_for_file from . import utils -from db import db -from journalist_app import create_app -from models import Submission, Reply -import store -from store import Storage, queued_add_checksum_for_file, async_add_checksum_for_file - @pytest.fixture(scope="function") -def test_storage( -) -> Generator[Storage, None, None]: +def test_storage() -> Generator[Storage, None, None]: # Setup the filesystem for the storage object with TemporaryDirectory() as data_dir_name: data_dir = Path(data_dir_name) @@ -40,12 +38,11 @@ def test_storage( def create_file_in_source_dir(base_dir, filesystem_id, filename): """Helper function for simulating files""" - source_directory = os.path.join(base_dir, - filesystem_id) + source_directory = os.path.join(base_dir, filesystem_id) os.makedirs(source_directory) file_path = os.path.join(source_directory, filename) - with io.open(file_path, 'a'): + with io.open(file_path, "a"): os.utime(file_path, None) return source_directory, file_path @@ -53,9 +50,9 @@ def create_file_in_source_dir(base_dir, filesystem_id, filename): def test_path_returns_filename_of_folder(test_storage): """`Storage.path` is called in this way in - journalist.delete_collection + journalist.delete_collection """ - filesystem_id = 'example' + filesystem_id = "example" generated_absolute_path = test_storage.path(filesystem_id) expected_absolute_path = os.path.join(test_storage.storage_path, filesystem_id) @@ -64,38 +61,35 @@ def test_path_returns_filename_of_folder(test_storage): def test_path_returns_filename_of_items_within_folder(test_storage): """`Storage.path` is called in this way in journalist.bulk_delete""" - filesystem_id = 'example' - item_filename = '1-quintuple_cant-msg.gpg' + filesystem_id = "example" + item_filename = "1-quintuple_cant-msg.gpg" generated_absolute_path = test_storage.path(filesystem_id, item_filename) - expected_absolute_path = os.path.join(test_storage.storage_path, - filesystem_id, item_filename) + expected_absolute_path = os.path.join(test_storage.storage_path, filesystem_id, item_filename) assert generated_absolute_path == expected_absolute_path def test_path_without_filesystem_id(test_storage): - filesystem_id = 'example' - item_filename = '1-quintuple_cant-msg.gpg' + filesystem_id = "example" + item_filename = "1-quintuple_cant-msg.gpg" basedir = os.path.join(test_storage.storage_path, filesystem_id) os.makedirs(basedir) path_to_file = os.path.join(basedir, item_filename) - with open(path_to_file, 'a'): + with open(path_to_file, "a"): os.utime(path_to_file, None) - generated_absolute_path = \ - test_storage.path_without_filesystem_id(item_filename) + generated_absolute_path = test_storage.path_without_filesystem_id(item_filename) - expected_absolute_path = os.path.join(test_storage.storage_path, - filesystem_id, item_filename) + expected_absolute_path = os.path.join(test_storage.storage_path, filesystem_id, item_filename) assert generated_absolute_path == expected_absolute_path def test_path_without_filesystem_id_duplicate_files(test_storage): - filesystem_id = 'example' - filesystem_id_duplicate = 'example2' - item_filename = '1-quintuple_cant-msg.gpg' + filesystem_id = "example" + filesystem_id_duplicate = "example2" + item_filename = "1-quintuple_cant-msg.gpg" basedir = os.path.join(test_storage.storage_path, filesystem_id) duplicate_basedir = os.path.join(test_storage.storage_path, filesystem_id_duplicate) @@ -103,7 +97,7 @@ def test_path_without_filesystem_id_duplicate_files(test_storage): for directory in [basedir, duplicate_basedir]: os.makedirs(directory) path_to_file = os.path.join(directory, item_filename) - with open(path_to_file, 'a'): + with open(path_to_file, "a"): os.utime(path_to_file, None) with pytest.raises(store.TooManyFilesException): @@ -111,15 +105,14 @@ def test_path_without_filesystem_id_duplicate_files(test_storage): def test_path_without_filesystem_id_no_file(test_storage): - item_filename = 'not there' + item_filename = "not there" with pytest.raises(store.NoFileFoundException): test_storage.path_without_filesystem_id(item_filename) def test_verify_path_not_absolute(test_storage): with pytest.raises(store.PathException): - test_storage.verify( - os.path.join(test_storage.storage_path, '..', 'etc', 'passwd')) + test_storage.verify(os.path.join(test_storage.storage_path, "..", "etc", "passwd")) def test_verify_in_store_dir(test_storage): @@ -131,7 +124,7 @@ def test_verify_in_store_dir(test_storage): def test_verify_store_path_not_absolute(test_storage): with pytest.raises(store.PathException) as e: - test_storage.verify('..') + test_storage.verify("..") assert e.message == "Path not valid in store: .." @@ -151,18 +144,18 @@ def test_verify_rejects_symlinks(test_storage): def test_verify_store_dir_not_absolute(): with pytest.raises(store.PathException) as exc_info: - Storage('..', '/') + Storage("..", "/") msg = str(exc_info.value) - assert re.compile('storage_path.*is not absolute').match(msg) + assert re.compile("storage_path.*is not absolute").match(msg) def test_verify_store_temp_dir_not_absolute(): with pytest.raises(store.PathException) as exc_info: - Storage('/', '..') + Storage("/", "..") msg = str(exc_info.value) - assert re.compile('temp_dir.*is not absolute').match(msg) + assert re.compile("temp_dir.*is not absolute").match(msg) def test_verify_regular_submission_in_sourcedir_returns_true(test_storage): @@ -173,7 +166,7 @@ def test_verify_regular_submission_in_sourcedir_returns_true(test_storage): naming scheme of submissions. """ source_directory, file_path = create_file_in_source_dir( - test_storage.storage_path, 'example-filesystem-id', '1-regular-doc.gz.gpg' + test_storage.storage_path, "example-filesystem-id", "1-regular-doc.gz.gpg" ) assert test_storage.verify(file_path) @@ -182,55 +175,53 @@ def test_verify_regular_submission_in_sourcedir_returns_true(test_storage): def test_verify_invalid_file_extension_in_sourcedir_raises_exception(test_storage): source_directory, file_path = create_file_in_source_dir( - test_storage.storage_path, 'example-filesystem-id', 'not_valid.txt' + test_storage.storage_path, "example-filesystem-id", "not_valid.txt" ) with pytest.raises(store.PathException) as e: test_storage.verify(file_path) - assert 'Path not valid in store: {}'.format(file_path) in str(e) + assert "Path not valid in store: {}".format(file_path) in str(e) def test_verify_invalid_filename_in_sourcedir_raises_exception(test_storage): source_directory, file_path = create_file_in_source_dir( - test_storage.storage_path, 'example-filesystem-id', 'NOTVALID.gpg' + test_storage.storage_path, "example-filesystem-id", "NOTVALID.gpg" ) with pytest.raises(store.PathException) as e: test_storage.verify(file_path) - assert e.message == 'Path not valid in store: {}'.format(file_path) + assert e.message == "Path not valid in store: {}".format(file_path) def test_get_zip(journalist_app, test_source, app_storage, config): with journalist_app.app_context(): - submissions = utils.db_helper.submit( - app_storage, test_source['source'], 2) - filenames = [os.path.join(config.STORE_DIR, - test_source['filesystem_id'], - submission.filename) - for submission in submissions] - - archive = zipfile.ZipFile( - app_storage.get_bulk_archive(submissions)) + submissions = utils.db_helper.submit(app_storage, test_source["source"], 2) + filenames = [ + os.path.join(config.STORE_DIR, test_source["filesystem_id"], submission.filename) + for submission in submissions + ] + + archive = zipfile.ZipFile(app_storage.get_bulk_archive(submissions)) archivefile_contents = archive.namelist() for archived_file, actual_file in zip(archivefile_contents, filenames): - with io.open(actual_file, 'rb') as f: + with io.open(actual_file, "rb") as f: actual_file_content = f.read() zipped_file_content = archive.read(archived_file) assert zipped_file_content == actual_file_content [email protected]('db_model', [Submission, Reply]) [email protected]("db_model", [Submission, Reply]) def test_add_checksum_for_file(config, app_storage, db_model): - ''' + """ Check that when we execute the `add_checksum_for_file` function, the database object is correctly updated with the actual hash of the file. We have to create our own app in order to have more control over the SQLAlchemy sessions. The fixture pushes a single app context that forces us to work within a single transaction. - ''' + """ app = create_app(config) test_storage = app_storage @@ -243,11 +234,11 @@ def test_add_checksum_for_file(config, app_storage, db_model): source_app_storage=test_storage, ) source = source_user.get_db_record() - target_file_path = test_storage.path(source.filesystem_id, '1-foo-msg.gpg') - test_message = b'hash me!' - expected_hash = 'f1df4a6d8659471333f7f6470d593e0911b4d487856d88c83d2d187afa195927' + target_file_path = test_storage.path(source.filesystem_id, "1-foo-msg.gpg") + test_message = b"hash me!" + expected_hash = "f1df4a6d8659471333f7f6470d593e0911b4d487856d88c83d2d187afa195927" - with open(target_file_path, 'wb') as f: + with open(target_file_path, "wb") as f: f.write(test_message) if db_model == Submission: @@ -260,26 +251,25 @@ def test_add_checksum_for_file(config, app_storage, db_model): db.session.commit() db_obj_id = db_obj.id - queued_add_checksum_for_file(db_model, - db_obj_id, - target_file_path, - app.config['SQLALCHEMY_DATABASE_URI']) + queued_add_checksum_for_file( + db_model, db_obj_id, target_file_path, app.config["SQLALCHEMY_DATABASE_URI"] + ) with app.app_context(): # requery to get a new object db_obj = db_model.query.filter_by(id=db_obj_id).one() - assert db_obj.checksum == 'sha256:' + expected_hash + assert db_obj.checksum == "sha256:" + expected_hash [email protected]('db_model', [Submission, Reply]) [email protected]("db_model", [Submission, Reply]) def test_async_add_checksum_for_file(config, app_storage, db_model): - ''' + """ Check that when we execute the `add_checksum_for_file` function, the database object is correctly updated with the actual hash of the file. We have to create our own app in order to have more control over the SQLAlchemy sessions. The fixture pushes a single app context that forces us to work within a single transaction. - ''' + """ app = create_app(config) with app.app_context(): @@ -290,11 +280,11 @@ def test_async_add_checksum_for_file(config, app_storage, db_model): source_app_storage=app_storage, ) source = source_user.get_db_record() - target_file_path = app_storage.path(source.filesystem_id, '1-foo-msg.gpg') - test_message = b'hash me!' - expected_hash = 'f1df4a6d8659471333f7f6470d593e0911b4d487856d88c83d2d187afa195927' + target_file_path = app_storage.path(source.filesystem_id, "1-foo-msg.gpg") + test_message = b"hash me!" + expected_hash = "f1df4a6d8659471333f7f6470d593e0911b4d487856d88c83d2d187afa195927" - with open(target_file_path, 'wb') as f: + with open(target_file_path, "wb") as f: f.write(test_message) if db_model == Submission: @@ -314,7 +304,7 @@ def test_async_add_checksum_for_file(config, app_storage, db_model): with app.app_context(): # requery to get a new object db_obj = db_model.query.filter_by(id=db_obj_id).one() - assert db_obj.checksum == 'sha256:' + expected_hash + assert db_obj.checksum == "sha256:" + expected_hash def test_path_configuration_is_immutable(test_storage): diff --git a/securedrop/tests/test_submission_cleanup.py b/securedrop/tests/test_submission_cleanup.py --- a/securedrop/tests/test_submission_cleanup.py +++ b/securedrop/tests/test_submission_cleanup.py @@ -4,7 +4,6 @@ from db import db from management import submissions from models import Submission - from tests import utils diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -1,57 +1,51 @@ # -*- coding: utf-8 -*- import os -from datetime import datetime -from datetime import timedelta +from datetime import datetime, timedelta from pathlib import Path -from db import db import i18n import i18n_tool import journalist_app import source_app import template_filters +from db import db from flask import session from sh import pybabel + from .utils.env import TESTS_DIR def verify_rel_datetime_format(app): with app.test_client() as c: - c.get('/') - assert session.get('locale') == "en_US" - result = template_filters.rel_datetime_format( - datetime(2016, 1, 1, 1, 1, 1)) + c.get("/") + assert session.get("locale") == "en_US" + result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1)) assert "January 1, 2016 at 1:01:01 AM UTC" == result - result = template_filters.rel_datetime_format( - datetime(2016, 1, 1, 1, 1, 1), fmt="yyyy") + result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1), fmt="yyyy") assert "2016" == result test_time = datetime.utcnow() - timedelta(hours=2) - result = template_filters.rel_datetime_format(test_time, - relative=True) + result = template_filters.rel_datetime_format(test_time, relative=True) assert "2 hours ago" == result - c.get('/?l=fr_FR') - assert session.get('locale') == 'fr_FR' - result = template_filters.rel_datetime_format( - datetime(2016, 1, 1, 1, 1, 1)) + c.get("/?l=fr_FR") + assert session.get("locale") == "fr_FR" + result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1)) assert "1 janvier 2016 à 01:01:01 TU" == result - result = template_filters.rel_datetime_format( - datetime(2016, 1, 1, 1, 1, 1), fmt="yyyy") + result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1), fmt="yyyy") assert "2016" == result test_time = datetime.utcnow() - timedelta(hours=2) - result = template_filters.rel_datetime_format(test_time, - relative=True) - assert u"2\xa0heures" in result + result = template_filters.rel_datetime_format(test_time, relative=True) + assert "2\xa0heures" in result def verify_filesizeformat(app): with app.test_client() as c: - c.get('/') - assert session.get('locale') == "en_US" + c.get("/") + assert session.get("locale") == "en_US" assert "1 byte" == template_filters.filesizeformat(1) assert "2 bytes" == template_filters.filesizeformat(2) value = 1024 * 3 @@ -65,20 +59,20 @@ def verify_filesizeformat(app): value *= 1024 assert "3,072 TB" == template_filters.filesizeformat(value) - c.get('/?l=fr_FR') - assert session.get('locale') == 'fr_FR' - assert u'1\xa0octet' == template_filters.filesizeformat(1) - assert u"2\xa0octets" == template_filters.filesizeformat(2) + c.get("/?l=fr_FR") + assert session.get("locale") == "fr_FR" + assert "1\xa0octet" == template_filters.filesizeformat(1) + assert "2\xa0octets" == template_filters.filesizeformat(2) value = 1024 * 3 - assert u"3\u202fko" == template_filters.filesizeformat(value) + assert "3\u202fko" == template_filters.filesizeformat(value) value *= 1024 - assert u"3\u202fMo" == template_filters.filesizeformat(value) + assert "3\u202fMo" == template_filters.filesizeformat(value) value *= 1024 - assert u"3\u202fGo" == template_filters.filesizeformat(value) + assert "3\u202fGo" == template_filters.filesizeformat(value) value *= 1024 - assert u"3\u202fTo" == template_filters.filesizeformat(value) + assert "3\u202fTo" == template_filters.filesizeformat(value) value *= 1024 - assert u"072\u202fTo" in template_filters.filesizeformat(value) + assert "072\u202fTo" in template_filters.filesizeformat(value) # We can't use fixtures because these options are set at app init time, and we @@ -94,21 +88,26 @@ def test_journalist_filters(config): def do_test(config, create_app): - config.SUPPORTED_LOCALES = ['en_US', 'fr_FR'] + config.SUPPORTED_LOCALES = ["en_US", "fr_FR"] config.TRANSLATION_DIRS = Path(config.TEMP_DIR) - i18n_tool.I18NTool().main([ - '--verbose', - 'translate-messages', - '--mapping', os.path.join(TESTS_DIR, 'i18n/babel.cfg'), - '--translations-dir', config.TEMP_DIR, - '--sources', os.path.join(TESTS_DIR, 'i18n/code.py'), - '--extract-update', - '--compile', - ]) - - for l in ('en_US', 'fr_FR'): - pot = os.path.join(config.TEMP_DIR, 'messages.pot') - pybabel('init', '-i', pot, '-d', config.TEMP_DIR, '-l', l) + i18n_tool.I18NTool().main( + [ + "--verbose", + "translate-messages", + "--mapping", + os.path.join(TESTS_DIR, "i18n/babel.cfg"), + "--translations-dir", + config.TEMP_DIR, + "--sources", + os.path.join(TESTS_DIR, "i18n/code.py"), + "--extract-update", + "--compile", + ] + ) + + for l in ("en_US", "fr_FR"): + pot = os.path.join(config.TEMP_DIR, "messages.pot") + pybabel("init", "-i", pot, "-d", config.TEMP_DIR, "-l", l) app = create_app(config) with app.app_context(): diff --git a/securedrop/tests/test_worker.py b/securedrop/tests/test_worker.py --- a/securedrop/tests/test_worker.py +++ b/securedrop/tests/test_worker.py @@ -26,9 +26,9 @@ def start_rq_worker(config, queue_name=None): "/opt/venvs/securedrop-app-code/bin/rqworker", "--path", config.SECUREDROP_ROOT, - queue_name + queue_name, ], - preexec_fn=os.setsid + preexec_fn=os.setsid, ) diff --git a/securedrop/tests/utils/__init__.py b/securedrop/tests/utils/__init__.py --- a/securedrop/tests/utils/__init__.py +++ b/securedrop/tests/utils/__init__.py @@ -14,16 +14,20 @@ def flaky_filter_xfail(err, *args): If the test is expected to fail, let's not run it again. """ - return '_pytest.outcomes.XFailed' == '{}.{}'.format( + return "_pytest.outcomes.XFailed" == "{}.{}".format( err[0].__class__.__module__, err[0].__class__.__qualname__ ) def login_user(app, test_user): - resp = app.post('/login', - data={'username': test_user['username'], - 'password': test_user['password'], - 'token': TOTP(test_user['otp_secret']).now()}, - follow_redirects=True) + resp = app.post( + "/login", + data={ + "username": test_user["username"], + "password": test_user["password"], + "token": TOTP(test_user["otp_secret"]).now(), + }, + follow_redirects=True, + ) assert resp.status_code == 200 - assert hasattr(g, 'user') # ensure logged in + assert hasattr(g, "user") # ensure logged in diff --git a/securedrop/tests/utils/asynchronous.py b/securedrop/tests/utils/asynchronous.py --- a/securedrop/tests/utils/asynchronous.py +++ b/securedrop/tests/utils/asynchronous.py @@ -5,7 +5,7 @@ import time # This is an arbitarily defined value in the SD codebase and not something from rqworker -REDIS_SUCCESS_RETURN_VALUE = 'success' +REDIS_SUCCESS_RETURN_VALUE = "success" def wait_for_redis_worker(job, timeout=60): @@ -23,9 +23,9 @@ def wait_for_redis_worker(job, timeout=60): if job.result == REDIS_SUCCESS_RETURN_VALUE: return elif job.result not in (None, REDIS_SUCCESS_RETURN_VALUE): - assert False, 'Redis worker failed!' + assert False, "Redis worker failed!" time.sleep(0.1) - assert False, 'Redis worker timed out!' + assert False, "Redis worker timed out!" def wait_for_assertion(assertion_expression, timeout=10): diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -3,14 +3,13 @@ filesystem) interaction. """ import datetime -import math import io +import math import os import random from typing import Dict, List import mock - from db import db from encryption import EncryptionManager from journalist_app.utils import mark_seen @@ -37,7 +36,7 @@ def init_journalist(first_name=None, last_name=None, is_admin=False): password=user_pw, first_name=first_name, last_name=last_name, - is_admin=is_admin + is_admin=is_admin, ) db.session.add(user) db.session.commit() @@ -72,8 +71,7 @@ def reply(storage, journalist, source, num_replies): replies = [] for _ in range(num_replies): source.interaction_count += 1 - fname = "{}-{}-reply.gpg".format(source.interaction_count, - source.journalist_filename) + fname = "{}-{}-reply.gpg".format(source.interaction_count, source.journalist_filename) EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=source.filesystem_id, @@ -98,7 +96,7 @@ def mock_verify_token(testcase): :param unittest.TestCase testcase: The test case for which to patch TOTP verification. """ - patcher = mock.patch('Journalist.verify_token') + patcher = mock.patch("Journalist.verify_token") testcase.addCleanup(patcher.stop) testcase.mock_journalist_verify_token = patcher.start() testcase.mock_journalist_verify_token.return_value = True @@ -165,14 +163,14 @@ def submit(storage, source, num_submissions, submission_type="message"): source.interaction_count, source.journalist_filename, "pipe.txt", - io.BytesIO(b"Ceci n'est pas une pipe.") + io.BytesIO(b"Ceci n'est pas une pipe."), ) else: fpath = storage.save_message_submission( source.filesystem_id, source.interaction_count, source.journalist_filename, - str(os.urandom(1)) + str(os.urandom(1)), ) submission = Submission(source, fpath, storage) submissions.append(submission) @@ -184,11 +182,10 @@ def submit(storage, source, num_submissions, submission_type="message"): def new_codename(client, session): - """Helper function to go through the "generate codename" flow. - """ - client.post('/generate', data={'tor2web_check': 'href="fake.onion"'}) - tab_id, codename = next(iter(session['codenames'].items())) - client.post('/create', data={'tab_id': tab_id}) + """Helper function to go through the "generate codename" flow.""" + client.post("/generate", data={"tor2web_check": 'href="fake.onion"'}) + tab_id, codename = next(iter(session["codenames"].items())) + client.post("/create", data={"tab_id": tab_id}) return codename @@ -224,14 +221,14 @@ def bulk_setup_for_seen_only(journo: Journalist, storage: Storage) -> List[Dict] unseen_replies = list(set(replies).difference(set(seen_replies))) not_downloaded = list(set(files + messages).difference(set(seen_files + seen_messages))) - collection['source'] = source - collection['seen_files'] = seen_files - collection['seen_messages'] = seen_messages - collection['seen_replies'] = seen_replies - collection['unseen_files'] = unseen_files - collection['unseen_messages'] = unseen_messages - collection['unseen_replies'] = unseen_replies - collection['not_downloaded'] = not_downloaded + collection["source"] = source + collection["seen_files"] = seen_files + collection["seen_messages"] = seen_messages + collection["seen_replies"] = seen_replies + collection["unseen_files"] = unseen_files + collection["unseen_messages"] = unseen_messages + collection["unseen_replies"] = unseen_replies + collection["not_downloaded"] = not_downloaded setup_collection.append(collection) diff --git a/securedrop/tests/utils/env.py b/securedrop/tests/utils/env.py --- a/securedrop/tests/utils/env.py +++ b/securedrop/tests/utils/env.py @@ -4,22 +4,16 @@ import os import shutil import threading +from os.path import abspath, dirname, isdir, join, realpath from pathlib import Path -from os.path import abspath -from os.path import dirname -from os.path import isdir -from os.path import join -from os.path import realpath from db import db - -TESTS_DIR = abspath(join(dirname(realpath(__file__)), '..')) +TESTS_DIR = abspath(join(dirname(realpath(__file__)), "..")) def create_directories(config): - """Create directories for the file store. - """ + """Create directories for the file store.""" # config.SECUREDROP_DATA_ROOT and config.GPG_KEY_DIR already get created by the # setup_journalist_key_and_gpg_folder fixture for d in [config.STORE_DIR, config.TEMP_DIR]: diff --git a/securedrop/tests/utils/i18n.py b/securedrop/tests/utils/i18n.py --- a/securedrop/tests/utils/i18n.py +++ b/securedrop/tests/utils/i18n.py @@ -5,15 +5,11 @@ from typing import Dict, Generator, Iterable, List, Optional, Tuple import pytest -from babel.core import ( - get_locale_identifier, - parse_locale, -) +from babel.core import get_locale_identifier, parse_locale from babel.messages.catalog import Catalog from babel.messages.pofile import read_po from bs4 import BeautifulSoup from flask_babel import force_locale - from sdconfig import SDConfig @@ -96,11 +92,7 @@ def xfail_untranslated_messages(config: SDConfig, locale: str, msgids: Iterable[ for msgid in msgids: m = catalog.get(msgid) if not m: - pytest.xfail( - "locale {} message catalog lacks msgid: {}".format(locale, msgid) - ) + pytest.xfail("locale {} message catalog lacks msgid: {}".format(locale, msgid)) if not m.string: - pytest.xfail( - "locale {} has no translation for msgid: {}".format(locale, msgid) - ) + pytest.xfail("locale {} has no translation for msgid: {}".format(locale, msgid)) yield diff --git a/securedrop/tests/utils/instrument.py b/securedrop/tests/utils/instrument.py --- a/securedrop/tests/utils/instrument.py +++ b/securedrop/tests/utils/instrument.py @@ -9,14 +9,12 @@ """ -from urllib.parse import urlparse, urljoin +from urllib.parse import urljoin, urlparse import pytest +from flask import message_flashed, template_rendered -from flask import template_rendered, message_flashed - - -__all__ = ['InstrumentedApp'] +__all__ = ["InstrumentedApp"] class ContextVariableDoesNotExist(Exception): @@ -24,7 +22,6 @@ class ContextVariableDoesNotExist(Exception): class InstrumentedApp: - def __init__(self, app): self.app = app @@ -36,7 +33,7 @@ def __enter__(self): return self def __exit__(self, *nargs): - if getattr(self, 'app', None) is not None: + if getattr(self, "app", None) is not None: del self.app del self.templates[:] @@ -53,7 +50,7 @@ def _add_template(self, app, template, context): self.templates = [] self.templates.append((template, context)) - def assert_message_flashed(self, message, category='message'): + def assert_message_flashed(self, message, category="message"): """ Checks if a given message was flashed. @@ -64,10 +61,11 @@ def assert_message_flashed(self, message, category='message'): if _message == message and _category == category: return True - raise AssertionError("Message '{}' in category '{}' wasn't flashed" - .format(message, category)) + raise AssertionError( + "Message '{}' in category '{}' wasn't flashed".format(message, category) + ) - def assert_template_used(self, name, tmpl_name_attribute='name'): + def assert_template_used(self, name, tmpl_name_attribute="name"): """ Checks if a given template is used in the request. If the template engine used is not Jinja2, provide ``tmpl_name_attribute`` with a @@ -85,8 +83,11 @@ def assert_template_used(self, name, tmpl_name_attribute='name'): used_templates.append(template) - raise AssertionError("Template {} not used. Templates were used: {}" - .format(name, ' '.join(repr(used_templates)))) + raise AssertionError( + "Template {} not used. Templates were used: {}".format( + name, " ".join(repr(used_templates)) + ) + ) def get_context_variable(self, name): """ @@ -115,8 +116,7 @@ def assert_context(self, name, value, message=None): try: assert self.get_context_variable(name) == value, message except ContextVariableDoesNotExist: - pytest.fail(message or - "Context variable does not exist: {}".format(name)) + pytest.fail(message or "Context variable does not exist: {}".format(name)) def assert_redirects(self, response, location, message=None): """ @@ -131,14 +131,13 @@ def assert_redirects(self, response, location, message=None): if parts.netloc: expected_location = location else: - server_name = self.app.config.get('SERVER_NAME') or 'localhost.localdomain' + server_name = self.app.config.get("SERVER_NAME") or "localhost.localdomain" expected_location = urljoin("http://%s" % server_name, location) valid_status_codes = (301, 302, 303, 305, 307) - valid_status_code_str = ', '.join([str(code) - for code in valid_status_codes]) - not_redirect = "HTTP Status {} expected but got {}" \ - .format(valid_status_code_str, response.status_code) - assert (response.status_code in (valid_status_codes, message) - or not_redirect) + valid_status_code_str = ", ".join([str(code) for code in valid_status_codes]) + not_redirect = "HTTP Status {} expected but got {}".format( + valid_status_code_str, response.status_code + ) + assert response.status_code in (valid_status_codes, message) or not_redirect assert response.location == expected_location, message
Enable black and isort for this repo We've been trialing `black` and `isort` for auto-formatting Python code in other SecureDrop repos, and are generally happy with the combination. An example configuration can be found here: https://github.com/freedomofpress/securedrop-client/blob/main/pyproject.toml https://github.com/freedomofpress/securedrop-client/blob/main/Makefile We'll want to use the same setup for SecureDrop Core, with the same settings. As with previous migrations (e.g., https://github.com/freedomofpress/securedrop-client/pull/1115), we'll use `.git-blame-ignore-revs` to ensure that original attribution of modified lines is preserved in `git blame` output.
@nabla-c0d3 Perhaps you'd be interested in collaborating with us on this, after the type annotation stuff is merged (will probably still take us a couple of weeks to get through; thanks for all your work on it so far)? We're aiming to work on this late in the 10/15-10/29 sprint, or early in the following one. (@rmol is still focused on churning through the PR backlog to make this a bit easier, so bumped back to backlog for now.) (Doesn't need to be coupled to the next release, removing from milestone for now.) Optimistically adding this to the 2.4.0 milestone, would like to land upcoming large changes first if possible though. As part of this it would be nice if we could remove the useless `# -*- coding: utf-8 -*-` lines and enforce a newline at the end of every file.
2022-06-22T22:36:46Z
[]
[]
freedomofpress/securedrop
6,485
freedomofpress__securedrop-6485
[ "6475" ]
2cfb0f90ab28f42c7b7e80eba9144c0509c27933
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -16,7 +16,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import collections -from typing import List, Set +from typing import Dict, List, Set from babel.core import ( Locale, @@ -175,18 +175,21 @@ def map_locale_display_names(config: SDConfig) -> None: to distinguish them. For languages with more than one translation, like Chinese, we do need the additional detail. """ - seen: Set[str] = set() + + language_locale_counts = collections.defaultdict(int) # type: Dict[str, int] + for l in sorted(config.SUPPORTED_LOCALES): + locale = RequestLocaleInfo(l) + language_locale_counts[locale.language] += 1 + locale_map = collections.OrderedDict() for l in sorted(config.SUPPORTED_LOCALES): if Locale.parse(l) not in USABLE_LOCALES: continue locale = RequestLocaleInfo(l) - if locale.language in seen: + if language_locale_counts[locale.language] > 1: # Disambiguate translations for this language. locale.use_display_name = True - else: - seen.add(locale.language) locale_map[str(locale)] = locale
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -410,3 +410,17 @@ def test_html_attributes(journalist_app, config): ) html = resp.data.decode("utf-8") assert '<html lang="en-US" dir="ltr">' in html + + +def test_same_lang_diff_locale(journalist_app, config): + """ + Verify that when two locales with the same lang are specified, the full locale + name is used for both. + """ + del journalist_app + config.SUPPORTED_LOCALES = ["en_US", "pt_BR", "pt_PT"] + app = journalist_app_module.create_app(config).test_client() + resp = app.get("/", follow_redirects=True) + html = resp.data.decode("utf-8") + assert "português (Brasil)" in html + assert "português (Portugal)" in html
`map_locale_display_names()` does not set `use_display_name` for the first of multiple locales for a language ## Description For languages like `pt` and `zh` for which we now have multiple translated locales, `map_locale_display_names()` sets `use_display_name` for only the second and following locales. Prior to an overzealous refactoring in #6406, it would be set for all locales for a multi-locale language. ## Steps to Reproduce Reported by @deeplow in <https://forum.securedrop.org/t/can-pt-br-become-portugues-brasil-instead-of-just-portugues/1455>. *Test cases TK.* ## Expected Behavior * `pt_BR` = `Português (Brasil)` * `pt_PT` = `Português (Portugal)` ## Actual Behavior * `pt_BR` = `Português` * `pt_PT` = `Português (Portugal)`
2022-07-11T14:12:19Z
[]
[]
freedomofpress/securedrop
6,490
freedomofpress__securedrop-6490
[ "6489" ]
5f4dce1515e57a1bf8247b178a1949b57e9fac02
diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -7,7 +7,7 @@ import flask import werkzeug from db import db -from encryption import EncryptionManager +from encryption import EncryptionManager, GpgKeyNotFoundError from flask import Markup, abort, current_app, escape, flash, redirect, send_file, url_for from flask_babel import gettext, ngettext from journalist_app.sessions import session @@ -402,8 +402,11 @@ def delete_collection(filesystem_id: str) -> None: if os.path.exists(path): Storage.get_default().move_to_shredder(path) - # Delete the source's reply keypair - EncryptionManager.get_default().delete_source_key_pair(filesystem_id) + # Delete the source's reply keypair, if it exists + try: + EncryptionManager.get_default().delete_source_key_pair(filesystem_id) + except GpgKeyNotFoundError: + pass # Delete their entry in the db source = get_source(filesystem_id, include_deleted=True) diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -176,13 +176,6 @@ def lookup(logged_in_source: SourceUser) -> str: # Sort the replies by date replies.sort(key=operator.attrgetter("date"), reverse=True) - # If not done yet, generate a keypair to encrypt replies from the journalist - encryption_mgr = EncryptionManager.get_default() - try: - encryption_mgr.get_source_public_key(logged_in_source.filesystem_id) - except GpgKeyNotFoundError: - encryption_mgr.generate_source_key_pair(logged_in_source) - return render_template( "lookup.html", is_user_logged_in=True, @@ -313,6 +306,13 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: normalize_timestamps(logged_in_source) + # If not done yet, generate a keypair to encrypt replies from the journalist + encryption_mgr = EncryptionManager.get_default() + try: + encryption_mgr.get_source_public_key(logged_in_source.filesystem_id) + except GpgKeyNotFoundError: + encryption_mgr.generate_source_key_pair(logged_in_source) + return redirect(url_for("main.lookup")) @view.route("/delete", methods=("POST",))
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -14,6 +14,7 @@ import pytest import version from db import db +from encryption import EncryptionManager from flaky import flaky from flask import escape, g, request, session, url_for from flask_babel import gettext @@ -119,16 +120,19 @@ def test_generate_already_logged_in(source_app): def test_create_new_source(source_app): + """Create new source, ensuring that reply key is not created at the same time""" with source_app.test_client() as app: - resp = app.post(url_for("main.generate"), data=GENERATE_DATA) - assert resp.status_code == 200 - tab_id = next(iter(session["codenames"].keys())) - resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) - assert SessionManager.is_user_logged_in(db_session=db.session) - # should be redirected to /lookup - text = resp.data.decode("utf-8") - assert "Submit Files" in text - assert "codenames" not in session + with patch.object(EncryptionManager, "get_source_public_key") as get_key: + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) + assert resp.status_code == 200 + tab_id = next(iter(session["codenames"].keys())) + resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) + assert SessionManager.is_user_logged_in(db_session=db.session) + # should be redirected to /lookup + text = resp.data.decode("utf-8") + assert "Submit Files" in text + assert "codenames" not in session + get_key.assert_not_called() def test_generate_as_post(source_app): @@ -364,18 +368,22 @@ def _dummy_submission(app): ) -def test_initial_submission_notification(source_app): +def test_initial_submission(source_app): """ Regardless of the type of submission (message, file, or both), the first submission is always greeted with a notification reminding sources to check back later for replies. + + A GPG keypair for replies should also be created. """ with source_app.test_client() as app: - new_codename(app, session) - resp = _dummy_submission(app) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "Thank you for sending this information to us." in text + with patch.object(EncryptionManager, "generate_source_key_pair") as gen_key: + new_codename(app, session) + resp = _dummy_submission(app) + assert resp.status_code == 200 + text = resp.data.decode("utf-8") + assert "Thank you for sending this information to us." in text + gen_key.assert_called_once() def test_submit_message(source_app):
Generate reply key on first submission Note that this change is being reverted! ## Description When a source visits /lookup for the first time, a GPG reply key is generated. However, if the source does not submit a message, it is impossible to reply to them, as their account is flagged as `pending` and not displayed in the JI. To avoid creating keys unnecessarily, the key could be created on submission instead if it does not already exist. ## User Research Evidence Observed behavior of sd instances ## User Stories As an admin, I want to keep a manageable number of source accounts and reply keys
2022-07-18T17:03:15Z
[]
[]
freedomofpress/securedrop
6,492
freedomofpress__securedrop-6492
[ "6491" ]
8d486dc6530671fe785aa600d38bc17e7976cf81
diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -23,7 +23,7 @@ def codename_detected(message: str, codename: str) -> bool: """ message = message.strip() - return compare_digest(message.strip(), codename) + return compare_digest(message.strip().encode("utf-8"), codename.encode("utf-8")) def flash_msg(
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -356,7 +356,10 @@ def _dummy_submission(app): """ return app.post( url_for("main.submit"), - data=dict(msg="Pay no attention to the man behind the curtain.", fh=(BytesIO(b""), "")), + data=dict( + msg="Hallo! ö, ü, ä, or ß...Pay no attention to the man behind the curtain.", + fh=(BytesIO(b""), ""), + ), follow_redirects=True, )
Initial messages containing non-ascii characters fail if codename filtering is enabled. ## Description Codename filtering was introduced in 2.3.0, allowing admins to block initial submissions containing only the user's codename, as they should not be shared with journalists. The filter uses the `compare_digest()` function to ensure constant-time comparison, but this fn will throw a `TypeError` if any of the strings being compared contain Unicode. ## Steps to Reproduce - start up `make dev` on 2.4.0 - visit the JI and enable codename filtering under Admin > Instance Config - visit the SI, create a new source, and submit an initial message containing unicode, ie `Hallo! ö, ü, ä, or ß` ## Expected Behavior - Message is submitted ## Actual Behavior - 500 error, and (in dev) stack trace due to TypeError ## Comments Suggestions to fix, any other relevant information.
2022-07-18T18:46:56Z
[]
[]
freedomofpress/securedrop
6,519
freedomofpress__securedrop-6519
[ "6511" ]
d2e739493331d3f838f610eac2f94737aeaffe0d
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -46,11 +46,9 @@ sdlog = logging.getLogger(__name__) -# We list two (2) pubkeys as authorized to sign SecureDrop release artifacts, -# to provide a transition window during key rotation. On or around v2.0.0, -# we can remove the older of the two keys and only trust the newer going forward. +# In the event of a key rotation, this list can be added to +# in order to support a transition period. RELEASE_KEYS = [ - "22245C81E3BAEB4138B36061310F561200F4AD77", "2359E6538C0613E652955E6C188EDD3B7B22E6A3", ] DEFAULT_KEYSERVER = "hkps://keys.openpgp.org" @@ -1004,9 +1002,6 @@ def update(args: argparse.Namespace) -> int: ).decode("utf-8") good_sig_text = [ - 'Good signature from "SecureDrop Release Signing ' + 'Key"', - 'Good signature from "SecureDrop Release Signing ' - + 'Key <[email protected]>"', 'Good signature from "SecureDrop Release Signing ' + 'Key <[email protected]>"', ] @@ -1021,7 +1016,7 @@ def update(args: argparse.Namespace) -> int: # appears on the second line of the output, and that there is a single # match from good_sig_text[] if ( - (RELEASE_KEYS[0] in gpg_lines[1] or RELEASE_KEYS[1] in gpg_lines[1]) + any(key in gpg_lines[1] for key in RELEASE_KEYS) and len(good_sig_matches) == 1 and bad_sig_text not in sig_result ):
diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- # # SecureDrop whistleblower submission system -# Copyright (C) 2017 Loic Dachary <[email protected]> +# Copyright (C) 2017- Freedom of the Press Foundation and SecureDrop +# contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by @@ -247,46 +248,13 @@ def test_get_release_key_from_valid_keyserver(self, tmpdir, caplog): @pytest.mark.parametrize( "git_output", [ - b"gpg: Signature made Tue 13 Mar " - b"2018 01:14:11 AM UTC\n" - b"gpg: using RSA key " - b"22245C81E3BAEB4138B36061310F561200F4AD77\n" - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n', - b"gpg: Signature made Thu 20 Jul " - b"2017 08:12:25 PM EDT\n" - b"gpg: using RSA key " - b"22245C81E3BAEB4138B36061310F561200F4AD77\n" - b'gpg: Good signature from "SecureDrop Release ' - b"Signing Key " - b'<[email protected]>"\n', b"gpg: Signature made Thu 20 Jul " - b"2017 08:12:25 PM EDT\n" + b"2022 08:12:25 PM EDT\n" b"gpg: using RSA key " b"2359E6538C0613E652955E6C188EDD3B7B22E6A3\n" b'gpg: Good signature from "SecureDrop Release ' b"Signing Key " - b'<[email protected]>"\n', - b"gpg: Signature made Thu 20 Jul " - b"2017 08:12:25 PM EDT\n" - b"gpg: using RSA key " - b"2359E6538C0613E652955E6C188EDD3B7B22E6A3\n" - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n' - b'gpg: aka "SecureDrop Release ' - b"Signing Key " - b'<[email protected]>" ' - b"[unknown]\n", - b"gpg: Signature made Thu 20 Jul " - b"2017 08:12:25 PM EDT\n" - b"gpg: using RSA key " - b"22245C81E3BAEB4138B36061310F561200F4AD77\n" - b'gpg: Good signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n' - b'gpg: aka "SecureDrop Release ' - b"Signing Key " - b'<[email protected]>" ' - b"[unknown]\n", + b'<[email protected]>" [unknown]\n', ], ) def test_update_signature_verifies(self, tmpdir, caplog, git_output): @@ -295,6 +263,9 @@ def test_update_signature_verifies(self, tmpdir, caplog, git_output): patchers = [ mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")), mock.patch("subprocess.check_call"), + # securedrop-admin checks if there is a branch with the same name as a tag + # that is being verified, and bails if there is. To ensure the verification + # succeeds, we have to mock the "not a valid ref" output it looks for. mock.patch( "subprocess.check_output", side_effect=[ @@ -322,7 +293,49 @@ def test_update_unexpected_exception_git_refs(self, tmpdir, caplog): args = argparse.Namespace(root=git_repo_path) git_output = ( - b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: Signature made Tue 13 Mar 2022 01:14:11 AM UTC\n" + b"gpg: using RSA key " + b"2359E6538C0613E652955E6C188EDD3B7B22E6A3\n" + b'gpg: Good signature from "SecureDrop Release ' + b'Signing Key <[email protected]>" [unknown]\n' + ) + + patchers = [ + mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")), + mock.patch("subprocess.check_call"), + mock.patch( + "subprocess.check_output", + side_effect=[ + git_output, + subprocess.CalledProcessError(1, "cmd", b"a random error"), + ], + ), + ] + + for patcher in patchers: + patcher.start() + + try: + ret_code = securedrop_admin.update(args) + assert "Applying SecureDrop updates..." in caplog.text + assert "Signature verification successful." not in caplog.text + assert "Updated to SecureDrop" not in caplog.text + assert ret_code == 1 + finally: + for patcher in patchers: + patcher.stop() + + def test_outdated_signature_does_not_verify(self, tmpdir, caplog): + """ + When a tag is signed with a release key that is no longer valid + Then the signature of a current tag should not verify + """ + + git_repo_path = str(tmpdir) + args = argparse.Namespace(root=git_repo_path) + + git_output = ( + b"gpg: Signature made Tue 13 Mar 2022 01:14:11 AM UTC\n" b"gpg: using RSA key " b"22245C81E3BAEB4138B36061310F561200F4AD77\n" b'gpg: Good signature from "SecureDrop Release ' @@ -336,7 +349,7 @@ def test_update_unexpected_exception_git_refs(self, tmpdir, caplog): "subprocess.check_output", side_effect=[ git_output, - subprocess.CalledProcessError(1, "cmd", b"a random error"), + subprocess.CalledProcessError(1, "cmd", b"not a valid ref"), ], ), ] @@ -359,11 +372,11 @@ def test_update_signature_does_not_verify(self, tmpdir, caplog): args = argparse.Namespace(root=git_repo_path) git_output = ( - b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: Signature made Tue 13 Mar 2022 01:14:11 AM UTC\n" b"gpg: using RSA key " - b"22245C81E3BAEB4138B36061310F561200F4AD77\n" + b"2359E6538C0613E652955E6C188EDD3B7B22E6A3\n" b'gpg: BAD signature from "SecureDrop Release ' - b'Signing Key" [unknown]\n' + b'Signing Key <[email protected]>" [unknown]\n' ) with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): @@ -380,11 +393,11 @@ def test_update_malicious_key_named_fingerprint(self, tmpdir, caplog): args = argparse.Namespace(root=git_repo_path) git_output = ( - b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: Signature made Tue 13 Mar 2022 01:14:11 AM UTC\n" b"gpg: using RSA key " b"1234567812345678123456781234567812345678\n" - b'gpg: Good signature from "22245C81E3BAEB4138' - b'B36061310F561200F4AD77" [unknown]\n' + b'gpg: Good signature from "2359E6538C0613E652' + b'955E6C188EDD3B7B22E6A3" [unknown]\n' ) with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): @@ -401,11 +414,12 @@ def test_update_malicious_key_named_good_sig(self, tmpdir, caplog): args = argparse.Namespace(root=git_repo_path) git_output = ( - b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: Signature made Tue 13 Mar 2022 01:14:11 AM UTC\n" b"gpg: using RSA key " b"1234567812345678123456781234567812345678\n" b"gpg: Good signature from Good signature from " - b'"SecureDrop Release Signing Key" [unknown]\n' + b'"SecureDrop Release Signing Key <[email protected]>" ' + b"[unknown]\n" ) with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")): @@ -422,12 +436,13 @@ def test_update_malicious_key_named_good_sig_fingerprint(self, tmpdir, caplog): args = argparse.Namespace(root=git_repo_path) git_output = ( - b"gpg: Signature made Tue 13 Mar 2018 01:14:11 AM UTC\n" + b"gpg: Signature made Tue 13 Mar 2022 01:14:11 AM UTC\n" b"gpg: using RSA key " b"1234567812345678123456781234567812345678\n" b"gpg: Good signature from 22245C81E3BAEB4138" - b"B36061310F561200F4AD77 Good signature from " - b'"SecureDrop Release Signing Key" [unknown]\n' + b"955E6C188EDD3B7B22E6A3 Good signature from " + b'"SecureDrop Release Signing Key <[email protected]>" ' + b"[unknown]\n" ) with mock.patch("securedrop_admin.check_for_updates", return_value=(True, "0.6.1")):
Phase out old signing key in `securedrop-admin` `securedrop-admin` currently still trusts the old signing key for releases. It's been more than a year since the [full key rotation](https://media.securedrop.org/media/documents/signing-key-transition.txt) (not to be confused with the recent expiry bump), so I think this can be safely phased out: https://github.com/freedomofpress/securedrop/blob/2f2db872f60bbc9024e0b35b8ebcdc2f5695acb2/admin/securedrop_admin/__init__.py#L49-L55
Yup, tis an easy fix/test, adding to 2.5.0
2022-08-16T19:15:52Z
[]
[]
freedomofpress/securedrop
6,529
freedomofpress__securedrop-6529
[ "4452" ]
87d84cf3a6ea8a66bc470ee137d7a56c1b13024d
diff --git a/securedrop/management/run.py b/securedrop/management/run.py --- a/securedrop/management/run.py +++ b/securedrop/management/run.py @@ -167,9 +167,6 @@ def run(args: Any) -> None: # pragma: no cover procs = [ lambda: DevServerProcess("Source Interface", ["python", "source.py"], "blue"), lambda: DevServerProcess("Journalist Interface", ["python", "journalist.py"], "cyan"), - lambda: DevServerProcess( - "SASS Compiler", ["sass", "--watch", "sass:static/css"], "magenta" - ), ] monitor = DevServerProcessMonitor(procs)
diff --git a/molecule/builder-focal/tests/test_build_dependencies.py b/molecule/builder-focal/tests/test_build_dependencies.py --- a/molecule/builder-focal/tests/test_build_dependencies.py +++ b/molecule/builder-focal/tests/test_build_dependencies.py @@ -9,15 +9,6 @@ testinfra_hosts = ["docker://{}-sd-app".format(SECUREDROP_TARGET_DISTRIBUTION)] -def test_sass_gem_installed(host): - """ - Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS. - """ - c = host.run("gem list") - assert "sass (3.4.23)" in c.stdout - assert c.rc == 0 - - @pytest.mark.xfail(reason="This check conflicts with the concept of pegging" "dependencies") def test_build_all_packages_updated(host): """ diff --git a/molecule/builder-focal/tests/test_securedrop_deb_package.py b/molecule/builder-focal/tests/test_securedrop_deb_package.py --- a/molecule/builder-focal/tests/test_securedrop_deb_package.py +++ b/molecule/builder-focal/tests/test_securedrop_deb_package.py @@ -266,12 +266,6 @@ def test_deb_package_contains_no_generated_assets(securedrop_app_code_contents: re.M, ) - # no SASS files should exist. - assert not re.search("^.*sass$", securedrop_app_code_contents, re.M) - - # no .map files should exist. - assert not re.search("^.*css.map$", securedrop_app_code_contents, re.M) - @pytest.mark.parametrize("deb", deb_paths.values()) def test_deb_package_contains_expected_conffiles(host: Host, deb: Path): @@ -307,8 +301,7 @@ def test_deb_package_contains_expected_conffiles(host: Host, deb: Path): def test_securedrop_app_code_contains_css(securedrop_app_code_contents: str) -> None: """ - Ensures the `securedrop-app-code` package contains files that - are generated during the `sass` build process. + Ensures the `securedrop-app-code` package contains necessary css files """ for css_type in ["journalist", "source"]: assert re.search(
Ruby sass gem used at build time has reached end-of-life Per https://github.com/sass/ruby-sass (which is archived) and https://sass-lang.com/ruby-sass, this gem, which is [used at package build time](https://github.com/freedomofpress/securedrop/blob/develop/install_files/ansible-base/roles/build-securedrop-app-code-deb-pkg/tasks/sass.yml) for CSS generation, has reached end-of-life. We should consider migrating to a maintained codebase, like [sassc](https://github.com/sass/sassc) / `libsass`. Note that we're also using a pinned outdated version due to #1594; we could update now that we're on Xenial, but that no longer seems worth resolving at this point.
Since I started working on the SI frontend, I looked into this a bit: * [sassc](https://github.com/sass/sassc), while available from Debian/Ubuntu/Fedora repos, is now also deprecated but (supposedly) maintained (at time of writing the CI badges show that builds fail :shrug:) * [DartSass](https://github.com/sass/dart-sass) is the only library/tool that is being actively worked on anymore. It requires either node.js to run the compiled-to-JS version, or Dart to build a native version. Dart itself is not available in Debian/Ubuntu (or Fedora) repos, instead they provide their own repo. They also release binaries on GitHub, but there's no signatures for those. However, it may turn out that relying on Sass at all may not be necessary - after all, SecureDrop is an unusual webapp that has different targets and goals than most contemporary web apps. I'll look into that first, once I'm closer with #6211 > However, it may turn out that relying on Sass at all may not be necessary - after all, SecureDrop is an unusual webapp that has different targets and goals than most contemporary web apps. I'll look into that first, once I'm closer with https://github.com/freedomofpress/securedrop/issues/6211 @eaon I'm curious how you feel about this now that #6315 has landed. If we're still stuck with sass in the short term, I would like to switch us over to sassc, which is at least maintained in Debian, allowing us to drop all the ruby stuff from our stack. Briefly discussed with @eaon, we could theoretically get rid of sass but it would require compiling everything to CSS and switching to CSS variables, etc. and I'm not ready to take that all on. I'm first going to see how difficult it would be to drop in sassc, as that would be enough to unblock my Debian packaging work. I generated journalist.css using both the ruby gem and sassc, the diff is: https://gist.github.com/legoktm/8700e8e132a592f00689c040d7a3fdec Differences: * single quotes instead of double quotes * escape sequences instead of unicode symbols * omitting `0.` prefix for numbers * weird comment indentation
2022-08-29T20:58:10Z
[]
[]
freedomofpress/securedrop
6,530
freedomofpress__securedrop-6530
[ "6527" ]
ee00104ab2cb4e7b94b218722228050e40ad69e6
diff --git a/admin/bootstrap.py b/admin/bootstrap.py --- a/admin/bootstrap.py +++ b/admin/bootstrap.py @@ -63,17 +63,8 @@ def run_command(command: List[str]) -> Iterator[bytes]: def is_tails() -> bool: - try: - id = subprocess.check_output("lsb_release --id --short", shell=True).decode("utf-8").strip() - except subprocess.CalledProcessError: - return False - - # dirty hack to unreliably detect Tails 4.0~beta2 - if id == "Debian": - if os.uname()[1] == "amnesia": - id = "Tails" - - return id == "Tails" + with open("/etc/os-release") as f: + return "TAILS_PRODUCT_NAME" in f.read() def clean_up_old_tails_venv(virtualenv_dir: str = VENV_DIR) -> None: @@ -84,18 +75,19 @@ def clean_up_old_tails_venv(virtualenv_dir: str = VENV_DIR) -> None: venv, so it'll get recreated. """ if is_tails(): - try: - dist = subprocess.check_output("lsb_release --codename --short", shell=True).strip() - except subprocess.CalledProcessError: - return None - - # Tails 5 is based on bullseye / Python 3.9 - if dist == b"bullseye": - python_lib_path = os.path.join(virtualenv_dir, "lib/python3.7") - if os.path.exists(python_lib_path): - sdlog.info("Tails 4 virtualenv detected. Removing it.") - shutil.rmtree(virtualenv_dir) - sdlog.info("Tails 4 virtualenv deleted.") + with open("/etc/os-release") as f: + os_release = f.readlines() + for line in os_release: + if line.startswith("TAILS_VERSION_ID="): + version = line.split("=")[1].strip().strip('"') + if version.startswith("5."): + # Tails 5 is based on Python 3.9 + python_lib_path = os.path.join(virtualenv_dir, "lib/python3.7") + if os.path.exists(python_lib_path): + sdlog.info("Tails 4 virtualenv detected. Removing it.") + shutil.rmtree(virtualenv_dir) + sdlog.info("Tails 4 virtualenv deleted.") + break def checkenv(args: argparse.Namespace) -> None: diff --git a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py --- a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py +++ b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py @@ -124,10 +124,9 @@ subprocess.call(["gio", "set", path_desktop + shortcut, "metadata::trusted", "true"], env=env) # in Tails 4, reload gnome-shell desktop icons extension to update with changes above -cmd = ["lsb_release", "--id", "--short"] -p = subprocess.check_output(cmd) -distro_id = p.rstrip() -if distro_id == "Debian" and os.uname()[1] == "amnesia": +with open("/etc/os-release") as f: + is_tails = "TAILS_PRODUCT_NAME" in f.read() +if is_tails: subprocess.call(["gnome-shell-extension-tool", "-r", "desktop-icons@csoriano"], env=env) # reacquire uid0 and notify the user diff --git a/securedrop/server_os.py b/securedrop/server_os.py --- a/securedrop/server_os.py +++ b/securedrop/server_os.py @@ -1,14 +1,14 @@ import functools -import subprocess FOCAL_VERSION = "20.04" @functools.lru_cache() def get_os_release() -> str: - return subprocess.run( - ["/usr/bin/lsb_release", "--release", "--short"], - check=True, - stdout=subprocess.PIPE, - universal_newlines=True, - ).stdout.strip() + with open("/etc/os-release") as f: + os_release = f.readlines() + for line in os_release: + if line.startswith("VERSION_ID="): + version_id = line.split("=")[1].strip().strip('"') + break + return version_id
diff --git a/admin/tests/test_securedrop-admin-setup.py b/admin/tests/test_securedrop-admin-setup.py --- a/admin/tests/test_securedrop-admin-setup.py +++ b/admin/tests/test_securedrop-admin-setup.py @@ -82,7 +82,7 @@ def test_python3_buster_venv_deleted_in_bullseye(self, tmpdir, caplog): python_lib_path = os.path.join(str(tmpdir), "lib/python3.7") os.makedirs(python_lib_path) with mock.patch("bootstrap.is_tails", return_value=True): - with mock.patch("subprocess.check_output", return_value=b"bullseye"): + with mock.patch("builtins.open", mock.mock_open(read_data='TAILS_VERSION_ID="5.0"')): bootstrap.clean_up_old_tails_venv(venv_path) assert "Tails 4 virtualenv detected." in caplog.text assert "Tails 4 virtualenv deleted." in caplog.text
Remove usage of lsb_release ## Description lsb_release is mostly obsolete these days, instead we should read from `/etc/os-release`. It's still used in https://github.com/freedomofpress/securedrop/blob/develop/securedrop/server_os.py, as well as: ``` user@dev ~/g/f/securedrop> ack lsb_release --ignore-dir=.venv admin/bootstrap.py 67: id = subprocess.check_output("lsb_release --id --short", shell=True).decode("utf-8").strip() 88: dist = subprocess.check_output("lsb_release --codename --short", shell=True).strip() securedrop/server_os.py 10: ["/usr/bin/lsb_release", "--release", "--short"], install_files/ansible-base/roles/tails-config/files/securedrop_init.py 127:cmd = ["lsb_release", "--id", "--short"] install_files/ansible-base/roles/build-securedrop-app-code-deb-pkg/files/usr.sbin.apache2 101: /usr/bin/lsb_release rix, install_files/ansible-base/inventory-dynamic 131: Returns output of `lsb_release --id --short`, to check 134: cmd = ["lsb_release", "--id", "--short"] install_files/securedrop-app-code/debian/rules 5:SECUREDROP_BUILD_PLATFORM=$(shell lsb_release -sc) ``` * https://0pointer.de/blog/projects/os-release (announcement, addresses "why not lsb_release") * https://www.freedesktop.org/software/systemd/man/os-release.html
Should we use grep/awk to read `VERSION_ID` from `/etc/os-release`? ``` $ /usr/bin/lsb_release --release --short 20.04 $ cat /etc/os-release | grep VERSION_ID | cut -d \" -f 2 20.04 $ awk -F\" '$1=="VERSION_ID=" { print $2 ;}' /etc/os-release 20.04 ``` So in Python code I think we can just do the string parsing in Python itself. For shell scripting I tend to like `source /etc/os-release` and then use them as environment variables. But if that's not possible, or not a good idea because of potential name conflicts, then yeah, some grep/cut/awk oneliner is fine.
2022-08-30T14:11:39Z
[]
[]
freedomofpress/securedrop
6,543
freedomofpress__securedrop-6543
[ "2421", "6173" ]
29ee0a155eea90d0613e2d867a1d99882042b240
diff --git a/securedrop/manage.py b/securedrop/manage.py --- a/securedrop/manage.py +++ b/securedrop/manage.py @@ -331,7 +331,7 @@ def get_args() -> argparse.ArgumentParser: parser.add_argument( "--store-dir", default=config.STORE_DIR, - help=("directory in which the documents are stored"), + help=("directory in which the files are stored"), ) subps = parser.add_subparsers() # Add/remove journalists + admins diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -292,9 +292,9 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: elif msg and not fh: html_contents = gettext("Thanks! We received your message.") elif fh and not msg: - html_contents = gettext("Thanks! We received your document.") + html_contents = gettext("Thanks! We received your file.") else: - html_contents = gettext("Thanks! We received your message and document.") + html_contents = gettext("Thanks! We received your file and message.") flash_msg("success", gettext("Success!"), html_contents)
diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -462,7 +462,7 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): in text ) - assert "No documents have been submitted!" in text + assert "There are no submissions!" in text # Make sure the collection is deleted from the filesystem def assertion(): diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -373,7 +373,7 @@ def test_login_valid_credentials(config, journalist_app, test_journo, locale): follow_redirects=True, ) assert page_language(resp.data) == language_tag(locale) - msgids = ["All Sources", "No documents have been submitted!"] + msgids = ["All Sources", "There are no submissions!"] with xfail_untranslated_messages(config, locale, msgids): resp_text = resp.data.decode("utf-8") for msgid in msgids: diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -467,7 +467,7 @@ def test_submit_file(source_app): ) assert resp.status_code == 200 text = resp.data.decode("utf-8") - assert "Thanks! We received your document" in text + assert "Thanks! We received your file" in text def test_submit_both(source_app): @@ -481,7 +481,7 @@ def test_submit_both(source_app): ) assert resp.status_code == 200 text = resp.data.decode("utf-8") - assert "Thanks! We received your message and document" in text + assert "Thanks! We received your file and message" in text def test_submit_antispam(source_app):
Use "Submissions" instead of "Documents" and "Messages" in source application strings. # Bug _This is a good first issue. If you have questions ask in this ticket or reach out via our [Gitter channel](https://gitter.im/freedomofpress/securedrop)._ ## Description There are mixed usages of the terms "Submissions", "Documents", and "Messages" in both English and German. Found by @xella ## Expected Behavior We use the term "submissions" consistently in user-facing strings. Change use of word "document" across SI and JI, to "file" ## Description In confirmation messaging in the Source UI, on the "All Sources" page of the JI, and maybe on the individual Source page in the JI, the word "document" is shown. In the H2 and Body copy of the SI, we have already changed the word to "File," and I believe in the SDW Client have also made the update. The file-name format including the word "doc" for files in the `.gz` filename, I'm not too worried about. it's more in the SI confirmation messaging and possible error messaging, as well as in the JI, that it feels nitpicky and out of place. ## User Research Evidence ![image](https://user-images.githubusercontent.com/8262612/142579763-a0725fe3-5c30-4fa8-ba28-5b9bb5ab8305.png) ## User Stories As a Source submitting an image, there is a cognitive disconnect when I get a confirmation message thanking me for my document. As a journalist, it is adding cognitive friction to see "doc" when I know they're "files."
True, this is confusing. I think standardizing on submissions is the best call. Submissions are then divided into files and messages. We should stop using the term documents, as the use of that term has been confusing: the uploaded files can be videos, pictures, or "documents" (PDFs, office documents). "document" and "submission" are still both in use, this is are relatively easy fix, so can be bumped up in priority. A quick addendum to this: Having to clarify that "doc" in the filename doesn't mean it's a Microsoft Word document file but any kind of file (image, video, etc) is something I go out of my way to explain in SecureDrop training sessions to avoid confused trainees.
2022-09-14T19:13:59Z
[]
[]
freedomofpress/securedrop
6,550
freedomofpress__securedrop-6550
[ "6357" ]
4623ec9d4db9f8a4bf1441a46440efc5ef5b0354
diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -2,7 +2,6 @@ import binascii import os -from html import escape from typing import Optional, Union import werkzeug @@ -132,7 +131,7 @@ def update_org_name() -> Union[str, werkzeug.Response]: if form.validate_on_submit(): try: value = request.form["organization_name"] - InstanceConfig.set_organization_name(escape(value, quote=True)) + InstanceConfig.set_organization_name(value) flash(gettext("Preferences saved."), "org-name-success") except Exception: flash(gettext("Failed to update organization name."), "org-name-error")
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -7,7 +7,6 @@ import random import zipfile from base64 import b64decode -from html import escape as htmlescape from io import BytesIO from pathlib import Path @@ -2003,25 +2002,6 @@ def test_orgname_oversized_fails(config, journalist_app, test_admin, locale): assert InstanceConfig.get_current().organization_name == "SecureDrop" -@flaky(rerun_filter=utils.flaky_filter_xfail) [email protected]("locale", get_test_locales()) -def test_orgname_html_escaped(config, journalist_app, test_admin, locale): - t_name = '"> <a href=foo>' - with journalist_app.test_client() as app: - _login_user(app, test_admin["username"], test_admin["password"], test_admin["otp_secret"]) - form = journalist_app_module.forms.OrgNameForm(organization_name=t_name) - assert InstanceConfig.get_current().organization_name == "SecureDrop" - with InstrumentedApp(journalist_app) as ins: - resp = app.post( - url_for("admin.update_org_name", l=locale), data=form.data, follow_redirects=True - ) - assert page_language(resp.data) == language_tag(locale) - msgids = ["Preferences saved."] - with xfail_untranslated_messages(config, locale, msgids): - ins.assert_message_flashed(gettext(msgids[0]), "org-name-success") - assert InstanceConfig.get_current().organization_name == htmlescape(t_name, quote=True) - - def test_logo_default_available(journalist_app): # if the custom image is available, this test will fail custom_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png")
Organization name gets escaped twice ## Description When configuring an instance's name as (for example) "Hello & World", the `&` shows up as `&amp;` wherever the organization name is used, because it is escaped when it is being set and again when it is being displayed. ## Comments As far as I can tell, the organization name is the only user provided input that is escaped before it is set - oversight or intentional?
Probably more overzealousness!
2022-09-19T18:50:31Z
[]
[]
freedomofpress/securedrop
6,557
freedomofpress__securedrop-6557
[ "6387" ]
54bfd2531ea1a77584c37f3943eb1cd741837193
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -63,6 +63,9 @@ MAX_NAMESERVERS = 3 LIST_SPLIT_RE = re.compile(r"\s*,\s*|\s+") +I18N_CONF = "securedrop/i18n.json" +I18N_DEFAULT_LOCALES = {"en_US"} + class FingerprintException(Exception): pass @@ -204,24 +207,27 @@ def __init__(self, appdir: str) -> None: self.translation_dir = os.path.realpath(os.path.join(appdir, "translations")) def get_translations(self) -> Set[str]: - translations = set(["en_US"]) + translations = I18N_DEFAULT_LOCALES for dirname in os.listdir(self.translation_dir): if dirname != "messages.pot": translations.add(dirname) return translations class ValidateLocales(Validator): - def __init__(self, basedir: str) -> None: - self.basedir = basedir + def __init__(self, basedir: str, supported: Set[str]) -> None: + present = SiteConfig.Locales(basedir).get_translations() + self.available = present & supported + super(SiteConfig.ValidateLocales, self).__init__() def validate(self, document: Document) -> bool: desired = document.text.split() - existing = SiteConfig.Locales(self.basedir).get_translations() - missing = set(desired) - set(existing) + missing = set(desired) - self.available if not missing: return True - raise ValidationError(message="The following locales do not exist " + " ".join(missing)) + raise ValidationError( + message="The following locales are not available " + " ".join(missing) + ) class ValidateOSSECUsername(Validator): def validate(self, document: Document) -> bool: @@ -268,8 +274,14 @@ def __init__(self, args: argparse.Namespace) -> None: # Hold runtime configuration before save, to support # referencing other responses during validation self._config_in_progress = {} # type: Dict - translations = SiteConfig.Locales(self.args.app_path).get_translations() - translations_as_str = " ".join(translations) + + supported_locales = I18N_DEFAULT_LOCALES.copy() + i18n_conf_path = os.path.join(args.root, I18N_CONF) + if os.path.exists(i18n_conf_path): + with open(i18n_conf_path) as i18n_conf_file: + i18n_conf = json.load(i18n_conf_file) + supported_locales.update(set(i18n_conf["supported_locales"].keys())) + locale_validator = SiteConfig.ValidateLocales(self.args.app_path, supported_locales) self.desc = [ ( @@ -503,8 +515,8 @@ def __init__(self, args: argparse.Namespace) -> None: [], list, "Space separated list of additional locales to support " - "(" + translations_as_str + ")", - SiteConfig.ValidateLocales(self.args.app_path), + "(" + " ".join(sorted(list(locale_validator.available))) + ")", + locale_validator, str.split, lambda config: True, ), diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -4,6 +4,7 @@ import argparse import glob import io +import json import logging import os import re @@ -13,7 +14,8 @@ import textwrap from argparse import _SubParsersAction from os.path import abspath, dirname, join, realpath -from typing import List, Optional, Set +from pathlib import Path +from typing import Dict, List, Optional, Set import version from sh import git, msgfmt, msgmerge, pybabel, sed, xgettext @@ -21,6 +23,15 @@ logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger(__name__) +I18N_CONF = os.path.join(os.path.dirname(__file__), "i18n.json") + +# Map components of the "securedrop" Weblate project (keys) to their filesystem +# paths (values) relative to the repository root. +LOCALE_DIR = { + "securedrop": "securedrop/translations", + "desktop": "install_files/ansible-base/roles/tails-config/templates", +} + class I18NTool: # @@ -33,92 +44,9 @@ class I18NTool: # display in the interface. # desktop: The language code used for dekstop icons. # - supported_languages = { - "ar": { - "name": "Arabic", - "desktop": "ar", - }, - "ca": { - "name": "Catalan", - "desktop": "ca", - }, - "cs": { - "name": "Czech", - "desktop": "cs", - }, - "de_DE": { - "name": "German", - "desktop": "de_DE", - }, - "el": { - "name": "Greek", - "desktop": "el", - }, - "es_ES": { - "name": "Spanish", - "desktop": "es_ES", - }, - "fr_FR": { - "name": "French", - "desktop": "fr", - }, - "hi": { - "name": "Hindi", - "desktop": "hi", - }, - "is": { - "name": "Icelandic", - "desktop": "is", - }, - "it_IT": { - "name": "Italian", - "desktop": "it", - }, - "nb_NO": { - "name": "Norwegian", - "desktop": "nb_NO", - }, - "nl": { - "name": "Dutch", - "desktop": "nl", - }, - "pt_BR": { - "name": "Portuguese, Brasil", - "desktop": "pt_BR", - }, - "pt_PT": { - "name": "Portuguese, Portugal", - "desktop": "pt_PT", - }, - "ro": { - "name": "Romanian", - "desktop": "ro", - }, - "ru": { - "name": "Russian", - "desktop": "ru", - }, - "sk": { - "name": "Slovak", - "desktop": "sk", - }, - "sv": { - "name": "Swedish", - "desktop": "sv", - }, - "tr": { - "name": "Turkish", - "desktop": "tr", - }, - "zh_Hans": { - "name": "Chinese, Simplified", - "desktop": "zh_Hans", - }, - "zh_Hant": { - "name": "Chinese, Traditional", - "desktop": "zh_Hant", - }, - } + with open(I18N_CONF) as i18n_conf: + conf = json.load(i18n_conf) + supported_languages = conf["supported_locales"] release_tag_re = re.compile(r"^\d+\.\d+\.\d+$") translated_commit_re = re.compile("Translated using Weblate") updated_commit_re = re.compile(r"(?:updated from| (?:revision|commit):) (\w+)") @@ -158,7 +86,7 @@ def translate_messages(self, args: argparse.Namespace) -> None: "--strip-comments", "--add-location=never", "--no-wrap", - *sources + *sources, ) sed("-i", "-e", '/^"POT-Creation-Date/d', messages_file) @@ -190,7 +118,7 @@ def translate_desktop(self, args: argparse.Namespace) -> None: "[email protected]", "--copyright-holder=Freedom of the Press Foundation", *sources, - **k + **k, ) sed("-i", "-e", '/^"POT-Creation-Date/d', messages_file, **k) @@ -291,7 +219,8 @@ def set_translate_desktop_parser(self, subps: _SubParsersAction) -> None: ) translations_dir = join( dirname(realpath(__file__)), - "../install_files/ansible-base/roles/tails-config/templates", + "..", + LOCALE_DIR["desktop"], ) sources = "desktop-journalist-icon.j2.in,desktop-source-icon.j2.in" self.set_translate_parser(parser, translations_dir, sources) @@ -347,56 +276,62 @@ def update_from_weblate(self, args: argparse.Namespace) -> None: Pull in updated translations from the i18n repo. """ self.ensure_i18n_remote(args) - codes = list(self.supported_languages.keys()) - if args.supported_languages: - codes = args.supported_languages.split(",") - for code in sorted(codes): - info = self.supported_languages[code] - def need_update(path: str) -> bool: - """ - Check if the file is different in the i18n repo. - """ + # Check out *all* remote changes to the LOCALE_DIRs. + git( + "-C", + args.root, + "checkout", + args.target, + "--", + *LOCALE_DIR.values(), + ) - exists = os.path.exists(join(args.root, path)) - k = {"_cwd": args.root} - git.checkout(args.target, "--", path, **k) - git.reset("HEAD", "--", path, **k) - if not exists: - return True + # Use the LOCALE_DIR corresponding to the "securedrop" component to + # determine which locales are present. + locale_dir = os.path.join(args.root, LOCALE_DIR["securedrop"]) + locales = self.translated_locales(locale_dir) + if args.supported_languages: + codes = args.supported_languages.split(",") + locales = {code: locales[code] for code in locales if code in codes} - return self.file_is_modified(join(args.root, path)) + # Then iterate over all locales present and decide which to stage and commit. + for code, path in locales.items(): + paths = [] def add(path: str) -> None: """ Add the file to the git index. """ git("-C", args.root, "add", path) + paths.append(path) - updated = False - # - # Add changes to web .po files - # - path = "securedrop/translations/{l}/LC_MESSAGES/messages.po".format( - l=code # noqa: E741 - ) - if need_update(path): - add(path) - updated = True - # - # Add changes to desktop .po files - # - desktop_code = info["desktop"] - path = join( - "install_files/ansible-base/roles", - "tails-config/templates/{l}.po".format(l=desktop_code), # noqa: E741 - ) - if need_update(path): + # Any translated locale may have changes that need to be staged from the + # securedrop/securedrop component. + add(path) + + # Only supported locales may have changes that need to be staged from the + # securedrop/desktop component, because the link between the two components + # is defined in I18N_CONF when a language is marked supported. + try: + info = self.supported_languages[code] + name = info["name"] + desktop_code = info["desktop"] + path = join( + LOCALE_DIR["desktop"], + "{l}.po".format(l=desktop_code), # noqa: E741 + ) add(path) - updated = True + except KeyError: + log.info( + f"{code} has translations but is not marked as supported; " + f"skipping desktop translation" + ) + name = code - if updated: - self.commit_changes(args, code) + # Try to commit changes for this locale no matter what, even if it turns out to be a + # no-op. + self.commit_changes(args, code, name, paths) def translators( self, args: argparse.Namespace, path: str, since_commit: Optional[str] @@ -438,17 +373,32 @@ def get_path_commits(self, root: str, path: str) -> List[str]: "--no-pager", "-C", root, "log", "--format=%H", path, _encoding="utf-8" ).splitlines() - def commit_changes(self, args: argparse.Namespace, code: str) -> None: + def translated_locales(self, path: str) -> Dict[str, str]: + """Return a dictionary of all locale directories present in `path`, where the keys + are the base (directory) names and the values are the full paths.""" + p = Path(path) + return {x.name: str(x) for x in p.iterdir() if x.is_dir()} + + def commit_changes( + self, args: argparse.Namespace, code: str, name: str, paths: List[str] + ) -> None: + """Check if any of the given paths have had changed staged. If so, commit them.""" self.require_git_email_name(args.root) authors = set() # type: Set[str] - diffs = "{}".format(git("--no-pager", "-C", args.root, "diff", "--name-only", "--cached")) + diffs = "{}".format( + git("--no-pager", "-C", args.root, "diff", "--name-only", "--cached", *paths) + ) + + # If nothing was changed, "git commit" will return nonzero as a no-op. + if len(diffs) == 0: + return # for each modified file, find the last commit made by this # function, then collect all the contributors since that # commit, so they can be credited in this one. if no commit # with the right message is found, just use the most recent # commit that touched the file. - for path in sorted(diffs.strip().split("\n")): + for path in paths: path_commits = self.get_path_commits(args.root, path) since_commit = None for path_commit in path_commits: @@ -465,7 +415,6 @@ def commit_changes(self, args: argparse.Namespace, code: str) -> None: authors_as_str = "\n ".join(sorted(authors)) current = git("-C", args.root, "rev-parse", args.target) - info = self.supported_languages[code] message = textwrap.dedent( """ l10n: updated {name} ({code}) @@ -477,10 +426,8 @@ def commit_changes(self, args: argparse.Namespace, code: str) -> None: repo: {remote} commit: {current} """ - ).format( - remote=args.url, name=info["name"], authors=authors_as_str, code=code, current=current - ) - git("-C", args.root, "commit", "-m", message) + ).format(remote=args.url, name=name, authors=authors_as_str, code=code, current=current) + git("-C", args.root, "commit", "-m", message, *paths) def set_update_from_weblate_parser(self, subps: _SubParsersAction) -> None: parser = subps.add_parser("update-from-weblate", help=("Import translations from weblate")) @@ -590,8 +537,8 @@ def get_commit_timestamp(self, root: str, commit: Optional[str]) -> str: def list_translators(self, args: argparse.Namespace) -> None: self.ensure_i18n_remote(args) - app_template = "securedrop/translations/{}/LC_MESSAGES/messages.po" - desktop_template = "install_files/ansible-base/roles/tails-config/templates/{}.po" + app_template = "{}/{}/LC_MESSAGES/messages.po" + desktop_template = LOCALE_DIR["desktop"] + "/{}.po" since = None if args.all: print("Listing all translators who have ever helped") @@ -601,7 +548,7 @@ def list_translators(self, args: argparse.Namespace) -> None: for code, info in sorted(self.supported_languages.items()): translators = set([]) paths = [ - app_template.format(code), + app_template.format(LOCALE_DIR["securedrop"], code), desktop_template.format(info["desktop"]), ] for path in paths:
diff --git a/admin/tests/files/securedrop/i18n.json b/admin/tests/files/securedrop/i18n.json new file mode 100644 --- /dev/null +++ b/admin/tests/files/securedrop/i18n.json @@ -0,0 +1,16 @@ +{ + "supported_locales": { + "de_DE": { + "name": "German", + "desktop": "de_DE" + }, + "es_ES": { + "name": "Spanish", + "desktop": "es_ES" + }, + "fr_FR": { + "name": "French", + "desktop": "fr" + } + } +} diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -140,6 +140,9 @@ def setup_function(function): for name in ["de_DE", "es_ES", "fr_FR", "pt_BR"]: dircmd = "mkdir -p {0}/securedrop/translations/{1}".format(SD_DIR, name) subprocess.check_call(dircmd.split()) + subprocess.check_call( + "cp {0}/files/securedrop/i18n.json {1}/securedrop".format(CURRENT_DIR, SD_DIR).split() + ) def teardown_function(function): diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -480,13 +480,16 @@ def test_exit_codes(self, tmpdir): class TestSiteConfig(object): - def test_exists(self): + def test_exists(self, tmpdir): args = argparse.Namespace( - site_config="DOES_NOT_EXIST", ansible_path=".", app_path=dirname(__file__) + site_config="DOES_NOT_EXIST", + ansible_path=".", + app_path=dirname(__file__), + root=tmpdir, ) assert not securedrop_admin.SiteConfig(args).exists() args = argparse.Namespace( - site_config=__file__, ansible_path=".", app_path=dirname(__file__) + site_config=__file__, ansible_path=".", app_path=dirname(__file__), root=tmpdir ) assert securedrop_admin.SiteConfig(args).exists() @@ -623,9 +626,12 @@ def test_validate_optional_fingerprint(self): assert validator.validate(Document("012345678901234567890123456789ABCDEFABCD")) assert validator.validate(Document("")) - def test_sanitize_fingerprint(self): + def test_sanitize_fingerprint(self, tmpdir): args = argparse.Namespace( - site_config="DOES_NOT_EXIST", ansible_path=".", app_path=dirname(__file__) + site_config="DOES_NOT_EXIST", + ansible_path=".", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) assert "ABC" == site_config.sanitize_fingerprint(" A bc") @@ -643,7 +649,9 @@ def test_locales(self): assert "fr_FR" in translations def test_validate_locales(self): - validator = securedrop_admin.SiteConfig.ValidateLocales(dirname(__file__)) + validator = securedrop_admin.SiteConfig.ValidateLocales( + dirname(__file__), {"en_US", "fr_FR"} + ) assert validator.validate(Document("en_US fr_FR ")) with pytest.raises(ValidationError) as e: validator.validate(Document("BAD")) @@ -652,7 +660,10 @@ def test_validate_locales(self): def test_save(self, tmpdir): site_config_path = join(str(tmpdir), "site_config") args = argparse.Namespace( - site_config=site_config_path, ansible_path=".", app_path=dirname(__file__) + site_config=site_config_path, + ansible_path=".", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) site_config.config = {"var1": "val1", "var2": "val2"} @@ -665,9 +676,12 @@ def test_save(self, tmpdir): ) assert expected == io.open(site_config_path).read() - def test_validate_gpg_key(self, caplog): + def test_validate_gpg_key(self, tmpdir, caplog): args = argparse.Namespace( - site_config="INVALID", ansible_path="tests/files", app_path=dirname(__file__) + site_config="INVALID", + ansible_path="tests/files", + app_path=dirname(__file__), + root=tmpdir, ) good_config = { "securedrop_app_gpg_public_key": "test_journalist_key.pub", @@ -689,9 +703,12 @@ def test_validate_gpg_key(self, caplog): site_config.validate_gpg_keys() assert "FAIL does not match" in str(e) - def test_journalist_alert_email(self): + def test_journalist_alert_email(self, tmpdir): args = argparse.Namespace( - site_config="INVALID", ansible_path="tests/files", app_path=dirname(__file__) + site_config="INVALID", + ansible_path="tests/files", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) site_config.config = { @@ -723,6 +740,7 @@ def test_update_config(self, mock_save, mock_validate_input): site_config="tests/files/site-specific", ansible_path="tests/files", app_path=dirname(__file__), + root="tests/files", ) site_config = securedrop_admin.SiteConfig(args) @@ -736,7 +754,10 @@ def test_update_config(self, mock_save, mock_validate_input): def test_update_config_no_site_specific(self, validate_gpg_keys, mock_validate_input, tmpdir): site_config_path = join(str(tmpdir), "site_config") args = argparse.Namespace( - site_config=site_config_path, ansible_path=".", app_path=dirname(__file__) + site_config=site_config_path, + ansible_path=".", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) assert site_config.load_and_update_config() @@ -744,11 +765,12 @@ def test_update_config_no_site_specific(self, validate_gpg_keys, mock_validate_i validate_gpg_keys.assert_called_once() assert exists(site_config_path) - def test_load_and_update_config(self): + def test_load_and_update_config(self, tmpdir): args = argparse.Namespace( site_config="tests/files/site-specific", ansible_path="tests/files", app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) with mock.patch("securedrop_admin.SiteConfig.update_config"): @@ -759,6 +781,7 @@ def test_load_and_update_config(self): site_config="tests/files/site-specific-missing-entries", ansible_path="tests/files", app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) with mock.patch("securedrop_admin.SiteConfig.update_config"): @@ -766,7 +789,10 @@ def test_load_and_update_config(self): assert site_config.config != {} args = argparse.Namespace( - site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + site_config="UNKNOWN", + ansible_path="tests/files", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) with mock.patch("securedrop_admin.SiteConfig.update_config"): @@ -797,7 +823,7 @@ def verify_prompt_boolean(self, site_config, desc): assert site_config.user_prompt_config_one(desc, "YES") is True assert site_config.user_prompt_config_one(desc, "NO") is False - def test_desc_conditional(self): + def test_desc_conditional(self, tmpdir): """Ensure that conditional prompts behave correctly. Prompts which depend on another question should only be @@ -827,6 +853,7 @@ def test_desc_conditional(self): site_config="tests/files/site-specific", ansible_path="tests/files", app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) site_config.desc = questions @@ -904,9 +931,12 @@ def verify_prompt_securedrop_supported_locales(self, site_config, desc): with pytest.raises(ValidationError): site_config.user_prompt_config_one(desc, "wrong") - def test_user_prompt_config_one(self): + def test_user_prompt_config_one(self, tmpdir): args = argparse.Namespace( - site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + site_config="UNKNOWN", + ansible_path="tests/files", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) @@ -922,9 +952,12 @@ def auto_prompt(prompt, default, **kwargs): print("checking " + method) getattr(self, method)(site_config, desc) - def test_validated_input(self): + def test_validated_input(self, tmpdir): args = argparse.Namespace( - site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + site_config="UNKNOWN", + ansible_path="tests/files", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) @@ -941,17 +974,21 @@ def auto_prompt(prompt, default, **kwargs): assert "a b" == site_config.validated_input("", ["a", "b"], lambda: True, None) assert "{}" == site_config.validated_input("", {}, lambda: True, None) - def test_load(self, caplog): + def test_load(self, tmpdir, caplog): args = argparse.Namespace( site_config="tests/files/site-specific", ansible_path="tests/files", app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) assert "app_hostname" in site_config.load() args = argparse.Namespace( - site_config="UNKNOWN", ansible_path="tests/files", app_path=dirname(__file__) + site_config="UNKNOWN", + ansible_path="tests/files", + app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) with pytest.raises(IOError) as e: @@ -963,6 +1000,7 @@ def test_load(self, caplog): site_config="tests/files/corrupted", ansible_path="tests/files", app_path=dirname(__file__), + root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) with pytest.raises(yaml.YAMLError) as e:
centralize list of supported languages ## Description The current state of play: 1. Users can only use SecureDrop in a language configured by the instance's administrator. (#2378, #2561) 2. Administrators can only configure languages present in their working copy's `securedrop/translations` directory. (#2516) But: 3. [x] To keep translations in sync even if they fall (or have not yet reached) 100% translation coverage, we need to have them present in `securedrop/translations`. (#6156) Therefore: 4. [x] `i18n_tool.py` and `securedrop-admin sdconfig` need to share a centralized list of *supported* languages. This can be thought of as `securedrop`'s companion to freedomofpress/securedrop-client#1438—and as another incremental step away from the `securedrop` repository itself as the Server's packaging. ## User Research Evidence In #6156, I tried to sync up a language not yet supported and needed a [sequence diagram](https://gist.github.com/cfm/30ef449a7adaee0f1437d39822eb7dae) to do it. :-) ## User Stories As a translator, I want to be able to request (volunteer!) a new language to translate without placing a large operational or maintenance burden on the SecureDrop project *until and unless* the translation can be considered supported and ready to be deployed. * Currently, a translator can add a new language directly in Weblate, whereupon it will receive the _current_ string catalog but no future updates. This is what's happened with the languages reported in #6156.) As a Localization Manager, I want to be able to add languages and facilitate their translation when they've not yet reached, or may have fallen below, the 100% coverage threshold to be considered supported. * Formalize language-support lifecycle: 80% or 90% threshold for _losing_ support? As a SecureDrop administrator, I (still) want to be able to configure only supported languages, no matter what else may be present in my `securedrop` working copy.
2022-09-22T05:32:58Z
[]
[]
freedomofpress/securedrop
6,563
freedomofpress__securedrop-6563
[ "5761" ]
81bc70d484cc58346e1638c05d45ec37262b4e51
diff --git a/securedrop/alembic/env.py b/securedrop/alembic/env.py --- a/securedrop/alembic/env.py +++ b/securedrop/alembic/env.py @@ -20,9 +20,10 @@ # These imports are only needed for offline generation of automigrations. # Importing them in a prod-like environment breaks things. from journalist_app import create_app # noqa - from sdconfig import config as sdconfig # noqa + from sdconfig import SecureDropConfig # noqa # App context is needed for autogenerated migrations + sdconfig = SecureDropConfig.get_current() create_app(sdconfig).app_context().push() except Exception: # Only reraise the exception in 'dev' where a developer actually cares diff --git a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py --- a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py +++ b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py @@ -17,7 +17,7 @@ try: from journalist_app import create_app - from sdconfig import config + from sdconfig import SecureDropConfig from store import NoFileFoundException, Storage, TooManyFilesException except ImportError: # This is a fresh install, and config.py has not been created yet. @@ -49,6 +49,7 @@ def upgrade() -> None: replies = conn.execute(sa.text(raw_sql_grab_orphaned_objects("replies"))).fetchall() try: + config = SecureDropConfig.get_current() app = create_app(config) with app.app_context(): for submission in submissions: diff --git a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py --- a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py +++ b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py @@ -14,7 +14,7 @@ try: from journalist_app import create_app from models import Reply, Submission - from sdconfig import config + from sdconfig import SecureDropConfig from store import Storage, queued_add_checksum_for_file from worker import create_queue except: # noqa @@ -46,6 +46,7 @@ def upgrade() -> None: ) try: + config = SecureDropConfig.get_current() app = create_app(config) # we need an app context for the rq worker extension to work properly diff --git a/securedrop/encryption.py b/securedrop/encryption.py --- a/securedrop/encryption.py +++ b/securedrop/encryption.py @@ -9,6 +9,7 @@ import pretty_bad_protocol as gnupg from redis import Redis +from sdconfig import SecureDropConfig if typing.TYPE_CHECKING: from source_user import SourceUser @@ -122,13 +123,11 @@ def __init__(self, gpg_key_dir: Path, journalist_key_fingerprint: str) -> None: @classmethod def get_default(cls) -> "EncryptionManager": - # Late import so the module can be used without a config.py in the parent folder - from sdconfig import config - global _default_encryption_mgr if _default_encryption_mgr is None: + config = SecureDropConfig.get_current() _default_encryption_mgr = cls( - gpg_key_dir=Path(config.GPG_KEY_DIR), + gpg_key_dir=config.GPG_KEY_DIR, journalist_key_fingerprint=config.JOURNALIST_KEY, ) return _default_encryption_mgr diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -27,7 +27,7 @@ ) from flask import Flask, current_app, g, request, session from flask_babel import Babel -from sdconfig import FALLBACK_LOCALE, SDConfig +from sdconfig import FALLBACK_LOCALE, SecureDropConfig class RequestLocaleInfo: @@ -99,7 +99,7 @@ def language_tag(self) -> str: return get_locale_identifier(parse_locale(str(self.locale)), sep="-") -def configure_babel(config: SDConfig, app: Flask) -> Babel: +def configure_babel(config: SecureDropConfig, app: Flask) -> Babel: """ Set up Flask-Babel according to the SecureDrop configuration. """ @@ -128,7 +128,7 @@ def parse_locale_set(codes: List[str]) -> Set[Locale]: return {Locale.parse(code) for code in codes} -def validate_locale_configuration(config: SDConfig, babel: Babel) -> Set[Locale]: +def validate_locale_configuration(config: SecureDropConfig, babel: Babel) -> Set[Locale]: """ Check that configured locales are available in the filesystem and therefore usable by Babel. Warn about configured locales that are not usable, unless we're left with @@ -161,7 +161,7 @@ def validate_locale_configuration(config: SDConfig, babel: Babel) -> Set[Locale] def map_locale_display_names( - config: SDConfig, usable_locales: Set[Locale] + config: SecureDropConfig, usable_locales: Set[Locale] ) -> OrderedDict[str, RequestLocaleInfo]: """ Create a map of locale identifiers to names for display. @@ -192,13 +192,13 @@ def map_locale_display_names( return locale_map -def configure(config: SDConfig, app: Flask) -> None: +def configure(config: SecureDropConfig, app: Flask) -> None: babel = configure_babel(config, app) usable_locales = validate_locale_configuration(config, babel) app.config["LOCALES"] = map_locale_display_names(config, usable_locales) -def get_locale(config: SDConfig) -> str: +def get_locale(config: SecureDropConfig) -> str: """ Return the best supported locale for a request. @@ -253,7 +253,7 @@ def get_accepted_languages() -> List[str]: return accept_languages -def set_locale(config: SDConfig) -> None: +def set_locale(config: SecureDropConfig) -> None: """ Update locale info in request and session. """ diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -3,8 +3,9 @@ from execution import asynchronous from journalist_app import create_app from models import Source -from sdconfig import config +from sdconfig import SecureDropConfig +config = SecureDropConfig.get_current() app = create_app(config) diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -1,9 +1,6 @@ -# -*- coding: utf-8 -*- - -import typing from datetime import datetime -from os import path from pathlib import Path +from typing import Any, Optional, Tuple, Union import i18n import template_filters @@ -16,19 +13,9 @@ from journalist_app.sessions import Session, session from journalist_app.utils import get_source from models import InstanceConfig -from werkzeug.exceptions import default_exceptions - -# https://www.python.org/dev/peps/pep-0484/#runtime-or-type-checking -if typing.TYPE_CHECKING: - # flake8 can not understand type annotation yet. - # That is why all type annotation relative import - # statements has to be marked as noqa. - # http://flake8.pycqa.org/en/latest/user/error-codes.html?highlight=f401 - from typing import Any, Optional, Tuple, Union # noqa: F401 - - from sdconfig import SDConfig # noqa: F401 - from werkzeug import Response # noqa: F401 - from werkzeug.exceptions import HTTPException # noqa: F401 +from sdconfig import SecureDropConfig +from werkzeug import Response +from werkzeug.exceptions import HTTPException, default_exceptions _insecure_views = ["main.login", "static"] _insecure_api_views = ["api.get_token", "api.get_endpoints"] @@ -52,11 +39,11 @@ def get_logo_url(app: Flask) -> str: raise FileNotFoundError -def create_app(config: "SDConfig") -> Flask: +def create_app(config: SecureDropConfig) -> Flask: app = Flask( __name__, - template_folder=config.JOURNALIST_TEMPLATES_DIR, - static_folder=path.join(config.SECUREDROP_ROOT, "static"), + template_folder=str(config.JOURNALIST_TEMPLATES_DIR.absolute()), + static_folder=config.STATIC_DIR.absolute(), ) app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS) @@ -86,8 +73,8 @@ def handle_csrf_error(e: CSRFError) -> "Response": return redirect(url_for("main.login")) def _handle_http_exception( - error: "HTTPException", - ) -> "Tuple[Union[Response, str], Optional[int]]": + error: HTTPException, + ) -> Tuple[Union[Response, str], Optional[int]]: # Workaround for no blueprint-level 404/5 error handlers, see: # https://github.com/pallets/flask/issues/503#issuecomment-71383286 # TODO: clean up API error handling such that all except 404/5s are @@ -117,7 +104,7 @@ def update_instance_config() -> None: InstanceConfig.get_default(refresh=True) @app.before_request - def setup_g() -> "Optional[Response]": + def setup_g() -> Optional[Response]: """Store commonly used values in Flask's special g object""" i18n.set_locale(config) @@ -149,11 +136,11 @@ def setup_g() -> "Optional[Response]": return None - app.register_blueprint(main.make_blueprint(config)) - app.register_blueprint(account.make_blueprint(config), url_prefix="/account") - app.register_blueprint(admin.make_blueprint(config), url_prefix="/admin") - app.register_blueprint(col.make_blueprint(config), url_prefix="/col") - api_blueprint = api.make_blueprint(config) + app.register_blueprint(main.make_blueprint()) + app.register_blueprint(account.make_blueprint(), url_prefix="/account") + app.register_blueprint(admin.make_blueprint(), url_prefix="/admin") + app.register_blueprint(col.make_blueprint(), url_prefix="/col") + api_blueprint = api.make_blueprint() app.register_blueprint(api_blueprint, url_prefix="/api/v1") csrf.exempt(api_blueprint) diff --git a/securedrop/journalist_app/account.py b/securedrop/journalist_app/account.py --- a/securedrop/journalist_app/account.py +++ b/securedrop/journalist_app/account.py @@ -13,10 +13,9 @@ validate_user, ) from passphrases import PassphraseGenerator -from sdconfig import SDConfig -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint() -> Blueprint: view = Blueprint("account", __name__) @view.route("/account", methods=("GET",)) diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -31,12 +31,11 @@ Submission, ) from passphrases import PassphraseGenerator -from sdconfig import SDConfig from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint() -> Blueprint: view = Blueprint("admin", __name__) @view.route("/", methods=("GET", "POST")) diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -23,7 +23,6 @@ Submission, WrongPasswordException, ) -from sdconfig import SDConfig from sqlalchemy import Column from sqlalchemy.exc import IntegrityError from store import NotEncrypted, Storage @@ -37,7 +36,7 @@ def get_or_404(model: db.Model, object_id: str, column: Column) -> db.Model: return result -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint() -> Blueprint: api = Blueprint("api", __name__) @api.route("/") diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -35,12 +35,11 @@ mark_seen, ) from models import Reply, Submission -from sdconfig import SDConfig from sqlalchemy.orm.exc import NoResultFound from store import Storage -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint() -> Blueprint: view = Blueprint("col", __name__) @view.route("/add_star/<filesystem_id>", methods=("POST",)) diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -25,13 +25,12 @@ from journalist_app.sessions import session from journalist_app.utils import bulk_delete, download, get_source, validate_user from models import Reply, SeenReply, Source, SourceStar, Submission -from sdconfig import SDConfig from sqlalchemy.orm import joinedload from sqlalchemy.sql import func from store import Storage -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint() -> Blueprint: view = Blueprint("main", __name__) @view.route("/login", methods=("GET", "POST")) diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -32,7 +32,7 @@ Submission, ) from passphrases import PassphraseGenerator -from sdconfig import config +from sdconfig import SecureDropConfig from source_user import create_source_user from specialstrings import strings from sqlalchemy.exc import IntegrityError @@ -371,6 +371,7 @@ def load(args: argparse.Namespace) -> None: if not os.environ.get("SECUREDROP_ENV"): os.environ["SECUREDROP_ENV"] = "dev" + config = SecureDropConfig.get_current() app = journalist_app.create_app(config) with app.app_context(): journalists = create_default_journalists() diff --git a/securedrop/manage.py b/securedrop/manage.py --- a/securedrop/manage.py +++ b/securedrop/manage.py @@ -12,6 +12,7 @@ import time import traceback from argparse import _SubParsersAction +from pathlib import Path from typing import List, Optional from flask.ctx import AppContext @@ -27,7 +28,7 @@ from db import db # noqa: E402 -from management import app_context, config # noqa: E402 +from management import SecureDropConfig, app_context # noqa: E402 from management.run import run # noqa: E402 from management.submissions import ( # noqa: E402 add_check_db_disconnect_parser, @@ -50,13 +51,19 @@ def obtain_input(text: str) -> str: return input(text) -def reset(args: argparse.Namespace, context: Optional[AppContext] = None) -> int: +def reset( + args: argparse.Namespace, + alembic_ini_path: Path = Path("alembic.ini"), + context: Optional[AppContext] = None, +) -> int: """Clears the SecureDrop development applications' state, restoring them to the way they were immediately after running `setup_dev.sh`. This command: 1. Erases the development sqlite database file. 2. Regenerates the database. 3. Erases stored submissions and replies from the store dir. """ + config = SecureDropConfig.get_current() + # Erase the development db file if not hasattr(config, "DATABASE_FILE"): raise Exception( @@ -92,13 +99,8 @@ def reset(args: argparse.Namespace, context: Optional[AppContext] = None) -> int with context or app_context(): db.create_all() else: - # We have to override the hardcoded .ini file because during testing - # the value in the .ini doesn't exist. - ini_dir = os.path.dirname(getattr(config, "TEST_ALEMBIC_INI", "alembic.ini")) - # 3. Migrate it to 'head' - # nosemgrep: python.lang.security.audit.subprocess-shell-true.subprocess-shell-true - subprocess.check_call("cd {} && alembic upgrade head".format(ini_dir), shell=True) # nosec + subprocess.check_call(["alembic", "upgrade", "head"], cwd=alembic_ini_path.parent) # Clear submission/reply storage try: @@ -311,6 +313,7 @@ def listdir_fullpath(d: str) -> List[str]: def init_db(args: argparse.Namespace) -> None: + config = SecureDropConfig.get_current() user = pwd.getpwnam(args.user) subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) os.chown(config.DATABASE_FILE, user.pw_uid, user.pw_gid) @@ -319,6 +322,7 @@ def init_db(args: argparse.Namespace) -> None: def get_args() -> argparse.ArgumentParser: + config = SecureDropConfig.get_current() parser = argparse.ArgumentParser( prog=__file__, description="Management " "and testing utility for SecureDrop." ) @@ -390,6 +394,8 @@ def get_args() -> argparse.ArgumentParser: def set_clean_tmp_parser(subps: _SubParsersAction, name: str) -> None: + config = SecureDropConfig.get_current() + parser = subps.add_parser(name, help="Cleanup the " "SecureDrop temp directory.") default_days = 7 parser.add_argument( diff --git a/securedrop/management/__init__.py b/securedrop/management/__init__.py --- a/securedrop/management/__init__.py +++ b/securedrop/management/__init__.py @@ -2,10 +2,11 @@ from typing import Generator import journalist_app -from sdconfig import config +from sdconfig import SecureDropConfig @contextmanager def app_context() -> Generator: + config = SecureDropConfig.get_current() with journalist_app.create_app(config).app_context(): yield diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -872,7 +872,7 @@ class JournalistLoginAttempt(db.Model): __tablename__ = "journalist_login_attempt" id = Column(Integer, primary_key=True) - timestamp = Column(DateTime, default=datetime.datetime.utcnow) + timestamp = Column(DateTime, default=datetime.datetime.utcnow, nullable=True) journalist_id = Column(Integer, ForeignKey("journalists.id"), nullable=False) def __init__(self, journalist: Journalist) -> None: diff --git a/securedrop/passphrases.py b/securedrop/passphrases.py --- a/securedrop/passphrases.py +++ b/securedrop/passphrases.py @@ -2,7 +2,7 @@ from secrets import SystemRandom from typing import Dict, List, NewType, Optional, Set -from sdconfig import config +from sdconfig import SecureDropConfig # A list of words to be used by as a passphrase # For example: "recede anytime acorn durably discuss" @@ -99,7 +99,8 @@ def __init__( def get_default(cls) -> "PassphraseGenerator": global _default_generator if _default_generator is None: - language_to_words = _parse_available_words_list(Path(config.SECUREDROP_ROOT)) + config = SecureDropConfig.get_current() + language_to_words = _parse_available_words_list(config.SECUREDROP_ROOT) _default_generator = cls(language_to_words) return _default_generator diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -1,155 +1,99 @@ +from dataclasses import dataclass +from importlib import import_module from pathlib import Path -from typing import Dict, Optional, Set, Type - -import config as _config +from typing import Dict, List, Optional FALLBACK_LOCALE = "en_US" +DEFAULT_SECUREDROP_ROOT = Path(__file__).absolute().parent -# Adding a subclass here allows for adding attributes without modifying config.py -class JournalistInterfaceConfig(_config.JournalistInterfaceFlaskConfig): - SESSION_COOKIE_NAME = "js" - SESSION_SIGNER_SALT = "js_session" - SESSION_KEY_PREFIX = "js_session:" - SESSION_LIFETIME = 2 * 60 * 60 - SESSION_RENEW_COUNT = 5 - - -class SourceInterfaceConfig(_config.SourceInterfaceFlaskConfig): - SESSION_COOKIE_NAME = "ss" - - -class SDConfig: - def __init__(self) -> None: - try: - self.JOURNALIST_APP_FLASK_CONFIG_CLS = JournalistInterfaceConfig # type: Type - except AttributeError: - pass - - try: - self.SOURCE_APP_FLASK_CONFIG_CLS = SourceInterfaceConfig # type: Type - except AttributeError: - pass - - try: - self.DATABASE_ENGINE = _config.DATABASE_ENGINE # type: str - except AttributeError: - pass - - try: - self.DATABASE_FILE = _config.DATABASE_FILE # type: str - except AttributeError: - pass - - self.DATABASE_USERNAME = getattr(_config, "DATABASE_USERNAME", None) # type: Optional[str] - self.DATABASE_PASSWORD = getattr(_config, "DATABASE_PASSWORD", None) # type: Optional[str] - self.DATABASE_HOST = getattr(_config, "DATABASE_HOST", None) # type: Optional[str] - self.DATABASE_NAME = getattr(_config, "DATABASE_NAME", None) # type: Optional[str] - - try: - self.ADJECTIVES = _config.ADJECTIVES # type: str - except AttributeError: - pass - - try: - self.NOUNS = _config.NOUNS # type: str - except AttributeError: - pass - - try: - self.GPG_KEY_DIR = _config.GPG_KEY_DIR # type: str - except AttributeError: - pass - - try: - self.JOURNALIST_KEY = _config.JOURNALIST_KEY # type: str - except AttributeError: - pass - - try: - self.JOURNALIST_TEMPLATES_DIR = _config.JOURNALIST_TEMPLATES_DIR # type: str - except AttributeError: - pass - - try: - self.SCRYPT_GPG_PEPPER = _config.SCRYPT_GPG_PEPPER # type: str - except AttributeError: - pass - - try: - self.SCRYPT_ID_PEPPER = _config.SCRYPT_ID_PEPPER # type: str - except AttributeError: - pass - - try: - self.SCRYPT_PARAMS = _config.SCRYPT_PARAMS # type: Dict[str, int] - except AttributeError: - pass - - try: - self.SECUREDROP_DATA_ROOT = _config.SECUREDROP_DATA_ROOT # type: str - except AttributeError: - pass - - try: - self.SECUREDROP_ROOT = _config.SECUREDROP_ROOT # type: str - except AttributeError: - pass - - self.SESSION_EXPIRATION_MINUTES: int = getattr(_config, "SESSION_EXPIRATION_MINUTES", 120) - - try: - self.SOURCE_TEMPLATES_DIR = _config.SOURCE_TEMPLATES_DIR # type: str - except AttributeError: - pass - - try: - self.TEMP_DIR = _config.TEMP_DIR # type: str - except AttributeError: - pass - - try: - self.STORE_DIR = _config.STORE_DIR # type: str - except AttributeError: - pass - - try: - self.WORKER_PIDFILE = _config.WORKER_PIDFILE # type: str - except AttributeError: - pass - - self.env = getattr(_config, "env", "prod") # type: str - if self.env == "test": - self.RQ_WORKER_NAME = "test" # type: str - else: - self.RQ_WORKER_NAME = "default" - - # Config entries used by i18n.py - # Use en_US as the default locale if the key is not defined in _config - self.DEFAULT_LOCALE = getattr( - _config, - "DEFAULT_LOCALE", - FALLBACK_LOCALE, - ) # type: str - supported_locales = set( - getattr(_config, "SUPPORTED_LOCALES", [self.DEFAULT_LOCALE]) - ) # type: Set[str] - supported_locales.add(self.DEFAULT_LOCALE) - self.SUPPORTED_LOCALES = sorted(list(supported_locales)) - - translation_dirs_in_conf = getattr(_config, "TRANSLATION_DIRS", None) # type: Optional[str] - if translation_dirs_in_conf: - self.TRANSLATION_DIRS = Path(translation_dirs_in_conf) # type: Path - else: - try: - self.TRANSLATION_DIRS = Path(_config.SECUREDROP_ROOT) / "translations" - except AttributeError: - pass + +@dataclass(frozen=True) +class _FlaskAppConfig: + """Config fields that are common to the Journalist and Source interfaces.""" + + SESSION_COOKIE_NAME: str + SECRET_KEY: str + + DEBUG: bool + TESTING: bool + WTF_CSRF_ENABLED: bool + + # Use MAX_CONTENT_LENGTH to mimic the behavior of Apache's LimitRequestBody + # in the development environment. See #1714. + MAX_CONTENT_LENGTH: int + + # This is recommended for performance, and also resolves #369 + USE_X_SENDFILE: bool + + +@dataclass(frozen=True) +class JournalistInterfaceConfig(_FlaskAppConfig): + # Additional config for JI Redis sessions + SESSION_SIGNER_SALT: str = "js_session" + SESSION_KEY_PREFIX: str = "js_session:" + SESSION_LIFETIME: int = 2 * 60 * 60 + SESSION_RENEW_COUNT: int = 5 + + +@dataclass(frozen=True) +class SourceInterfaceConfig(_FlaskAppConfig): + pass + + +@dataclass(frozen=True) +class SecureDropConfig: + JOURNALIST_APP_FLASK_CONFIG_CLS: JournalistInterfaceConfig + SOURCE_APP_FLASK_CONFIG_CLS: SourceInterfaceConfig + + GPG_KEY_DIR: Path + JOURNALIST_KEY: str + SCRYPT_GPG_PEPPER: str + SCRYPT_ID_PEPPER: str + SCRYPT_PARAMS: Dict[str, int] + + SECUREDROP_DATA_ROOT: Path + + DATABASE_ENGINE: str + DATABASE_FILE: Path + + # The following fields cannot be None if the DB engine is NOT sqlite + DATABASE_USERNAME: Optional[str] + DATABASE_PASSWORD: Optional[str] + DATABASE_HOST: Optional[str] + DATABASE_NAME: Optional[str] + + SECUREDROP_ROOT: Path + STATIC_DIR: Path + TRANSLATION_DIRS: Path + SOURCE_TEMPLATES_DIR: Path + JOURNALIST_TEMPLATES_DIR: Path + NOUNS: Path + ADJECTIVES: Path + + DEFAULT_LOCALE: str + SUPPORTED_LOCALES: List[str] + + SESSION_EXPIRATION_MINUTES: float + + RQ_WORKER_NAME: str + + @property + def TEMP_DIR(self) -> Path: + # We use a directory under the SECUREDROP_DATA_ROOT instead of `/tmp` because + # we need to expose this directory via X-Send-File, and want to minimize the + # potential for exposing unintended files. + return self.SECUREDROP_DATA_ROOT / "tmp" + + @property + def STORE_DIR(self) -> Path: + return self.SECUREDROP_DATA_ROOT / "store" @property def DATABASE_URI(self) -> str: if self.DATABASE_ENGINE == "sqlite": - db_uri = self.DATABASE_ENGINE + ":///" + self.DATABASE_FILE + db_uri = f"{self.DATABASE_ENGINE}:///{self.DATABASE_FILE}" + else: if self.DATABASE_USERNAME is None: raise RuntimeError("Missing DATABASE_USERNAME entry from config.py") @@ -173,5 +117,137 @@ def DATABASE_URI(self) -> str: ) return db_uri - -config = SDConfig() # type: SDConfig + @classmethod + def get_current(cls) -> "SecureDropConfig": + global _current_config + if _current_config is None: + # Retrieve the config by parsing it from ./config.py + _current_config = _parse_config_from_file(config_module_name="config") + return _current_config + + +_current_config: Optional[SecureDropConfig] = None + + +def _parse_config_from_file(config_module_name: str) -> SecureDropConfig: + """Parse the config from a config.py file.""" + config_from_local_file = import_module(config_module_name) + + # Parse the local config; as there are SD instances with very old config files + # the parsing logic here has to assume some values might be missing, and hence + # set default values for such config entries + final_db_engine = getattr(config_from_local_file, "DATABASE_ENGINE", "sqlite") + final_db_username = getattr(config_from_local_file, "DATABASE_USERNAME", None) + final_db_password = getattr(config_from_local_file, "DATABASE_PASSWORD", None) + final_db_host = getattr(config_from_local_file, "DATABASE_HOST", None) + final_db_name = getattr(config_from_local_file, "DATABASE_NAME", None) + + final_default_locale = getattr(config_from_local_file, "DEFAULT_LOCALE", FALLBACK_LOCALE) + final_supp_locales = getattr(config_from_local_file, "SUPPORTED_LOCALES", [FALLBACK_LOCALE]) + final_sess_expiration_mins = getattr(config_from_local_file, "SESSION_EXPIRATION_MINUTES", 120) + + final_worker_name = getattr(config_from_local_file, "RQ_WORKER_NAME", "default") + + final_scrypt_params = getattr( + config_from_local_file, "SCRYPT_PARAMS", dict(N=2**14, r=8, p=1) + ) + + try: + final_securedrop_root = Path(config_from_local_file.SECUREDROP_ROOT) + except AttributeError: + final_securedrop_root = DEFAULT_SECUREDROP_ROOT + + try: + final_securedrop_data_root = Path(config_from_local_file.SECUREDROP_DATA_ROOT) + except AttributeError: + final_securedrop_data_root = Path("/var/lib/securedrop") + + try: + final_db_file = Path(config_from_local_file.DATABASE_FILE) + except AttributeError: + final_db_file = final_securedrop_data_root / "db.sqlite" + + try: + final_gpg_key_dir = Path(config_from_local_file.GPG_KEY_DIR) + except AttributeError: + final_gpg_key_dir = final_securedrop_data_root / "keys" + + try: + final_nouns = Path(config_from_local_file.NOUNS) + except AttributeError: + final_nouns = final_securedrop_root / "dictionaries" / "nouns.txt" + + try: + final_adjectives = Path(config_from_local_file.ADJECTIVES) + except AttributeError: + final_adjectives = final_securedrop_root / "dictionaries" / "adjectives.txt" + + try: + final_static_dir = Path(config_from_local_file.STATIC_DIR) # type: ignore + except AttributeError: + final_static_dir = final_securedrop_root / "static" + + try: + final_transl_dir = Path(config_from_local_file.TRANSLATION_DIRS) # type: ignore + except AttributeError: + final_transl_dir = final_securedrop_root / "translations" + + try: + final_source_tmpl_dir = Path(config_from_local_file.SOURCE_TEMPLATES_DIR) + except AttributeError: + final_source_tmpl_dir = final_securedrop_root / "source_templates" + + try: + final_journ_tmpl_dir = Path(config_from_local_file.JOURNALIST_TEMPLATES_DIR) + except AttributeError: + final_journ_tmpl_dir = final_securedrop_root / "journalist_templates" + + # Parse the Flask configurations + journ_flask_config = config_from_local_file.JournalistInterfaceFlaskConfig + parsed_journ_flask_config = JournalistInterfaceConfig( + SECRET_KEY=journ_flask_config.SECRET_KEY, + SESSION_COOKIE_NAME=getattr(journ_flask_config, "SESSION_COOKIE_NAME", "js"), + DEBUG=getattr(journ_flask_config, "DEBUG", False), + TESTING=getattr(journ_flask_config, "TESTING", False), + WTF_CSRF_ENABLED=getattr(journ_flask_config, "WTF_CSRF_ENABLED", True), + MAX_CONTENT_LENGTH=getattr(journ_flask_config, "MAX_CONTENT_LENGTH", 524288000), + USE_X_SENDFILE=getattr(journ_flask_config, "USE_X_SENDFILE", False), + ) + source_flask_config = config_from_local_file.SourceInterfaceFlaskConfig + parsed_source_flask_config = SourceInterfaceConfig( + SECRET_KEY=source_flask_config.SECRET_KEY, + SESSION_COOKIE_NAME=getattr(journ_flask_config, "SESSION_COOKIE_NAME", "ss"), + DEBUG=getattr(journ_flask_config, "DEBUG", False), + TESTING=getattr(journ_flask_config, "TESTING", False), + WTF_CSRF_ENABLED=getattr(journ_flask_config, "WTF_CSRF_ENABLED", True), + MAX_CONTENT_LENGTH=getattr(journ_flask_config, "MAX_CONTENT_LENGTH", 524288000), + USE_X_SENDFILE=getattr(journ_flask_config, "USE_X_SENDFILE", False), + ) + + return SecureDropConfig( + JOURNALIST_APP_FLASK_CONFIG_CLS=parsed_journ_flask_config, + SOURCE_APP_FLASK_CONFIG_CLS=parsed_source_flask_config, + GPG_KEY_DIR=final_gpg_key_dir, + JOURNALIST_KEY=config_from_local_file.JOURNALIST_KEY, + SCRYPT_GPG_PEPPER=config_from_local_file.SCRYPT_GPG_PEPPER, + SCRYPT_ID_PEPPER=config_from_local_file.SCRYPT_ID_PEPPER, + SCRYPT_PARAMS=final_scrypt_params, + SECUREDROP_DATA_ROOT=final_securedrop_data_root, + SECUREDROP_ROOT=final_securedrop_root, + DATABASE_ENGINE=final_db_engine, + DATABASE_FILE=final_db_file, + DATABASE_USERNAME=final_db_username, + DATABASE_PASSWORD=final_db_password, + DATABASE_HOST=final_db_host, + DATABASE_NAME=final_db_name, + STATIC_DIR=final_static_dir, + TRANSLATION_DIRS=final_transl_dir, + SOURCE_TEMPLATES_DIR=final_source_tmpl_dir, + JOURNALIST_TEMPLATES_DIR=final_journ_tmpl_dir, + NOUNS=final_nouns, + ADJECTIVES=final_adjectives, + DEFAULT_LOCALE=final_default_locale, + SUPPORTED_LOCALES=final_supp_locales, + SESSION_EXPIRATION_MINUTES=final_sess_expiration_mins, + RQ_WORKER_NAME=final_worker_name, + ) diff --git a/securedrop/source.py b/securedrop/source.py --- a/securedrop/source.py +++ b/securedrop/source.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- - -from sdconfig import config +from sdconfig import SecureDropConfig from source_app import create_app -app = create_app(config) - - if __name__ == "__main__": # pragma: no cover + config = SecureDropConfig.get_current() + app = create_app(config) debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host app.run(debug=debug, host="0.0.0.0", port=8080) # nosec diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -1,6 +1,5 @@ import os import time -from os import path from pathlib import Path from typing import Optional, Tuple @@ -14,7 +13,7 @@ from flask_wtf.csrf import CSRFError, CSRFProtect from models import InstanceConfig from request_that_secures_file_uploads import RequestThatSecuresFileUploads -from sdconfig import SDConfig +from sdconfig import SecureDropConfig from source_app import api, info, main from source_app.decorators import ignore_static from source_app.utils import clear_session_and_redirect_to_logged_out_page @@ -36,11 +35,11 @@ def get_logo_url(app: Flask) -> str: raise FileNotFoundError -def create_app(config: SDConfig) -> Flask: +def create_app(config: SecureDropConfig) -> Flask: app = Flask( __name__, - template_folder=config.SOURCE_TEMPLATES_DIR, - static_folder=path.join(config.SECUREDROP_ROOT, "static"), + template_folder=str(config.SOURCE_TEMPLATES_DIR.absolute()), + static_folder=config.STATIC_DIR.absolute(), ) app.request_class = RequestThatSecuresFileUploads app.config.from_object(config.SOURCE_APP_FLASK_CONFIG_CLS) @@ -118,7 +117,7 @@ def internal_error(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: # Obscure the creation time of source private keys by touching them all # on startup. - private_keys = Path(config.GPG_KEY_DIR) / "private-keys-v1.d" + private_keys = config.GPG_KEY_DIR / "private-keys-v1.d" now = time.time() for entry in os.scandir(private_keys): if not entry.is_file() or not entry.name.endswith(".key"): diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -5,11 +5,11 @@ import version from flask import Blueprint, make_response from models import InstanceConfig -from sdconfig import SDConfig +from sdconfig import SecureDropConfig from source_app.utils import get_sourcev3_url -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint(config: SecureDropConfig) -> Blueprint: view = Blueprint("api", __name__) @view.route("/metadata") diff --git a/securedrop/source_app/info.py b/securedrop/source_app/info.py --- a/securedrop/source_app/info.py +++ b/securedrop/source_app/info.py @@ -6,11 +6,11 @@ from encryption import EncryptionManager from flask import Blueprint, redirect, render_template, send_file, url_for from flask_babel import gettext -from sdconfig import SDConfig +from sdconfig import SecureDropConfig from source_app.utils import flash_msg, get_sourcev3_url -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint(config: SecureDropConfig) -> Blueprint: view = Blueprint("info", __name__) @view.route("/tor2web-warning") diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -24,7 +24,7 @@ from flask_babel import gettext from models import InstanceConfig, Reply, Submission, get_one_or_else from passphrases import DicewarePassphrase, PassphraseGenerator -from sdconfig import SDConfig +from sdconfig import SecureDropConfig from source_app.decorators import login_required from source_app.forms import LoginForm, SubmissionForm from source_app.session_manager import SessionManager @@ -45,7 +45,7 @@ from store import Storage -def make_blueprint(config: SDConfig) -> Blueprint: +def make_blueprint(config: SecureDropConfig) -> Blueprint: view = Blueprint("main", __name__) @view.route("/") diff --git a/securedrop/source_app/session_manager.py b/securedrop/source_app/session_manager.py --- a/securedrop/source_app/session_manager.py +++ b/securedrop/source_app/session_manager.py @@ -3,6 +3,7 @@ import sqlalchemy from flask import session +from sdconfig import SecureDropConfig from source_user import InvalidPassphraseError, SourceUser, authenticate_source_user if TYPE_CHECKING: @@ -36,9 +37,6 @@ class SessionManager: def log_user_in( cls, db_session: sqlalchemy.orm.Session, supplied_passphrase: "DicewarePassphrase" ) -> SourceUser: - # Late import so the module can be used without a config.py in the parent folder - from sdconfig import config - # Validate the passphrase; will raise an exception if it is not valid source_user = authenticate_source_user( db_session=db_session, supplied_passphrase=supplied_passphrase @@ -48,6 +46,7 @@ def log_user_in( session[cls._SESSION_COOKIE_KEY_FOR_CODENAME] = supplied_passphrase # Save the session expiration date in the user's session cookie + config = SecureDropConfig.get_current() session_duration = timedelta(minutes=config.SESSION_EXPIRATION_MINUTES) session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] = ( datetime.now(timezone.utc) + session_duration diff --git a/securedrop/source_user.py b/securedrop/source_user.py --- a/securedrop/source_user.py +++ b/securedrop/source_user.py @@ -8,6 +8,7 @@ import models from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf import scrypt +from sdconfig import SecureDropConfig from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session @@ -169,11 +170,9 @@ def derive_source_filesystem_id(self, source_passphrase: "DicewarePassphrase") - @classmethod def get_default(cls) -> "_SourceScryptManager": - # Late import so _SourceScryptManager can be used without a config.py in the parent folder - from sdconfig import config - global _default_scrypt_mgr if _default_scrypt_mgr is None: + config = SecureDropConfig.get_current() _default_scrypt_mgr = cls( salt_for_gpg_secret=config.SCRYPT_GPG_PEPPER.encode("utf-8"), salt_for_filesystem_id=config.SCRYPT_ID_PEPPER.encode("utf-8"), @@ -216,11 +215,10 @@ def generate_journalist_designation(self) -> str: @classmethod def get_default(cls) -> "_DesignationGenerator": - # Late import so _SourceScryptManager can be used without a config.py in the parent folder - from sdconfig import config - global _default_designation_generator if _default_designation_generator is None: + config = SecureDropConfig.get_current() + # Parse the nouns and adjectives files from the config nouns = Path(config.NOUNS).read_text().strip().splitlines() adjectives = Path(config.ADJECTIVES).read_text().strip().splitlines() diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -12,6 +12,7 @@ import rm from encryption import EncryptionManager from flask import current_app +from sdconfig import SecureDropConfig from secure_tempfile import SecureTemporaryFile from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker @@ -111,12 +112,10 @@ def __init__(self, storage_path: str, temp_dir: str) -> None: @classmethod def get_default(cls) -> "Storage": - from sdconfig import config - global _default_storage - if _default_storage is None: - _default_storage = cls(config.STORE_DIR, config.TEMP_DIR) + config = SecureDropConfig.get_current() + _default_storage = cls(str(config.STORE_DIR), str(config.TEMP_DIR)) return _default_storage @@ -386,8 +385,7 @@ def save_message_submission( def async_add_checksum_for_file(db_obj: "Union[Submission, Reply]", storage: Storage) -> str: - from sdconfig import config - + config = SecureDropConfig.get_current() return create_queue(config.RQ_WORKER_NAME).enqueue( queued_add_checksum_for_file, type(db_obj),
diff --git a/securedrop/tests/config_from_2014.py b/securedrop/tests/config_from_2014.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/config_from_2014.py @@ -0,0 +1,84 @@ +"""This file contains the oldest config.py file available from Securedrop's Git repo, at +https://github.com/freedomofpress/securedrop/blob/5aa8a4432949201893afbac0f506c60d93fa7483 +/securedrop/config.py.example + +We use it to ensure that we can parse very old config files. +""" +import os + + +# Default values for production, may be overridden later based on environment +class FlaskConfig(object): + DEBUG = False + TESTING = False + WTF_CSRF_ENABLED = True + + +# Use different secret keys for the two different applications so their +# sessions can't be confused. +# TODO consider using salts instead: http://pythonhosted.org//itsdangerous/#the-salt +class SourceInterfaceFlaskConfig(FlaskConfig): + SECRET_KEY = "{{ source_secret_key }}" + + +class JournalistInterfaceFlaskConfig(FlaskConfig): + SECRET_KEY = "{{ journalist_secret_key }}" + + +# These files are in the same directory as config.py. Use absolute paths to +# avoid potential problems with the test runner - otherwise, you have to be in +# this directory when you run the code. +CODE_ROOT = os.path.dirname(os.path.realpath(__file__)) + +SOURCE_TEMPLATES_DIR = os.path.join(CODE_ROOT, "source_templates") +JOURNALIST_TEMPLATES_DIR = os.path.join(CODE_ROOT, "journalist_templates") +WORD_LIST = os.path.join(CODE_ROOT, "wordlist") +NOUNS = os.path.join(CODE_ROOT, "dictionaries/nouns.txt") +ADJECTIVES = os.path.join(CODE_ROOT, "./dictionaries/adjectives.txt") + +JOURNALIST_PIDFILE = "/tmp/journalist.pid" +SOURCE_PIDFILE = "/tmp/source.pid" + +# "head -c 32 /dev/urandom | base64" for constructing public ID from source codename +SCRYPT_ID_PEPPER = "{{ scrypt_id_pepper }}" +# "head -c 32 /dev/urandom | base64" for stretching source codename into GPG passphrase +SCRYPT_GPG_PEPPER = "{{ scrypt_gpg_pepper }}" +SCRYPT_PARAMS = dict(N=2**14, r=8, p=1) + +# Fingerprint of the public key to use for encrypting submissions +# Defaults to test_journalist_key.pub, which is used for development and testing +JOURNALIST_KEY = "{{ journalist_key }}" + +# Directory where SecureDrop stores the database file, GPG keyring, and +# encrypted submissions. +SECUREDROP_ROOT = "{{ securedrop_root }}" + +# Modify configuration for alternative environments +env = os.environ.get("SECUREDROP_ENV") or "prod" + +if env == "prod": + pass +elif env == "dev": + # Enable Flask's debugger for development + FlaskConfig.DEBUG = False +elif env == "test": + FlaskConfig.TESTING = True + # Disable CSRF checks for tests to make writing tests easier + FlaskConfig.WTF_CSRF_ENABLED = False + # TODO use a unique temporary directory for each test so we can parallelize them + SECUREDROP_ROOT = "/tmp/securedrop" + +# The following configuration is dependent on SECUREDROP_ROOT + +# Directory where encrypted submissions are stored +STORE_DIR = os.path.join(SECUREDROP_ROOT, "store") + +# Directory where GPG keyring is stored +GPG_KEY_DIR = os.path.join(SECUREDROP_ROOT, "keys") + +# Database configuration +# TODO we currently use sqlite in production since it is sufficient and simple, +# but in the future may want to be able to choose a different database +# depending on the environment +DATABASE_ENGINE = "sqlite" +DATABASE_FILE = os.path.join(SECUREDROP_ROOT, "db.sqlite") diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -7,10 +7,10 @@ import subprocess from os import path from pathlib import Path -from tempfile import TemporaryDirectory from typing import Any, Dict, Generator, Tuple from unittest import mock from unittest.mock import PropertyMock +from uuid import uuid4 import models import pretty_bad_protocol as gnupg @@ -24,12 +24,12 @@ from journalist_app import create_app as create_journalist_app from passphrases import PassphraseGenerator from pyotp import TOTP -from sdconfig import SDConfig +from sdconfig import DEFAULT_SECUREDROP_ROOT, SecureDropConfig from source_app import create_app as create_source_app from source_user import _SourceScryptManager, create_source_user from store import Storage from tests import utils -from tests.functional.sd_config_v2 import DEFAULT_SECUREDROP_ROOT +from tests.factories import SecureDropConfigFactory from tests.utils import i18n # Quiet down gnupg output. (See Issue #2595) @@ -127,40 +127,24 @@ def setup_journalist_key_and_gpg_folder() -> Generator[Tuple[str, Path], None, N def config( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, str], -) -> Generator[SDConfig, None, None]: - config = SDConfig() +) -> Generator[SecureDropConfig, None, None]: journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - config.GPG_KEY_DIR = str(gpg_key_dir) - config.JOURNALIST_KEY = journalist_key_fingerprint - - # Setup the filesystem for the application - with TemporaryDirectory() as data_dir_name: - data_dir = Path(data_dir_name) - config.SECUREDROP_DATA_ROOT = str(data_dir) - - store_dir = data_dir / "store" - store_dir.mkdir() - config.STORE_DIR = str(store_dir) - - tmp_dir = data_dir / "tmp" - tmp_dir.mkdir() - config.TEMP_DIR = str(tmp_dir) - - # Create the db file - sqlite_db_path = data_dir / "db.sqlite" - config.DATABASE_FILE = str(sqlite_db_path) - subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) - - config.SUPPORTED_LOCALES = i18n.get_test_locales() - - # Set this newly-created config as the "global" config - with mock.patch.object(sdconfig, "config", config): + worker_name, _ = setup_rqworker + config = SecureDropConfigFactory.create( + SECUREDROP_DATA_ROOT=Path(f"/tmp/sd-tests/conftest-{uuid4()}"), + GPG_KEY_DIR=gpg_key_dir, + JOURNALIST_KEY=journalist_key_fingerprint, + SUPPORTED_LOCALES=i18n.get_test_locales(), + RQ_WORKER_NAME=worker_name, + ) - yield config + # Set this newly-created config as the current config + with mock.patch.object(sdconfig.SecureDropConfig, "get_current", return_value=config): + yield config @pytest.fixture(scope="function") -def alembic_config(config: SDConfig) -> str: +def alembic_config(config: SecureDropConfig) -> str: base_dir = path.join(path.dirname(__file__), "..") migrations_dir = path.join(base_dir, "alembic") ini = configparser.ConfigParser() @@ -169,26 +153,20 @@ def alembic_config(config: SDConfig) -> str: ini.set("alembic", "script_location", path.join(migrations_dir)) ini.set("alembic", "sqlalchemy.url", config.DATABASE_URI) - alembic_path = path.join(config.SECUREDROP_DATA_ROOT, "alembic.ini") + alembic_path = config.SECUREDROP_DATA_ROOT / "alembic.ini" with open(alembic_path, "w") as f: ini.write(f) - return alembic_path + return str(alembic_path) @pytest.fixture(scope="function") -def app_storage(config: SDConfig) -> "Storage": - return Storage(config.STORE_DIR, config.TEMP_DIR) +def app_storage(config: SecureDropConfig) -> "Storage": + return Storage(str(config.STORE_DIR), str(config.TEMP_DIR)) @pytest.fixture(scope="function") -def source_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, None]: - config.SOURCE_APP_FLASK_CONFIG_CLS.TESTING = True - config.SOURCE_APP_FLASK_CONFIG_CLS.USE_X_SENDFILE = False - - # Disable CSRF checks to make writing tests easier - config.SOURCE_APP_FLASK_CONFIG_CLS.WTF_CSRF_ENABLED = False - +def source_app(config: SecureDropConfig, app_storage: Storage) -> Generator[Flask, None, None]: with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = app_storage app = create_source_app(config) @@ -203,13 +181,7 @@ def source_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, @pytest.fixture(scope="function") -def journalist_app(config: SDConfig, app_storage: Storage) -> Generator[Flask, None, None]: - config.JOURNALIST_APP_FLASK_CONFIG_CLS.TESTING = True - config.JOURNALIST_APP_FLASK_CONFIG_CLS.USE_X_SENDFILE = False - - # Disable CSRF checks to make writing tests easier - config.JOURNALIST_APP_FLASK_CONFIG_CLS.WTF_CSRF_ENABLED = False - +def journalist_app(config: SecureDropConfig, app_storage: Storage) -> Generator[Flask, None, None]: with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = app_storage app = create_journalist_app(config) diff --git a/securedrop/tests/functional/factories.py b/securedrop/tests/factories.py similarity index 59% rename from securedrop/tests/functional/factories.py rename to securedrop/tests/factories.py --- a/securedrop/tests/functional/factories.py +++ b/securedrop/tests/factories.py @@ -3,8 +3,13 @@ from pathlib import Path from typing import List, Optional +from sdconfig import ( + DEFAULT_SECUREDROP_ROOT, + JournalistInterfaceConfig, + SecureDropConfig, + SourceInterfaceConfig, +) from tests.functional.db_session import _get_fake_db_module -from tests.functional.sd_config_v2 import DEFAULT_SECUREDROP_ROOT, FlaskAppConfig, SecureDropConfig from tests.utils.db_helper import reset_database @@ -12,14 +17,30 @@ def _generate_random_token() -> str: return secrets.token_hex(32) -class FlaskAppConfigFactory: +class JournalistInterfaceConfigFactory: @staticmethod - def create(SESSION_COOKIE_NAME: str) -> FlaskAppConfig: - """Create a Flask app config suitable for the unit tests.""" - return FlaskAppConfig( - SESSION_COOKIE_NAME=SESSION_COOKIE_NAME, + def create() -> JournalistInterfaceConfig: + return JournalistInterfaceConfig( + SESSION_COOKIE_NAME="js", SECRET_KEY=_generate_random_token(), TESTING=True, + DEBUG=False, + MAX_CONTENT_LENGTH=524288000, + USE_X_SENDFILE=False, + # Disable CSRF checks to make writing tests easier + WTF_CSRF_ENABLED=False, + ) + + +class SourceInterfaceConfigFactory: + @staticmethod + def create() -> SourceInterfaceConfig: + return SourceInterfaceConfig( + SESSION_COOKIE_NAME="ss", + SECRET_KEY=_generate_random_token(), + TESTING=True, + DEBUG=False, + MAX_CONTENT_LENGTH=524288000, USE_X_SENDFILE=False, # Disable CSRF checks to make writing tests easier WTF_CSRF_ENABLED=False, @@ -34,8 +55,8 @@ def create( JOURNALIST_KEY: str, RQ_WORKER_NAME: str, SESSION_EXPIRATION_MINUTES: float = 120, - NOUNS: Path = DEFAULT_SECUREDROP_ROOT / "dictionaries" / "nouns.txt", - ADJECTIVES: Path = DEFAULT_SECUREDROP_ROOT / "dictionaries" / "adjectives.txt", + NOUNS: Optional[Path] = None, + ADJECTIVES: Optional[Path] = None, SUPPORTED_LOCALES: Optional[List[str]] = None, DEFAULT_LOCALE: str = "en_US", TRANSLATION_DIRS: Path = DEFAULT_SECUREDROP_ROOT / "translations", @@ -51,24 +72,30 @@ def create( SECUREDROP_DATA_ROOT.mkdir(parents=True) database_file = SECUREDROP_DATA_ROOT / "db.sqlite" + dictionaries_path = DEFAULT_SECUREDROP_ROOT / "dictionaries" + config = SecureDropConfig( SESSION_EXPIRATION_MINUTES=SESSION_EXPIRATION_MINUTES, - SECUREDROP_DATA_ROOT=str(SECUREDROP_DATA_ROOT), - DATABASE_FILE=str(database_file), + SECUREDROP_DATA_ROOT=SECUREDROP_DATA_ROOT, SECUREDROP_ROOT=DEFAULT_SECUREDROP_ROOT, + DATABASE_FILE=database_file, DATABASE_ENGINE="sqlite", - JOURNALIST_APP_FLASK_CONFIG_CLS=FlaskAppConfigFactory.create(SESSION_COOKIE_NAME="js"), - SOURCE_APP_FLASK_CONFIG_CLS=FlaskAppConfigFactory.create(SESSION_COOKIE_NAME="ss"), + DATABASE_USERNAME=None, + DATABASE_PASSWORD=None, + DATABASE_HOST=None, + DATABASE_NAME=None, + JOURNALIST_APP_FLASK_CONFIG_CLS=JournalistInterfaceConfigFactory.create(), + SOURCE_APP_FLASK_CONFIG_CLS=SourceInterfaceConfigFactory.create(), SCRYPT_GPG_PEPPER=_generate_random_token(), SCRYPT_ID_PEPPER=_generate_random_token(), SCRYPT_PARAMS=dict(N=2**14, r=8, p=1), - WORKER_PIDFILE="/tmp/securedrop_test_worker.pid", - NOUNS=str(NOUNS), - ADJECTIVES=str(ADJECTIVES), RQ_WORKER_NAME=RQ_WORKER_NAME, - GPG_KEY_DIR=str(GPG_KEY_DIR), + NOUNS=NOUNS if NOUNS else dictionaries_path / "nouns.txt", + ADJECTIVES=ADJECTIVES if ADJECTIVES else dictionaries_path / "adjectives.txt", + GPG_KEY_DIR=GPG_KEY_DIR, JOURNALIST_KEY=JOURNALIST_KEY, SUPPORTED_LOCALES=SUPPORTED_LOCALES if SUPPORTED_LOCALES is not None else ["en_US"], + STATIC_DIR=DEFAULT_SECUREDROP_ROOT / "static", TRANSLATION_DIRS=TRANSLATION_DIRS, SOURCE_TEMPLATES_DIR=DEFAULT_SECUREDROP_ROOT / "source_templates", JOURNALIST_TEMPLATES_DIR=DEFAULT_SECUREDROP_ROOT / "journalist_templates", @@ -81,8 +108,8 @@ def create( initialized_db_module.create_all() # Create the other directories - Path(config.TEMP_DIR).mkdir(parents=True) - Path(config.STORE_DIR).mkdir(parents=True) + config.TEMP_DIR.mkdir(parents=True) + config.STORE_DIR.mkdir(parents=True) # All done return config diff --git a/securedrop/tests/functional/conftest.py b/securedrop/tests/functional/conftest.py --- a/securedrop/tests/functional/conftest.py +++ b/securedrop/tests/functional/conftest.py @@ -12,11 +12,11 @@ import pytest import requests from models import Journalist +from sdconfig import SecureDropConfig from selenium.webdriver.firefox.webdriver import WebDriver from source_user import SourceUser +from tests.factories import SecureDropConfigFactory from tests.functional.db_session import get_database_session -from tests.functional.factories import SecureDropConfigFactory -from tests.functional.sd_config_v2 import SecureDropConfig from tests.functional.web_drivers import WebDriverTypeEnum, get_web_driver @@ -45,16 +45,13 @@ def _get_unused_port() -> int: def _start_source_server(port: int, config_to_use: SecureDropConfig) -> None: # This function will be called in a separate Process that runs the source app # Modify the sdconfig module in the app's memory so that it mirrors the supplied config - # Do this BEFORE importing any other module of the application so the modified config is - # what eventually gets imported by the app's code import sdconfig + from source_app import create_app - sdconfig.config = config_to_use # type: ignore + sdconfig._current_config = config_to_use # Then start the source app - from source_app import create_app - - source_app = create_app(config_to_use) # type: ignore + source_app = create_app(config_to_use) source_app.run(port=port, debug=True, use_reloader=False, threaded=True) @@ -65,20 +62,17 @@ def _start_journalist_server( ) -> None: # This function will be called in a separate Process that runs the journalist app # Modify the sdconfig module in the app's memory so that it mirrors the supplied config - # Do this BEFORE importing any other module of the application so the modified config is - # what eventually gets imported by the app's code import sdconfig - - sdconfig.config = config_to_use # type: ignore - - # Then start the journalist app from journalist_app import create_app + sdconfig._current_config = config_to_use + # Some tests require a specific state to be set (such as having a submission) if journalist_app_setup_callback: journalist_app_setup_callback(config_to_use) - journalist_app = create_app(config_to_use) # type: ignore + # Then start the journalist app + journalist_app = create_app(config_to_use) journalist_app.run(port=port, debug=True, use_reloader=False, threaded=True) diff --git a/securedrop/tests/functional/pageslayout/test_journalist_col.py b/securedrop/tests/functional/pageslayout/test_journalist_col.py --- a/securedrop/tests/functional/pageslayout/test_journalist_col.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_col.py @@ -20,11 +20,11 @@ from uuid import uuid4 import pytest +from sdconfig import SecureDropConfig +from tests.factories import SecureDropConfigFactory from tests.functional.app_navigators.journalist_app_nav import JournalistAppNavigator from tests.functional.conftest import SdServersFixtureResult, spawn_sd_servers -from tests.functional.factories import SecureDropConfigFactory from tests.functional.pageslayout.utils import list_locales, save_screenshot_and_html -from tests.functional.sd_config_v2 import SecureDropConfig def _create_source_and_submission_and_delete_source_key(config_in_use: SecureDropConfig) -> None: diff --git a/securedrop/tests/functional/pageslayout/test_source_session_layout.py b/securedrop/tests/functional/pageslayout/test_source_session_layout.py --- a/securedrop/tests/functional/pageslayout/test_source_session_layout.py +++ b/securedrop/tests/functional/pageslayout/test_source_session_layout.py @@ -3,9 +3,9 @@ from typing import Generator, Tuple import pytest +from tests.factories import SecureDropConfigFactory from tests.functional.app_navigators.source_app_nav import SourceAppNavigator from tests.functional.conftest import SdServersFixtureResult, spawn_sd_servers -from tests.functional.factories import SecureDropConfigFactory from tests.functional.pageslayout.utils import list_locales, save_screenshot_and_html # Very short session expiration time diff --git a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py --- a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py +++ b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py @@ -1,5 +1,3 @@ -from pathlib import Path - import pytest from encryption import EncryptionManager from selenium.common.exceptions import NoSuchElementException @@ -53,7 +51,7 @@ def test_submit_and_retrieve_happy_path( apps_sd_config = sd_servers_with_clean_state.config_in_use retrieved_message = journ_app_nav.journalist_downloads_first_message( encryption_mgr_to_use_for_decryption=EncryptionManager( - gpg_key_dir=Path(apps_sd_config.GPG_KEY_DIR), + gpg_key_dir=apps_sd_config.GPG_KEY_DIR, journalist_key_fingerprint=apps_sd_config.JOURNALIST_KEY, ) ) diff --git a/securedrop/tests/functional/sd_config_v2.py b/securedrop/tests/functional/sd_config_v2.py deleted file mode 100644 --- a/securedrop/tests/functional/sd_config_v2.py +++ /dev/null @@ -1,107 +0,0 @@ -from dataclasses import dataclass, field -from pathlib import Path -from typing import Dict, List, Optional - - -@dataclass(frozen=True) -class FlaskAppConfig: - SESSION_COOKIE_NAME: str - SECRET_KEY: str - - DEBUG: bool = False - TESTING: bool = False - WTF_CSRF_ENABLED: bool = True - - # Use MAX_CONTENT_LENGTH to mimic the behavior of Apache's LimitRequestBody - # in the development environment. See #1714. - MAX_CONTENT_LENGTH: int = 524288000 - - # This is recommended for performance, and also resolves #369 - USE_X_SENDFILE: bool = True - - # additional config for JI Redis sessions - SESSION_SIGNER_SALT: str = "js_session" - SESSION_KEY_PREFIX: str = "js_session:" - SESSION_LIFETIME: int = 2 * 60 * 60 - SESSION_RENEW_COUNT: int = 5 - - -DEFAULT_SECUREDROP_ROOT = Path(__file__).absolute().parent.parent.parent - - -# TODO(AD): This mirrors the field in an SDConfig; it is intended to eventually replace it -@dataclass(frozen=True) -class SecureDropConfig: - JOURNALIST_APP_FLASK_CONFIG_CLS: FlaskAppConfig - SOURCE_APP_FLASK_CONFIG_CLS: FlaskAppConfig - - GPG_KEY_DIR: str - JOURNALIST_KEY: str - SCRYPT_GPG_PEPPER: str - SCRYPT_ID_PEPPER: str - SCRYPT_PARAMS: Dict[str, int] - - SECUREDROP_DATA_ROOT: str - - DATABASE_ENGINE: str - DATABASE_FILE: str - - # The following fields are required if the DB engine is NOT sqlite - DATABASE_USERNAME: Optional[str] = None - DATABASE_PASSWORD: Optional[str] = None - DATABASE_HOST: Optional[str] = None - DATABASE_NAME: Optional[str] = None - - SECUREDROP_ROOT: str = str(DEFAULT_SECUREDROP_ROOT) - TRANSLATION_DIRS: Path = DEFAULT_SECUREDROP_ROOT / "translations" - SOURCE_TEMPLATES_DIR: str = str(DEFAULT_SECUREDROP_ROOT / "source_templates") - JOURNALIST_TEMPLATES_DIR: str = str(DEFAULT_SECUREDROP_ROOT / "journalist_templates") - NOUNS: str = str(DEFAULT_SECUREDROP_ROOT / "dictionaries" / "nouns.txt") - ADJECTIVES: str = str(DEFAULT_SECUREDROP_ROOT / "dictionaries" / "adjectives.txt") - - DEFAULT_LOCALE: str = "en_US" - SUPPORTED_LOCALES: List[str] = field(default_factory=lambda: ["en_US"]) - - SESSION_EXPIRATION_MINUTES: float = 120 - - WORKER_PIDFILE: str = "/tmp/securedrop_worker.pid" - RQ_WORKER_NAME: str = "default" - - @property - def TEMP_DIR(self) -> str: - # We use a directory under the SECUREDROP_DATA_ROOT instead of `/tmp` because - # we need to expose this directory via X-Send-File, and want to minimize the - # potential for exposing unintended files. - return str(Path(self.SECUREDROP_DATA_ROOT) / "tmp") - - @property - def STORE_DIR(self) -> str: - return str(Path(self.SECUREDROP_DATA_ROOT) / "store") - - @property - def DATABASE_URI(self) -> str: - if self.DATABASE_ENGINE == "sqlite": - db_uri = f"{self.DATABASE_ENGINE}:///{self.DATABASE_FILE}" - - else: - if self.DATABASE_USERNAME is None: - raise RuntimeError("Missing DATABASE_USERNAME entry from config.py") - if self.DATABASE_PASSWORD is None: - raise RuntimeError("Missing DATABASE_PASSWORD entry from config.py") - if self.DATABASE_HOST is None: - raise RuntimeError("Missing DATABASE_HOST entry from config.py") - if self.DATABASE_NAME is None: - raise RuntimeError("Missing DATABASE_NAME entry from config.py") - - db_uri = ( - self.DATABASE_ENGINE - + "://" - + self.DATABASE_USERNAME - + ":" - + self.DATABASE_PASSWORD - + "@" - + self.DATABASE_HOST - + "/" - + self.DATABASE_NAME - ) - return db_uri diff --git a/securedrop/tests/functional/test_admin_interface.py b/securedrop/tests/functional/test_admin_interface.py --- a/securedrop/tests/functional/test_admin_interface.py +++ b/securedrop/tests/functional/test_admin_interface.py @@ -5,17 +5,17 @@ import pytest from models import Journalist +from sdconfig import SecureDropConfig from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.support import expected_conditions +from tests.factories import SecureDropConfigFactory from tests.functional.app_navigators.journalist_app_nav import JournalistAppNavigator from tests.functional.app_navigators.source_app_nav import SourceAppNavigator from tests.functional.conftest import SdServersFixtureResult, spawn_sd_servers from tests.functional.db_session import get_database_session -from tests.functional.factories import SecureDropConfigFactory -from tests.functional.sd_config_v2 import SecureDropConfig class TestAdminInterfaceAddUser: diff --git a/securedrop/tests/functional/test_journalist.py b/securedrop/tests/functional/test_journalist.py --- a/securedrop/tests/functional/test_journalist.py +++ b/securedrop/tests/functional/test_journalist.py @@ -20,16 +20,16 @@ from uuid import uuid4 import pytest +from sdconfig import SecureDropConfig from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys +from tests.factories import SecureDropConfigFactory from tests.functional.app_navigators.journalist_app_nav import JournalistAppNavigator from tests.functional.conftest import ( SdServersFixtureResult, create_source_and_submission, spawn_sd_servers, ) -from tests.functional.factories import SecureDropConfigFactory -from tests.functional.sd_config_v2 import SecureDropConfig class TestJournalist: diff --git a/securedrop/tests/functional/test_sd_config_v2.py b/securedrop/tests/functional/test_sd_config_v2.py deleted file mode 100644 --- a/securedrop/tests/functional/test_sd_config_v2.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Set - -from tests.functional.factories import SecureDropConfigFactory - - -def _get_public_attributes(obj: object) -> Set[str]: - attributes = set(attr_name for attr_name in dir(obj) if not attr_name.startswith("_")) - return attributes - - -class TestSecureDropConfigV2: - def test_v1_and_v2_have_the_same_attributes(self, config, tmp_path): - sd_config_v1 = config - sd_config_v2 = SecureDropConfigFactory.create( - SECUREDROP_DATA_ROOT=tmp_path, - RQ_WORKER_NAME="", - GPG_KEY_DIR=tmp_path, - JOURNALIST_KEY="", - ) - - attributes_in_sd_config_v1 = _get_public_attributes(sd_config_v1) - attributes_in_sd_config_v1.remove("env") # Legacy attribute that's not needed in v2 - attributes_in_sd_config_v2 = _get_public_attributes(sd_config_v2) - - assert attributes_in_sd_config_v1 == attributes_in_sd_config_v2 diff --git a/securedrop/tests/functional/test_source_designation_collision.py b/securedrop/tests/functional/test_source_designation_collision.py --- a/securedrop/tests/functional/test_source_designation_collision.py +++ b/securedrop/tests/functional/test_source_designation_collision.py @@ -1,9 +1,9 @@ from pathlib import Path import pytest +from tests.factories import SecureDropConfigFactory from tests.functional.app_navigators.source_app_nav import SourceAppNavigator from tests.functional.conftest import spawn_sd_servers -from tests.functional.factories import SecureDropConfigFactory @pytest.fixture(scope="session") diff --git a/securedrop/tests/functional/test_submit_and_retrieve_message.py b/securedrop/tests/functional/test_submit_and_retrieve_message.py --- a/securedrop/tests/functional/test_submit_and_retrieve_message.py +++ b/securedrop/tests/functional/test_submit_and_retrieve_message.py @@ -1,5 +1,3 @@ -from pathlib import Path - from encryption import EncryptionManager from tests.functional.app_navigators.journalist_app_nav import JournalistAppNavigator from tests.functional.app_navigators.source_app_nav import SourceAppNavigator @@ -42,7 +40,7 @@ def test_submit_and_retrieve_happy_path( servers_sd_config = sd_servers_with_clean_state.config_in_use retrieved_message = journ_app_nav.journalist_downloads_first_message( encryption_mgr_to_use_for_decryption=EncryptionManager( - gpg_key_dir=Path(servers_sd_config.GPG_KEY_DIR), + gpg_key_dir=servers_sd_config.GPG_KEY_DIR, journalist_key_fingerprint=servers_sd_config.JOURNALIST_KEY, ) ) diff --git a/securedrop/tests/migrations/migration_b58139cfdc8c.py b/securedrop/tests/migrations/migration_b58139cfdc8c.py --- a/securedrop/tests/migrations/migration_b58139cfdc8c.py +++ b/securedrop/tests/migrations/migration_b58139cfdc8c.py @@ -126,7 +126,7 @@ def __init__(self, config): # as this class requires access to the Storage object, which is no longer # attached to app, we create it here and mock the call to return it below. - self.storage = Storage(config.STORE_DIR, config.TEMP_DIR) + self.storage = Storage(str(config.STORE_DIR), str(config.TEMP_DIR)) def load_data(self): global DATA diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -11,7 +11,9 @@ from alembic.script import ScriptDirectory from db import db from journalist_app import create_app +from sdconfig import SecureDropConfig from sqlalchemy import text +from tests.utils.db_helper import reset_database MIGRATION_PATH = path.join(path.dirname(__file__), "..", "alembic", "versions") @@ -22,6 +24,13 @@ WHITESPACE_REGEX = re.compile(r"\s+") [email protected](scope="function") +def _reset_db(config: SecureDropConfig) -> None: + # The config fixture creates all the models in the DB, but most alembic tests expect an + # empty DB, so we reset the DB via this fixture + reset_database(config.DATABASE_FILE) + + def list_migrations(cfg_path, head): cfg = AlembicConfig(cfg_path) script = ScriptDirectory.from_config(cfg) @@ -108,10 +117,7 @@ def test_alembic_head_matches_db_models(journalist_app, alembic_config, config): """ models_schema = get_schema(journalist_app) - os.remove(config.DATABASE_FILE) - - # Create database file - subprocess.check_call(["sqlite3", config.DATABASE_FILE, ".databases"]) + reset_database(config.DATABASE_FILE) upgrade(alembic_config, "head") # Recreate the app to get a new SQLALCHEMY_DATABASE_URI @@ -126,13 +132,13 @@ def test_alembic_head_matches_db_models(journalist_app, alembic_config, config): @pytest.mark.parametrize("migration", ALL_MIGRATIONS) -def test_alembic_migration_up_and_down(alembic_config, config, migration): +def test_alembic_migration_up_and_down(alembic_config, config, migration, _reset_db): upgrade(alembic_config, migration) downgrade(alembic_config, "base") @pytest.mark.parametrize("migration", ALL_MIGRATIONS) -def test_schema_unchanged_after_up_then_downgrade(alembic_config, config, migration): +def test_schema_unchanged_after_up_then_downgrade(alembic_config, config, migration, _reset_db): # Create the app here. Using a fixture will init the database. app = create_app(config) @@ -164,7 +170,7 @@ def test_schema_unchanged_after_up_then_downgrade(alembic_config, config, migrat @pytest.mark.parametrize("migration", ALL_MIGRATIONS) -def test_upgrade_with_data(alembic_config, config, migration): +def test_upgrade_with_data(alembic_config, config, migration, _reset_db): migrations = list_migrations(alembic_config, migration) if len(migrations) == 1: # Degenerate case where there is no data for the first migration @@ -190,7 +196,7 @@ def test_upgrade_with_data(alembic_config, config, migration): @pytest.mark.parametrize("migration", ALL_MIGRATIONS) -def test_downgrade_with_data(alembic_config, config, migration): +def test_downgrade_with_data(alembic_config, config, migration, _reset_db): # Upgrade to the target upgrade(alembic_config, migration) diff --git a/securedrop/tests/test_config.py b/securedrop/tests/test_config.py --- a/securedrop/tests/test_config.py +++ b/securedrop/tests/test_config.py @@ -1,47 +1,26 @@ -import importlib - -import config as _config - - -def test_missing_config_attribute_is_handled(): - """ - Test handling of incomplete configurations. - - Long-running SecureDrop instances might not have ever updated - config.py, so could be missing newer settings. This tests that - sdconfig.SDConfig can be initialized without error with such a - configuration. - """ - attributes_to_test = ( - "JournalistInterfaceFlaskConfig", - "SourceInterfaceFlaskConfig", - "DATABASE_ENGINE", - "DATABASE_FILE", - "ADJECTIVES", - "NOUNS", - "GPG_KEY_DIR", - "JOURNALIST_KEY", - "JOURNALIST_TEMPLATES_DIR", - "SCRYPT_GPG_PEPPER", - "SCRYPT_ID_PEPPER", - "SCRYPT_PARAMS", - "SECUREDROP_DATA_ROOT", - "SECUREDROP_ROOT", - "SESSION_EXPIRATION_MINUTES", - "SOURCE_TEMPLATES_DIR", - "TEMP_DIR", - "STORE_DIR", - "WORKER_PIDFILE", - ) +from pathlib import Path - try: - importlib.reload(_config) +from sdconfig import _parse_config_from_file + + +def test_parse_2014_config(): + # Given a config file from 2014 + config_module_from_2014 = "tests.config_from_2014" - for a in attributes_to_test: - delattr(_config, a) + # When trying to parse it, it succeeds + assert _parse_config_from_file(config_module_from_2014) + + +def test_parse_current_config(): + # Given a config file that is current; copy the example file to a proper Python module + current_sample_config = Path(__file__).absolute().parent.parent / "config.py.example" + current_config_module = "config_current" + current_config_file = Path(__file__).absolute().parent / f"{current_config_module}.py" + try: + current_config_file.write_text(current_sample_config.read_text()) - from sdconfig import SDConfig + # When trying to parse it, it succeeds + assert _parse_config_from_file(f"tests.{current_config_module}") - SDConfig() finally: - importlib.reload(_config) + current_config_file.unlink(missing_ok=True) diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -31,9 +31,8 @@ from flask import render_template, render_template_string, request, session from flask_babel import gettext from i18n import parse_locale_set -from sdconfig import FALLBACK_LOCALE -from tests.functional.factories import SecureDropConfigFactory -from tests.functional.sd_config_v2 import DEFAULT_SECUREDROP_ROOT, SecureDropConfig +from sdconfig import DEFAULT_SECUREDROP_ROOT, FALLBACK_LOCALE, SecureDropConfig +from tests.factories import SecureDropConfigFactory from werkzeug.datastructures import Headers NEVER_LOCALE = "eo" # Esperanto diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -10,6 +10,7 @@ from base64 import b64decode from io import BytesIO from pathlib import Path +from typing import Tuple import journalist_app as journalist_app_module import models @@ -17,7 +18,7 @@ from db import db from encryption import EncryptionManager, GpgKeyNotFoundError from flaky import flaky -from flask import current_app, escape, g, url_for +from flask import escape, g, url_for from flask_babel import gettext, ngettext from journalist_app.sessions import session from journalist_app.utils import mark_seen @@ -37,20 +38,21 @@ ) from passphrases import PassphraseGenerator from pyotp import TOTP -from sdconfig import config +from source_user import create_source_user from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import StaleDataError from sqlalchemy.sql.expression import func - -from . import utils -from .utils.i18n import ( +from store import Storage +from tests import utils +from tests.factories import SecureDropConfigFactory +from tests.utils.i18n import ( get_plural_tests, get_test_locales, language_tag, page_language, xfail_untranslated_messages, ) -from .utils.instrument import InstrumentedApp +from tests.utils.instrument import InstrumentedApp # Smugly seed the RNG for deterministic testing random.seed(r"¯\_(ツ)_/¯") @@ -1732,7 +1734,7 @@ def test_admin_add_user_too_short_username(config, journalist_app, test_admin, l if i != 0 ), ) -def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, secret): +def test_admin_add_user_yubikey_odd_length(config, journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: _login_user( app, @@ -1770,7 +1772,7 @@ def test_admin_add_user_yubikey_odd_length(journalist_app, test_admin, locale, s "locale, secret", ((locale, " " * i) for locale in get_test_locales() for i in range(3)), ) -def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, secret): +def test_admin_add_user_yubikey_blank_secret(config, journalist_app, test_admin, locale, secret): with journalist_app.test_client() as app: _login_user( app, @@ -1802,7 +1804,7 @@ def test_admin_add_user_yubikey_blank_secret(journalist_app, test_admin, locale, @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) -def test_admin_add_user_yubikey_valid_length(journalist_app, test_admin, locale): +def test_admin_add_user_yubikey_valid_length(config, journalist_app, test_admin, locale): otp = "1234567890123456789012345678901234567890" with journalist_app.test_client() as app: @@ -1836,7 +1838,9 @@ def test_admin_add_user_yubikey_valid_length(journalist_app, test_admin, locale) @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) -def test_admin_add_user_yubikey_correct_length_with_whitespace(journalist_app, test_admin, locale): +def test_admin_add_user_yubikey_correct_length_with_whitespace( + config, journalist_app, test_admin, locale +): otp = "12 34 56 78 90 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90" with journalist_app.test_client() as app: @@ -2326,7 +2330,7 @@ def test_orgname_oversized_fails(config, journalist_app, test_admin, locale): assert InstanceConfig.get_current().organization_name == "SecureDrop" -def test_logo_default_available(journalist_app): +def test_logo_default_available(journalist_app, config): # if the custom image is available, this test will fail custom_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/custom_logo.png") if os.path.exists(custom_image_location): @@ -2774,7 +2778,7 @@ def test_valid_user_first_last_name_change(config, journalist_app, test_journo, @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize("locale", get_test_locales()) -def test_valid_user_invalid_first_last_name_change(journalist_app, test_journo, locale): +def test_valid_user_invalid_first_last_name_change(config, journalist_app, test_journo, locale): with journalist_app.test_client() as app: overly_long_name = "a" * (Journalist.MAX_NAME_LEN + 1) _login_user( @@ -3077,37 +3081,48 @@ def test_login_with_invalid_password_doesnt_call_argon2(mocker, test_journo): assert not mock_argon2.called -def test_render_locales(config, journalist_app, test_journo, test_source): +def test_render_locales( + setup_journalist_key_and_gpg_folder: Tuple[str, Path], + setup_rqworker: Tuple[str, str], +) -> None: """the locales.html template must collect both request.args (l=XX) and request.view_args (/<filesystem_id>) to build the URL to change the locale """ - - # We use the `journalist_app` fixture to generate all our tables, but we - # don't use it during the test because we need to inject the i18n settings - # (which are only triggered during `create_app` - config.SUPPORTED_LOCALES = ["en_US", "fr_FR"] - app = journalist_app_module.create_app(config) + journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder + worker_name, _ = setup_rqworker + config_with_fr_locale = SecureDropConfigFactory.create( + SECUREDROP_DATA_ROOT=Path(f"/tmp/sd-tests/render_locales"), + GPG_KEY_DIR=gpg_key_dir, + JOURNALIST_KEY=journalist_key_fingerprint, + SUPPORTED_LOCALES=["en_US", "fr_FR"], + RQ_WORKER_NAME=worker_name, + ) + app = journalist_app_module.create_app(config_with_fr_locale) app.config["SERVER_NAME"] = "localhost.localdomain" # needed for url_for - url = url_for("col.col", filesystem_id=test_source["filesystem_id"]) + with app.app_context(): + journo_user, journo_pw = utils.db_helper.init_journalist(is_admin=False) + source_user = create_source_user( + db_session=db.session, + source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), + source_app_storage=Storage( + str(config_with_fr_locale.STORE_DIR), str(config_with_fr_locale.TEMP_DIR) + ), + ) - # we need the relative URL, not the full url including proto / localhost - url_end = url.replace("http://", "") - url_end = url_end[url_end.index("/") + 1 :] + url = url_for("col.col", filesystem_id=source_user.filesystem_id) + # we need the relative URL, not the full url including proto / localhost + url_end = url.replace("http://", "") + url_end = url_end[url_end.index("/") + 1 :] - with app.test_client() as app: - _login_user( - app, - test_journo["username"], - test_journo["password"], - test_journo["otp_secret"], - ) - resp = app.get(url + "?l=fr_FR") + with app.test_client() as app: + _login_user(app, journo_user.username, journo_pw, journo_user.otp_secret) + resp = app.get(url + "?l=fr_FR") - # check that links to i18n URLs are/aren't present - text = resp.data.decode("utf-8") - assert "?l=fr_FR" not in text, text - assert url_end + "?l=en_US" in text, text + # check that links to i18n URLs are/aren't present + text = resp.data.decode("utf-8") + assert "?l=fr_FR" not in text, text + assert url_end + "?l=en_US" in text, text def test_download_selected_submissions_and_replies( diff --git a/securedrop/tests/test_manage.py b/securedrop/tests/test_manage.py --- a/securedrop/tests/test_manage.py +++ b/securedrop/tests/test_manage.py @@ -6,6 +6,7 @@ import logging import os import time +from pathlib import Path import manage import mock @@ -140,26 +141,21 @@ def test_get_username_to_delete(mocker): def test_reset(journalist_app, test_journo, alembic_config, config): - original_config = manage.config - try: - # We need to override the config to point at the per-test DB - manage.config = config - with journalist_app.app_context() as context: - # Override the hardcoded alembic.ini value - manage.config.TEST_ALEMBIC_INI = alembic_config - - args = argparse.Namespace(store_dir=config.STORE_DIR) - return_value = manage.reset(args=args, context=context) - - assert return_value == 0 - assert os.path.exists(config.DATABASE_FILE) - assert os.path.exists(config.STORE_DIR) - - # Verify journalist user present in the database is gone - res = Journalist.query.filter_by(username=test_journo["username"]).one_or_none() - assert res is None - finally: - manage.config = original_config + with journalist_app.app_context() as context: + args = argparse.Namespace(store_dir=config.STORE_DIR) + # We have to override the hardcoded alembic .ini file because during testing + # the value in the .ini doesn't exist. + return_value = manage.reset( + args=args, alembic_ini_path=Path(alembic_config), context=context + ) + + assert return_value == 0 + assert config.DATABASE_FILE.exists() + assert config.STORE_DIR.exists() + + # Verify journalist user present in the database is gone + res = Journalist.query.filter_by(username=test_journo["username"]).one_or_none() + assert res is None def test_get_username(mocker): diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -85,6 +85,7 @@ def test_journalist_filters(): def do_test(create_app): test_config = create_config_for_i18n_test(supported_locales=["en_US", "fr_FR"]) + i18n_dir = Path(__file__).absolute().parent / "i18n" i18n_tool.I18NTool().main( [ diff --git a/securedrop/tests/utils/i18n.py b/securedrop/tests/utils/i18n.py --- a/securedrop/tests/utils/i18n.py +++ b/securedrop/tests/utils/i18n.py @@ -11,7 +11,7 @@ from babel.messages.pofile import read_po from bs4 import BeautifulSoup from flask_babel import force_locale -from sdconfig import SDConfig +from sdconfig import SecureDropConfig @functools.lru_cache(maxsize=None) @@ -73,7 +73,7 @@ def page_language(page_text: str) -> Optional[str]: @contextlib.contextmanager def xfail_untranslated_messages( - config: SDConfig, locale: str, msgids: Iterable[str] + config: SecureDropConfig, locale: str, msgids: Iterable[str] ) -> Generator[None, None, None]: """ Trigger pytest.xfail for untranslated strings.
legacy `config.py` files may prevent the web applications from starting or break functionality ## Description See #5757 - instances without the SESSION_EXPIRY_MINUTES attribute defined in `config.py` were failing to start after a code update that assumed all required attributes were defined was pushed. This was fixed in #5759 but other problems may lurk in older config files. It might be worth: - looking at historical updates to `config.py` to figure out what attributes were added and when, and making sure they're handled correctly in future code updates - figuring out how to better manage app config (@heartsucker had a long-running PR for this that I can't find now - another option is to move more attributes into the database) - figuring out how to update `config.py` to a valid state during an application update
Old PR by @heartsucker: https://github.com/freedomofpress/securedrop/pull/3850 Old, related issue: #1966 During the 1.7.0 release postmortem, other suggestions were proposed by the team: - Testing historical possible versions of config.py - Separating the configuration between private (salts, secrets) configuration and public (common configuration) - Move as much configuration as possible to the database - Add logic to the restore script, to "update" the configuration to the update the configuration with the latest/expected values Given the complexity of this logic, but also the state being different across instances based on when the instance was first set up (config.py is carried over via backups but is not touched by the application role on subsequent installs), we should perform a timeboxed investigation to carefully review the current implementation, and propose next steps (which may include one or more tasks included in this thread)
2022-09-25T08:51:27Z
[]
[]
freedomofpress/securedrop
6,580
freedomofpress__securedrop-6580
[ "6547" ]
7833d0037a72a2337ed6898f0d533a7fe10f8f15
diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -18,7 +18,6 @@ from typing import Dict, List, Optional, Set import version -from sh import git, msgfmt, msgmerge, pybabel, xgettext logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger(__name__) @@ -59,10 +58,10 @@ def ensure_i18n_remote(self, args: argparse.Namespace) -> None: Make sure we have a git remote for the i18n repo. """ - k = {"_cwd": args.root} - if b"i18n" not in git.remote(**k).stdout: - git.remote.add("i18n", args.url, **k) - git.fetch("i18n", **k) + k = {"cwd": args.root} + if "i18n" not in subprocess.check_output(["git", "remote"], encoding="utf-8", **k): + subprocess.check_call(["git", "remote", "add", "i18n", args.url], **k) + subprocess.check_call(["git", "fetch", "i18n"], **k) def translate_messages(self, args: argparse.Namespace) -> None: messages_file = Path(args.translations_dir).absolute() / "messages.pot" @@ -71,22 +70,26 @@ def translate_messages(self, args: argparse.Namespace) -> None: if not os.path.exists(args.translations_dir): os.makedirs(args.translations_dir) sources = args.sources.split(",") - pybabel.extract( - "--charset=utf-8", - "--mapping", - args.mapping, - "--output", - str(messages_file), - "--project=SecureDrop", - "--version", - args.version, - "[email protected]", - "--copyright-holder=Freedom of the Press Foundation", - "--add-comments=Translators:", - "--strip-comments", - "--add-location=never", - "--no-wrap", - *sources, + subprocess.check_call( + [ + "pybabel", + "extract", + "--charset=utf-8", + "--mapping", + args.mapping, + "--output", + messages_file, + "--project=SecureDrop", + "--version", + args.version, + "[email protected]", + "--copyright-holder=Freedom of the Press Foundation", + "--add-comments=Translators:", + "--strip-comments", + "--add-location=never", + "--no-wrap", + *sources, + ] ) msg_file_content = messages_file.read_text() @@ -101,31 +104,42 @@ def translate_messages(self, args: argparse.Namespace) -> None: ): tglob = "{}/*/LC_MESSAGES/*.po".format(args.translations_dir) for translation in glob.iglob(tglob): - msgmerge("--previous", "--update", "--no-wrap", translation, messages_file) + subprocess.check_call( + [ + "msgmerge", + "--previous", + "--update", + "--no-wrap", + translation, + messages_file, + ] + ) log.warning(f"messages translations updated in {messages_file}") else: log.warning("messages translations are already up to date") if args.compile and len(os.listdir(args.translations_dir)) > 1: - pybabel.compile("--directory", args.translations_dir) + subprocess.check_call(["pybabel", "compile", "--directory", args.translations_dir]) def translate_desktop(self, args: argparse.Namespace) -> None: messages_file = Path(args.translations_dir).absolute() / "desktop.pot" if args.extract_update: sources = args.sources.split(",") - k = {"_cwd": args.translations_dir} - xgettext( - "--output=desktop.pot", - "--language=Desktop", - "--keyword", - "--keyword=Name", - "--package-version", - args.version, - "[email protected]", - "--copyright-holder=Freedom of the Press Foundation", - *sources, - **k, + subprocess.check_call( + [ + "xgettext", + "--output=desktop.pot", + "--language=Desktop", + "--keyword", + "--keyword=Name", + "--package-version", + args.version, + "[email protected]", + "--copyright-holder=Freedom of the Press Foundation", + *sources, + ], + cwd=args.translations_dir, ) msg_file_content = messages_file.read_text() updated_content = _remove_from_content_line_with_text( @@ -138,7 +152,7 @@ def translate_desktop(self, args: argparse.Namespace) -> None: if not f.endswith(".po"): continue po_file = os.path.join(args.translations_dir, f) - msgmerge("--update", po_file, messages_file) + subprocess.check_call(["msgmerge", "--update", po_file, messages_file]) log.warning(f"messages translations updated in {messages_file}") else: log.warning("desktop translations are already up to date") @@ -153,15 +167,18 @@ def translate_desktop(self, args: argparse.Namespace) -> None: for source in args.sources.split(","): target = source.rstrip(".in") - msgfmt( - "--desktop", - "--template", - source, - "-o", - target, - "-d", - ".", - _cwd=args.translations_dir, + subprocess.check_call( + [ + "msgfmt", + "--desktop", + "--template", + source, + "-o", + target, + "-d", + ".", + ], + cwd=args.translations_dir, ) self.sort_desktop_template(join(args.translations_dir, target)) finally: @@ -263,12 +280,11 @@ def update_docs(self, args: argparse.Namespace) -> None: io.open(l10n_txt, mode="w").write(l10n_content) self.require_git_email_name(includes) if self.file_is_modified(l10n_txt): - k = {"_cwd": includes} - git.add("l10n.txt", **k) + subprocess.check_call(["git", "add", "l10n.txt"], cwd=includes) msg = "docs: update the list of supported languages" - git.commit("-m", msg, "l10n.txt", **k) + subprocess.check_call(["git", "commit", "-m", msg, "l10n.txt"], cwd=includes) log.warning(l10n_txt + " updated") - git_show_out = git.show(**k) + git_show_out = subprocess.check_output(["git", "show"], encoding="utf-8", cwd=includes) log.warning(git_show_out) else: log.warning(l10n_txt + " already up to date") @@ -289,13 +305,15 @@ def update_from_weblate(self, args: argparse.Namespace) -> None: self.ensure_i18n_remote(args) # Check out *all* remote changes to the LOCALE_DIRs. - git( - "-C", - args.root, - "checkout", - args.target, - "--", - *LOCALE_DIR.values(), + subprocess.check_call( + [ + "git", + "checkout", + args.target, + "--", + *LOCALE_DIR.values(), + ], + cwd=args.root, ) # Use the LOCALE_DIR corresponding to the "securedrop" component to @@ -314,7 +332,7 @@ def add(path: str) -> None: """ Add the file to the git index. """ - git("-C", args.root, "add", path) + subprocess.check_call(["git", "add", path], cwd=args.root) paths.append(path) # Any translated locale may have changes that need to be staged from the @@ -364,7 +382,7 @@ def translators( log_command.extend([args.target, "--", path]) - log_lines = subprocess.check_output(log_command).decode("utf-8").strip().split("\n") + log_lines = subprocess.check_output(log_command, encoding="utf-8").strip().splitlines() path_changes = [c.split("\x1e") for c in log_lines] path_changes = [ c @@ -380,9 +398,8 @@ def get_path_commits(self, root: str, path: str) -> List[str]: """ Returns the list of commit hashes involving the path, most recent first. """ - return git( - "--no-pager", "-C", root, "log", "--format=%H", path, _encoding="utf-8" - ).splitlines() + cmd = ["git", "--no-pager", "log", "--format=%H", path] + return subprocess.check_output(cmd, encoding="utf-8", cwd=root).splitlines() def translated_locales(self, path: str) -> Dict[str, str]: """Return a dictionary of all locale directories present in `path`, where the keys @@ -396,9 +413,8 @@ def commit_changes( """Check if any of the given paths have had changed staged. If so, commit them.""" self.require_git_email_name(args.root) authors = set() # type: Set[str] - diffs = "{}".format( - git("--no-pager", "-C", args.root, "diff", "--name-only", "--cached", *paths) - ) + cmd = ["git", "--no-pager", "diff", "--name-only", "--cached", *paths] + diffs = subprocess.check_output(cmd, cwd=args.root, encoding="utf-8") # If nothing was changed, "git commit" will return nonzero as a no-op. if len(diffs) == 0: @@ -413,8 +429,10 @@ def commit_changes( path_commits = self.get_path_commits(args.root, path) since_commit = None for path_commit in path_commits: - commit_message = "{}".format( - git("--no-pager", "-C", args.root, "show", path_commit, _encoding="utf-8") + commit_message = subprocess.check_output( + ["git", "--no-pager", "show", path_commit], + encoding="utf-8", + cwd=args.root, ) m = self.updated_commit_re.search(commit_message) if m: @@ -425,7 +443,9 @@ def commit_changes( authors_as_str = "\n ".join(sorted(authors)) - current = git("-C", args.root, "rev-parse", args.target) + current = subprocess.check_output( + ["git", "rev-parse", args.target], cwd=args.root, encoding="utf-8" + ) message = textwrap.dedent( """ l10n: updated {name} ({code}) @@ -438,7 +458,8 @@ def commit_changes( commit: {current} """ ).format(remote=args.url, name=name, authors=authors_as_str, code=code, current=current) - git("-C", args.root, "commit", "-m", message, *paths) + subprocess.check_call(["git", "commit", "-m", message, *paths], cwd=args.root) + log.debug(f"Committing with this message: {message}") def set_update_from_weblate_parser(self, subps: _SubParsersAction) -> None: parser = subps.add_parser("update-from-weblate", help=("Import translations from weblate"))
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -17,6 +17,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import re +import subprocess from pathlib import Path from typing import List @@ -31,7 +32,6 @@ from flask_babel import gettext from i18n import parse_locale_set from sdconfig import FALLBACK_LOCALE -from sh import pybabel from tests.functional.factories import SecureDropConfigFactory from tests.functional.sd_config_v2 import DEFAULT_SECUREDROP_ROOT, SecureDropConfig from werkzeug.datastructures import Headers @@ -259,7 +259,7 @@ def test_i18n(): ) pot = translation_dirs / "messages.pot" - pybabel("init", "-i", pot, "-d", translation_dirs, "-l", "en_US") + subprocess.check_call(["pybabel", "init", "-i", pot, "-d", translation_dirs, "-l", "en_US"]) for (locale, translated_msg) in ( ("fr_FR", "code bonjour"), @@ -268,7 +268,7 @@ def test_i18n(): ("nb_NO", "code norwegian"), ("es_ES", "code spanish"), ): - pybabel("init", "-i", pot, "-d", translation_dirs, "-l", locale) + subprocess.check_call(["pybabel", "init", "-i", pot, "-d", translation_dirs, "-l", locale]) # Populate the po file with a translation po_file = translation_dirs / locale / "LC_MESSAGES" / "messages.po" diff --git a/securedrop/tests/test_i18n_tool.py b/securedrop/tests/test_i18n_tool.py --- a/securedrop/tests/test_i18n_tool.py +++ b/securedrop/tests/test_i18n_tool.py @@ -4,6 +4,7 @@ import os import shutil import signal +import subprocess import time from os.path import abspath, dirname, exists, getmtime, join, realpath from pathlib import Path @@ -11,7 +12,6 @@ import i18n_tool import pytest from mock import patch -from sh import git, msginit, pybabel, touch from tests.test_i18n import set_msg_translation_in_po_file @@ -81,8 +81,17 @@ def test_translate_desktop_l10n(self, tmpdir): ("ro", "SOURCE RO"), ]: po_file = Path(tmpdir) / f"{locale}.po" - msginit( - "--no-translator", "--locale", locale, "--output", po_file, "--input", messages_file + subprocess.check_call( + [ + "msginit", + "--no-translator", + "--locale", + locale, + "--output", + po_file, + "--input", + messages_file, + ] ) set_msg_translation_in_po_file( po_file=po_file, @@ -139,7 +148,18 @@ def test_translate_messages_l10n(self, tmpdir): locale = "en_US" locale_dir = join(str(tmpdir), locale) - pybabel("init", "-i", messages_file, "-d", str(tmpdir), "-l", locale) + subprocess.check_call( + [ + "pybabel", + "init", + "-i", + messages_file, + "-d", + str(tmpdir), + "-l", + locale, + ] + ) # Add a dummy translation po_file = Path(locale_dir) / "LC_MESSAGES/messages.po" @@ -185,7 +205,9 @@ def test_translate_messages_compile_arg(self, tmpdir): locale = "en_US" locale_dir = join(str(tmpdir), locale) po_file = join(locale_dir, "LC_MESSAGES/messages.po") - pybabel(["init", "-i", messages_file, "-d", str(tmpdir), "-l", locale]) + subprocess.check_call( + ["pybabel", "init", "-i", messages_file, "-d", str(tmpdir), "-l", locale] + ) assert exists(po_file) # pretend this happened a few seconds ago few_seconds_ago = time.time() - 60 @@ -241,25 +263,25 @@ def test_translate_messages_compile_arg(self, tmpdir): assert b"template hello i18n" not in mo def test_require_git_email_name(self, tmpdir): - k = {"_cwd": str(tmpdir)} - git("init", **k) + k = {"cwd": str(tmpdir)} + subprocess.check_call(["git", "init"], **k) with pytest.raises(Exception) as excinfo: i18n_tool.I18NTool.require_git_email_name(str(tmpdir)) assert "please set name" in str(excinfo.value) - git.config("user.email", "[email protected]", **k) - git.config("user.name", "Your Name", **k) + subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) + subprocess.check_call(["git", "config", "user.name", "Your Name"], **k) assert i18n_tool.I18NTool.require_git_email_name(str(tmpdir)) def test_update_docs(self, tmpdir, caplog): - k = {"_cwd": str(tmpdir)} - git.init(**k) - git.config("user.email", "[email protected]", **k) - git.config("user.name", "Your Name", **k) + k = {"cwd": str(tmpdir)} + subprocess.check_call(["git", "init"], **k) + subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) + subprocess.check_call(["git", "config", "user.name", "Your Name"], **k) os.makedirs(join(str(tmpdir), "docs/includes")) - touch("docs/includes/l10n.txt", **k) - git.add("docs/includes/l10n.txt", **k) - git.commit("-m", "init", **k) + subprocess.check_call(["touch", "docs/includes/l10n.txt"], **k) + subprocess.check_call(["git", "add", "docs/includes/l10n.txt"], **k) + subprocess.check_call(["git", "commit", "-m", "init"], **k) i18n_tool.I18NTool().main(["--verbose", "update-docs", "--docs-repo-dir", str(tmpdir)]) assert "l10n.txt updated" in caplog.text @@ -271,23 +293,23 @@ def test_update_from_weblate(self, tmpdir, caplog): d = str(tmpdir) for repo in ("i18n", "securedrop"): os.mkdir(join(d, repo)) - k = {"_cwd": join(d, repo)} - git.init(**k) - git.config("user.email", "[email protected]", **k) - git.config("user.name", "Loïc Nordhøy", **k) - touch("README.md", **k) - git.add("README.md", **k) - git.commit("-m", "README", "README.md", **k) + k = {"cwd": join(d, repo)} + subprocess.check_call(["git", "init"], **k) + subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) + subprocess.check_call(["git", "config", "user.name", "Loïc Nordhøy"], **k) + subprocess.check_call(["touch", "README.md"], **k) + subprocess.check_call(["git", "add", "README.md"], **k) + subprocess.check_call(["git", "commit", "-m", "README", "README.md"], **k) for o in os.listdir(join(self.dir, "i18n")): f = join(self.dir, "i18n", o) if os.path.isfile(f): shutil.copyfile(f, join(d, "i18n", o)) else: shutil.copytree(f, join(d, "i18n", o)) - k = {"_cwd": join(d, "i18n")} - git.add("securedrop", "install_files", **k) - git.commit("-m", "init", "-a", **k) - git.checkout("-b", "i18n", "master", **k) + k = {"cwd": join(d, "i18n")} + subprocess.check_call(["git", "add", "securedrop", "install_files"], **k) + subprocess.check_call(["git", "commit", "-m", "init", "-a"], **k) + subprocess.check_call(["git", "checkout", "-b", "i18n", "master"], **k) def r(): return "".join([str(l) for l in caplog.records]) @@ -350,7 +372,11 @@ def r(): ) assert "l10n: updated Dutch (nl)" not in r() assert "l10n: updated German (de_DE)" not in r() - message = str(git("--no-pager", "-C", "securedrop", "show", _cwd=d, _encoding="utf-8")) + message = subprocess.check_output( + ["git", "--no-pager", "-C", "securedrop", "show"], + cwd=d, + encoding="utf-8", + ) assert "Loïc" in message # an update is done to nl in weblate @@ -362,14 +388,15 @@ def r(): updated_content = content.replace(text_to_update, "INACTIVITEIT") po_file.write_text(updated_content) - git.add(str(po_file), **k) - git.config("user.email", "[email protected]", **k) - git.config("user.name", "Someone Else", **k) - git.commit("-m", "translation change", str(po_file), **k) + k = {"cwd": join(d, "i18n")} + subprocess.check_call(["git", "add", str(po_file)], **k) + subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) + subprocess.check_call(["git", "config", "user.name", "Someone Else"], **k) + subprocess.check_call(["git", "commit", "-m", "translation change", str(po_file)], **k) - k = {"_cwd": join(d, "securedrop")} - git.config("user.email", "[email protected]", **k) - git.config("user.name", "Someone Else", **k) + k = {"cwd": join(d, "securedrop")} + subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) + subprocess.check_call(["git", "config", "user.name", "Someone Else"], **k) # # the nl translation update from weblate is copied @@ -390,6 +417,10 @@ def r(): ) assert "l10n: updated Dutch (nl)" in r() assert "l10n: updated German (de_DE)" not in r() - message = str(git("--no-pager", "-C", "securedrop", "show", _cwd=d)) + message = subprocess.check_output( + ["git", "--no-pager", "-C", "securedrop", "show"], + cwd=d, + encoding="utf-8", + ) assert "Someone Else" in message assert "Loïc" not in message diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -1,3 +1,4 @@ +import subprocess from datetime import datetime, timedelta from pathlib import Path @@ -8,7 +9,6 @@ import template_filters from db import db from flask import session -from sh import pybabel from tests.test_i18n import create_config_for_i18n_test @@ -104,7 +104,7 @@ def do_test(create_app): for l in ("en_US", "fr_FR"): pot = Path(test_config.TEMP_DIR) / "messages.pot" - pybabel("init", "-i", pot, "-d", test_config.TEMP_DIR, "-l", l) + subprocess.check_call(["pybabel", "init", "-i", pot, "-d", test_config.TEMP_DIR, "-l", l]) app = create_app(test_config) with app.app_context():
Remove `sh` dependency *This is a good first issue for new contributors to take on, if you have any questions, please ask on the task or in our [Gitter room](https://gitter.im/freedomofpress/securedrop)!* ## Description `sh` is a pretty cool project, it allows you to shell out to programs as if they were native Python programs. This comes with a downside, it obfuscates the underlying command being run, and it's an extra dependency. Here are all the places we use it: ``` Targets Occurrences of 'from sh import' in Project Found Occurrences in Project (4 usages found) Unclassified (4 usages found) securedrop (4 usages found) securedrop (1 usage found) i18n_tool.py (1 usage found) 19 from sh import git, msgfmt, msgmerge, pybabel, sed, xgettext securedrop/tests (3 usages found) test_i18n.py (1 usage found) 34 from sh import pybabel, sed test_i18n_tool.py (1 usage found) 13 from sh import git, msginit, pybabel, sed, touch test_template_filters.py (1 usage found) 13 from sh import pybabel ``` Given how minimal its usage is (just `i18n_tool.py` plus tests), I propose we replace it with explicit `subprocess.check_output(...)` calls. The biggest advantage of this removal is that `pybabel` will be the only dependency needed to compile translations at package build time.
Hi @legoktm , I would love to work on this issue! Has it been assigned to anyone yet? Thanks! Nope, go for it! Let me know if you have any questions. Before seeing this issue, I had already started removing usages of `sh.sed()` in code that I was touching. I have opened a PR that removes calls to `sed()`: https://github.com/freedomofpress/securedrop/pull/6562 I will not work on other usages of `sh` so this issue is still available. OK, thanks for the heads up! I won't touch those calls, then.
2022-09-29T20:32:46Z
[]
[]
freedomofpress/securedrop
6,586
freedomofpress__securedrop-6586
[ "6582" ]
3036ebbf9d0b49e2b3ad82851b0a38b30b8c2c43
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ long_description=long_description, long_description_content_type="text/markdown", license="AGPLv3+", - python_requires=">=3.5", + python_requires=">=3.8", url="https://github.com/freedomofpress/securedrop", classifiers=( "Development Status :: 5 - Stable",
diff --git a/molecule/builder-focal/tests/test_build_dependencies.py b/molecule/builder-focal/tests/test_build_dependencies.py --- a/molecule/builder-focal/tests/test_build_dependencies.py +++ b/molecule/builder-focal/tests/test_build_dependencies.py @@ -3,7 +3,7 @@ import pytest SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -SECUREDROP_PYTHON_VERSION = os.environ.get("SECUREDROP_PYTHON_VERSION", "3.5") +SECUREDROP_PYTHON_VERSION = os.environ.get("SECUREDROP_PYTHON_VERSION", "3.8") DH_VIRTUALENV_VERSION = "1.2.2" testinfra_hosts = ["docker://{}-sd-app".format(SECUREDROP_TARGET_DISTRIBUTION)]
Clean up outdated references to Python 3.5 *This is a good first issue for new contributors to take on, if you have any questions, please ask on the task or in our [Gitter room](https://gitter.im/freedomofpress/securedrop)!* ## Description SecureDrop now runs on focal, which uses Python 3.8. But there are still references to Python 3.5 that need to be cleaned up. Some should be dropped outright, others should be switched to 3.8. Some examples: ``` $ rg python3\\.5 install_files/securedrop-grsec-focal/opt/securedrop/paxctld.conf 98:/usr/bin/python3.5 E molecule/testinfra/vars/app-qubes-staging.yml 13:securedrop_venv_site_packages: "{{ securedrop_venv }}/lib/python3.5/site-packages" molecule/testinfra/vars/prodVM.yml 12:securedrop_venv_site_packages: "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages" install_files/ansible-base/roles/build-securedrop-app-code-deb-pkg/files/usr.sbin.apache2 71: /etc/python3.5/sitecustomize.py r, 109: /usr/local/lib/python3.5/dist-packages/ r, 117: /opt/venvs/securedrop-app-code/lib/python3.5/ r, 118: /opt/venvs/securedrop-app-code/lib/python3.5/** rm, securedrop/scripts/rqrequeue 9:sys.path.insert(0, "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages") # noqa: E402 securedrop/scripts/shredder 14: 0, "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages" securedrop/scripts/source_deleter 14: 0, "/opt/venvs/securedrop-app-code/lib/python3.5/site-packages" $ rg 3\\.5 --type=py molecule/builder-focal/tests/test_build_dependencies.py 6:SECUREDROP_PYTHON_VERSION = os.environ.get("SECUREDROP_PYTHON_VERSION", "3.5") setup.py 14: python_requires=">=3.5", ```
Hey there can you assign me for this issue @donheshanthaka Go for it!
2022-10-02T16:32:19Z
[]
[]
freedomofpress/securedrop
6,657
freedomofpress__securedrop-6657
[ "6655" ]
3288be8bc43590f6d797bed4610e54ff99cb9648
diff --git a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py --- a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py +++ b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py @@ -8,10 +8,10 @@ import os import uuid +import argon2 import pyotp import sqlalchemy as sa from alembic import op -from passlib.hash import argon2 # raise the errors if we're not in production raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" @@ -33,7 +33,7 @@ def generate_passphrase_hash() -> str: passphrase = PassphraseGenerator.get_default().generate_passphrase() - return argon2.using(**ARGON2_PARAMS).hash(passphrase) + return argon2.PasswordHasher(**ARGON2_PARAMS).hash(passphrase) def create_deleted() -> int: diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -8,6 +8,7 @@ from logging import Logger from typing import Any, Callable, Dict, List, Optional, Union +import argon2 import pyotp import qrcode @@ -20,7 +21,6 @@ from flask import url_for from flask_babel import gettext, ngettext from markupsafe import Markup -from passlib.hash import argon2 from passphrases import PassphraseGenerator from pyotp import HOTP, TOTP from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, LargeBinary, String @@ -35,7 +35,7 @@ if os.environ.get("SECUREDROP_ENV") == "test": LOGIN_HARDENING = False -ARGON2_PARAMS = dict(memory_cost=2**16, rounds=4, parallelism=2) +ARGON2_PARAMS = {"memory_cost": 2**16, "time_cost": 4, "parallelism": 2, "type": argon2.Type.ID} # Required length for hex-format HOTP secrets as input by users HOTP_SECRET_LENGTH = 40 # 160 bits == 40 hex digits (== 32 ascii-encoded chars in db) @@ -479,10 +479,11 @@ def set_password(self, passphrase: "Optional[str]") -> None: self.check_password_acceptable(passphrase) + hasher = argon2.PasswordHasher(**ARGON2_PARAMS) # "migrate" from the legacy case if not self.passphrase_hash: - self.passphrase_hash = argon2.using(**ARGON2_PARAMS).hash(passphrase) - # passlib creates one merged field that embeds randomly generated + self.passphrase_hash = hasher.hash(passphrase) + # argon2 creates one merged field that embeds randomly generated # salt in the output like $alg$salt$hash self.pw_hash = None self.pw_salt = None @@ -491,7 +492,7 @@ def set_password(self, passphrase: "Optional[str]") -> None: if self.passphrase_hash and self.valid_password(passphrase): return - self.passphrase_hash = argon2.using(**ARGON2_PARAMS).hash(passphrase) + self.passphrase_hash = hasher.hash(passphrase) def set_name(self, first_name: Optional[str], last_name: Optional[str]) -> None: if first_name: @@ -550,9 +551,13 @@ def valid_password(self, passphrase: "Optional[str]") -> bool: # No check on minimum password length here because some passwords # may have been set prior to setting the mininum password length. + hasher = argon2.PasswordHasher(**ARGON2_PARAMS) if self.passphrase_hash: # default case - is_valid = argon2.verify(passphrase, self.passphrase_hash) + try: + is_valid = hasher.verify(self.passphrase_hash, passphrase) + except argon2.exceptions.VerificationError: + is_valid = False else: # legacy support if self.pw_salt is None: @@ -567,13 +572,28 @@ def valid_password(self, passphrase: "Optional[str]") -> bool: self._scrypt_hash(passphrase, self.pw_salt), self.pw_hash ) - # migrate new passwords - if is_valid and not self.passphrase_hash: - self.passphrase_hash = argon2.using(**ARGON2_PARAMS).hash(passphrase) - # passlib creates one merged field that embeds randomly generated - # salt in the output like $alg$salt$hash + # If the passphrase isn't valid, bail out now + if not is_valid: + return False + # From here on we can assume the passphrase was valid + + # Perform migration checks + needs_update = False + if self.passphrase_hash: + # Check if the hash needs an update + if hasher.check_needs_rehash(self.passphrase_hash): + self.passphrase_hash = hasher.hash(passphrase) + needs_update = True + else: + # Migrate to an argon2 hash, which creates one merged field + # that embeds randomly generated salt in the output like + # $alg$salt$hash + self.passphrase_hash = hasher.hash(passphrase) self.pw_salt = None self.pw_hash = None + needs_update = True + + if needs_update: db.session.add(self) db.session.commit()
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -2617,6 +2617,7 @@ def test_passphrase_migration_on_verification(journalist_app): # check that the migration happened assert journalist.passphrase_hash is not None + assert journalist.passphrase_hash.startswith("$argon2") assert journalist.pw_salt is None assert journalist.pw_hash is None @@ -2639,6 +2640,7 @@ def test_passphrase_migration_on_reset(journalist_app): # check that the migration happened assert journalist.passphrase_hash is not None + assert journalist.passphrase_hash.startswith("$argon2") assert journalist.pw_salt is None assert journalist.pw_hash is None @@ -2646,6 +2648,19 @@ def test_passphrase_migration_on_reset(journalist_app): assert journalist.valid_password(VALID_PASSWORD) +def test_passphrase_argon2i_migration(test_journo): + """verify argon2i hashes work and then are migrated to argon2id""" + journalist = test_journo["journalist"] + # But use our password hash + journalist.passphrase_hash = ( + "$argon2i$v=19$m=65536,t=4,p=2$JfFkLIJ2ogPUDI19XiBzHA$kaKNVckLLQNNBnmllMWqXg" + ) + db.session.add(journalist) + db.session.commit() + assert journalist.valid_password("correct horse battery staple profanity oil chewy") + assert journalist.passphrase_hash.startswith("$argon2id$") + + def test_journalist_reply_view(journalist_app, test_source, test_journo, app_storage): source, _ = utils.db_helper.init_source(app_storage) journalist, _ = utils.db_helper.init_journalist() @@ -3054,7 +3069,7 @@ def db_assertion(): def test_login_with_invalid_password_doesnt_call_argon2(mocker, test_journo): - mock_argon2 = mocker.patch("models.argon2.verify") + mock_argon2 = mocker.patch("models.argon2.PasswordHasher") invalid_pw = "a" * (Journalist.MAX_PASSWORD_LEN + 1) with pytest.raises(InvalidPasswordLength): @@ -3062,16 +3077,6 @@ def test_login_with_invalid_password_doesnt_call_argon2(mocker, test_journo): assert not mock_argon2.called -def test_valid_login_calls_argon2(mocker, test_journo): - mock_argon2 = mocker.patch("models.argon2.verify") - Journalist.login( - test_journo["username"], - test_journo["password"], - TOTP(test_journo["otp_secret"]).now(), - ) - assert mock_argon2.called - - def test_render_locales(config, journalist_app, test_journo, test_source): """the locales.html template must collect both request.args (l=XX) and request.view_args (/<filesystem_id>) to build the URL to
Journalist passphrases should be hashed with Argon2id instead of Argon2i *Originally filed as https://github.com/freedomofpress/securedrop-security/issues/86* We currently use Argon2i to encrypt journalist passphrases: ``` sqlite> select passphrase_hash from journalists; $argon2i$v=19$m=65536,t=4,p=2$otS6V+rd29u79z6nFAJAaA$fWn/7La/sHiQAM7YPOLo5Q $argon2i$v=19$m=65536,t=4,p=2$VAoBIMSY8957T6lVCsFYKw$Z8vGfVR/P87pNqmn0oz/yg $argon2i$v=19$m=65536,t=4,p=2$Quj9H4PwntPau5fSOgdgjA$qzvLuOzgN86ITlpdepFiJQ ``` However, Argon2id is what's recommended these days, [this SO answer goes into depth and summarizes with](https://security.stackexchange.com/questions/193351/in-2018-what-is-the-recommended-hash-to-store-passwords-bcrypt-scrypt-argon2): > In short: use Argon2id if you can, use Argon2d in almost every other case, consider Argon2i if you really do need memory side-channel attack resistance. Part of the issue here is that we fell behind on upgrading passlib. The latest version of it uses Argon2id by default (our argon2-cffi version already defaults to id).
@lsd-cat wrote: > The is definitely low priority, as our passphrase scheme is safe enough anyway, however of course we better keep updated with the latest standard. Did we do any hash migration in the past? If not how do we want to handle that? @legoktm wrote: > The last password migration we did added a new column and did the rehashing whenever the user logged in ([freedomofpress/securedrop#3506](https://github.com/freedomofpress/securedrop/pull/3506)) > > I think can do roughly the same thing by just looking at the hash prefix, I wrote some pseudo-code at [freedomofpress/securedrop#6631](https://github.com/freedomofpress/securedrop/issues/6631) (public ticket for dropping the passlib dependency). I think it makes sense to tackle both tickets at the same time. > > Given that this is low priority, is it OK to disclose and patch publicly? Or keep it private until close-to-release time? (not 2.5.0 to be clear) @lsd-cat wrote: > I will double check the migration code this week, ok from me to go publicly with it :) @lsd-cat wrote: > +1 in dropping passlib given our use case! @l3th3 wrote: > Also +1 for moving towards argon2id and argon2-cffi. The passlib issues section made me cry :sob:
2022-10-19T19:41:21Z
[]
[]
freedomofpress/securedrop
6,658
freedomofpress__securedrop-6658
[ "6554" ]
3288be8bc43590f6d797bed4610e54ff99cb9648
diff --git a/securedrop/version.py b/securedrop/version.py --- a/securedrop/version.py +++ b/securedrop/version.py @@ -1 +1 @@ -__version__ = "2.5.0~rc1" +__version__ = "2.6.0~rc1" diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ setuptools.setup( name="securedrop-app-code", - version="2.5.0~rc1", + version="2.6.0~rc1", author="Freedom of the Press Foundation", author_email="[email protected]", description="SecureDrop Server",
diff --git a/molecule/builder-focal/tests/vars.yml b/molecule/builder-focal/tests/vars.yml --- a/molecule/builder-focal/tests/vars.yml +++ b/molecule/builder-focal/tests/vars.yml @@ -1,5 +1,5 @@ --- -securedrop_version: "2.5.0~rc1" +securedrop_version: "2.6.0~rc1" ossec_version: "3.6.0" keyring_version: "0.1.6" config_version: "0.1.4"
Release SecureDrop 2.5.0 This is a tracking issue for the release of SecureDrop 2.5.0 # Schedule: **Feature / string freeze:** 2022-09-27 **Pre-release announcement:** 2022-10-04 **Release date:** 2022-10-11 **Release manager:** @zenmonkeykstop **Deputy release manager:** @cfm **Communications manager:** @nathandyer **Deputy CM:** @eloquence **Localization manager:** @cfm **Deputy LM:** @eaon # Testing: QA team: TK Test scenarios: [QA Matrix for 2.5.0](https://docs.google.com/spreadsheets/d/1O8FrIh1UYRgFw8m1AnMw5tVe19TFjpBqE0aaA7rc-iY/edit) _SecureDrop maintainers and testers:_ As you QA 2.5.0, please report back your testing results as comments on this ticket. File GitHub issues for any problems found, tag them "QA: Release", and associate them with the [2.5.0 milestone](https://github.com/freedomofpress/securedrop/milestone/79) for tracking (or ask a maintainer to do so). Test debian packages will be posted on https://apt-test.freedom.press signed with [the test key](https://gist.githubusercontent.com/conorsch/ec4008b111bc3142fca522693f3cce7e/raw/2968621e8ad92db4505a31fcc5776422d7d26729/apt-test%2520apt%2520pubkey) ## Test plan: - [x] #6558 - [x] #6596 - [x] #6637 ## [Test Plan for 2.5.0](https://github.com/freedomofpress/securedrop/wiki/2.5.0-Test-Plan) # Localization management High-level summary of these steps can be found here: https://docs.securedrop.org/en/stable/development/i18n.html#two-weeks-before-the-release-string-freeze Duplicating that content as checkboxes below, for visibility: - [x] Update translations on latest develop, following [docs for i18n procedures](https://docs.securedrop.org/en/stable/development/i18n.html#update-strings-to-be-translated) - [x] Update strings served on Weblate, [following docs](https://docs.securedrop.org/en/stable/development/i18n.html#merge-develop-to-weblate) - [x] [Update Weblate screenshots](https://docs.securedrop.org/en/stable/development/i18n.html#update-weblate-screenshots) so translators can see new or modified source strings in context. - [x] Update the [i18n timeline](https://forum.securedrop.org/t/about-the-translations-category/16) in the translation section of the forum. - [x] Add a [Weblate announcement](https://weblate.securedrop.org/admin/trans/announcement) with the translation timeline for the release. Important: make sure the Notify users box is checked, so that translators receive an email alert. - [x] Remind all developers about the string freeze in [Gitter](https://gitter.im/freedomofpress/securedrop). - [x] Remind all translators about the string freeze in the Localization Lab channel in the [IFF Mattermost](https://internetfreedomfestival.org/wiki/index.php/IFF_Mattermost). # Release management ## Prepare release candidate (2.5.0~rc1) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.5.0~rc1 release changelog - [x] Branch release/2.5.0 from develop - [x] Prepare 2.5.0~rc1 - [x] Build debs, preserving build log, and put up `2.5.0~rc1` on test apt server - [x] Commit build log. ## RC2 skipped # Release management ## Prepare release candidate (2.5.0~rc3) - [x] Link to latest version of Tails, including release candidates, to test against during QA - [x] Prepare 2.5.0~rc3 release changelog - [x] Branch release/2.5.0 from develop - [x] Prepare 2.5.0~rc3 - [x] Build debs, preserving build log, and put up `2.5.0~rc3` on test apt server - [x] Commit build log. ## Final release - [x] Ensure builder in release branch is updated and/or update builder image - [x] Push signed tag - [x] Pre-Flight: Test updater logic in Tails (apt-qa tracks the `release` branch in the LFS repo) - [x] Build final Debian packages for 2.5.0 (and preserve build log) - [x] Commit package build log to https://github.com/freedomofpress/build-logs - [x] Upload Debian packages to apt-qa server via PR from `release` branch in LFS repo - [x] Pre-Flight: Test that install and upgrade from 2.4.2 to 2.5.0 works w/ prod repo debs (apt-qa.freedom.press polls the `release` branch in the LFS repo for the debs) - [x] Flip apt QA server to prod status (merge to `main` in the LFS repo) - [x] Merge Docs branch changes to ``main`` and verify new docs build in securedrop-docs repo - [x] Prepare release messaging ## Post release - [x] Create GitHub release object - [x] Once release object is created, update version in `securedrop-docs` (version information in Wagtail is updated automatically) - [x] Verify new docs show up on https://docs.securedrop.org - [x] Publish announcements - [ ] Merge changelog back to `develop` - [ ] Update roadmap wiki page: https://github.com/freedomofpress/securedrop/wiki/Development-Roadmap
2022-10-19T21:01:28Z
[]
[]
freedomofpress/securedrop
6,659
freedomofpress__securedrop-6659
[ "6648" ]
657bb8d8ed983be8a7005dc1ce6a4e0596616cd7
diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -389,7 +389,10 @@ def translators( log_command.extend([args.target, "--", path]) - log_lines = subprocess.check_output(log_command, encoding="utf-8").strip().splitlines() + # NB. We use an explicit str.split("\n") here because str.splitlines() splits on a + # set of characters that includes the \x1e "record separator" we pass to "git log + # --format" in log_command. See #6648. + log_lines = subprocess.check_output(log_command, encoding="utf-8").strip().split("\n") path_changes = [c.split("\x1e") for c in log_lines] path_changes = [ c
diff --git a/securedrop/tests/test_i18n_tool.py b/securedrop/tests/test_i18n_tool.py --- a/securedrop/tests/test_i18n_tool.py +++ b/securedrop/tests/test_i18n_tool.py @@ -392,7 +392,9 @@ def r(): subprocess.check_call(["git", "add", str(po_file)], **k) subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) subprocess.check_call(["git", "config", "user.name", "Someone Else"], **k) - subprocess.check_call(["git", "commit", "-m", "translation change", str(po_file)], **k) + subprocess.check_call( + ["git", "commit", "-m", "Translated using Weblate", str(po_file)], **k + ) k = {"cwd": join(d, "securedrop")} subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) @@ -417,6 +419,8 @@ def r(): ) assert "l10n: updated Dutch (nl)" in r() assert "l10n: updated German (de_DE)" not in r() + + # The translator is credited in Git history. message = subprocess.check_output( ["git", "--no-pager", "-C", "securedrop", "show"], cwd=d, @@ -424,3 +428,18 @@ def r(): ) assert "Someone Else" in message assert "Loïc" not in message + + # The "list-translators" command correctly reads the translator from Git history. + caplog.clear() + i18n_tool.I18NTool().main( + [ + "--verbose", + "list-translators", + "--all", + "--root", + join(str(tmpdir), "securedrop"), + "--url", + join(str(tmpdir), "i18n"), + ] + ) + assert "Someone Else" in caplog.text
`i18n_tool.py update-from-weblate` no longer detects translators for attribution ## Description After #6580, including with the fix proposed in #6629, `i18n_tool.py update-from-weblate` fails to detect the translators to credit for each per-language commit. ## Steps to Reproduce ```sh-session user@sd-dev:~/securedrop$ securedrop/bin/dev-shell ./i18n_tool.py update-from-weblate ``` ## Expected Behavior ```sh-session user@sd-dev:~/securedrop$ git log -n 1 --no-show-signature i18n-merge commit eb99e5c2f98ee3b901294251399280e0abf0c043 (origin/i18n-merge, i18n-merge) Author: Cory Francis Myers <[email protected]> Date: Mon Oct 17 23:58:21 2022 +0000 l10n: updated bn (bn) contributors: Oymate diyaf updated from: repo: https://github.com/freedomofpress/securedrop-i18n commit: 95b4cc8f2cdf2bb7f338b4c2cc996704a1f1909 ``` ## Actual Behavior ```sh-session user@sd-dev:~/securedrop$ git log -n 1 --no-show-signature commit e7642f527c09172304dafe578aec4cd182d9cd0d (HEAD -> develop) Author: Cory Francis Myers <[email protected]> Date: Tue Oct 18 00:57:00 2022 +0000 l10n: updated bn (bn) contributors: updated from: repo: https://github.com/freedomofpress/securedrop-i18n commit: 95b4cc8f2cdf2bb7f338b4c2cc996704a1f1909d ``` ## Comments I haven't had time to debug this as part of the v2.5.0 localization merge, so for #6646 I've worked around it locally with: ```sh-session user@sd-dev:~/securedrop$ git revert -m1 -n 94c6bbb ```
Previously it was: ```python log_lines = subprocess.check_output(log_command).decode("utf-8").strip().split("\n") ``` And now it is: ```python log_lines = subprocess.check_output(log_command, encoding="utf-8").strip().splitlines() ```
2022-10-20T01:46:30Z
[]
[]
freedomofpress/securedrop
6,681
freedomofpress__securedrop-6681
[ "6420" ]
d3e5dea8d157aceb379daaa987f722136458391b
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -16,7 +16,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import collections -from typing import Dict, List, Set +from typing import Dict, List, OrderedDict, Set from babel.core import ( Locale, @@ -25,7 +25,7 @@ negotiate_locale, parse_locale, ) -from flask import Flask, g, request, session +from flask import Flask, current_app, g, request, session from flask_babel import Babel from sdconfig import FALLBACK_LOCALE, SDConfig @@ -128,7 +128,7 @@ def parse_locale_set(codes: List[str]) -> Set[Locale]: return {Locale.parse(code) for code in codes} -def validate_locale_configuration(config: SDConfig, babel: Babel) -> None: +def validate_locale_configuration(config: SDConfig, babel: Babel) -> Set[Locale]: """ Check that configured locales are available in the filesystem and therefore usable by Babel. Warn about configured locales that are not usable, unless we're left with @@ -157,16 +157,12 @@ def validate_locale_configuration(config: SDConfig, babel: Babel) -> None: f"None of the default locales {defaults} are in the set of usable locales {usable}" ) - global USABLE_LOCALES - USABLE_LOCALES = usable + return usable -# TODO(#6420): avoid relying on and manipulating on this global state -LOCALES = collections.OrderedDict() # type: collections.OrderedDict[str, RequestLocaleInfo] -USABLE_LOCALES = set() # type: Set[Locale] - - -def map_locale_display_names(config: SDConfig) -> None: +def map_locale_display_names( + config: SDConfig, usable_locales: Set[Locale] +) -> OrderedDict[str, RequestLocaleInfo]: """ Create a map of locale identifiers to names for display. @@ -183,7 +179,7 @@ def map_locale_display_names(config: SDConfig) -> None: locale_map = collections.OrderedDict() for l in sorted(config.SUPPORTED_LOCALES): - if Locale.parse(l) not in USABLE_LOCALES: + if Locale.parse(l) not in usable_locales: continue locale = RequestLocaleInfo(l) @@ -193,14 +189,13 @@ def map_locale_display_names(config: SDConfig) -> None: locale_map[str(locale)] = locale - global LOCALES - LOCALES = locale_map + return locale_map def configure(config: SDConfig, app: Flask) -> None: babel = configure_babel(config, app) - validate_locale_configuration(config, babel) - map_locale_display_names(config) + usable_locales = validate_locale_configuration(config, babel) + app.config["LOCALES"] = map_locale_display_names(config, usable_locales) def get_locale(config: SDConfig) -> str: @@ -223,7 +218,8 @@ def get_locale(config: SDConfig) -> str: preferences.append(config.DEFAULT_LOCALE) preferences.append(FALLBACK_LOCALE) - negotiated = negotiate_locale(preferences, LOCALES.keys()) + locales = current_app.config["LOCALES"] + negotiated = negotiate_locale(preferences, locales.keys()) if not negotiated: raise ValueError("No usable locale") @@ -264,4 +260,4 @@ def set_locale(config: SDConfig) -> None: locale = get_locale(config) g.localeinfo = RequestLocaleInfo(locale) # pylint: disable=assigning-non-slot session["locale"] = locale - g.locales = LOCALES # pylint: disable=assigning-non-slot + g.locales = current_app.config["LOCALES"] # pylint: disable=assigning-non-slot
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -296,7 +296,7 @@ def test_i18n(): ): with app.app_context(): db.create_all() - assert list(i18n.LOCALES.keys()) == test_config.SUPPORTED_LOCALES + assert list(app.config["LOCALES"].keys()) == test_config.SUPPORTED_LOCALES verify_i18n(app) @@ -311,7 +311,6 @@ def test_no_usable_fallback_locale(): test_config = create_config_for_i18n_test( default_locale=NEVER_LOCALE, supported_locales=[NEVER_LOCALE] ) - i18n.USABLE_LOCALES = set() with pytest.raises(ValueError, match="in the set of usable locales"): journalist_app_module.create_app(test_config) diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -2,7 +2,6 @@ from datetime import datetime, timedelta from pathlib import Path -import i18n import i18n_tool import journalist_app import source_app @@ -110,6 +109,6 @@ def do_test(create_app): with app.app_context(): db.create_all() - assert list(i18n.LOCALES.keys()) == test_config.SUPPORTED_LOCALES + assert list(app.config["LOCALES"].keys()) == test_config.SUPPORTED_LOCALES verify_filesizeformat(app) verify_rel_datetime_format(app)
runtime `i18n` configuration manipulates global state I guess we already do this for LOCALES, but I think continuing the pattern should be accompanied by a TODO that manipulating/relying on global state is not desirable. _Originally posted by @legoktm in https://github.com/freedomofpress/securedrop/pull/6406#discussion_r863080227_
(This is not a good first issue yet, I will add some more detail on what the plan is to fix this before it's ready for others to take on)
2022-11-13T00:58:10Z
[]
[]
freedomofpress/securedrop
6,720
freedomofpress__securedrop-6720
[ "6699" ]
cedb13b4794ae688748e291fb2f5a439bd6848d0
diff --git a/admin/bootstrap.py b/admin/bootstrap.py --- a/admin/bootstrap.py +++ b/admin/bootstrap.py @@ -1,4 +1,3 @@ -# -*- mode: python; coding: utf-8 -*- # # Copyright (C) 2013-2018 Freedom of the Press Foundation & al # Copyright (C) 2018 Loic Dachary <[email protected]> @@ -53,9 +52,8 @@ def run_command(command: List[str]) -> Iterator[bytes]: """ popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if popen.stdout is None: - raise EnvironmentError("Could not run command: None stdout") - for stdout_line in iter(popen.stdout.readline, b""): - yield stdout_line + raise OSError("Could not run command: None stdout") + yield from iter(popen.stdout.readline, b"") popen.stdout.close() return_code = popen.wait() if return_code: @@ -111,10 +109,8 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: """ sdlog.info("Installing SecureDrop Admin dependencies") sdlog.info( - ( - "You'll be prompted for the temporary Tails admin password," - " which was set on Tails login screen" - ) + "You'll be prompted for the temporary Tails admin password," + " which was set on Tails login screen" ) apt_command = [ @@ -142,7 +138,7 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: # under Tails 2.x. If updates are being applied, don't try to pile # on with more apt requests. sdlog.error( - ("Failed to install apt dependencies. Check network" " connection and try again.") + "Failed to install apt dependencies. Check network" " connection and try again." ) raise @@ -181,7 +177,7 @@ def envsetup(args: argparse.Namespace, virtualenv_dir: str = VENV_DIR) -> None: ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) - sdlog.error(("Unable to create virtualenv. Check network settings" " and try again.")) + sdlog.error("Unable to create virtualenv. Check network settings" " and try again.") sdlog.debug("Cleaning up virtualenv") if os.path.exists(virtualenv_dir): shutil.rmtree(virtualenv_dir) @@ -234,23 +230,21 @@ def install_pip_dependencies( "only-if-needed", ] - sdlog.info("Checking {} for securedrop-admin".format(desc)) + sdlog.info(f"Checking {desc} for securedrop-admin") try: pip_output = subprocess.check_output( maybe_torify() + pip_install_cmd, stderr=subprocess.STDOUT ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) - sdlog.error( - ("Failed to install {}. Check network" " connection and try again.".format(desc)) - ) + sdlog.error("Failed to install {}. Check network" " connection and try again.".format(desc)) raise sdlog.debug(pip_output) if "Successfully installed" in str(pip_output): - sdlog.info("{} for securedrop-admin upgraded".format(desc)) + sdlog.info(f"{desc} for securedrop-admin upgraded") else: - sdlog.info("{} for securedrop-admin are up-to-date".format(desc)) + sdlog.info(f"{desc} for securedrop-admin are up-to-date") def parse_argv(argv: List[str]) -> argparse.Namespace: diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -1,4 +1,3 @@ -# -*- mode: python; coding: utf-8 -*- # # Copyright (C) 2013-2018 Freedom of the Press Foundation & al # Copyright (C) 2018 Loic Dachary <[email protected]> @@ -26,7 +25,6 @@ import argparse import base64 import functools -import io import ipaddress import json import logging @@ -154,7 +152,7 @@ def split_list(text: str) -> List[str]: class ValidatePath(Validator): def __init__(self, basedir: str) -> None: self.basedir = basedir - super(SiteConfig.ValidatePath, self).__init__() + super().__init__() def validate(self, document: Document) -> bool: if document.text == "": @@ -168,7 +166,7 @@ class ValidateOptionalPath(ValidatePath): def validate(self, document: Document) -> bool: if document.text == "": return True - return super(SiteConfig.ValidateOptionalPath, self).validate(document) + return super().validate(document) class ValidateYesNo(Validator): def validate(self, document: Document) -> bool: @@ -192,7 +190,7 @@ class ValidateOptionalFingerprint(ValidateFingerprint): def validate(self, document: Document) -> bool: if document.text == "": return True - return super(SiteConfig.ValidateOptionalFingerprint, self).validate(document) + return super().validate(document) class ValidateInt(Validator): def validate(self, document: Document) -> bool: @@ -200,7 +198,7 @@ def validate(self, document: Document) -> bool: return True raise ValidationError(message="Must be an integer") - class Locales(object): + class Locales: def __init__(self, appdir: str) -> None: self.translation_dir = os.path.realpath(os.path.join(appdir, "translations")) @@ -216,7 +214,7 @@ def __init__(self, basedir: str, supported: Set[str]) -> None: present = SiteConfig.Locales(basedir).get_translations() self.available = present & supported - super(SiteConfig.ValidateLocales, self).__init__() + super().__init__() def validate(self, document: Document) -> bool: desired = document.text.split() @@ -252,7 +250,7 @@ def validate(self, document: Document) -> bool: class ValidateOSSECEmail(ValidateEmail): def validate(self, document: Document) -> bool: - super(SiteConfig.ValidateOSSECEmail, self).validate(document) + super().validate(document) text = document.text if "[email protected]" != text: return True @@ -264,7 +262,7 @@ class ValidateOptionalEmail(ValidateEmail): def validate(self, document: Document) -> bool: if document.text == "": return True - return super(SiteConfig.ValidateOptionalEmail, self).validate(document) + return super().validate(document) def __init__(self, args: argparse.Namespace) -> None: self.args = args @@ -604,9 +602,9 @@ def validate_gpg_keys(self) -> bool: except subprocess.CalledProcessError as e: sdlog.debug(e.output) raise FingerprintException( - "fingerprint {} ".format(fingerprint) + f"fingerprint {fingerprint} " + "does not match " - + "the public key {}".format(public_key) + + f"the public key {public_key}" ) return True @@ -631,7 +629,7 @@ def exists(self) -> bool: return os.path.exists(self.args.site_config) def save(self) -> None: - with io.open(self.args.site_config, "w") as site_config_file: + with open(self.args.site_config, "w") as site_config_file: yaml.safe_dump(self.config, site_config_file, default_flow_style=False) def clean_config(self, config: Dict) -> Dict: @@ -683,14 +681,14 @@ def load(self, validate: bool = True) -> Dict: to current specifications. """ try: - with io.open(self.args.site_config) as site_config_file: + with open(self.args.site_config) as site_config_file: c = yaml.safe_load(site_config_file) return self.clean_config(c) if validate else c - except IOError: + except OSError: sdlog.error("Config file missing, re-run with sdconfig") raise except yaml.YAMLError: - sdlog.error("There was an issue processing {}".format(self.args.site_config)) + sdlog.error(f"There was an issue processing {self.args.site_config}") raise @@ -736,10 +734,10 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: "You are not running the most recent signed SecureDrop release " "on this workstation." ) - sdlog.error("Latest available version: {}".format(latest_tag)) + sdlog.error(f"Latest available version: {latest_tag}") if branch_status is not None: - sdlog.error("Current branch status: {}".format(branch_status)) + sdlog.error(f"Current branch status: {branch_status}") else: sdlog.error("Problem determining current branch status.") @@ -805,7 +803,7 @@ def find_or_generate_new_torv3_keys(args: argparse.Namespace) -> int: """ secret_key_path = os.path.join(args.ansible_path, "tor_v3_keys.json") if os.path.exists(secret_key_path): - print("Tor v3 onion service keys already exist in: {}".format(secret_key_path)) + print(f"Tor v3 onion service keys already exist in: {secret_key_path}") return 0 # No old keys, generate and store them first app_journalist_public_key, app_journalist_private_key = generate_new_v3_keys() @@ -823,7 +821,7 @@ def find_or_generate_new_torv3_keys(args: argparse.Namespace) -> int: } with open(secret_key_path, "w") as fobj: json.dump(tor_v3_service_info, fobj, indent=4) - print("Tor v3 onion service keys generated and stored in: {}".format(secret_key_path)) + print(f"Tor v3 onion service keys generated and stored in: {secret_key_path}") return 0 @@ -886,7 +884,7 @@ def restore_securedrop(args: argparse.Namespace) -> int: ] ansible_cmd_extras = [ - "restore_file='{}'".format(restore_file_basename), + f"restore_file='{restore_file_basename}'", ] if args.restore_skip_tor: @@ -904,10 +902,8 @@ def run_tails_config(args: argparse.Namespace) -> int: """Configure Tails environment post SD install""" sdlog.info("Configuring Tails workstation environment") sdlog.info( - ( - "You'll be prompted for the temporary Tails admin password," - " which was set on Tails login screen" - ) + "You'll be prompted for the temporary Tails admin password," + " which was set on Tails login screen" ) ansible_cmd = [ os.path.join(args.ansible_path, "securedrop-tails.yml"), @@ -1034,7 +1030,7 @@ def update(args: argparse.Namespace) -> int: ): # Finally, we check that there is no branch of the same name # prior to reporting success. - cmd = ["git", "show-ref", "--heads", "--verify", "refs/heads/{}".format(latest_tag)] + cmd = ["git", "show-ref", "--heads", "--verify", f"refs/heads/{latest_tag}"] try: # We expect this to produce a non-zero exit code, which # will produce a subprocess.CalledProcessError @@ -1063,7 +1059,7 @@ def update(args: argparse.Namespace) -> int: git_checkout_cmd = ["git", "checkout", latest_tag] subprocess.check_call(git_checkout_cmd, cwd=args.root) - sdlog.info("Updated to SecureDrop {}.".format(latest_tag)) + sdlog.info(f"Updated to SecureDrop {latest_tag}.") return 0 @@ -1213,10 +1209,10 @@ def main(argv: List[str]) -> None: print("Process was interrupted.") sys.exit(EXIT_INTERRUPT) except subprocess.CalledProcessError as e: - print("ERROR (run with -v for more): {msg}".format(msg=e), file=sys.stderr) + print(f"ERROR (run with -v for more): {e}", file=sys.stderr) sys.exit(EXIT_SUBPROCESS_ERROR) except Exception as e: - raise SystemExit("ERROR (run with -v for more): {msg}".format(msg=e)) + raise SystemExit(f"ERROR (run with -v for more): {e}") if return_code == 0: sys.exit(EXIT_SUCCESS) else: diff --git a/install_files/ansible-base/callback_plugins/ansible_version_check.py b/install_files/ansible-base/callback_plugins/ansible_version_check.py --- a/install_files/ansible-base/callback_plugins/ansible_version_check.py +++ b/install_files/ansible-base/callback_plugins/ansible_version_check.py @@ -1,6 +1,3 @@ -# -*- encoding:utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import sys import ansible diff --git a/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py b/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py --- a/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py +++ b/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py @@ -48,11 +48,11 @@ def __init__(self, ossec_version): @property def ossec_tarball_filename(self): - return "ossec-hids-{}.tar.gz".format(self.ossec_version) + return f"ossec-hids-{self.ossec_version}.tar.gz" @property def ossec_tarball_url(self): - return self.REPO_URL + "/archive/{}.tar.gz".format(self.ossec_version) + return self.REPO_URL + f"/archive/{self.ossec_version}.tar.gz" @property def ossec_signature_url(self): @@ -62,7 +62,7 @@ def ossec_signature_url(self): @property def ossec_signature_filename(self): - return "ossec-hids-{}.tar.gz.asc".format(self.ossec_version) + return f"ossec-hids-{self.ossec_version}.tar.gz.asc" def main(): diff --git a/install_files/ansible-base/roles/restore/files/compare_torrc.py b/install_files/ansible-base/roles/restore/files/compare_torrc.py --- a/install_files/ansible-base/roles/restore/files/compare_torrc.py +++ b/install_files/ansible-base/roles/restore/files/compare_torrc.py @@ -6,7 +6,6 @@ # print a warning and exit. # -from __future__ import print_function import os import re @@ -18,7 +17,7 @@ def get_tor_versions(path): Determine which service versions are offered in the given torrc. """ service_re = re.compile(r"HiddenServiceDir\s+(?:.*)/(.*)") - versions = set([]) + versions = set() with open(path) as f: for line in f: m = service_re.match(line) diff --git a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py --- a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py +++ b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py @@ -1,7 +1,6 @@ #!/usr/bin/python3 import grp -import io import os import pwd import subprocess @@ -43,28 +42,28 @@ # load torrc_additions if os.path.isfile(path_torrc_additions): - with io.open(path_torrc_additions) as f: + with open(path_torrc_additions) as f: torrc_additions = f.read() else: - sys.exit("Error opening {0} for reading".format(path_torrc_additions)) + sys.exit(f"Error opening {path_torrc_additions} for reading") # load torrc if os.path.isfile(path_torrc_backup): - with io.open(path_torrc_backup) as f: + with open(path_torrc_backup) as f: torrc = f.read() else: if os.path.isfile(path_torrc): - with io.open(path_torrc) as f: + with open(path_torrc) as f: torrc = f.read() else: - sys.exit("Error opening {0} for reading".format(path_torrc)) + sys.exit(f"Error opening {path_torrc} for reading") # save a backup - with io.open(path_torrc_backup, "w") as f: + with open(path_torrc_backup, "w") as f: f.write(torrc) # append the additions -with io.open(path_torrc, "w") as f: +with open(path_torrc, "w") as f: f.write(torrc + torrc_additions) # check for v3 aths files @@ -108,11 +107,11 @@ env["XDG_CURRENT_DESKTOP"] = "GNOME" env["DESKTOP_SESSION"] = "default" env["DISPLAY"] = ":1" -env["XDG_RUNTIME_DIR"] = "/run/user/{}".format(amnesia_uid) +env["XDG_RUNTIME_DIR"] = f"/run/user/{amnesia_uid}" env["XDG_DATA_DIR"] = "/usr/share/gnome:/usr/local/share/:/usr/share/" env["HOME"] = "/home/amnesia" env["LOGNAME"] = "amnesia" -env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/run/user/{}/bus".format(amnesia_uid) +env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path=/run/user/{amnesia_uid}/bus" # remove existing shortcut, recreate symlink and change metadata attribute # to trust .desktop @@ -202,7 +201,7 @@ "/etc/ssl/certs/DST_Root_CA_X3.pem", pem_file.name, ], - universal_newlines=True, + text=True, env=env, ) @@ -226,7 +225,7 @@ except subprocess.CalledProcessError: sys.exit(0) # Don't break tailsconfig trying to fix this - except IOError: + except OSError: sys.exit(0) finally: diff --git a/journalist_gui/journalist_gui/SecureDropUpdater.py b/journalist_gui/journalist_gui/SecureDropUpdater.py --- a/journalist_gui/journalist_gui/SecureDropUpdater.py +++ b/journalist_gui/journalist_gui/SecureDropUpdater.py @@ -168,7 +168,7 @@ def run(self): class UpdaterApp(QtWidgets.QMainWindow, updaterUI.Ui_MainWindow): def __init__(self, parent=None): - super(UpdaterApp, self).__init__(parent) + super().__init__(parent) self.setupUi(self) self.statusbar.setSizeGripEnabled(False) self.output = strings.initial_text_box diff --git a/journalist_gui/journalist_gui/resources_rc.py b/journalist_gui/journalist_gui/resources_rc.py --- a/journalist_gui/journalist_gui/resources_rc.py +++ b/journalist_gui/journalist_gui/resources_rc.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.9.5) diff --git a/journalist_gui/journalist_gui/updaterUI.py b/journalist_gui/journalist_gui/updaterUI.py --- a/journalist_gui/journalist_gui/updaterUI.py +++ b/journalist_gui/journalist_gui/updaterUI.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Form implementation generated from reading ui file 'journalist_gui/mainwindow.ui' # # Created by: PyQt5 UI code generator 5.10 @@ -9,7 +7,7 @@ from PyQt5 import QtCore, QtGui, QtWidgets -class Ui_MainWindow(object): +class Ui_MainWindow: def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(400, 500) diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -6,7 +6,6 @@ Vars should be placed in `testinfra/vars/<hostname>.yml`. """ -import io import os from typing import Any, Dict @@ -26,7 +25,7 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): Vars must be stored in `testinfra/vars/<hostname>.yml`. """ filepath = os.path.join(os.path.dirname(__file__), "vars", hostname + ".yml") - with io.open(filepath, "r") as f: + with open(filepath) as f: hostvars = yaml.safe_load(f) hostvars["securedrop_venv_site_packages"] = hostvars["securedrop_venv_site_packages"].format( @@ -41,7 +40,7 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): os.path.dirname(__file__), "../../install_files/ansible-base/group_vars/all/site-specific" ) if os.path.isfile(prod_filepath): - with io.open(prod_filepath, "r") as f: + with open(prod_filepath) as f: prodvars = yaml.safe_load(f) def _prod_override(vars_key, prod_key): @@ -63,7 +62,7 @@ def _prod_override(vars_key, prod_key): "../../install_files/ansible-base/roles/install-fpf-repo/defaults/main.yml", ) # noqa: E501 if os.path.isfile(repo_filepath): - with io.open(repo_filepath, "r") as f: + with open(repo_filepath) as f: repovars = yaml.safe_load(f) if "apt_repo_url" in repovars: hostvars["fpf_apt_repo_url"] = repovars["apt_repo_url"] diff --git a/securedrop/alembic/env.py b/securedrop/alembic/env.py --- a/securedrop/alembic/env.py +++ b/securedrop/alembic/env.py @@ -1,5 +1,3 @@ -from __future__ import with_statement - import os import sys from logging.config import fileConfig diff --git a/securedrop/db.py b/securedrop/db.py --- a/securedrop/db.py +++ b/securedrop/db.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() diff --git a/securedrop/debian/ossec-common/var/ossec/checksdconfig.py b/securedrop/debian/ossec-common/var/ossec/checksdconfig.py --- a/securedrop/debian/ossec-common/var/ossec/checksdconfig.py +++ b/securedrop/debian/ossec-common/var/ossec/checksdconfig.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# -*- coding: utf-8 -*- import argparse import subprocess @@ -33,7 +32,7 @@ def list_iptables_rules() -> dict: - result = subprocess.run(["iptables", "-S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + result = subprocess.run(["iptables", "-S"], capture_output=True) rules = result.stdout.decode("utf-8").splitlines() policies = [r for r in rules if r.startswith("-P")] input_rules = [r for r in rules if r.startswith("-A INPUT")] diff --git a/securedrop/encryption.py b/securedrop/encryption.py --- a/securedrop/encryption.py +++ b/securedrop/encryption.py @@ -116,7 +116,7 @@ def __init__(self, gpg_key_dir: Path, journalist_key_fingerprint: str) -> None: try: self.get_journalist_public_key() except GpgKeyNotFoundError: - raise EnvironmentError( + raise OSError( f"The journalist public key with fingerprint {journalist_key_fingerprint}" f" has not been imported into GPG." ) diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -1,9 +1,7 @@ #!/opt/venvs/securedrop-app-code/bin/python -# -*- coding: utf-8 -*- import argparse import glob -import io import json import logging import os @@ -102,7 +100,7 @@ def translate_messages(self, args: argparse.Namespace) -> None: self.file_is_modified(str(messages_file)) and len(os.listdir(args.translations_dir)) > 1 ): - tglob = "{}/*/LC_MESSAGES/*.po".format(args.translations_dir) + tglob = f"{args.translations_dir}/*/LC_MESSAGES/*.po" for translation in glob.iglob(tglob): subprocess.check_call( [ @@ -217,7 +215,7 @@ def set_translate_parser( parser.add_argument( "--translations-dir", default=translations_dir, - help="Base directory for translation files (default {})".format(translations_dir), + help=f"Base directory for translation files (default {translations_dir})", ) parser.add_argument( "--version", @@ -230,7 +228,7 @@ def set_translate_parser( parser.add_argument( "--sources", default=sources, - help="Source files and directories to extract (default {})".format(sources), + help=f"Source files and directories to extract (default {sources})", ) def set_translate_messages_parser(self, subps: _SubParsersAction) -> None: @@ -244,7 +242,7 @@ def set_translate_messages_parser(self, subps: _SubParsersAction) -> None: parser.add_argument( "--mapping", default=mapping, - help="Mapping of files to consider (default {})".format(mapping), + help=f"Mapping of files to consider (default {mapping})", ) parser.set_defaults(func=self.translate_messages) @@ -269,7 +267,7 @@ def require_git_email_name(git_dir: str) -> bool: ) # nosemgrep: python.lang.security.audit.subprocess-shell-true.subprocess-shell-true if subprocess.call(cmd, shell=True): # nosec - if "docker" in io.open("/proc/1/cgroup").read(): + if "docker" in open("/proc/1/cgroup").read(): log.error( "remember ~/.gitconfig does not exist " "in the dev-shell Docker container, " @@ -284,7 +282,7 @@ def update_docs(self, args: argparse.Namespace) -> None: l10n_content += "* " + info["name"] + " (``" + code + "``)\n" includes = abspath(join(args.docs_repo_dir, "docs/includes")) l10n_txt = join(includes, "l10n.txt") - io.open(l10n_txt, mode="w").write(l10n_content) + open(l10n_txt, mode="w").write(l10n_content) self.require_git_email_name(includes) if self.file_is_modified(l10n_txt): subprocess.check_call(["git", "add", "l10n.txt"], cwd=includes) @@ -355,7 +353,7 @@ def add(path: str) -> None: desktop_code = info["desktop"] path = join( LOCALE_DIR["desktop"], - "{l}.po".format(l=desktop_code), # noqa: E741 + f"{desktop_code}.po", # noqa: E741 ) add(path) except KeyError: @@ -400,7 +398,7 @@ def translators( if len(c) > 1 and c[2] != since_commit and self.translated_commit_re.match(c[1]) ] log.debug("Path changes for %s: %s", path, path_changes) - translators = set([c[0] for c in path_changes]) + translators = {c[0] for c in path_changes} log.debug("Translators for %s: %s", path, translators) return translators @@ -586,9 +584,9 @@ def list_translators(self, args: argparse.Namespace) -> None: print("Listing all translators who have ever helped") else: since = args.since if args.since else self.get_last_release(args.root) - print("Listing translators who have helped since {}".format(since)) + print(f"Listing translators who have helped since {since}") for code, info in sorted(self.supported_languages.items()): - translators = set([]) + translators = set() paths = [ app_template.format(LOCALE_DIR["securedrop"], code), desktop_template.format(info["desktop"]), @@ -598,7 +596,7 @@ def list_translators(self, args: argparse.Namespace) -> None: t = self.translators(args, path, since) translators.update(t) except Exception as e: - print("Could not check git history of {}: {}".format(path, e), file=sys.stderr) + print(f"Could not check git history of {path}: {e}", file=sys.stderr) print( "{} ({}):{}".format( code, diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from encryption import EncryptionManager, GpgKeyNotFoundError from execution import asynchronous from journalist_app import create_app diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -61,7 +61,7 @@ class JSONEncoder(json.JSONEncoder): def default(self, obj: "Any") -> "Any": if isinstance(obj, datetime): return obj.strftime(API_DATETIME_FORMAT) - super(JSONEncoder, self).default(obj) + super().default(obj) app.json_encoder = JSONEncoder diff --git a/securedrop/journalist_app/account.py b/securedrop/journalist_app/account.py --- a/securedrop/journalist_app/account.py +++ b/securedrop/journalist_app/account.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from typing import Union import werkzeug diff --git a/securedrop/journalist_app/admin.py b/securedrop/journalist_app/admin.py --- a/securedrop/journalist_app/admin.py +++ b/securedrop/journalist_app/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import binascii import os from typing import Optional, Union @@ -329,9 +327,7 @@ def delete_user(user_id: int) -> werkzeug.Response: if user_id == session.get_uid(): # Do not flash because the interface already has safe guards. # It can only happen by manually crafting a POST request - current_app.logger.error( - "Admin {} tried to delete itself".format(session.get_user().username) - ) + current_app.logger.error(f"Admin {session.get_user().username} tried to delete itself") abort(403) elif not user: current_app.logger.error( @@ -344,7 +340,7 @@ def delete_user(user_id: int) -> werkzeug.Response: # Do not flash because the interface does not expose this. # It can only happen by manually crafting a POST request current_app.logger.error( - 'Admin {} tried to delete "deleted" user'.format(session.get_user().username) + f'Admin {session.get_user().username} tried to delete "deleted" user' ) abort(403) else: diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -329,19 +329,19 @@ def seen() -> Tuple[flask.Response, int]: for file_uuid in request.json.get("files", []): f = Submission.query.filter(Submission.uuid == file_uuid).one_or_none() if f is None or not f.is_file: - abort(404, "file not found: {}".format(file_uuid)) + abort(404, f"file not found: {file_uuid}") targets.add(f) for message_uuid in request.json.get("messages", []): m = Submission.query.filter(Submission.uuid == message_uuid).one_or_none() if m is None or not m.is_message: - abort(404, "message not found: {}".format(message_uuid)) + abort(404, f"message not found: {message_uuid}") targets.add(m) for reply_uuid in request.json.get("replies", []): r = Reply.query.filter(Reply.uuid == reply_uuid).one_or_none() if r is None: - abort(404, "reply not found: {}".format(reply_uuid)) + abort(404, f"reply not found: {reply_uuid}") targets.add(r) # now mark everything seen. diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from pathlib import Path import werkzeug @@ -145,7 +143,7 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: ), "error", ) - current_app.logger.error("File {} not found".format(file)) + current_app.logger.error(f"File {file} not found") return redirect(url_for("col.col", filesystem_id=filesystem_id)) # mark as seen by the current user @@ -161,7 +159,7 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: message = Submission.query.filter(Submission.filename == fn).one() mark_seen([message], journalist) except NoResultFound as e: - current_app.logger.error("Could not mark {} as seen: {}".format(fn, e)) + current_app.logger.error(f"Could not mark {fn} as seen: {e}") return send_file( Storage.get_default().path(filesystem_id, fn), diff --git a/securedrop/journalist_app/decorators.py b/securedrop/journalist_app/decorators.py --- a/securedrop/journalist_app/decorators.py +++ b/securedrop/journalist_app/decorators.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from functools import wraps from typing import Any, Callable diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import typing from typing import Any @@ -47,7 +45,7 @@ def __call__(self, form: FlaskForm, field: Field) -> None: other_name=self.other_field_name, name=field.name ) ) - super(RequiredIf, self).__call__(form, field) + super().__call__(form, field) else: field.errors[:] = [] raise StopValidation() diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from datetime import datetime, timezone from pathlib import Path from typing import Union @@ -141,7 +140,7 @@ def reply() -> werkzeug.Response: return redirect(url_for("col.col", filesystem_id=g.filesystem_id)) g.source.interaction_count += 1 - filename = "{0}-{1}-reply.gpg".format( + filename = "{}-{}-reply.gpg".format( g.source.interaction_count, g.source.journalist_filename ) EncryptionManager.get_default().encrypt_journalist_reply( diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import binascii import os from datetime import datetime, timezone @@ -45,7 +44,7 @@ def commit_account_changes(user: Journalist) -> None: gettext("An unexpected error occurred! Please " "inform your admin."), "error", ) - current_app.logger.error("Account changes for '{}' failed: {}".format(user, e)) + current_app.logger.error(f"Account changes for '{user}' failed: {e}") db.session.rollback() else: flash(gettext("Account updated."), "success") @@ -90,7 +89,7 @@ def validate_user( LoginThrottledException, InvalidPasswordLength, ) as e: - current_app.logger.error("Login for '{}' failed: {}".format(username, e)) + current_app.logger.error(f"Login for '{username}' failed: {e}") login_flashed_msg = error_message if error_message else gettext("Login failed.") if isinstance(e, LoginThrottledException): @@ -161,9 +160,7 @@ def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: gettext("An unexpected error occurred! " "Please inform your admin."), "error", ) - current_app.logger.error( - "set_hotp_secret '{}' (id {}) failed: {}".format(otp_secret, user.id, e) - ) + current_app.logger.error(f"set_hotp_secret '{otp_secret}' (id {user.id}) failed: {e}") return False return True diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -1,5 +1,4 @@ #!/opt/venvs/securedrop-app-code/bin/python -# -*- coding: utf-8 -*- """ Loads test data into the SecureDrop database. @@ -49,7 +48,7 @@ def fraction(s: str) -> float: f = float(s) if 0 <= f <= 1: return f - raise ValueError("{} should be a float between 0 and 1".format(s)) + raise ValueError(f"{s} should be a float between 0 and 1") def non_negative_int(s: str) -> int: @@ -59,7 +58,7 @@ def non_negative_int(s: str) -> int: f = float(s) if f.is_integer() and f >= 0: return int(f) - raise ValueError("{} is not a non-negative integer".format(s)) + raise ValueError(f"{s} is not a non-negative integer") def random_bool() -> bool: @@ -220,7 +219,7 @@ def add_reply( Adds a single reply to a source. """ record_source_interaction(source) - fname = "{}-{}-reply.gpg".format(source.interaction_count, source.journalist_filename) + fname = f"{source.interaction_count}-{source.journalist_filename}-reply.gpg" EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=source.filesystem_id, reply_in=next(replies), diff --git a/securedrop/manage.py b/securedrop/manage.py --- a/securedrop/manage.py +++ b/securedrop/manage.py @@ -1,5 +1,4 @@ #!/opt/venvs/securedrop-app-code/bin/python -# -*- coding: utf-8 -*- import argparse import logging @@ -183,7 +182,7 @@ def _add_user(is_admin: bool = False, context: Optional[AppContext] = None) -> i print("Note: Passwords are now autogenerated.") password = PassphraseGenerator.get_default().generate_passphrase() - print("This user's password is: {}".format(password)) + print(f"This user's password is: {password}") is_hotp = _get_yubikey_usage() otp_secret = None @@ -197,7 +196,7 @@ def _add_user(is_admin: bool = False, context: Optional[AppContext] = None) -> i if len(tmp_str) != 40: print( "The length of the secret is not correct. " - "Expected 40 characters, but received {0}. " + "Expected 40 characters, but received {}. " "Try again.".format(len(tmp_str)) ) continue @@ -224,7 +223,7 @@ def _add_user(is_admin: bool = False, context: Optional[AppContext] = None) -> i print(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) return 1 else: - print('User "{}" successfully added'.format(username)) + print(f'User "{username}" successfully added') if not otp_secret: # Print the QR code for FreeOTP print("\nScan the QR code below with FreeOTP:\n") @@ -288,14 +287,14 @@ def delete_user(args: argparse.Namespace, context: Optional[AppContext] = None) else: raise e - print('User "{}" successfully deleted'.format(username)) + print(f'User "{username}" successfully deleted') return 0 def clean_tmp(args: argparse.Namespace) -> int: """Cleanup the SecureDrop temp directory.""" if not os.path.exists(args.directory): - log.debug("{} does not exist, do nothing".format(args.directory)) + log.debug(f"{args.directory} does not exist, do nothing") return 0 def listdir_fullpath(d: str) -> List[str]: @@ -305,9 +304,9 @@ def listdir_fullpath(d: str) -> List[str]: for path in listdir_fullpath(args.directory): if time.time() - os.stat(path).st_mtime > too_old: os.remove(path) - log.debug("{} removed".format(path)) + log.debug(f"{path} removed") else: - log.debug("{} modified less than {} days ago".format(path, args.days)) + log.debug(f"{path} modified less than {args.days} days ago") return 0 diff --git a/securedrop/management/run.py b/securedrop/management/run.py --- a/securedrop/management/run.py +++ b/securedrop/management/run.py @@ -51,7 +51,7 @@ def __init__(self, label: str, cmd: List[str], color: str) -> None: self.cmd = cmd self.color = color - super(DevServerProcess, self).__init__( # type: ignore + super().__init__( # type: ignore self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, @@ -60,7 +60,7 @@ def __init__(self, label: str, cmd: List[str], color: str) -> None: ) def print_label(self, to: TextIO) -> None: - label = "\n => {} <= \n\n".format(self.label) + label = f"\n => {self.label} <= \n\n" if to.isatty(): label = colorize(label, self.color, True) to.write(label) diff --git a/securedrop/management/submissions.py b/securedrop/management/submissions.py --- a/securedrop/management/submissions.py +++ b/securedrop/management/submissions.py @@ -71,7 +71,7 @@ def delete_disconnected_db_submissions(args: argparse.Namespace) -> None: if not args.force: remove = input("Enter 'y' to delete all submissions missing files: ") == "y" if remove: - print("Removing submission IDs {}...".format(ids)) + print(f"Removing submission IDs {ids}...") db.session.query(Submission).filter(Submission.id.in_(ids)).delete( synchronize_session="fetch" ) @@ -152,13 +152,13 @@ def delete_disconnected_fs_submissions(args: argparse.Namespace) -> None: for i, f in enumerate(disconnected_files, 1): remove = args.force if not args.force: - remove = input("Enter 'y' to delete {}: ".format(f)) == "y" + remove = input(f"Enter 'y' to delete {f}: ") == "y" if remove: filesize = os.stat(f).st_size if i > 1: eta = filesize / rate - eta_msg = " (ETA to remove {:d} bytes: {:.0f}s )".format(filesize, eta) - print("Securely removing file {}/{} {}{}...".format(i, filecount, f, eta_msg)) + eta_msg = f" (ETA to remove {filesize:d} bytes: {eta:.0f}s )" + print(f"Securely removing file {i}/{filecount} {f}{eta_msg}...") start = time.time() secure_delete(f) file_elapsed = time.time() - start @@ -171,7 +171,7 @@ def delete_disconnected_fs_submissions(args: argparse.Namespace) -> None: ) ) else: - print("Not removing {}.".format(f)) + print(f"Not removing {f}.") def were_there_submissions_today( diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -55,7 +55,7 @@ def get_one_or_else( ) failure_method(500) except NoResultFound as e: - logger.error("Found none when one was expected: %s" % (e,)) + logger.error(f"Found none when one was expected: {e}") failure_method(404) @@ -338,14 +338,14 @@ class FirstOrLastNameError(Exception): """Generic error for names that are invalid.""" def __init__(self, msg: str) -> None: - super(FirstOrLastNameError, self).__init__(msg) + super().__init__(msg) class InvalidNameLength(FirstOrLastNameError): """Raised when attempting to create a Journalist with an invalid name length.""" def __init__(self) -> None: - super(InvalidNameLength, self).__init__(gettext("Name too long")) + super().__init__(gettext("Name too long")) class LoginThrottledException(Exception): @@ -451,7 +451,7 @@ def __init__( self.set_hotp_secret(otp_secret) def __repr__(self) -> str: - return "<Journalist {0}{1}>".format(self.username, " [admin]" if self.is_admin else "") + return "<Journalist {}{}>".format(self.username, " [admin]" if self.is_admin else "") def _scrypt_hash(self, password: str, salt: bytes) -> bytes: backend = default_backend() @@ -557,7 +557,7 @@ def valid_password(self, passphrase: "Optional[str]") -> bool: # legacy support if self.pw_salt is None: raise ValueError( - "Should never happen: pw_salt is none for legacy Journalist {}".format(self.id) + f"Should never happen: pw_salt is none for legacy Journalist {self.id}" ) # For type checking @@ -609,14 +609,14 @@ def totp(self) -> "TOTP": if self.is_totp: return pyotp.TOTP(self.otp_secret) else: - raise ValueError("{} is not using TOTP".format(self)) + raise ValueError(f"{self} is not using TOTP") @property def hotp(self) -> "HOTP": if not self.is_totp: return pyotp.HOTP(self.otp_secret) else: - raise ValueError("{} is not using HOTP".format(self)) + raise ValueError(f"{self} is not using HOTP") @property def shared_secret_qrcode(self) -> Markup: diff --git a/securedrop/passphrases.py b/securedrop/passphrases.py --- a/securedrop/passphrases.py +++ b/securedrop/passphrases.py @@ -38,7 +38,7 @@ def __init__( self._language_to_words = language_to_words if self._fallback_language not in self._language_to_words: raise InvalidWordListError( - "Missing words list for fallback language '{}'".format(self._fallback_language) + f"Missing words list for fallback language '{self._fallback_language}'" ) # Validate each words list diff --git a/securedrop/rm.py b/securedrop/rm.py --- a/securedrop/rm.py +++ b/securedrop/rm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # SecureDrop whistleblower submission system # Copyright (C) 2017 Loic Dachary <[email protected]> @@ -39,7 +38,7 @@ def shred(path: str, delete: bool = True) -> None: """ if not os.path.exists(path): - raise EnvironmentError(path) + raise OSError(path) if not os.path.isfile(path): raise ValueError("The shred function only works on files.") @@ -95,7 +94,7 @@ def check_secure_delete_capability() -> bool: try: subprocess.check_output(["shred", "--help"]) return True - except EnvironmentError as e: + except OSError as e: if e.errno != errno.ENOENT: raise logging.error("The shred utility is missing.") diff --git a/securedrop/secure_tempfile.py b/securedrop/secure_tempfile.py --- a/securedrop/secure_tempfile.py +++ b/securedrop/secure_tempfile.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- import base64 -import io import os from tempfile import _TemporaryFileWrapper # type: ignore from typing import Optional, Union @@ -13,7 +11,7 @@ from pretty_bad_protocol._util import _STREAMLIKE_TYPES -class SecureTemporaryFile(_TemporaryFileWrapper, object): +class SecureTemporaryFile(_TemporaryFileWrapper): """Temporary file that provides on-the-fly encryption. Buffering large submissions in memory as they come in requires too @@ -53,9 +51,9 @@ def __init__(self, store_dir: str) -> None: data = base64.urlsafe_b64encode(os.urandom(32)) self.tmp_file_id = data.decode("utf-8").strip("=") - self.filepath = os.path.join(store_dir, "{}.aes".format(self.tmp_file_id)) - self.file = io.open(self.filepath, "w+b") - super(SecureTemporaryFile, self).__init__(self.file, self.filepath) + self.filepath = os.path.join(store_dir, f"{self.tmp_file_id}.aes") + self.file = open(self.filepath, "w+b") + super().__init__(self.file, self.filepath) def create_key(self) -> None: """Generates a unique, pseudorandom AES key, stored ephemerally in @@ -135,7 +133,7 @@ def close(self) -> None: # Since tempfile._TemporaryFileWrapper.close() does other cleanup, # (i.e. deleting the temp file on disk), we need to call it also. - super(SecureTemporaryFile, self).close() + super().close() # python-gnupg will not recognize our SecureTemporaryFile as a stream-like type diff --git a/securedrop/server_os.py b/securedrop/server_os.py --- a/securedrop/server_os.py +++ b/securedrop/server_os.py @@ -3,7 +3,7 @@ FOCAL_VERSION = "20.04" [email protected]_cache() [email protected]_cache def get_os_release() -> str: with open("/etc/os-release") as f: os_release = f.readlines() diff --git a/securedrop/source_app/info.py b/securedrop/source_app/info.py --- a/securedrop/source_app/info.py +++ b/securedrop/source_app/info.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from io import BytesIO # noqa import flask diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -1,4 +1,3 @@ -import io import operator import os from base64 import urlsafe_b64encode @@ -118,7 +117,7 @@ def create() -> werkzeug.Response: source_app_storage=Storage.get_default(), ) except (SourcePassphraseCollisionError, SourceDesignationCollisionError) as e: - current_app.logger.error("Could not create a source: {}".format(e)) + current_app.logger.error(f"Could not create a source: {e}") flash_msg( "error", None, @@ -159,7 +158,7 @@ def lookup(logged_in_source: SourceUser) -> str: reply.filename, ) try: - with io.open(reply_path, "rb") as f: + with open(reply_path, "rb") as f: contents = f.read() decrypted_reply = EncryptionManager.get_default().decrypt_journalist_reply( for_source_user=logged_in_source, ciphertext_in=contents diff --git a/securedrop/source_app/utils.py b/securedrop/source_app/utils.py --- a/securedrop/source_app/utils.py +++ b/securedrop/source_app/utils.py @@ -93,14 +93,14 @@ def check_url_file(path: str, regexp: str) -> "Optional[str]": files in /var/lib/securedrop (as the Apache user can't read Tor config) """ try: - f = open(path, "r") + f = open(path) contents = f.readline().strip() f.close() if re.match(regexp, contents): return contents else: return None - except IOError: + except OSError: return None diff --git a/securedrop/source_user.py b/securedrop/source_user.py --- a/securedrop/source_user.py +++ b/securedrop/source_user.py @@ -109,7 +109,7 @@ def create_source_user( except IntegrityError: db_session.rollback() raise SourcePassphraseCollisionError( - "Passphrase already used by another Source (filesystem_id {})".format(filesystem_id) + f"Passphrase already used by another Source (filesystem_id {filesystem_id})" ) # Create the source's folder diff --git a/securedrop/specialstrings.py b/securedrop/specialstrings.py --- a/securedrop/specialstrings.py +++ b/securedrop/specialstrings.py @@ -1,6 +1,6 @@ strings = [ """This is a test message without markup!""", - """This is a test message with markup and characters such as \, \\, \', \" and ". """ + """This is a test message with markup and characters such as \\, \\, \', \" and ". """ + """<strong>This text should not be bold</strong>!""", # noqa: W605, E501 """~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%""", """Ω≈ç√∫˜µ≤≥÷ diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import binascii import gzip import os @@ -96,11 +95,11 @@ def safe_renames(old: str, new: str) -> None: class Storage: def __init__(self, storage_path: str, temp_dir: str) -> None: if not os.path.isabs(storage_path): - raise PathException("storage_path {} is not absolute".format(storage_path)) + raise PathException(f"storage_path {storage_path} is not absolute") self.__storage_path = storage_path if not os.path.isabs(temp_dir): - raise PathException("temp_dir {} is not absolute".format(temp_dir)) + raise PathException(f"temp_dir {temp_dir} is not absolute") self.__temp_dir = temp_dir # where files and directories are sent to be securely deleted @@ -159,7 +158,7 @@ def verify(self, p: str) -> bool: if os.path.isfile(p) and VALIDATE_FILENAME(os.path.basename(p)): return True - raise PathException("Path not valid in store: {}".format(p)) + raise PathException(f"Path not valid in store: {p}") def path(self, filesystem_id: str, filename: str = "") -> str: """ @@ -192,14 +191,12 @@ def path_without_filesystem_id(self, filename: str) -> str: if len(joined_paths) > 1: raise TooManyFilesException("Found duplicate files!") elif len(joined_paths) == 0: - raise NoFileFoundException("File not found: {}".format(filename)) + raise NoFileFoundException(f"File not found: {filename}") else: absolute = joined_paths[0] if not self.verify(absolute): - raise PathException( - """Could not resolve "{}" to a path within the store.""".format(filename) - ) + raise PathException(f"""Could not resolve "{filename}" to a path within the store.""") return absolute def get_bulk_archive( @@ -209,7 +206,7 @@ def get_bulk_archive( zip_file = tempfile.NamedTemporaryFile( prefix="tmp_securedrop_bulk_dl_", dir=self.__temp_dir, delete=False ) - sources = set([i.source.journalist_designation for i in selected_submissions]) + sources = {i.source.journalist_designation for i in selected_submissions} # The below nested for-loops are there to create a more usable # folder structure per #383 missing_files = False @@ -233,13 +230,13 @@ def get_bulk_archive( filename, arcname=os.path.join( fname, - "%s_%s" % (document_number, submission.source.last_updated.date()), + f"{document_number}_{submission.source.last_updated.date()}", os.path.basename(filename), ), ) else: missing_files = True - current_app.logger.error("File {} not found".format(filename)) + current_app.logger.error(f"File {filename} not found") if missing_files: raise FileNotFoundError @@ -261,14 +258,14 @@ def move_to_shredder(self, path: str) -> None: shredder directory. """ if not self.verify(path): - raise ValueError("""Path is not within the store: "{}" """.format(path)) + raise ValueError(f"""Path is not within the store: "{path}" """) if not os.path.exists(path): - raise ValueError("""Path does not exist: "{}" """.format(path)) + raise ValueError(f"""Path does not exist: "{path}" """) relpath = os.path.relpath(path, start=self.storage_path) dest = os.path.join(tempfile.mkdtemp(dir=self.__shredder_path), relpath) - current_app.logger.info("Moving {} to shredder: {}".format(path, dest)) + current_app.logger.info(f"Moving {path} to shredder: {dest}") safe_renames(path, dest) def clear_shredder(self) -> None: @@ -291,27 +288,25 @@ def clear_shredder(self) -> None: # again, shouldn't occur in the store -- will # result in the file data being shredded once for # each link. - current_app.logger.info( - "Deleting link {} to {}".format(abs_file, os.readlink(abs_file)) - ) + current_app.logger.info(f"Deleting link {abs_file} to {os.readlink(abs_file)}") os.unlink(abs_file) continue if self.shredder_contains(abs_file): targets.append(abs_file) target_count = len(targets) - current_app.logger.info("Files to delete: {}".format(target_count)) + current_app.logger.info(f"Files to delete: {target_count}") for i, t in enumerate(targets, 1): - current_app.logger.info("Securely deleting file {}/{}: {}".format(i, target_count, t)) + current_app.logger.info(f"Securely deleting file {i}/{target_count}: {t}") rm.secure_delete(t) - current_app.logger.info("Securely deleted file {}/{}: {}".format(i, target_count, t)) + current_app.logger.info(f"Securely deleted file {i}/{target_count}: {t}") directories_to_remove = set(directories) dir_count = len(directories_to_remove) for i, d in enumerate(reversed(sorted(directories_to_remove)), 1): - current_app.logger.debug("Removing directory {}/{}: {}".format(i, dir_count, d)) + current_app.logger.debug(f"Removing directory {i}/{dir_count}: {d}") os.rmdir(d) - current_app.logger.debug("Removed directory {}/{}: {}".format(i, dir_count, d)) + current_app.logger.debug(f"Removed directory {i}/{dir_count}: {d}") def save_file_submission( self, @@ -340,7 +335,7 @@ def save_file_submission( # file. Given various usability constraints in GPG and Tails, this # is the most user-friendly way we have found to do this. - encrypted_file_name = "{0}-{1}-doc.gz.gpg".format(count, journalist_filename) + encrypted_file_name = f"{count}-{journalist_filename}-doc.gz.gpg" encrypted_file_path = self.path(filesystem_id, encrypted_file_name) with SecureTemporaryFile("/tmp") as stf: # nosec with gzip.GzipFile(filename=sanitized_filename, mode="wb", fileobj=stf, mtime=0) as gzf: @@ -365,7 +360,7 @@ def save_pre_encrypted_reply( if "-----BEGIN PGP MESSAGE-----" not in content.split("\n")[0]: raise NotEncrypted - encrypted_file_name = "{0}-{1}-reply.gpg".format(count, journalist_filename) + encrypted_file_name = f"{count}-{journalist_filename}-reply.gpg" encrypted_file_path = self.path(filesystem_id, encrypted_file_name) with open(encrypted_file_path, "w") as fh: @@ -376,7 +371,7 @@ def save_pre_encrypted_reply( def save_message_submission( self, filesystem_id: str, count: int, journalist_filename: str, message: str ) -> str: - filename = "{0}-{1}-msg.gpg".format(count, journalist_filename) + filename = f"{count}-{journalist_filename}-msg.gpg" msg_loc = self.path(filesystem_id, filename) EncryptionManager.get_default().encrypt_source_message( message_in=message, diff --git a/securedrop/template_filters.py b/securedrop/template_filters.py --- a/securedrop/template_filters.py +++ b/securedrop/template_filters.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import math from datetime import datetime diff --git a/securedrop/upload-screenshots.py b/securedrop/upload-screenshots.py --- a/securedrop/upload-screenshots.py +++ b/securedrop/upload-screenshots.py @@ -107,7 +107,7 @@ def __init__( self.session = requests.Session() headers = { "User-Agent": self.user_agent, - "Authorization": "Token {}".format(token), + "Authorization": f"Token {token}", } self.session.headers.update(headers) @@ -130,7 +130,7 @@ def get_existing_screenshots(self) -> List[Dict[str, str]]: screenshots += screenshots_page["results"] request_count += 1 if request_count >= self.request_limit: - msg = "Request limit of {} exceeded. Aborting.".format(self.request_limit) + msg = f"Request limit of {self.request_limit} exceeded. Aborting." raise RequestLimitError(msg) return screenshots @@ -168,7 +168,7 @@ def upload(self, check_existing_screenshots: bool = True) -> None: image = {"image": open(file, "rb")} if existing_screenshot_url is not None: - print("Replacing existing screenshot {}".format(basename)) + print(f"Replacing existing screenshot {basename}") response = self.session.post(existing_screenshot_url, files=image) response.raise_for_status() else: @@ -177,14 +177,12 @@ def upload(self, check_existing_screenshots: bool = True) -> None: "project_slug": "securedrop", "component_slug": "securedrop", } - print("Uploading new screenshot {}".format(basename)) + print(f"Uploading new screenshot {basename}") response = self.session.post(self.screenshots_endpoint, files=image, data=fields) response.raise_for_status() - result_url = urljoin( - self.base_url, "screenshots/{}/{}".format(self.project, self.component) - ) - print("Upload complete. Visit {} to review the results.".format(result_url)) + result_url = urljoin(self.base_url, f"screenshots/{self.project}/{self.component}") + print(f"Upload complete. Visit {result_url} to review the results.") class BadOrMissingTokenError(Exception): diff --git a/securedrop/worker.py b/securedrop/worker.py --- a/securedrop/worker.py +++ b/securedrop/worker.py @@ -73,11 +73,11 @@ def requeue_interrupted_jobs(queue_name: str) -> None: started_job_registry = StartedJobRegistry(queue=queue) queued_job_ids = queue.get_job_ids() - logging.debug("queued jobs: {}".format(queued_job_ids)) + logging.debug(f"queued jobs: {queued_job_ids}") started_job_ids = started_job_registry.get_job_ids() - logging.debug("started jobs: {}".format(started_job_ids)) + logging.debug(f"started jobs: {started_job_ids}") job_ids = [j for j in started_job_ids if j not in queued_job_ids] - logging.debug("candidate job ids: {}".format(job_ids)) + logging.debug(f"candidate job ids: {job_ids}") if not job_ids: logging.debug("No interrupted jobs found in started job registry.")
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -1,4 +1,3 @@ -import io import os import re import shutil @@ -118,7 +117,7 @@ def setup_function(function): global SD_DIR SD_DIR = tempfile.mkdtemp() - ANSIBLE_BASE = "{0}/install_files/ansible-base".format(SD_DIR) + ANSIBLE_BASE = f"{SD_DIR}/install_files/ansible-base" for name in ["roles", "tasks"]: shutil.copytree( @@ -131,22 +130,20 @@ def setup_function(function): os.path.join(CURRENT_DIR, "../../install_files/ansible-base", name), ANSIBLE_BASE ) - cmd = "mkdir -p {0}/group_vars/all".format(ANSIBLE_BASE).split() + cmd = f"mkdir -p {ANSIBLE_BASE}/group_vars/all".split() subprocess.check_call(cmd) for name in ["sd_admin_test.pub", "ca.crt", "sd.crt", "key.asc"]: - subprocess.check_call( - "cp -r {0}/files/{1} {2}".format(CURRENT_DIR, name, ANSIBLE_BASE).split() - ) + subprocess.check_call(f"cp -r {CURRENT_DIR}/files/{name} {ANSIBLE_BASE}".split()) for name in ["de_DE", "es_ES", "fr_FR", "pt_BR"]: - dircmd = "mkdir -p {0}/securedrop/translations/{1}".format(SD_DIR, name) + dircmd = f"mkdir -p {SD_DIR}/securedrop/translations/{name}" subprocess.check_call(dircmd.split()) subprocess.check_call( - "cp {0}/files/securedrop/i18n.json {1}/securedrop".format(CURRENT_DIR, SD_DIR).split() + f"cp {CURRENT_DIR}/files/securedrop/i18n.json {SD_DIR}/securedrop".split() ) def teardown_function(function): - subprocess.check_call("rm -rf {0}".format(SD_DIR).split()) + subprocess.check_call(f"rm -rf {SD_DIR}".split()) def verify_username_prompt(child): @@ -290,7 +287,7 @@ def verify_install_has_valid_config(): Checks that securedrop-admin install validates the configuration. """ cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") - child = pexpect.spawn("python {0} --force --root {1} install".format(cmd, SD_DIR)) + child = pexpect.spawn(f"python {cmd} --force --root {SD_DIR} install") child.expect(b"SUDO password:", timeout=5) child.close() @@ -300,7 +297,7 @@ def test_install_with_no_config(): Checks that securedrop-admin install complains about a missing config file. """ cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") - child = pexpect.spawn("python {0} --force --root {1} install".format(cmd, SD_DIR)) + child = pexpect.spawn(f"python {cmd} --force --root {SD_DIR} install") child.expect(b'ERROR: Please run "securedrop-admin sdconfig" first.', timeout=5) child.expect(pexpect.EOF, timeout=5) child.close() @@ -310,7 +307,7 @@ def test_install_with_no_config(): def test_sdconfig_on_first_run(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") - child = pexpect.spawn("python {0} --force --root {1} sdconfig".format(cmd, SD_DIR)) + child = pexpect.spawn(f"python {cmd} --force --root {SD_DIR} sdconfig") verify_username_prompt(child) child.sendline("") verify_reboot_prompt(child) @@ -373,7 +370,7 @@ def test_sdconfig_on_first_run(): def test_sdconfig_enable_journalist_alerts(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") - child = pexpect.spawn("python {0} --force --root {1} sdconfig".format(cmd, SD_DIR)) + child = pexpect.spawn(f"python {cmd} --force --root {SD_DIR} sdconfig") verify_username_prompt(child) child.sendline("") verify_reboot_prompt(child) @@ -439,7 +436,7 @@ def test_sdconfig_enable_journalist_alerts(): def test_sdconfig_enable_https_on_source_interface(): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") - child = pexpect.spawn("python {0} --force --root {1} sdconfig".format(cmd, SD_DIR)) + child = pexpect.spawn(f"python {cmd} --force --root {SD_DIR} sdconfig") verify_username_prompt(child) child.sendline("") verify_reboot_prompt(child) @@ -535,7 +532,7 @@ def securedrop_git_repo(tmpdir): os.chdir(os.path.join(str(tmpdir), "securedrop/admin")) subprocess.check_call("git reset --hard".split()) # Now we will put in our own git configuration - with io.open("../.git/config", "w") as fobj: + with open("../.git/config", "w") as fobj: fobj.write(GIT_CONFIG) # Let us move to an older tag subprocess.check_call("git checkout 0.6".split()) @@ -547,8 +544,8 @@ def securedrop_git_repo(tmpdir): subprocess.check_call( [ "cp", - "{}/securedrop/admin/.coverage".format(str(tmpdir)), - "{}/../.coverage.{}".format(CURRENT_DIR, test_name), + f"{str(tmpdir)}/securedrop/admin/.coverage", + f"{CURRENT_DIR}/../.coverage.{test_name}", ] ) except subprocess.CalledProcessError: @@ -575,7 +572,7 @@ def set_reliable_keyserver(gpgdir): def test_check_for_update_when_updates_needed(securedrop_git_repo): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") - fullcmd = "coverage run {0} --root {1} check_for_updates".format(cmd, ansible_base) + fullcmd = f"coverage run {cmd} --root {ansible_base} check_for_updates" child = pexpect.spawn(fullcmd) child.expect(b"Update needed", timeout=20) @@ -598,7 +595,7 @@ def test_check_for_update_when_updates_not_needed(securedrop_git_repo): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") - fullcmd = "coverage run {0} --root {1} check_for_updates".format(cmd, ansible_base) + fullcmd = f"coverage run {cmd} --root {ansible_base} check_for_updates" child = pexpect.spawn(fullcmd) child.expect(b"All updates applied", timeout=20) @@ -615,7 +612,7 @@ def test_update(securedrop_git_repo): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") - child = pexpect.spawn("coverage run {0} --root {1} update".format(cmd, ansible_base)) + child = pexpect.spawn(f"coverage run {cmd} --root {ansible_base} update") output = child.read() assert b"Updated to SecureDrop" in output @@ -643,7 +640,7 @@ def test_update_fails_when_no_signature_present(securedrop_git_repo): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") - child = pexpect.spawn("coverage run {0} --root {1} update".format(cmd, ansible_base)) + child = pexpect.spawn(f"coverage run {cmd} --root {ansible_base} update") output = child.read() assert b"Updated to SecureDrop" not in output assert b"Signature verification failed" in output @@ -675,7 +672,7 @@ def test_update_with_duplicate_branch_and_tag(securedrop_git_repo): cmd = os.path.join(os.path.dirname(CURRENT_DIR), "securedrop_admin/__init__.py") ansible_base = os.path.join(str(securedrop_git_repo), "securedrop/install_files/ansible-base") - child = pexpect.spawn("coverage run {0} --root {1} update".format(cmd, ansible_base)) + child = pexpect.spawn(f"coverage run {cmd} --root {ansible_base} update") output = child.read() # Verify that we do not falsely check out a branch instead of a tag. assert b"Switched to branch" not in output diff --git a/admin/tests/test_securedrop-admin-setup.py b/admin/tests/test_securedrop-admin-setup.py --- a/admin/tests/test_securedrop-admin-setup.py +++ b/admin/tests/test_securedrop-admin-setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # SecureDrop whistleblower submission system # Copyright (C) 2017 Loic Dachary <[email protected]> @@ -20,13 +19,13 @@ import argparse import os import subprocess +from unittest import mock import bootstrap -import mock import pytest -class TestSecureDropAdmin(object): +class TestSecureDropAdmin: def test_verbose(self, capsys): bootstrap.setup_logger(verbose=True) bootstrap.sdlog.debug("VISIBLE") diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # SecureDrop whistleblower submission system # Copyright (C) 2017- Freedom of the Press Foundation and SecureDrop @@ -19,14 +18,13 @@ # import argparse -import io import json import os import subprocess import textwrap from os.path import basename, dirname, exists, join +from unittest import mock -import mock import pytest import securedrop_admin import yaml @@ -34,13 +32,13 @@ from prompt_toolkit.validation import ValidationError -class Document(object): +class Document: def __init__(self, text): self.text = text @flaky -class TestSecureDropAdmin(object): +class TestSecureDropAdmin: def test_verbose(self, capsys): securedrop_admin.setup_logger(verbose=True) securedrop_admin.sdlog.debug("VISIBLE") @@ -494,7 +492,7 @@ def test_exit_codes(self, tmpdir): assert e.value.code == securedrop_admin.EXIT_INTERRUPT -class TestSiteConfig(object): +class TestSiteConfig: def test_exists(self, tmpdir): args = argparse.Namespace( site_config="DOES_NOT_EXIST", @@ -689,7 +687,7 @@ def test_save(self, tmpdir): var2: val2 """ ) - assert expected == io.open(site_config_path).read() + assert expected == open(site_config_path).read() def test_validate_gpg_key(self, tmpdir, caplog): args = argparse.Namespace( diff --git a/journalist_gui/test_gui.py b/journalist_gui/test_gui.py --- a/journalist_gui/test_gui.py +++ b/journalist_gui/test_gui.py @@ -75,7 +75,7 @@ def setUp(self): class WindowTestCase(AppTestCase): def setUp(self): - super(WindowTestCase, self).setUp() + super().setUp() self.window = UpdaterApp() self.window.show() QTest.qWaitForWindowExposed(self.window) diff --git a/molecule/ansible-config/tests/test_play_configuration.py b/molecule/ansible-config/tests/test_play_configuration.py --- a/molecule/ansible-config/tests/test_play_configuration.py +++ b/molecule/ansible-config/tests/test_play_configuration.py @@ -1,4 +1,3 @@ -import io import os import pytest @@ -58,7 +57,7 @@ def test_max_fail_percentage(host, playbook): the parameter, but we'll play it safe and require it everywhere, to avoid mistakes down the road. """ - with io.open(playbook, "r") as f: + with open(playbook) as f: playbook_yaml = yaml.safe_load(f) # Descend into playbook list structure to validate play attributes. for play in playbook_yaml: @@ -74,7 +73,7 @@ def test_any_errors_fatal(host, playbook): to "0", doing so ensures that any errors will cause an immediate failure on the playbook. """ - with io.open(playbook, "r") as f: + with open(playbook) as f: playbook_yaml = yaml.safe_load(f) # Descend into playbook list structure to validate play attributes. for play in playbook_yaml: @@ -89,7 +88,7 @@ def test_locale(host, playbook): The securedrop-prod and securedrop-staging playbooks should control the locale in the host environment by setting LC_ALL=C. """ - with io.open(os.path.join(ANSIBLE_BASE, playbook), "r") as f: + with open(os.path.join(ANSIBLE_BASE, playbook)) as f: playbook_yaml = yaml.safe_load(f) for play in playbook_yaml: assert "environment" in play diff --git a/molecule/builder-focal/tests/test_build_dependencies.py b/molecule/builder-focal/tests/test_build_dependencies.py --- a/molecule/builder-focal/tests/test_build_dependencies.py +++ b/molecule/builder-focal/tests/test_build_dependencies.py @@ -6,7 +6,7 @@ SECUREDROP_PYTHON_VERSION = os.environ.get("SECUREDROP_PYTHON_VERSION", "3.8") DH_VIRTUALENV_VERSION = "1.2.2" -testinfra_hosts = ["docker://{}-sd-app".format(SECUREDROP_TARGET_DISTRIBUTION)] +testinfra_hosts = [f"docker://{SECUREDROP_TARGET_DISTRIBUTION}-sd-app"] @pytest.mark.xfail(reason="This check conflicts with the concept of pegging" "dependencies") @@ -29,7 +29,7 @@ def test_python_version(host): we must be careful not to change Python as well. """ c = host.run("python3 --version") - version_string = "Python {}".format(SECUREDROP_PYTHON_VERSION) + version_string = f"Python {SECUREDROP_PYTHON_VERSION}" assert c.stdout.startswith(version_string) @@ -38,6 +38,6 @@ def test_dh_virtualenv(host): Confirm the expected version of dh-virtualenv is found. """ expected_version = DH_VIRTUALENV_VERSION - version_string = "dh_virtualenv {}".format(expected_version) + version_string = f"dh_virtualenv {expected_version}" c = host.run("dh_virtualenv --version") assert c.stdout.startswith(version_string) diff --git a/molecule/builder-focal/tests/test_securedrop_deb_package.py b/molecule/builder-focal/tests/test_securedrop_deb_package.py --- a/molecule/builder-focal/tests/test_securedrop_deb_package.py +++ b/molecule/builder-focal/tests/test_securedrop_deb_package.py @@ -8,7 +8,7 @@ from testinfra.host import Host SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -testinfra_hosts = ["docker://{}-sd-dpkg-verification".format(SECUREDROP_TARGET_DISTRIBUTION)] +testinfra_hosts = [f"docker://{SECUREDROP_TARGET_DISTRIBUTION}-sd-dpkg-verification"] def extract_package_name_from_filepath(filepath: str) -> str: @@ -164,9 +164,9 @@ def test_deb_packages_appear_installable(host: Host, deb: Path) -> None: # sudo is required to call `dpkg --install`, even as dry-run. with host.sudo(): - c = host.run("dpkg --install --dry-run {}".format(deb)) - assert "Selecting previously unselected package {}".format(package_name) in c.stdout - regex = "Preparing to unpack [./]+{} ...".format(re.escape(deb.name)) + c = host.run(f"dpkg --install --dry-run {deb}") + assert f"Selecting previously unselected package {package_name}" in c.stdout + regex = f"Preparing to unpack [./]+{re.escape(deb.name)} ..." assert re.search(regex, c.stdout, re.M) assert c.rc == 0 @@ -181,7 +181,7 @@ def test_deb_package_control_fields(host: Host, deb: Path) -> None: """ package_name = extract_package_name_from_filepath(str(deb)) # The `--field` option will display all fields if none are specified. - c = host.run("dpkg-deb --field {}".format(deb)) + c = host.run(f"dpkg-deb --field {deb}") assert "Maintainer: SecureDrop Team <[email protected]>" in c.stdout arch_all = ( @@ -196,14 +196,14 @@ def test_deb_package_control_fields(host: Host, deb: Path) -> None: else: assert "Architecture: amd64" in c.stdout - assert "Package: {}".format(package_name) in c.stdout + assert f"Package: {package_name}" in c.stdout assert c.rc == 0 @pytest.mark.parametrize("deb", deb_paths.values()) def test_deb_package_control_fields_homepage(host: Host, deb: Path): # The `--field` option will display all fields if none are specified. - c = host.run("dpkg-deb --field {}".format(deb)) + c = host.run(f"dpkg-deb --field {deb}") # The OSSEC source packages will have a different homepage; # all other packages should set securedrop.org as homepage. if deb.name.startswith("ossec-"): @@ -284,7 +284,7 @@ def test_deb_package_contains_expected_conffiles(host: Host, deb: Path): mktemp = host.run("mktemp -d") tmpdir = mktemp.stdout.strip() # The `--raw-extract` flag includes `DEBIAN/` dir with control files - host.run("dpkg-deb --raw-extract {} {}".format(deb, tmpdir)) + host.run(f"dpkg-deb --raw-extract {deb} {tmpdir}") conffiles_path = os.path.join(tmpdir, "DEBIAN", "conffiles") f = host.file(conffiles_path) @@ -349,7 +349,7 @@ def test_deb_package_lintian(host: Host, deb: Path, tag: str): """ Ensures lintian likes our Debian packages. """ - c = host.run("lintian --tags {} --no-tag-display-limit {}".format(tag, deb)) + c = host.run(f"lintian --tags {tag} --no-tag-display-limit {deb}") assert len(c.stdout) == 0 @@ -410,7 +410,7 @@ def test_jinja_files_not_present(host: Host, deb: Path): as-is into the debian packages. """ - c = host.run("dpkg-deb --contents {}".format(deb)) + c = host.run(f"dpkg-deb --contents {deb}") # There shouldn't be any files with a .j2 ending assert not re.search(r"^.*\.j2$", c.stdout, re.M) @@ -433,7 +433,7 @@ def test_ossec_binaries_are_present_agent(host: Host): c = host.run("dpkg-deb -c {}".format(deb_paths["ossec_agent"])) for wanted_file in wanted_files: assert re.search( - r"^.* .{}$".format(wanted_file), + rf"^.* .{wanted_file}$", c.stdout, re.M, ) @@ -474,7 +474,7 @@ def test_ossec_binaries_are_present_server(host: Host): c = host.run("dpkg-deb --contents {}".format(deb_paths["ossec_server"])) for wanted_file in wanted_files: assert re.search( - r"^.* .{}$".format(wanted_file), + rf"^.* .{wanted_file}$", c.stdout, re.M, ) @@ -494,7 +494,7 @@ def test_config_package_contains_expected_files(host: Host) -> None: c = host.run("dpkg-deb --contents {}".format(deb_paths["securedrop_config"])) for wanted_file in wanted_files: assert re.search( - r"^.* .{}$".format(wanted_file), + rf"^.* .{wanted_file}$", c.stdout, re.M, ) diff --git a/molecule/builder-focal/tests/test_security_updates.py b/molecule/builder-focal/tests/test_security_updates.py --- a/molecule/builder-focal/tests/test_security_updates.py +++ b/molecule/builder-focal/tests/test_security_updates.py @@ -5,7 +5,7 @@ import pytest SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -testinfra_hosts = ["docker://{}-sd-sec-update".format(SECUREDROP_TARGET_DISTRIBUTION)] +testinfra_hosts = [f"docker://{SECUREDROP_TARGET_DISTRIBUTION}-sd-sec-update"] def test_should_run(): diff --git a/molecule/testinfra/app-code/test_securedrop_app_code.py b/molecule/testinfra/app-code/test_securedrop_app_code.py --- a/molecule/testinfra/app-code/test_securedrop_app_code.py +++ b/molecule/testinfra/app-code/test_securedrop_app_code.py @@ -23,7 +23,7 @@ def test_apache_default_docroot_is_absent(host): "coreutils", "gnupg2", "libapache2-mod-xsendfile", - "libpython{}".format(python_version), + f"libpython{python_version}", "paxctld", "python3", "redis-server", @@ -57,7 +57,7 @@ def test_securedrop_application_test_locale(host): """ Ensure both SecureDrop DEFAULT_LOCALE and SUPPORTED_LOCALES are present. """ - securedrop_config = host.file("{}/config.py".format(securedrop_test_vars.securedrop_code)) + securedrop_config = host.file(f"{securedrop_test_vars.securedrop_code}/config.py") with host.sudo(): assert securedrop_config.is_file assert securedrop_config.contains("^DEFAULT_LOCALE") @@ -72,9 +72,7 @@ def test_securedrop_application_test_journalist_key(host): Ensure the SecureDrop Application GPG public key file is present. This is a test-only pubkey provided in the repository strictly for testing. """ - pubkey_file = host.file( - "{}/test_journalist_key.pub".format(securedrop_test_vars.securedrop_data) - ) + pubkey_file = host.file(f"{securedrop_test_vars.securedrop_data}/test_journalist_key.pub") # sudo is only necessary when testing against app hosts, since the # permissions are tighter. Let's elevate privileges so we're sure # we can read the correct file attributes and test them. @@ -86,7 +84,7 @@ def test_securedrop_application_test_journalist_key(host): # Let's make sure the corresponding fingerprint is specified # in the SecureDrop app configuration. - securedrop_config = host.file("{}/config.py".format(securedrop_test_vars.securedrop_code)) + securedrop_config = host.file(f"{securedrop_test_vars.securedrop_code}/config.py") with host.sudo(): assert securedrop_config.is_file assert securedrop_config.user == securedrop_test_vars.securedrop_code_owner @@ -105,7 +103,7 @@ def test_securedrop_application_sqlite_db(host): # sudo is necessary under the App hosts, which have restrictive file # permissions on the doc root. Not technically necessary under dev host. with host.sudo(): - f = host.file("{}/db.sqlite".format(securedrop_test_vars.securedrop_data)) + f = host.file(f"{securedrop_test_vars.securedrop_data}/db.sqlite") assert f.is_file assert f.user == securedrop_test_vars.securedrop_user assert f.group == securedrop_test_vars.securedrop_user diff --git a/molecule/testinfra/app-code/test_securedrop_rqrequeue.py b/molecule/testinfra/app-code/test_securedrop_rqrequeue.py --- a/molecule/testinfra/app-code/test_securedrop_rqrequeue.py +++ b/molecule/testinfra/app-code/test_securedrop_rqrequeue.py @@ -28,12 +28,12 @@ def test_securedrop_rqrequeue_service(host): "PrivateTmp=yes", "ProtectSystem=full", "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + f"ReadWriteDirectories={securedrop_test_vars.securedrop_data}", "Restart=always", "RestartSec=10s", "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + f"User={securedrop_test_vars.securedrop_user}", + f"WorkingDirectory={securedrop_test_vars.securedrop_code}", "", "[Install]", "WantedBy=multi-user.target\n", diff --git a/molecule/testinfra/app-code/test_securedrop_rqworker.py b/molecule/testinfra/app-code/test_securedrop_rqworker.py --- a/molecule/testinfra/app-code/test_securedrop_rqworker.py +++ b/molecule/testinfra/app-code/test_securedrop_rqworker.py @@ -23,17 +23,17 @@ def test_securedrop_rqworker_service(host): securedrop_test_vars.securedrop_code, securedrop_test_vars.securedrop_venv_site_packages, ), - "ExecStart={}/rqworker".format(securedrop_test_vars.securedrop_venv_bin), + f"ExecStart={securedrop_test_vars.securedrop_venv_bin}/rqworker", "PrivateDevices=yes", "PrivateTmp=yes", "ProtectSystem=full", "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + f"ReadWriteDirectories={securedrop_test_vars.securedrop_data}", "Restart=always", "RestartSec=10s", "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + f"User={securedrop_test_vars.securedrop_user}", + f"WorkingDirectory={securedrop_test_vars.securedrop_code}", "", "[Install]", "WantedBy=multi-user.target\n", diff --git a/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py b/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py --- a/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py +++ b/molecule/testinfra/app-code/test_securedrop_shredder_configuration.py @@ -27,12 +27,12 @@ def test_securedrop_shredder_service(host): "PrivateTmp=yes", "ProtectSystem=full", "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + f"ReadWriteDirectories={securedrop_test_vars.securedrop_data}", "Restart=always", "RestartSec=10s", "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + f"User={securedrop_test_vars.securedrop_user}", + f"WorkingDirectory={securedrop_test_vars.securedrop_code}", "", "[Install]", "WantedBy=multi-user.target\n", diff --git a/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py b/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py --- a/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py +++ b/molecule/testinfra/app-code/test_securedrop_source_deleter_configuration.py @@ -26,12 +26,12 @@ def test_securedrop_source_deleter_service(host): "PrivateTmp=yes", "ProtectSystem=full", "ReadOnlyDirectories=/", - "ReadWriteDirectories={}".format(securedrop_test_vars.securedrop_data), + f"ReadWriteDirectories={securedrop_test_vars.securedrop_data}", "Restart=always", "RestartSec=10s", "UMask=077", - "User={}".format(securedrop_test_vars.securedrop_user), - "WorkingDirectory={}".format(securedrop_test_vars.securedrop_code), + f"User={securedrop_test_vars.securedrop_user}", + f"WorkingDirectory={securedrop_test_vars.securedrop_code}", "", "[Install]", "WantedBy=multi-user.target\n", diff --git a/molecule/testinfra/app/apache/test_apache_journalist_interface.py b/molecule/testinfra/app/apache/test_apache_journalist_interface.py --- a/molecule/testinfra/app/apache/test_apache_journalist_interface.py +++ b/molecule/testinfra/app/apache/test_apache_journalist_interface.py @@ -17,9 +17,9 @@ def test_apache_headers_journalist_interface(host, header, value): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - header_unset = "Header onsuccess unset {}".format(header) + header_unset = f"Header onsuccess unset {header}" assert f.contains(header_unset) - header_set = 'Header always set {} "{}"'.format(header, value) + header_set = f'Header always set {header} "{value}"' assert f.contains(header_set) @@ -27,7 +27,7 @@ def test_apache_headers_journalist_interface(host, header, value): @pytest.mark.parametrize( "apache_opt", [ - "<VirtualHost {}:8080>".format(securedrop_test_vars.apache_listening_address), + f"<VirtualHost {securedrop_test_vars.apache_listening_address}:8080>", "WSGIDaemonProcess journalist processes=2 threads=30 display-name=%{{GROUP}} python-path={}".format( # noqa securedrop_test_vars.securedrop_code ), @@ -37,7 +37,7 @@ def test_apache_headers_journalist_interface(host, header, value): ), "WSGIPassAuthorization On", 'Header set Cache-Control "no-store"', - "Alias /static {}/static".format(securedrop_test_vars.securedrop_code), + f"Alias /static {securedrop_test_vars.securedrop_code}/static", "XSendFile On", "LimitRequestBody 524288000", "XSendFilePath /var/lib/securedrop/store/", @@ -60,7 +60,7 @@ def test_apache_config_journalist_interface(host, apache_opt): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - regex = "^{}$".format(re.escape(apache_opt)) + regex = f"^{re.escape(apache_opt)}$" assert re.search(regex, f.content_string, re.M) @@ -148,5 +148,5 @@ def test_apache_config_journalist_interface_access_control(host, apache_opt): Verifies the access control directives for the Journalist Interface. """ f = host.file("/etc/apache2/sites-available/journalist.conf") - regex = "^{}$".format(re.escape(apache_opt)) + regex = f"^{re.escape(apache_opt)}$" assert re.search(regex, f.content_string, re.M) diff --git a/molecule/testinfra/app/apache/test_apache_service.py b/molecule/testinfra/app/apache/test_apache_service.py --- a/molecule/testinfra/app/apache/test_apache_service.py +++ b/molecule/testinfra/app/apache/test_apache_service.py @@ -17,8 +17,8 @@ def test_apache_enabled_sites(host, apache_site): Ensure the Source and Journalist interfaces are enabled. """ with host.sudo(): - c = host.run("/usr/sbin/a2query -s {}".format(apache_site)) - assert "{} (enabled".format(apache_site) in c.stdout + c = host.run(f"/usr/sbin/a2query -s {apache_site}") + assert f"{apache_site} (enabled" in c.stdout assert c.rc == 0 @@ -32,8 +32,8 @@ def test_apache_disabled_sites(host, apache_site): """ Ensure the default HTML document root is disabled. """ - c = host.run("a2query -s {}".format(apache_site)) - assert "No site matches {} (disabled".format(apache_site) in c.stderr + c = host.run(f"a2query -s {apache_site}") + assert f"No site matches {apache_site} (disabled" in c.stderr assert c.rc == 32 @@ -74,5 +74,5 @@ def test_apache_listening(host, port): """ # sudo is necessary to read from /proc/net/tcp. with host.sudo(): - s = host.socket("tcp://{}:{}".format(securedrop_test_vars.apache_listening_address, port)) + s = host.socket(f"tcp://{securedrop_test_vars.apache_listening_address}:{port}") assert s.is_listening diff --git a/molecule/testinfra/app/apache/test_apache_source_interface.py b/molecule/testinfra/app/apache/test_apache_source_interface.py --- a/molecule/testinfra/app/apache/test_apache_source_interface.py +++ b/molecule/testinfra/app/apache/test_apache_source_interface.py @@ -17,16 +17,16 @@ def test_apache_headers_source_interface(host, header, value): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - header_unset = "Header onsuccess unset {}".format(header) + header_unset = f"Header onsuccess unset {header}" assert f.contains(header_unset) - header_set = 'Header always set {} "{}"'.format(header, value) + header_set = f'Header always set {header} "{value}"' assert f.contains(header_set) @pytest.mark.parametrize( "apache_opt", [ - "<VirtualHost {}:80>".format(securedrop_test_vars.apache_listening_address), + f"<VirtualHost {securedrop_test_vars.apache_listening_address}:80>", "WSGIDaemonProcess source processes=2 threads=30 display-name=%{{GROUP}} python-path={}".format( # noqa securedrop_test_vars.securedrop_code ), @@ -34,10 +34,10 @@ def test_apache_headers_source_interface(host, header, value): "WSGIScriptAlias / /var/www/source.wsgi", 'Header set Cache-Control "no-store"', "Header unset Etag", - "Alias /static {}/static".format(securedrop_test_vars.securedrop_code), + f"Alias /static {securedrop_test_vars.securedrop_code}/static", "XSendFile Off", "LimitRequestBody 524288000", - "ErrorLog {}".format(securedrop_test_vars.apache_source_log), + f"ErrorLog {securedrop_test_vars.apache_source_log}", ], ) def test_apache_config_source_interface(host, apache_opt): @@ -54,7 +54,7 @@ def test_apache_config_source_interface(host, apache_opt): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - regex = "^{}$".format(re.escape(apache_opt)) + regex = f"^{re.escape(apache_opt)}$" assert re.search(regex, f.content_string, re.M) @@ -116,5 +116,5 @@ def test_apache_config_source_interface_access_control(host, apache_opt): Verifies the access control directives for the Source Interface. """ f = host.file("/etc/apache2/sites-available/source.conf") - regex = "^{}$".format(re.escape(apache_opt)) + regex = f"^{re.escape(apache_opt)}$" assert re.search(regex, f.content_string, re.M) diff --git a/molecule/testinfra/app/apache/test_apache_system_config.py b/molecule/testinfra/app/apache/test_apache_system_config.py --- a/molecule/testinfra/app/apache/test_apache_system_config.py +++ b/molecule/testinfra/app/apache/test_apache_system_config.py @@ -66,7 +66,7 @@ def test_apache_config_settings(host, apache_opt): assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 - assert re.search("^{}$".format(re.escape(apache_opt)), f.content_string, re.M) + assert re.search(f"^{re.escape(apache_opt)}$", f.content_string, re.M) @pytest.mark.parametrize( @@ -125,8 +125,8 @@ def test_apache_modules_present(host, apache_module): disabled modules. """ with host.sudo(): - c = host.run("/usr/sbin/a2query -m {}".format(apache_module)) - assert "{} (enabled".format(apache_module) in c.stdout + c = host.run(f"/usr/sbin/a2query -m {apache_module}") + assert f"{apache_module} (enabled" in c.stdout assert c.rc == 0 @@ -147,8 +147,8 @@ def test_apache_modules_absent(host, apache_module): A separate test will check for disabled modules. """ with host.sudo(): - c = host.run("/usr/sbin/a2query -m {}".format(apache_module)) - assert "No module matches {} (disabled".format(apache_module) in c.stderr + c = host.run(f"/usr/sbin/a2query -m {apache_module}") + assert f"No module matches {apache_module} (disabled" in c.stderr assert c.rc == 32 diff --git a/molecule/testinfra/app/test_app_network.py b/molecule/testinfra/app/test_app_network.py --- a/molecule/testinfra/app/test_app_network.py +++ b/molecule/testinfra/app/test_app_network.py @@ -1,5 +1,4 @@ import difflib -import io import os import pytest @@ -38,7 +37,7 @@ def test_app_iptables_rules(host): ) # template out a local iptables jinja file - jinja_iptables = Template(io.open(iptables_file, "r").read()) + jinja_iptables = Template(open(iptables_file).read()) iptables_expected = jinja_iptables.render(**kwargs) with host.sudo(): diff --git a/molecule/testinfra/app/test_apparmor.py b/molecule/testinfra/app/test_apparmor.py --- a/molecule/testinfra/app/test_apparmor.py +++ b/molecule/testinfra/app/test_apparmor.py @@ -58,7 +58,7 @@ def test_apparmor_ensure_not_disabled(host, profile): Polling aa-status only checks the last config that was loaded, this ensures it wont be disabled on reboot. """ - f = host.file("/etc/apparmor.d/disabled/usr.sbin.{}".format(profile)) + f = host.file(f"/etc/apparmor.d/disabled/usr.sbin.{profile}") with host.sudo(): assert not f.exists @@ -68,7 +68,7 @@ def test_app_apparmor_complain(host, complain_pkg): """Ensure app-armor profiles are in complain mode for staging""" with host.sudo(): awk = "awk '/[0-9]+ profiles.*complain." "/{flag=1;next}/^[0-9]+.*/{flag=0}flag'" - c = host.check_output("aa-status | {}".format(awk)) + c = host.check_output(f"aa-status | {awk}") assert complain_pkg in c @@ -83,7 +83,7 @@ def test_app_apparmor_complain_count(host): def test_apparmor_enforced(host, aa_enforced): awk = "awk '/[0-9]+ profiles.*enforce./" "{flag=1;next}/^[0-9]+.*/{flag=0}flag'" with host.sudo(): - c = host.check_output("aa-status | {}".format(awk)) + c = host.check_output(f"aa-status | {awk}") assert aa_enforced in c diff --git a/molecule/testinfra/app/test_appenv.py b/molecule/testinfra/app/test_appenv.py --- a/molecule/testinfra/app/test_appenv.py +++ b/molecule/testinfra/app/test_appenv.py @@ -98,7 +98,7 @@ def test_gpg_key_in_keyring(host): def test_ensure_logo(host): """ensure default logo header file exists""" - f = host.file("{}/static/i/logo.png".format(sdvars.securedrop_code)) + f = host.file(f"{sdvars.securedrop_code}/static/i/logo.png") with host.sudo(): assert f.mode == 0o644 assert f.user == "root" @@ -109,7 +109,7 @@ def test_securedrop_tmp_clean_cron(host): """Ensure securedrop tmp clean cron job in place""" with host.sudo(): cronlist = host.run("crontab -u www-data -l").stdout - cronjob = "@daily {}/manage.py clean-tmp".format(sdvars.securedrop_code) + cronjob = f"@daily {sdvars.securedrop_code}/manage.py clean-tmp" assert cronjob in cronlist diff --git a/molecule/testinfra/app/test_ossec_agent.py b/molecule/testinfra/app/test_ossec_agent.py --- a/molecule/testinfra/app/test_ossec_agent.py +++ b/molecule/testinfra/app/test_ossec_agent.py @@ -16,7 +16,7 @@ def test_hosts_files(host): mon_host = sdvars.monitor_hostname assert f.contains(r"^127.0.0.1\s*localhost") - assert f.contains(r"^{}\s*{}\s*securedrop-monitor-server-alias$".format(mon_ip, mon_host)) + assert f.contains(rf"^{mon_ip}\s*{mon_host}\s*securedrop-monitor-server-alias$") def test_ossec_service_start_style(host): diff --git a/molecule/testinfra/app/test_tor_config.py b/molecule/testinfra/app/test_tor_config.py --- a/molecule/testinfra/app/test_tor_config.py +++ b/molecule/testinfra/app/test_tor_config.py @@ -52,7 +52,7 @@ def test_tor_torrc_options(host, torrc_option): assert f.is_file assert f.user == "debian-tor" assert f.mode == 0o644 - assert f.contains("^{}$".format(torrc_option)) + assert f.contains(f"^{torrc_option}$") def test_tor_torrc_sandbox(host): diff --git a/molecule/testinfra/app/test_tor_hidden_services.py b/molecule/testinfra/app/test_tor_hidden_services.py --- a/molecule/testinfra/app/test_tor_hidden_services.py +++ b/molecule/testinfra/app/test_tor_hidden_services.py @@ -54,7 +54,7 @@ def test_tor_service_hostnames(host, tor_service): ) assert client_auth.is_file else: - assert re.search("^{}$".format(ths_hostname_regex_v3), f.content_string) + assert re.search(f"^{ths_hostname_regex_v3}$", f.content_string) @pytest.mark.skip_in_prod @@ -78,10 +78,10 @@ def test_tor_services_config(host, tor_service): except IndexError: local_port = remote_port - port_regex = "HiddenServicePort {} 127.0.0.1:{}".format(remote_port, local_port) + port_regex = f"HiddenServicePort {remote_port} 127.0.0.1:{local_port}" - assert f.contains("^{}$".format(dir_regex)) - assert f.contains("^{}$".format(port_regex)) + assert f.contains(f"^{dir_regex}$") + assert f.contains(f"^{port_regex}$") # Check for block in file, to ensure declaration order service_regex = "\n".join([dir_regex, port_regex]) diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -54,7 +54,7 @@ def test_sources_list(host, repo): assert f.is_file assert f.user == "root" assert f.mode == 0o644 - repo_regex = "^{}$".format(re.escape(repo_config)) + repo_regex = f"^{re.escape(repo_config)}$" assert f.contains(repo_regex) @@ -70,7 +70,7 @@ def test_sources_list(host, repo): "APT::Periodic::Enable": "1", "Unattended-Upgrade::AutoFixInterruptedDpkg": "true", "Unattended-Upgrade::Automatic-Reboot": "true", - "Unattended-Upgrade::Automatic-Reboot-Time": "{}:00".format(test_vars.daily_reboot_time), + "Unattended-Upgrade::Automatic-Reboot-Time": f"{test_vars.daily_reboot_time}:00", "Unattended-Upgrade::Automatic-Reboot-WithUsers": "true", "Unattended-Upgrade::Origins-Pattern": [ "origin=${distro_id},archive=${distro_codename}", @@ -88,7 +88,7 @@ def test_unattended_upgrades_config(host, k, v): """ # Dump apt config to inspect end state, apt will build config # from all conf files on disk, e.g. 80securedrop. - c = host.run("apt-config dump --format '%v%n' {}".format(k)) + c = host.run(f"apt-config dump --format '%v%n' {k}") assert c.rc == 0 # Some values are lists, so support that in the params if hasattr(v, "__getitem__"): @@ -158,7 +158,7 @@ def test_apt_daily_timer_schedule(host): """ t = (int(test_vars.daily_reboot_time) - OFFSET_UPDATE) % 24 c = host.run("systemctl show apt-daily.timer") - assert "TimersCalendar={ OnCalendar=*-*-* " + "{:02d}".format(t) + ":00:00 ;" in c.stdout + assert "TimersCalendar={ OnCalendar=*-*-* " + f"{t:02d}" + ":00:00 ;" in c.stdout assert "RandomizedDelayUSec=20m" in c.stdout @@ -169,7 +169,7 @@ def test_apt_daily_upgrade_timer_schedule(host): """ t = (int(test_vars.daily_reboot_time) - OFFSET_UPGRADE) % 24 c = host.run("systemctl show apt-daily-upgrade.timer") - assert "TimersCalendar={ OnCalendar=*-*-* " + "{:02d}".format(t) + ":00:00 ;" in c.stdout + assert "TimersCalendar={ OnCalendar=*-*-* " + f"{t:02d}" + ":00:00 ;" in c.stdout assert "RandomizedDelayUSec=20m" in c.stdout diff --git a/molecule/testinfra/common/test_grsecurity.py b/molecule/testinfra/common/test_grsecurity.py --- a/molecule/testinfra/common/test_grsecurity.py +++ b/molecule/testinfra/common/test_grsecurity.py @@ -1,5 +1,4 @@ import difflib -import io import os import warnings @@ -52,9 +51,9 @@ def test_generic_kernels_absent(host, package): # Can't use the TestInfra Package module to check state=absent, # so let's check by shelling out to `dpkg -l`. Dpkg will automatically # honor simple regex in package names. - c = host.run("dpkg -l {}".format(package)) + c = host.run(f"dpkg -l {package}") assert c.rc == 1 - error_text = "dpkg-query: no packages found matching {}".format(package) + error_text = f"dpkg-query: no packages found matching {package}" assert error_text in c.stderr.strip() @@ -124,7 +123,7 @@ def test_grsecurity_paxtest(host): # https://github.com/freedomofpress/securedrop/issues/1039 if host.system_info.codename == "focal": memcpy_result = "Vulnerable" - with io.open(paxtest_template_path, "r") as f: + with open(paxtest_template_path) as f: paxtest_template = Template(f.read().rstrip()) paxtest_expected = paxtest_template.render(memcpy_result=memcpy_result) @@ -204,10 +203,10 @@ def test_wireless_disabled_in_kernel_config(host, kernel_opts): """ kernel_version = host.run("uname -r").stdout.strip() with host.sudo(): - kernel_config_path = "/boot/config-{}".format(kernel_version) + kernel_config_path = f"/boot/config-{kernel_version}" kernel_config = host.file(kernel_config_path).content_string - line = "# CONFIG_{} is not set".format(kernel_opts) + line = f"# CONFIG_{kernel_opts} is not set" assert line in kernel_config or kernel_opts not in kernel_config @@ -226,10 +225,10 @@ def test_kernel_options_enabled_config(host, kernel_opts): kernel_version = host.run("uname -r").stdout.strip() with host.sudo(): - kernel_config_path = "/boot/config-{}".format(kernel_version) + kernel_config_path = f"/boot/config-{kernel_version}" kernel_config = host.file(kernel_config_path).content_string - line = "{}=y".format(kernel_opts) + line = f"{kernel_opts}=y" assert line in kernel_config diff --git a/molecule/testinfra/common/test_release_upgrades.py b/molecule/testinfra/common/test_release_upgrades.py --- a/molecule/testinfra/common/test_release_upgrades.py +++ b/molecule/testinfra/common/test_release_upgrades.py @@ -23,7 +23,7 @@ def test_release_manager_upgrade_channel(host): config_path = "/etc/update-manager/release-upgrades" assert host.file(config_path).is_file - raw_output = host.check_output("grep '^Prompt' {}".format(config_path)) + raw_output = host.check_output(f"grep '^Prompt' {config_path}") _, channel = raw_output.split("=") assert channel == "never" diff --git a/molecule/testinfra/common/test_system_hardening.py b/molecule/testinfra/common/test_system_hardening.py --- a/molecule/testinfra/common/test_system_hardening.py +++ b/molecule/testinfra/common/test_system_hardening.py @@ -65,7 +65,7 @@ def test_blacklisted_kernel_modules(host, kernel_module): assert kernel_module not in c.stdout f = host.file("/etc/modprobe.d/blacklist.conf") - assert f.contains("^blacklist {}$".format(kernel_module)) + assert f.contains(f"^blacklist {kernel_module}$") def test_swap_disabled(host): @@ -124,7 +124,7 @@ def test_sshd_config(host, sshd_opts): sshd_config_file = host.file("/etc/ssh/sshd_config").content_string - line = "{} {}".format(sshd_opts[0], sshd_opts[1]) + line = f"{sshd_opts[0]} {sshd_opts[1]}" assert line in sshd_config_file diff --git a/molecule/testinfra/common/test_tor_mirror.py b/molecule/testinfra/common/test_tor_mirror.py --- a/molecule/testinfra/common/test_tor_mirror.py +++ b/molecule/testinfra/common/test_tor_mirror.py @@ -32,9 +32,9 @@ def test_tor_keyring_absent(host): # so let's check by shelling out to `dpkg -l`. Dpkg will automatically # honor simple regex in package names. package = "deb.torproject.org-keyring" - c = host.run("dpkg -l {}".format(package)) + c = host.run(f"dpkg -l {package}") assert c.rc == 1 - error_text = "dpkg-query: no packages found matching {}".format(package) + error_text = f"dpkg-query: no packages found matching {package}" assert error_text in c.stderr.strip() @@ -76,7 +76,7 @@ def test_tor_repo_absent(host, repo_pattern): in that repo. We're mirroring it to avoid breakage caused by untested updates (which has broken prod twice to date). """ - cmd = "grep -rF '{}' /etc/apt/".format(repo_pattern) + cmd = f"grep -rF '{repo_pattern}' /etc/apt/" c = host.run(cmd) # Grep returns non-zero when no matches, and we want no matches. assert c.rc != 0 diff --git a/molecule/testinfra/common/test_user_config.py b/molecule/testinfra/common/test_user_config.py --- a/molecule/testinfra/common/test_user_config.py +++ b/molecule/testinfra/common/test_user_config.py @@ -98,5 +98,5 @@ def test_sudoers_tmux_env_deprecated(host): old setting isn't still active. """ - f = host.file("/home/{}/.bashrc".format(sdvars.admin_user)) + f = host.file(f"/home/{sdvars.admin_user}/.bashrc") assert not f.contains(r"^. \/etc\/bashrc\.securedrop_additions$") diff --git a/molecule/testinfra/mon/test_mon_network.py b/molecule/testinfra/mon/test_mon_network.py --- a/molecule/testinfra/mon/test_mon_network.py +++ b/molecule/testinfra/mon/test_mon_network.py @@ -1,5 +1,4 @@ import difflib -import io import os import pytest @@ -38,7 +37,7 @@ def test_mon_iptables_rules(host): ) # template out a local iptables jinja file - jinja_iptables = Template(io.open(iptables_file, "r").read()) + jinja_iptables = Template(open(iptables_file).read()) iptables_expected = jinja_iptables.render(**kwargs) with host.sudo(): diff --git a/molecule/testinfra/mon/test_ossec_server.py b/molecule/testinfra/mon/test_ossec_server.py --- a/molecule/testinfra/mon/test_ossec_server.py +++ b/molecule/testinfra/mon/test_ossec_server.py @@ -89,7 +89,7 @@ def test_hosts_files(host): app_host = securedrop_test_vars.app_hostname assert f.contains("^127.0.0.1.*localhost") - assert f.contains(r"^{}\s*{}$".format(app_ip, app_host)) + assert f.contains(rf"^{app_ip}\s*{app_host}$") def test_ossec_log_contains_no_malformed_events(host): diff --git a/molecule/testinfra/mon/test_postfix.py b/molecule/testinfra/mon/test_postfix.py --- a/molecule/testinfra/mon/test_postfix.py +++ b/molecule/testinfra/mon/test_postfix.py @@ -26,7 +26,7 @@ def test_postfix_headers(host, header): f = host.file("/etc/postfix/header_checks") assert f.is_file assert f.mode == 0o644 - regex = "^{}$".format(re.escape(header)) + regex = f"^{re.escape(header)}$" assert re.search(regex, f.content_string, re.M) diff --git a/molecule/testinfra/ossec/test_journalist_mail.py b/molecule/testinfra/ossec/test_journalist_mail.py --- a/molecule/testinfra/ossec/test_journalist_mail.py +++ b/molecule/testinfra/ossec/test_journalist_mail.py @@ -9,7 +9,7 @@ SKIP_REASON = "unimplemented, see GH#3689" -class TestBase(object): +class TestBase: @pytest.fixture(autouse=True) def only_mon_staging_sudo(self, host): if host.backend.host != "mon-staging": @@ -47,22 +47,16 @@ def wait_for_command(self, host, cmd): # legacy only found in /etc/init.d such as postfix # def service_started(self, host, name): - assert self.run(host, "service {name} start".format(name=name)) - assert self.wait_for_command( - host, "service {name} status | grep -q 'is running'".format(name=name) - ) + assert self.run(host, f"service {name} start") + assert self.wait_for_command(host, f"service {name} status | grep -q 'is running'") def service_restarted(self, host, name): - assert self.run(host, "service {name} restart".format(name=name)) - assert self.wait_for_command( - host, "service {name} status | grep -q 'is running'".format(name=name) - ) + assert self.run(host, f"service {name} restart") + assert self.wait_for_command(host, f"service {name} status | grep -q 'is running'") def service_stopped(self, host, name): - assert self.run(host, "service {name} stop".format(name=name)) - assert self.wait_for_command( - host, "service {name} status | grep -q 'not running'".format(name=name) - ) + assert self.run(host, f"service {name} stop") + assert self.wait_for_command(host, f"service {name} status | grep -q 'not running'") class TestJournalistMail(TestBase): @@ -79,10 +73,8 @@ def test_procmail(self, host): self.ansible(host, "copy", "dest=/tmp/{f} src={d}/{f}".format(f=f, d=current_dir)) assert self.run(host, "/var/ossec/process_submissions_today.sh forget") assert self.run(host, "postsuper -d ALL") - assert self.run(host, "cat /tmp/{f} | mail -s 'abc' root@localhost".format(f=f)) - assert self.wait_for_command( - host, "mailq | grep -q {destination}@ossec.test".format(destination=destination) - ) + assert self.run(host, f"cat /tmp/{f} | mail -s 'abc' root@localhost") + assert self.wait_for_command(host, f"mailq | grep -q {destination}@ossec.test") self.service_stopped(host, "postfix") @pytest.mark.skip(reason=SKIP_REASON) @@ -96,12 +88,12 @@ def test_process_submissions_today(self, host): def test_send_encrypted_alert(self, host): self.service_started(host, "postfix") src = "../../install_files/ansible-base/roles/ossec/files/" "test_admin_key.sec" - self.ansible(host, "copy", "dest=/tmp/test_admin_key.sec src={src}".format(src=src)) + self.ansible(host, "copy", f"dest=/tmp/test_admin_key.sec src={src}") self.run(host, "gpg --homedir /var/ossec/.gnupg" " --import /tmp/test_admin_key.sec") def trigger(who, payload): - assert self.run(host, "! mailq | grep -q {who}@ossec.test".format(who=who)) + assert self.run(host, f"! mailq | grep -q {who}@ossec.test") assert self.run( host, """ @@ -111,7 +103,7 @@ def trigger(who, payload): who=who, payload=payload ), ) - assert self.wait_for_command(host, "mailq | grep -q {who}@ossec.test".format(who=who)) + assert self.wait_for_command(host, f"mailq | grep -q {who}@ossec.test") # # encrypted mail to journalist or ossec contact diff --git a/securedrop/tests/config_from_2014.py b/securedrop/tests/config_from_2014.py --- a/securedrop/tests/config_from_2014.py +++ b/securedrop/tests/config_from_2014.py @@ -8,7 +8,7 @@ # Default values for production, may be overridden later based on environment -class FlaskConfig(object): +class FlaskConfig: DEBUG = False TESTING = False WTF_CSRF_ENABLED = True diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -368,5 +368,5 @@ def _stop_test_rqworker(worker_pid_file: Path) -> None: def _get_pid_from_file(pid_file_name: Path) -> int: try: return int(open(pid_file_name).read()) - except IOError: + except OSError: return -1 diff --git a/securedrop/tests/i18n/code.py b/securedrop/tests/i18n/code.py --- a/securedrop/tests/i18n/code.py +++ b/securedrop/tests/i18n/code.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from flask_babel import gettext print(gettext("code hello i18n")) diff --git a/securedrop/tests/migrations/helpers.py b/securedrop/tests/migrations/helpers.py --- a/securedrop/tests/migrations/helpers.py +++ b/securedrop/tests/migrations/helpers.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import secrets import string diff --git a/securedrop/tests/migrations/migration_15ac9509fc68.py b/securedrop/tests/migrations/migration_15ac9509fc68.py --- a/securedrop/tests/migrations/migration_15ac9509fc68.py +++ b/securedrop/tests/migrations/migration_15ac9509fc68.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import string diff --git a/securedrop/tests/migrations/migration_1ddb81fb88c2.py b/securedrop/tests/migrations/migration_1ddb81fb88c2.py --- a/securedrop/tests/migrations/migration_1ddb81fb88c2.py +++ b/securedrop/tests/migrations/migration_1ddb81fb88c2.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from db import db from journalist_app import create_app from sqlalchemy import text diff --git a/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py b/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py --- a/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py +++ b/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import string from uuid import uuid4 diff --git a/securedrop/tests/migrations/migration_35513370ba0d.py b/securedrop/tests/migrations/migration_35513370ba0d.py --- a/securedrop/tests/migrations/migration_35513370ba0d.py +++ b/securedrop/tests/migrations/migration_35513370ba0d.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random from uuid import uuid4 diff --git a/securedrop/tests/migrations/migration_3d91d6948753.py b/securedrop/tests/migrations/migration_3d91d6948753.py --- a/securedrop/tests/migrations/migration_3d91d6948753.py +++ b/securedrop/tests/migrations/migration_3d91d6948753.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import uuid diff --git a/securedrop/tests/migrations/migration_3da3fcab826a.py b/securedrop/tests/migrations/migration_3da3fcab826a.py --- a/securedrop/tests/migrations/migration_3da3fcab826a.py +++ b/securedrop/tests/migrations/migration_3da3fcab826a.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os import random from uuid import uuid4 diff --git a/securedrop/tests/migrations/migration_48a75abc0121.py b/securedrop/tests/migrations/migration_48a75abc0121.py --- a/securedrop/tests/migrations/migration_48a75abc0121.py +++ b/securedrop/tests/migrations/migration_48a75abc0121.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import secrets import string diff --git a/securedrop/tests/migrations/migration_60f41bb14d98.py b/securedrop/tests/migrations/migration_60f41bb14d98.py --- a/securedrop/tests/migrations/migration_60f41bb14d98.py +++ b/securedrop/tests/migrations/migration_60f41bb14d98.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import string import uuid diff --git a/securedrop/tests/migrations/migration_6db892e17271.py b/securedrop/tests/migrations/migration_6db892e17271.py --- a/securedrop/tests/migrations/migration_6db892e17271.py +++ b/securedrop/tests/migrations/migration_6db892e17271.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import string import uuid diff --git a/securedrop/tests/migrations/migration_92fba0be98e9.py b/securedrop/tests/migrations/migration_92fba0be98e9.py --- a/securedrop/tests/migrations/migration_92fba0be98e9.py +++ b/securedrop/tests/migrations/migration_92fba0be98e9.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import pytest import sqlalchemy from db import db diff --git a/securedrop/tests/migrations/migration_a9fe328b053a.py b/securedrop/tests/migrations/migration_a9fe328b053a.py --- a/securedrop/tests/migrations/migration_a9fe328b053a.py +++ b/securedrop/tests/migrations/migration_a9fe328b053a.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import random import uuid diff --git a/securedrop/tests/migrations/migration_b060f38c0c31.py b/securedrop/tests/migrations/migration_b060f38c0c31.py --- a/securedrop/tests/migrations/migration_b060f38c0c31.py +++ b/securedrop/tests/migrations/migration_b060f38c0c31.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import uuid from typing import Any, Dict diff --git a/securedrop/tests/migrations/migration_b58139cfdc8c.py b/securedrop/tests/migrations/migration_b58139cfdc8c.py --- a/securedrop/tests/migrations/migration_b58139cfdc8c.py +++ b/securedrop/tests/migrations/migration_b58139cfdc8c.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- -import io import os import random import uuid from os import path +from unittest import mock -import mock from db import db from journalist_app import create_app from sqlalchemy import text @@ -48,7 +46,7 @@ def create_source(self): if self.source_id is not None: raise RuntimeError("Source already created") - self.source_filesystem_id = "aliruhglaiurhgliaurg-{}".format(self.counter) + self.source_filesystem_id = f"aliruhglaiurhgliaurg-{self.counter}" params = { "filesystem_id": self.source_filesystem_id, "uuid": str(uuid.uuid4()), @@ -148,7 +146,7 @@ def load_data(self): if not path.exists(dirname): os.mkdir(dirname) - with io.open(full_path, "wb") as f: + with open(full_path, "wb") as f: f.write(DATA) def check_upgrade(self): diff --git a/securedrop/tests/migrations/migration_c5a02eb52f2d.py b/securedrop/tests/migrations/migration_c5a02eb52f2d.py --- a/securedrop/tests/migrations/migration_c5a02eb52f2d.py +++ b/securedrop/tests/migrations/migration_c5a02eb52f2d.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import random import uuid diff --git a/securedrop/tests/migrations/migration_d9d36b6f4d1e.py b/securedrop/tests/migrations/migration_d9d36b6f4d1e.py --- a/securedrop/tests/migrations/migration_d9d36b6f4d1e.py +++ b/securedrop/tests/migrations/migration_d9d36b6f4d1e.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import secrets import pytest diff --git a/securedrop/tests/migrations/migration_de00920916bf.py b/securedrop/tests/migrations/migration_de00920916bf.py --- a/securedrop/tests/migrations/migration_de00920916bf.py +++ b/securedrop/tests/migrations/migration_de00920916bf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import random import uuid diff --git a/securedrop/tests/migrations/migration_e0a525cbab83.py b/securedrop/tests/migrations/migration_e0a525cbab83.py --- a/securedrop/tests/migrations/migration_e0a525cbab83.py +++ b/securedrop/tests/migrations/migration_e0a525cbab83.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import string import uuid diff --git a/securedrop/tests/migrations/migration_f2833ac34bb6.py b/securedrop/tests/migrations/migration_f2833ac34bb6.py --- a/securedrop/tests/migrations/migration_f2833ac34bb6.py +++ b/securedrop/tests/migrations/migration_f2833ac34bb6.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import string import uuid diff --git a/securedrop/tests/migrations/migration_faac8092c123.py b/securedrop/tests/migrations/migration_faac8092c123.py --- a/securedrop/tests/migrations/migration_faac8092c123.py +++ b/securedrop/tests/migrations/migration_faac8092c123.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - class UpgradeTester: """This migration has no upgrade because it is only the enabling of pragmas which do not affect database contents. diff --git a/securedrop/tests/migrations/migration_fccf57ceef02.py b/securedrop/tests/migrations/migration_fccf57ceef02.py --- a/securedrop/tests/migrations/migration_fccf57ceef02.py +++ b/securedrop/tests/migrations/migration_fccf57ceef02.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import random import uuid diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os import re import subprocess @@ -181,7 +179,7 @@ def test_upgrade_with_data(alembic_config, config, migration, _reset_db): upgrade(alembic_config, last_migration) # Dynamic module import - mod_name = "tests.migrations.migration_{}".format(migration) + mod_name = f"tests.migrations.migration_{migration}" mod = __import__(mod_name, fromlist=["UpgradeTester"]) # Load the test data @@ -201,7 +199,7 @@ def test_downgrade_with_data(alembic_config, config, migration, _reset_db): upgrade(alembic_config, migration) # Dynamic module import - mod_name = "tests.migrations.migration_{}".format(migration) + mod_name = f"tests.migrations.migration_{migration}" mod = __import__(mod_name, fromlist=["DowngradeTester"]) # Load the test data diff --git a/securedrop/tests/test_db.py b/securedrop/tests/test_db.py --- a/securedrop/tests/test_db.py +++ b/securedrop/tests/test_db.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- +from unittest.mock import MagicMock + import pytest -from mock import MagicMock from models import ( InstanceConfig, Journalist, diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # SecureDrop whistleblower submission system # Copyright (C) 2017 Loic Dachary <[email protected]> @@ -300,7 +299,7 @@ def test_i18n(): def test_parse_locale_set(): - assert parse_locale_set([FALLBACK_LOCALE]) == set([Locale.parse(FALLBACK_LOCALE)]) + assert parse_locale_set([FALLBACK_LOCALE]) == {Locale.parse(FALLBACK_LOCALE)} def test_no_usable_fallback_locale(): diff --git a/securedrop/tests/test_i18n_tool.py b/securedrop/tests/test_i18n_tool.py --- a/securedrop/tests/test_i18n_tool.py +++ b/securedrop/tests/test_i18n_tool.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - -import io import os import shutil import signal @@ -8,14 +5,14 @@ import time from os.path import abspath, dirname, exists, getmtime, join, realpath from pathlib import Path +from unittest.mock import patch import i18n_tool import pytest -from mock import patch from tests.test_i18n import set_msg_translation_in_po_file -class TestI18NTool(object): +class TestI18NTool: def setup(self): self.dir = abspath(dirname(realpath(__file__))) @@ -48,7 +45,7 @@ def test_translate_desktop_l10n(self, tmpdir): ) messages_file = join(str(tmpdir), "desktop.pot") assert exists(messages_file) - with io.open(messages_file) as fobj: + with open(messages_file) as fobj: pot = fobj.read() assert "SecureDrop Source Interfaces" in pot # pretend this happened a few seconds ago @@ -113,11 +110,11 @@ def test_translate_desktop_l10n(self, tmpdir): ] ) assert old_messages_mtime == getmtime(messages_file) - with io.open(po_file) as fobj: + with open(po_file) as fobj: po = fobj.read() assert "SecureDrop Source Interfaces" in po assert "SecureDrop Journalist Interfaces" not in po - with io.open(i18n_file) as fobj: + with open(i18n_file) as fobj: i18n = fobj.read() assert "SOURCE FR" in i18n @@ -141,7 +138,7 @@ def test_translate_messages_l10n(self, tmpdir): i18n_tool.I18NTool().main(args) messages_file = join(str(tmpdir), "messages.pot") assert exists(messages_file) - with io.open(messages_file, "rb") as fobj: + with open(messages_file, "rb") as fobj: pot = fobj.read() assert b"code hello i18n" in pot assert b"template hello i18n" in pot @@ -174,7 +171,7 @@ def test_translate_messages_l10n(self, tmpdir): assert not exists(mo_file) i18n_tool.I18NTool().main(args) assert exists(mo_file) - with io.open(mo_file, mode="rb") as fobj: + with open(mo_file, mode="rb") as fobj: mo = fobj.read() assert b"code hello i18n" in mo assert b"template hello i18n" in mo @@ -198,7 +195,7 @@ def test_translate_messages_compile_arg(self, tmpdir): ) messages_file = join(str(tmpdir), "messages.pot") assert exists(messages_file) - with io.open(messages_file) as fobj: + with open(messages_file) as fobj: pot = fobj.read() assert "code hello i18n" in pot @@ -257,7 +254,7 @@ def test_translate_messages_compile_arg(self, tmpdir): ] ) assert current_po_mtime == getmtime(po_file) - with io.open(mo_file, mode="rb") as fobj: + with open(mo_file, mode="rb") as fobj: mo = fobj.read() assert b"code hello i18n" in mo assert b"template hello i18n" not in mo diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -6,9 +6,9 @@ from base64 import b32encode from binascii import unhexlify from io import BytesIO +from unittest import mock import journalist_app as journalist_app_module -import mock from bs4 import BeautifulSoup from db import db from encryption import EncryptionManager @@ -464,10 +464,7 @@ def test_delete_collection(mocker, source_app, journalist_app, test_journo): assert resp.status_code == 200 text = resp.data.decode("utf-8") - assert ( - escape("The account and data for the source {} have been deleted.".format(col_name)) - in text - ) + assert escape(f"The account and data for the source {col_name} have been deleted.") in text assert "There are no submissions!" in text @@ -517,7 +514,7 @@ def test_delete_collections(mocker, journalist_app, source_app, test_journo): ) assert resp.status_code == 200 text = resp.data.decode("utf-8") - assert "The accounts and all data for {} sources".format(num_sources) in text + assert f"The accounts and all data for {num_sources} sources" in text # simulate the source_deleter's work journalist_app_module.utils.purge_deleted_sources() diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -10,6 +10,7 @@ from io import BytesIO from pathlib import Path from typing import Tuple +from unittest.mock import call, patch import journalist_app as journalist_app_module import pytest @@ -20,7 +21,6 @@ from flask_babel import gettext, ngettext from journalist_app.sessions import session from journalist_app.utils import mark_seen -from mock import call, patch from models import ( InstanceConfig, InvalidPasswordLength, @@ -2303,7 +2303,7 @@ def test_logo_default_available(journalist_app, config): def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admin, locale): # Save original logo to restore after test run logo_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") - with io.open(logo_image_location, "rb") as logo_file: + with open(logo_image_location, "rb") as logo_file: original_image = logo_file.read() try: @@ -2342,7 +2342,7 @@ def test_logo_upload_with_valid_image_succeeds(config, journalist_app, test_admi assert response.data == logo_bytes finally: # Restore original image to logo location for subsequent tests - with io.open(logo_image_location, "wb") as logo_file: + with open(logo_image_location, "wb") as logo_file: logo_file.write(original_image) @@ -2376,7 +2376,7 @@ def test_logo_upload_with_invalid_filetype_fails(config, journalist_app, test_ad def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): # Save original logo to restore after test run logo_image_location = os.path.join(config.SECUREDROP_ROOT, "static/i/logo.png") - with io.open(logo_image_location, "rb") as logo_file: + with open(logo_image_location, "rb") as logo_file: original_image = logo_file.read() try: @@ -2414,7 +2414,7 @@ def test_logo_upload_save_fails(config, journalist_app, test_admin, locale): ins.assert_message_flashed(gettext(msgids[0]), "logo-error") finally: # Restore original image to logo location for subsequent tests - with io.open(logo_image_location, "wb") as logo_file: + with open(logo_image_location, "wb") as logo_file: logo_file.write(original_image) @@ -3140,7 +3140,7 @@ def test_download_selected_submissions_and_replies( os.path.join( source.journalist_filename, source.journalist_designation, - "%s_%s" % (filename.split("-")[0], source.last_updated.date()), + "{}_{}".format(filename.split("-")[0], source.last_updated.date()), filename, ) ) @@ -3214,7 +3214,7 @@ def test_download_selected_submissions_and_replies_previously_seen( os.path.join( source.journalist_filename, source.journalist_designation, - "%s_%s" % (filename.split("-")[0], source.last_updated.date()), + "{}_{}".format(filename.split("-")[0], source.last_updated.date()), filename, ) ) @@ -3274,7 +3274,7 @@ def test_download_selected_submissions_previously_downloaded( os.path.join( source.journalist_filename, source.journalist_designation, - "%s_%s" % (filename.split("-")[0], source.last_updated.date()), + "{}_{}".format(filename.split("-")[0], source.last_updated.date()), filename, ) ) @@ -3329,7 +3329,7 @@ def test_download_selected_submissions_missing_files( .joinpath(file) .as_posix() ) - expected_calls.append(call("File {} not found".format(missing_file))) + expected_calls.append(call(f"File {missing_file} not found")) mocked_error_logger.assert_has_calls(expected_calls) @@ -3366,7 +3366,7 @@ def test_download_single_submission_missing_file( .as_posix() ) - mocked_error_logger.assert_called_once_with("File {} not found".format(missing_file)) + mocked_error_logger.assert_called_once_with(f"File {missing_file} not found") def test_download_unread_all_sources(journalist_app, test_journo, app_storage): diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import json import random from datetime import datetime @@ -1020,16 +1019,16 @@ def test_malformed_auth_token(journalist_app, journalist_api_token): with journalist_app.test_client() as app: # precondition to ensure token is even valid - resp = app.get(url, headers={"Authorization": "Token {}".format(journalist_api_token)}) + resp = app.get(url, headers={"Authorization": f"Token {journalist_api_token}"}) assert resp.status_code == 200 - resp = app.get(url, headers={"Authorization": "not-token {}".format(journalist_api_token)}) + resp = app.get(url, headers={"Authorization": f"not-token {journalist_api_token}"}) assert resp.status_code == 403 resp = app.get(url, headers={"Authorization": journalist_api_token}) assert resp.status_code == 403 - resp = app.get(url, headers={"Authorization": "too many {}".format(journalist_api_token)}) + resp = app.get(url, headers={"Authorization": f"too many {journalist_api_token}"}) assert resp.status_code == 403 diff --git a/securedrop/tests/test_manage.py b/securedrop/tests/test_manage.py --- a/securedrop/tests/test_manage.py +++ b/securedrop/tests/test_manage.py @@ -1,12 +1,11 @@ import argparse import datetime -import io import logging import os import time +from unittest import mock import manage -import mock from management import submissions from models import Journalist, db from passphrases import PassphraseGenerator @@ -180,7 +179,7 @@ def test_clean_tmp_do_nothing(caplog): def test_clean_tmp_too_young(config, caplog): args = argparse.Namespace(days=24 * 60 * 60, directory=config.TEMP_DIR, verbose=logging.DEBUG) # create a file - io.open(os.path.join(config.TEMP_DIR, "FILE"), "a").close() + open(os.path.join(config.TEMP_DIR, "FILE"), "a").close() manage.setup_verbosity(args) manage.clean_tmp(args) @@ -190,7 +189,7 @@ def test_clean_tmp_too_young(config, caplog): def test_clean_tmp_removed(config, caplog): args = argparse.Namespace(days=0, directory=config.TEMP_DIR, verbose=logging.DEBUG) fname = os.path.join(config.TEMP_DIR, "FILE") - with io.open(fname, "a"): + with open(fname, "a"): old = time.time() - 24 * 60 * 60 os.utime(fname, (old, old)) manage.setup_verbosity(args) @@ -214,8 +213,8 @@ def test_were_there_submissions_today(source_app, config, app_storage): source.last_updated = datetime.datetime.utcnow() - datetime.timedelta(hours=24 * 2) db.session.commit() submissions.were_there_submissions_today(args, context) - assert io.open(count_file).read() == "0" + assert open(count_file).read() == "0" source.last_updated = datetime.datetime.utcnow() db.session.commit() submissions.were_there_submissions_today(args, context) - assert io.open(count_file).read() == "1" + assert open(count_file).read() == "1" diff --git a/securedrop/tests/test_rm.py b/securedrop/tests/test_rm.py --- a/securedrop/tests/test_rm.py +++ b/securedrop/tests/test_rm.py @@ -12,7 +12,7 @@ def test_secure_delete_capability(config): path = os.environ["PATH"] try: - os.environ["PATH"] = "{}".format(config.TEMP_DIR) + os.environ["PATH"] = f"{config.TEMP_DIR}" assert rm.check_secure_delete_capability() is False fakeshred = os.path.join(config.TEMP_DIR, "shred") with open(fakeshred, "w") as f: diff --git a/securedrop/tests/test_secure_tempfile.py b/securedrop/tests/test_secure_tempfile.py --- a/securedrop/tests/test_secure_tempfile.py +++ b/securedrop/tests/test_secure_tempfile.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -import io import os import pytest @@ -56,7 +54,7 @@ def test_read_write_unicode(): def test_file_seems_encrypted(): f = SecureTemporaryFile("/tmp") f.write(MESSAGE) - with io.open(f.filepath, "rb") as fh: + with open(f.filepath, "rb") as fh: contents = fh.read() assert MESSAGE.encode("utf-8") not in contents diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # flake8: noqa: E741 import gzip import os @@ -10,6 +9,7 @@ from io import BytesIO, StringIO from pathlib import Path from unittest import mock +from unittest.mock import ANY, patch import pytest import version @@ -19,7 +19,6 @@ from flask import escape, g, request, session, url_for from flask_babel import gettext from journalist_app.utils import delete_collection -from mock import ANY, patch from models import InstanceConfig, Reply, Source from passphrases import PassphraseGenerator from source_app import api as source_app_api diff --git a/securedrop/tests/test_source_utils.py b/securedrop/tests/test_source_utils.py --- a/securedrop/tests/test_source_utils.py +++ b/securedrop/tests/test_source_utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import json import os @@ -17,7 +16,7 @@ def test_check_url_file(config): def write_url_file(path, content): url_file = open(path, "w") - url_file.write("{}\n".format(content)) + url_file.write(f"{content}\n") url_path = "test_source_url" diff --git a/securedrop/tests/test_store.py b/securedrop/tests/test_store.py --- a/securedrop/tests/test_store.py +++ b/securedrop/tests/test_store.py @@ -1,4 +1,3 @@ -import io import logging import os import re @@ -42,7 +41,7 @@ def create_file_in_source_dir(base_dir, filesystem_id, filename): os.makedirs(source_directory) file_path = os.path.join(source_directory, filename) - with io.open(file_path, "a"): + with open(file_path, "a"): os.utime(file_path, None) return source_directory, file_path @@ -119,7 +118,7 @@ def test_verify_in_store_dir(test_storage): with pytest.raises(store.PathException) as e: path = test_storage.storage_path + "_backup" test_storage.verify(path) - assert e.message == "Path not valid in store: {}".format(path) + assert e.message == f"Path not valid in store: {path}" def test_verify_store_path_not_absolute(test_storage): @@ -137,7 +136,7 @@ def test_verify_rejects_symlinks(test_storage): os.symlink("/foo", link) with pytest.raises(store.PathException) as e: test_storage.verify(link) - assert e.message == "Path not valid in store: {}".format(link) + assert e.message == f"Path not valid in store: {link}" finally: os.unlink(link) @@ -181,7 +180,7 @@ def test_verify_invalid_file_extension_in_sourcedir_raises_exception(test_storag with pytest.raises(store.PathException) as e: test_storage.verify(file_path) - assert "Path not valid in store: {}".format(file_path) in str(e) + assert f"Path not valid in store: {file_path}" in str(e) def test_verify_invalid_filename_in_sourcedir_raises_exception(test_storage): @@ -192,7 +191,7 @@ def test_verify_invalid_filename_in_sourcedir_raises_exception(test_storage): with pytest.raises(store.PathException) as e: test_storage.verify(file_path) - assert e.message == "Path not valid in store: {}".format(file_path) + assert e.message == f"Path not valid in store: {file_path}" def test_get_zip(journalist_app, test_source, app_storage, config): @@ -207,7 +206,7 @@ def test_get_zip(journalist_app, test_source, app_storage, config): archivefile_contents = archive.namelist() for archived_file, actual_file in zip(archivefile_contents, filenames): - with io.open(actual_file, "rb") as f: + with open(actual_file, "rb") as f: actual_file_content = f.read() zipped_file_content = archive.read(archived_file) assert zipped_file_content == actual_file_content @@ -379,7 +378,7 @@ def test_shredder_deletes_symlinks(journalist_app, app_storage, caplog): link = os.path.abspath(os.path.join(app_storage.shredder_path, "foo")) os.symlink(link_target, link) app_storage.clear_shredder() - assert "Deleting link {} to {}".format(link, link_target) in caplog.text + assert f"Deleting link {link} to {link_target}" in caplog.text assert not os.path.exists(link) @@ -396,6 +395,6 @@ def test_shredder_shreds(journalist_app, app_storage, caplog): f.write("testdata\n") app_storage.clear_shredder() - assert "Securely deleted file 1/1: {}".format(testfile) in caplog.text + assert f"Securely deleted file 1/1: {testfile}" in caplog.text assert not os.path.isfile(testfile) assert not os.path.isdir(testdir) diff --git a/securedrop/tests/test_worker.py b/securedrop/tests/test_worker.py --- a/securedrop/tests/test_worker.py +++ b/securedrop/tests/test_worker.py @@ -82,7 +82,7 @@ def test_job_interruption(config, caplog): # the running job should not be requeued worker.requeue_interrupted_jobs(queue_name) - skipped = "Skipping job {}, which is already being run by worker {}".format(job.id, w.key) + skipped = f"Skipping job {job.id}, which is already being run by worker {w.key}" assert skipped in caplog.text # kill the process group, to kill the worker and its workhorse @@ -93,7 +93,7 @@ def test_job_interruption(config, caplog): # after killing the worker, the interrupted job should be requeued worker.requeue_interrupted_jobs(queue_name) print(caplog.text) - assert "Requeuing job {}".format(job) in caplog.text + assert f"Requeuing job {job}" in caplog.text assert len(q.get_job_ids()) == 1 finally: q.delete() @@ -132,7 +132,7 @@ def test_worker_for_job(config): logging.debug( [ - "{}: state={}, job={}".format(w.pid, w.get_state(), w.get_current_job_id()) + f"{w.pid}: state={w.get_state()}, job={w.get_current_job_id()}" for w in worker.rq_workers(q) ] ) diff --git a/securedrop/tests/utils/api_helper.py b/securedrop/tests/utils/api_helper.py --- a/securedrop/tests/utils/api_helper.py +++ b/securedrop/tests/utils/api_helper.py @@ -1,7 +1,7 @@ def get_api_headers(token=""): if token: return { - "Authorization": "Token {}".format(token), + "Authorization": f"Token {token}", "Accept": "application/json", "Content-Type": "application/json", } diff --git a/securedrop/tests/utils/asynchronous.py b/securedrop/tests/utils/asynchronous.py --- a/securedrop/tests/utils/asynchronous.py +++ b/securedrop/tests/utils/asynchronous.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Testing utilities to block on and react to the success, failure, or timeout of asynchronous processes. """ diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Testing utilities that involve database (and often related filesystem) interaction. """ @@ -10,8 +9,8 @@ import subprocess from pathlib import Path from typing import Dict, List +from unittest import mock -import mock from db import db from encryption import EncryptionManager from journalist_app.utils import mark_seen @@ -73,7 +72,7 @@ def reply(storage, journalist, source, num_replies): replies = [] for _ in range(num_replies): source.interaction_count += 1 - fname = "{}-{}-reply.gpg".format(source.interaction_count, source.journalist_filename) + fname = f"{source.interaction_count}-{source.journalist_filename}-reply.gpg" EncryptionManager.get_default().encrypt_journalist_reply( for_source_with_filesystem_id=source.filesystem_id, diff --git a/securedrop/tests/utils/i18n.py b/securedrop/tests/utils/i18n.py --- a/securedrop/tests/utils/i18n.py +++ b/securedrop/tests/utils/i18n.py @@ -60,7 +60,7 @@ def message_catalog(translation_dir: Path, locale: str) -> Catalog: >>> german.get("Password").string 'Passwort' """ - return read_po(open((translation_dir / locale / "LC_MESSAGES" / "messages.po"))) + return read_po(open(translation_dir / locale / "LC_MESSAGES" / "messages.po")) def page_language(page_text: str) -> Optional[str]: @@ -95,7 +95,7 @@ def xfail_untranslated_messages( for msgid in msgids: m = catalog.get(msgid) if not m: - pytest.xfail("locale {} message catalog lacks msgid: {}".format(locale, msgid)) + pytest.xfail(f"locale {locale} message catalog lacks msgid: {msgid}") if not m.string: - pytest.xfail("locale {} has no translation for msgid: {}".format(locale, msgid)) + pytest.xfail(f"locale {locale} has no translation for msgid: {msgid}") yield diff --git a/securedrop/tests/utils/instrument.py b/securedrop/tests/utils/instrument.py --- a/securedrop/tests/utils/instrument.py +++ b/securedrop/tests/utils/instrument.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Taken from: flask_testing.utils @@ -61,9 +60,7 @@ def assert_message_flashed(self, message, category="message"): if _message == message and _category == category: return True - raise AssertionError( - "Message '{}' in category '{}' wasn't flashed".format(message, category) - ) + raise AssertionError(f"Message '{message}' in category '{category}' wasn't flashed") def assert_template_used(self, name, tmpl_name_attribute="name"): """ @@ -116,7 +113,7 @@ def assert_context(self, name, value, message=None): try: assert self.get_context_variable(name) == value, message except ContextVariableDoesNotExist: - pytest.fail(message or "Context variable does not exist: {}".format(name)) + pytest.fail(message or f"Context variable does not exist: {name}") def assert_redirects(self, response, location, message=None): """
Add pyupgrade to our toolchain ## Description pyupgrade is a tool that automatically rewrites code to use modern syntax. https://github.com/asottile/pyupgrade has a detailed list with examples. This would be similar to black/isort, in which we'd have a command like `make pyupgrade` that applies all the changes, and then another like `make pyupgrade-check` which verifies there are no unapplied changes. Note that black should always run after pyupgrade changes things. ## User Stories * As a developer, I want to automatically update Python code to modern patterns/syntax so I don't have to do it manually
@legoktm I can work on this if you'd like. I'm relatively new and don't have professional experience yet but I do open source sometimes and I've worked with `make` and `black` before, for example. Let me know! Hi @phershbe, thanks for your interest! I want to get input from other team members before we move ahead with this, that will probably take (or not) a week if you don't mind waiting, or I can suggest another task for you to work on now! @legoktm Yeah, of course, I'm not on any kind of timeline, I'm simply here to help and to practice. Thank you for offering another task ... I'm kind of intimated by a lot of stuff, any other easy tasks off the top of your head? I was looking at https://github.com/freedomofpress/securedrop/issues/6641. @phershbe: yep, that is (I think!) relatively straightforward (parsing the flask version out of requirements.txt). I'd also suggest #2484 (some code deletion), and #6515 (porting some regex checks to Python/flask).
2023-01-10T20:24:07Z
[]
[]
freedomofpress/securedrop
6,742
freedomofpress__securedrop-6742
[ "6741" ]
2156f9fd26d76586631d11a7fee7a46a8040d0cb
diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -5,6 +5,7 @@ from sdconfig import SecureDropConfig config = SecureDropConfig.get_current() +# app is imported by journalist.wsgi app = create_app(config) diff --git a/securedrop/source.py b/securedrop/source.py --- a/securedrop/source.py +++ b/securedrop/source.py @@ -1,9 +1,11 @@ from sdconfig import SecureDropConfig from source_app import create_app +config = SecureDropConfig.get_current() +# app is imported by source.wsgi +app = create_app(config) + if __name__ == "__main__": # pragma: no cover - config = SecureDropConfig.get_current() - app = create_app(config) debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host app.run(debug=debug, host="0.0.0.0", port=8080) # nosec diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -118,12 +118,15 @@ def internal_error(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: # Obscure the creation time of source private keys by touching them all # on startup. private_keys = config.GPG_KEY_DIR / "private-keys-v1.d" - now = time.time() - for entry in os.scandir(private_keys): - if not entry.is_file() or not entry.name.endswith(".key"): - continue - os.utime(entry.path, times=(now, now)) - # So the ctime is also updated - os.chmod(entry.path, entry.stat().st_mode) + # The folder may not exist yet in some dev/testing setups, + # and if it doesn't exist there's no mtime to obscure. + if private_keys.is_dir(): + now = time.time() + for entry in os.scandir(private_keys): + if not entry.is_file() or not entry.name.endswith(".key"): + continue + os.utime(entry.path, times=(now, now)) + # So the ctime is also updated + os.chmod(entry.path, entry.stat().st_mode) return app
diff --git a/molecule/testinfra/app/test_appenv.py b/molecule/testinfra/app/test_appenv.py --- a/molecule/testinfra/app/test_appenv.py +++ b/molecule/testinfra/app/test_appenv.py @@ -21,7 +21,7 @@ def test_app_wsgi(host): f = host.file("/var/www/source.wsgi") with host.sudo(): assert f.is_file - assert f.mode == 0o640 + assert f.mode == 0o644 assert f.user == "root" assert f.group == "root" assert f.contains("^import logging$") diff --git a/molecule/testinfra/app/test_smoke.py b/molecule/testinfra/app/test_smoke.py new file mode 100644 --- /dev/null +++ b/molecule/testinfra/app/test_smoke.py @@ -0,0 +1,33 @@ +""" +Basic smoke tests that verify the apps are functioning as expected +""" +import pytest +import testutils + +sdvars = testutils.securedrop_test_vars +testinfra_hosts = [sdvars.app_hostname] + + [email protected]( + "name,url,curl_flags", + ( + # We pass -L to follow the redirect from / to /login + ("journalist", "http://localhost:8080/", "L"), + ("source", "http://localhost:80/", ""), + ), +) +def test_interface_up(host, name, url, curl_flags): + """ + Ensure the respective interface is up with HTTP 200 if not, we try our + best to grab the error log and print it via an intentionally failed + assertion. + """ + response = host.run(f"curl -{curl_flags}i {url}").stdout + if "200 OK" not in response: + # Try to grab the log and print it via a failed assertion + with host.sudo(): + f = host.file(f"/var/log/apache2/{name}-error.log") + if f.exists: + assert "nopenopenope" in f.content_string + assert "200 OK" in response + assert "Powered by" in response diff --git a/securedrop/tests/test_wsgi.py b/securedrop/tests/test_wsgi.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_wsgi.py @@ -0,0 +1,22 @@ +import os +import subprocess +import sys +from pathlib import Path + +import pytest + + [email protected]("filename", ("journalist.wsgi", "source.wsgi")) +def test_wsgi(filename): + """ + Verify that all setup code and imports in the wsgi files work + + This is slightly hacky because it executes the wsgi files using + the current virtualenv, and we hack the paths so it works out. + """ + sd_dir = Path(__file__).parent.parent + wsgi = sd_dir / "debian/app-code/var/www" / filename + python_path = os.getenv("PYTHONPATH", "") + subprocess.check_call( + [sys.executable, str(wsgi)], env={"PYTHONPATH": f"{python_path}:{sd_dir}"} + )
SI issuing a 500 error and then timing out on `develop` ## Description The SI is failing to start from the `develop` branch, first failing with a 500 error and the log messages below (with logs enabled, and then just timing out: ``` [Fri Feb 03 21:37:34.589966 2023] [wsgi:info] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] mod_wsgi (pid=1330, process='source', application='localhost|'): Loading Python script file '/var/www/source.wsgi'. [Fri Feb 03 21:37:34.591940 2023] [wsgi:error] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] mod_wsgi (pid=1330): Failed to exec Python script file '/var/www/source.wsgi'. [Fri Feb 03 21:37:34.592605 2023] [wsgi:error] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] mod_wsgi (pid=1330): Exception occurred processing WSGI script '/var/www/source.wsgi'. [Fri Feb 03 21:37:34.593310 2023] [wsgi:error] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] Traceback (most recent call last): [Fri Feb 03 21:37:34.593658 2023] [wsgi:error] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] File "/var/www/source.wsgi", line 11, in <module> [Fri Feb 03 21:37:34.593894 2023] [wsgi:error] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] from source import app as application [Fri Feb 03 21:37:34.594012 2023] [wsgi:error] [pid 1330:tid 118957187065600] [remote 127.0.0.1:51894] ImportError: cannot import name 'app' from 'source' (/var/www/securedrop/source.py) ``` ## Steps to Reproduce - set up a prod VM instance on `.2.5.1` - build packages from `develop` with `make build-debs` - step through the upgrade scenario to apply said debs ## Expected Behavior - system is upgraded cleanly and SI and JI functionality is available ## Actual Behavior - JI is available, SI errors out with an initial 500 error as described. ## Comments This looks to have been introduced in https://github.com/freedomofpress/securedrop/pull/6563, specifically in the change in https://github.com/freedomofpress/securedrop/blob/c9e2a7a61c486e38e4fcf06b6196b59a115ce152/securedrop/source.py#L6 . Since `app` is now defined only within the `__name__ == 'main'` block, it isn't defined when run via WSGI (as opposed to directly within the dev env).
2023-02-06T18:45:12Z
[]
[]
freedomofpress/securedrop
6,754
freedomofpress__securedrop-6754
[ "6706" ]
7aed52b79916e0f742a99d863ddb54b8e50246d0
diff --git a/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py b/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py deleted file mode 100644 --- a/install_files/ansible-base/roles/build-ossec-deb-pkg/library/ossec_urls.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -DOCUMENTATION = """ ---- -module: ossec_urls -short_description: Gather facts for OSSEC download URLs -description: - - Gather version, checksum, and URL info for OSSEC downloads -author: - - Conor Schaefer (@conorsch) - - Freedom of the Press Foundation (@freedomofpress) -requirements: - - requests -options: - ossec_version: - description: - - version number of release to download - default: "3.6.0" - required: no -notes: - - The OSSEC version to download is hardcoded to avoid surprises. - If you want a newer version than the current default, you should - pass the version in via I(ossec_version). -""" -EXAMPLES = """ -- ossec_urls: - ossec_version: "3.6.0" -""" - - -HAS_REQUESTS = True -try: - import requests # lgtm [py/unused-import] # noqa: F401 -except ImportError: - HAS_REQUESTS = False - - -class OSSECURLs: - def __init__(self, ossec_version): - self.REPO_URL = "https://github.com/ossec/ossec-hids" - self.ossec_version = ossec_version - self.ansible_facts = dict( - ossec_version=self.ossec_version, - ossec_tarball_filename=self.ossec_tarball_filename, - ossec_tarball_url=self.ossec_tarball_url, - ossec_signature_filename=self.ossec_signature_filename, - ossec_signature_url=self.ossec_signature_url, - ) - - @property - def ossec_tarball_filename(self): - return f"ossec-hids-{self.ossec_version}.tar.gz" - - @property - def ossec_tarball_url(self): - return self.REPO_URL + f"/archive/{self.ossec_version}.tar.gz" - - @property - def ossec_signature_url(self): - return self.REPO_URL + "/releases/download/{}/{}".format( - self.ossec_version, self.ossec_signature_filename - ) - - @property - def ossec_signature_filename(self): - return f"ossec-hids-{self.ossec_version}.tar.gz.asc" - - -def main(): - module = AnsibleModule( # noqa: F405 - argument_spec=dict( - ossec_version=dict(default="3.6.0"), - ), - supports_check_mode=False, - ) - if not HAS_REQUESTS: - module.fail_json(msg="requests required for this module") - - ossec_version = module.params["ossec_version"] - try: - ossec_config = OSSECURLs(ossec_version=ossec_version) - except Exception: - msg = ( - "Failed to find checksum information for OSSEC v{}." - "Ensure you have the proper release specified, " - "and check the download page to confirm: " - "http://www.ossec.net/?page_id=19".format(ossec_version) - ) - module.fail_json(msg=msg) - - results = ossec_config.ansible_facts - - if results: - module.exit_json(changed=False, ansible_facts=results) - else: - msg = "Failed to fetch OSSEC URL facts." - module.fail_json(msg=msg) - - -from ansible.module_utils.basic import * # noqa E402,F403 - -main()
diff --git a/builder/tests/test_ossec_package.py b/builder/tests/test_ossec_package.py new file mode 100644 --- /dev/null +++ b/builder/tests/test_ossec_package.py @@ -0,0 +1,77 @@ +import re +import subprocess +from pathlib import Path + +OSSEC_VERSION = "3.6.0" + +SECUREDROP_ROOT = Path( + subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode().strip() +) +BUILD_DIRECTORY = SECUREDROP_ROOT / "build/focal" + + +def test_ossec_binaries_are_present_agent(): + """ + Inspect the package contents to ensure all ossec agent binaries are properly + included in the package. + """ + wanted_files = [ + "/var/ossec/bin/agent-auth", + "/var/ossec/bin/ossec-syscheckd", + "/var/ossec/bin/ossec-agentd", + "/var/ossec/bin/manage_agents", + "/var/ossec/bin/ossec-control", + "/var/ossec/bin/ossec-logcollector", + "/var/ossec/bin/util.sh", + "/var/ossec/bin/ossec-execd", + ] + path = BUILD_DIRECTORY / f"ossec-agent_{OSSEC_VERSION}+focal_amd64.deb" + contents = subprocess.check_output(["dpkg-deb", "-c", str(path)]).decode() + for wanted_file in wanted_files: + assert re.search( + r"^.* .{}$".format(wanted_file), + contents, + re.M, + ) + + +def test_ossec_binaries_are_present_server(): + """ + Inspect the package contents to ensure all ossec server binaries are properly + included in the package. + """ + wanted_files = [ + "/var/ossec/bin/ossec-maild", + "/var/ossec/bin/ossec-remoted", + "/var/ossec/bin/ossec-syscheckd", + "/var/ossec/bin/ossec-makelists", + "/var/ossec/bin/ossec-logtest", + "/var/ossec/bin/syscheck_update", + "/var/ossec/bin/ossec-reportd", + "/var/ossec/bin/ossec-agentlessd", + "/var/ossec/bin/manage_agents", + "/var/ossec/bin/rootcheck_control", + "/var/ossec/bin/ossec-control", + "/var/ossec/bin/ossec-dbd", + "/var/ossec/bin/ossec-csyslogd", + "/var/ossec/bin/ossec-regex", + "/var/ossec/bin/agent_control", + "/var/ossec/bin/ossec-monitord", + "/var/ossec/bin/clear_stats", + "/var/ossec/bin/ossec-logcollector", + "/var/ossec/bin/list_agents", + "/var/ossec/bin/verify-agent-conf", + "/var/ossec/bin/syscheck_control", + "/var/ossec/bin/util.sh", + "/var/ossec/bin/ossec-analysisd", + "/var/ossec/bin/ossec-execd", + "/var/ossec/bin/ossec-authd", + ] + path = BUILD_DIRECTORY / f"ossec-server_{OSSEC_VERSION}+focal_amd64.deb" + contents = subprocess.check_output(["dpkg-deb", "-c", str(path)]).decode() + for wanted_file in wanted_files: + assert re.search( + r"^.* .{}$".format(wanted_file), + contents, + re.M, + ) diff --git a/builder/tests/test_securedrop_deb_package.py b/builder/tests/test_securedrop_deb_package.py new file mode 100644 --- /dev/null +++ b/builder/tests/test_securedrop_deb_package.py @@ -0,0 +1,102 @@ +import os +import subprocess +import tempfile +from pathlib import Path + +import pytest + +SECUREDROP_ROOT = Path( + subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode().strip() +) +DEB_PATHS = list((SECUREDROP_ROOT / "build/focal").glob("*.deb")) + + [email protected](scope="module") +def securedrop_app_code_contents() -> str: + """ + Returns the content listing of the securedrop-app-code Debian package. + """ + try: + path = [pkg for pkg in DEB_PATHS if pkg.name.startswith("securedrop-app-code")][0] + except IndexError: + raise RuntimeError("Unable to find securedrop-app-code package in build/ folder") + return subprocess.check_output(["dpkg-deb", "--contents", path]).decode() + + [email protected]("deb", DEB_PATHS) +def test_deb_packages_appear_installable(deb: Path) -> None: + """ + Confirms that a dry-run of installation reports no errors. + Simple check for valid Debian package structure, but not thorough. + When run on a malformed package, `dpkg` will report: + + dpkg-deb: error: `foo.deb' is not a debian format archive + + Testing application behavior is left to the functional tests. + """ + + # Normally this is called as root, but we can get away with simply + # adding sbin to the path + path = os.getenv("PATH") + ":/usr/sbin" + subprocess.check_call(["dpkg", "--install", "--dry-run", deb], env={"PATH": path}) + + [email protected]("deb", DEB_PATHS) +def test_deb_package_contains_expected_conffiles(deb: Path): + """ + Ensures the `securedrop-app-code` package declares only allow-listed + `conffiles`. Several files in `/etc/` would automatically be marked + conffiles, which would break unattended updates to critical package + functionality such as AppArmor profiles. This test validates overrides + in the build logic to unset those conffiles. + + The same applies to `securedrop-config` too. + """ + if not deb.name.startswith(("securedrop-app-code", "securedrop-config")): + return + + with tempfile.TemporaryDirectory() as tmpdir: + subprocess.check_call(["dpkg-deb", "--control", deb, tmpdir]) + conffiles_path = Path(tmpdir) / "conffiles" + assert conffiles_path.exists() + # No files are currently allow-listed to be conffiles + assert conffiles_path.read_text().rstrip() == "" + + [email protected]( + "path", + ( + "/var/www/securedrop/.well-known/pki-validation/", + "/var/www/securedrop/translations/messages.pot", + "/var/www/securedrop/translations/de_DE/LC_MESSAGES/messages.mo", + ), +) +def test_app_code_paths(securedrop_app_code_contents: str, path: str): + """ + Ensures the `securedrop-app-code` package contains the specified paths + """ + for line in securedrop_app_code_contents.splitlines(): + if line.endswith(path): + assert True + return + + assert False, "not found" + + [email protected]( + "path", + ( + "/var/www/securedrop/static/.webassets-cache/", + "/var/www/securedrop/static/gen/", + "/var/www/securedrop/config.py", + "/var/www/static/i/custom_logo.png", + ".j2", + ), +) +def test_app_code_paths_missing(securedrop_app_code_contents: str, path: str): + """ + Ensures the `securedrop-app-code` package do *NOT* contain the specified paths + """ + for line in securedrop_app_code_contents.splitlines(): + if line.endswith(path): + assert False, line diff --git a/molecule/builder-focal/tests/conftest.py b/molecule/builder-focal/tests/conftest.py deleted file mode 100644 --- a/molecule/builder-focal/tests/conftest.py +++ /dev/null @@ -1,20 +0,0 @@ -""" -Import variables from vars.yml and inject into testutils namespace -""" - -import subprocess -from pathlib import Path - -import pytest - - [email protected](scope="session") -def securedrop_root() -> Path: - """ - Returns the root of the SecureDrop working tree for the test session. - """ - return Path( - subprocess.run(["git", "rev-parse", "--show-toplevel"], stdout=subprocess.PIPE, check=True) - .stdout.decode("utf-8") - .strip() - ) diff --git a/molecule/builder-focal/tests/test_build_dependencies.py b/molecule/builder-focal/tests/test_build_dependencies.py deleted file mode 100644 --- a/molecule/builder-focal/tests/test_build_dependencies.py +++ /dev/null @@ -1,43 +0,0 @@ -import os - -import pytest - -SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -SECUREDROP_PYTHON_VERSION = os.environ.get("SECUREDROP_PYTHON_VERSION", "3.8") -DH_VIRTUALENV_VERSION = "1.2.2" - -testinfra_hosts = [f"docker://{SECUREDROP_TARGET_DISTRIBUTION}-sd-app"] - - [email protected](reason="This check conflicts with the concept of pegging" "dependencies") -def test_build_all_packages_updated(host): - """ - Ensure a dist-upgrade has already been run, by checking that no - packages are eligible for upgrade currently. This will ensure that - all upgrades, security and otherwise, have been applied to the VM - used to build packages. - """ - c = host.run("apt-get --simulate -y dist-upgrade") - assert c.rc == 0 - assert "No packages will be installed, upgraded, or removed." in c.stdout - - -def test_python_version(host): - """ - The Python 3 version shouldn't change between LTS releases, but we're - pulling in some packages from Debian for dh-virtualenv support, so - we must be careful not to change Python as well. - """ - c = host.run("python3 --version") - version_string = f"Python {SECUREDROP_PYTHON_VERSION}" - assert c.stdout.startswith(version_string) - - -def test_dh_virtualenv(host): - """ - Confirm the expected version of dh-virtualenv is found. - """ - expected_version = DH_VIRTUALENV_VERSION - version_string = f"dh_virtualenv {expected_version}" - c = host.run("dh_virtualenv --version") - assert c.stdout.startswith(version_string) diff --git a/molecule/builder-focal/tests/test_legacy_paths.py b/molecule/builder-focal/tests/test_legacy_paths.py deleted file mode 100644 --- a/molecule/builder-focal/tests/test_legacy_paths.py +++ /dev/null @@ -1,23 +0,0 @@ -import pytest - - [email protected]( - "build_path", - [ - "/tmp/build-", - "/tmp/rsync-filter", - "/tmp/src_install_files", - "/tmp/build-securedrop-keyring", - "/tmp/build-securedrop-ossec-agent", - "/tmp/build-securedrop-ossec-server", - ], -) -def test_build_ossec_apt_dependencies(host, build_path): - """ - Ensure that unwanted build paths are absent. Most of these were created - as unwanted side-effects during CI-related changes to the build scripts. - - All paths are rightly considered "legacy" and should never be present on - the build host. This test is strictly for guarding against regressions. - """ - assert not host.file(build_path).exists diff --git a/molecule/builder-focal/tests/test_securedrop_deb_package.py b/molecule/builder-focal/tests/test_securedrop_deb_package.py deleted file mode 100644 --- a/molecule/builder-focal/tests/test_securedrop_deb_package.py +++ /dev/null @@ -1,510 +0,0 @@ -import os -import re -from pathlib import Path -from typing import Any, Dict, List, Optional, Pattern, Tuple - -import pytest -import yaml -from testinfra.host import Host - -SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -testinfra_hosts = [f"docker://{SECUREDROP_TARGET_DISTRIBUTION}-sd-dpkg-verification"] - - -def extract_package_name_from_filepath(filepath: str) -> str: - """ - Helper function to infer intended package name from - the absolute filepath, using a rather garish regex. - E.g., given: - securedrop-ossec-agent-2.8.2+0.3.10-amd64.deb - - returns: - - securedrop-ossec-agent - - which can then be used for comparisons in dpkg output. - """ - deb_basename = os.path.basename(filepath) - package_match = re.search(r"^([a-z\-]+(?!\d))", deb_basename) - assert package_match - package_name = package_match.groups()[0] - assert deb_basename.startswith(package_name) - return package_name - - -def load_securedrop_test_vars() -> Dict[str, Any]: - """ - Loads vars.yml into a dictionary. - """ - filepath = os.path.join(os.path.dirname(__file__), "vars.yml") - test_vars = yaml.safe_load(open(filepath)) - - # Tack on target OS for use in tests - test_vars["securedrop_target_distribution"] = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") - - return test_vars - - -securedrop_test_vars = load_securedrop_test_vars() - - -def make_deb_paths() -> Dict[str, Path]: - """ - Helper function to retrieve module-namespace test vars and format - the strings to interpolate version info. Keeps the test vars DRY - in terms of version info, and required since we can't rely on - Jinja-based evaluation of the YAML files (so we can't trivially - reuse vars in other var values, as is the case with Ansible). - """ - - substitutions = dict( - securedrop_version=securedrop_test_vars["securedrop_version"], - ossec_version=securedrop_test_vars["ossec_version"], - keyring_version=securedrop_test_vars["keyring_version"], - securedrop_target_distribution=securedrop_test_vars["securedrop_target_distribution"], - ) - - return { - package_name: Path(path.format(**substitutions)) - for package_name, path in securedrop_test_vars["deb_paths"].items() - } - - -deb_paths = make_deb_paths() - - [email protected](scope="module") -def securedrop_app_code_contents(host) -> str: - """ - Returns the content listing of the securedrop-app-code Debian package on the host. - """ - return host.run("dpkg-deb --contents {}".format(deb_paths["securedrop_app_code"])).stdout - - -def deb_tags() -> List[Tuple[Path, str]]: - """ - Helper function to build array of package and tag tuples - for lintian. - """ - tags = [] - - for deb in deb_paths.values(): - for tag in securedrop_test_vars["lintian_tags"]: - tags.append((deb, tag)) - - return tags - - -def get_source_paths( - starting_path: Path, - pattern: str = "**/*", - skip: Optional[List[Pattern]] = None, -) -> List[Path]: - """ - Returns paths under starting_path that match the given pattern. - - The starting_path argument specifies where to look for files. The - optional pattern and skip parameters can be used to filter the - results. - """ - paths = sorted(p for p in starting_path.glob(pattern)) - if skip: - paths = [p for p in paths if not any(s.search(str(p)) for s in skip)] - assert paths - return paths - - -def get_static_asset_paths(securedrop_root: Path, pattern: str) -> List[Path]: - """ - Returns static assets matching the pattern. - """ - static_dir = securedrop_root / "securedrop/static" - skip = [re.compile(p) for p in [r"\.map$", r"\.webassets-cache$", "custom_logo.png$"]] - return get_source_paths(static_dir, pattern, skip) - - -def verify_static_assets(securedrop_app_code_contents: str, securedrop_root: Path, pattern) -> None: - """ - Verifies that the securedrop-app-code package contains the given static assets. - - Example: verify_assets(securedrop_app_code_contents, "icons/**.png") - """ - for asset_path in get_static_asset_paths(securedrop_root, pattern): - assert re.search( - r"^.*\./var/www/" "{}$".format(asset_path.relative_to(securedrop_root)), - securedrop_app_code_contents, - re.M, - ) - - [email protected]("deb", deb_paths.values()) -def test_build_deb_packages(host: Host, deb: Path) -> None: - """ - Sanity check the built Debian packages for Control field - values and general package structure. - """ - deb_package = host.file(str(deb)) - assert deb_package.is_file - - [email protected]("deb", deb_paths.values()) -def test_deb_packages_appear_installable(host: Host, deb: Path) -> None: - """ - Confirms that a dry-run of installation reports no errors. - Simple check for valid Debian package structure, but not thorough. - When run on a malformed package, `dpkg` will report: - - dpkg-deb: error: `foo.deb' is not a debian format archive - - Testing application behavior is left to the functional tests. - """ - - package_name = extract_package_name_from_filepath(str(deb)) - assert deb.name.startswith(package_name) - - # sudo is required to call `dpkg --install`, even as dry-run. - with host.sudo(): - c = host.run(f"dpkg --install --dry-run {deb}") - assert f"Selecting previously unselected package {package_name}" in c.stdout - regex = f"Preparing to unpack [./]+{re.escape(deb.name)} ..." - assert re.search(regex, c.stdout, re.M) - assert c.rc == 0 - - [email protected]("deb", deb_paths.values()) -def test_deb_package_control_fields(host: Host, deb: Path) -> None: - """ - Ensure Debian Control fields are populated as expected in the package. - These checks are rather superficial, and don't actually confirm that the - .deb files are not broken. At a later date, consider integration tests - that actually use these built files during an Ansible provisioning run. - """ - package_name = extract_package_name_from_filepath(str(deb)) - # The `--field` option will display all fields if none are specified. - c = host.run(f"dpkg-deb --field {deb}") - - assert "Maintainer: SecureDrop Team <[email protected]>" in c.stdout - arch_all = ( - "securedrop-config", - "securedrop-keyring", - "securedrop-ossec-agent", - "securedrop-ossec-server", - ) - # Some packages are architecture independent - if package_name in arch_all: - assert "Architecture: all" in c.stdout - else: - assert "Architecture: amd64" in c.stdout - - assert f"Package: {package_name}" in c.stdout - assert c.rc == 0 - - [email protected]("deb", deb_paths.values()) -def test_deb_package_control_fields_homepage(host: Host, deb: Path): - # The `--field` option will display all fields if none are specified. - c = host.run(f"dpkg-deb --field {deb}") - # The OSSEC source packages will have a different homepage; - # all other packages should set securedrop.org as homepage. - if deb.name.startswith("ossec-"): - assert "Homepage: http://ossec.net" in c.stdout - else: - assert "Homepage: https://securedrop.org" in c.stdout - - -def test_securedrop_app_code_contains_no_config_file(securedrop_app_code_contents: str): - """ - Ensures the `securedrop-app-code` package does not ship a `config.py` - file. Doing so would clobber the site-specific changes made via Ansible. - """ - assert not re.search(r"^ ./var/www/securedrop/config.py$", securedrop_app_code_contents, re.M) - - -def test_securedrop_app_code_contains_pot_file(securedrop_app_code_contents: str): - """ - Ensures the `securedrop-app-code` package has the - messages.pot file - """ - assert re.search( - "^.* ./var/www/securedrop/translations/messages.pot$", - securedrop_app_code_contents, - re.M, - ) - - -def test_securedrop_app_code_contains_mo_files( - securedrop_root: Path, securedrop_app_code_contents: str -) -> None: - """ - Ensures the `securedrop-app-code` package has a compiled version of each .po file. - """ - po_paths = get_source_paths(securedrop_root / "securedrop/translations", "**/*.po") - mo_paths = [p.with_suffix(".mo") for p in po_paths] - for mo in mo_paths: - assert re.search( - r"^.* \./var/www/" "{}$".format(mo.relative_to(securedrop_root)), - securedrop_app_code_contents, - re.M, - ) - - -def test_deb_package_contains_no_generated_assets(securedrop_app_code_contents: str): - """ - Ensures the `securedrop-app-code` package does not ship minified - static assets previously built at runtime via Flask-Assets under /gen, and - which may be present in the source directory used to build from. - """ - # static/gen/ directory not should exist - assert not re.search( - r"^.*\./var/www/securedrop" "/static/gen/$", securedrop_app_code_contents, re.M - ) - - # static/.webassets-cache/ directory should not exist - assert not re.search( - r"^.*\./var/www/securedrop" "/static/.webassets-cache/$", - securedrop_app_code_contents, - re.M, - ) - - [email protected]("deb", deb_paths.values()) -def test_deb_package_contains_expected_conffiles(host: Host, deb: Path): - """ - Ensures the `securedrop-app-code` package declares only allow-listed - `conffiles`. Several files in `/etc/` would automatically be marked - conffiles, which would break unattended updates to critical package - functionality such as AppArmor profiles. This test validates overrides - in the build logic to unset those conffiles. - - The same applies to `securedrop-config` too. - """ - if not deb.name.startswith(("securedrop-app-code", "securedrop-config")): - return - - mktemp = host.run("mktemp -d") - tmpdir = mktemp.stdout.strip() - # The `--raw-extract` flag includes `DEBIAN/` dir with control files - host.run(f"dpkg-deb --raw-extract {deb} {tmpdir}") - conffiles_path = os.path.join(tmpdir, "DEBIAN", "conffiles") - f = host.file(conffiles_path) - - assert f.is_file - - conffiles = f.content_string.rstrip() - - # No files are currently allow-listed to be conffiles - assert conffiles == "" - - -def test_securedrop_app_code_contains_css(securedrop_app_code_contents: str) -> None: - """ - Ensures the `securedrop-app-code` package contains necessary css files - """ - for css_type in ["journalist", "source"]: - assert re.search( - r"^.*\./var/www/securedrop/static/" "css/{}.css$".format(css_type), - securedrop_app_code_contents, - re.M, - ) - - -def test_securedrop_app_code_contains_static_fonts( - securedrop_root: Path, securedrop_app_code_contents: str -): - """ - Ensures the `securedrop-app-code` package contains everything under securedrop/fonts. - """ - verify_static_assets(securedrop_app_code_contents, securedrop_root, "fonts/*.*") - - -def test_securedrop_app_code_contains_static_i( - securedrop_root: Path, securedrop_app_code_contents: str -): - """ - Ensures the `securedrop-app-code` package contains everything under securedrop/static/i. - """ - verify_static_assets(securedrop_app_code_contents, securedrop_root, "i/**/*.*") - - -def test_securedrop_app_code_contains_static_icons( - securedrop_root: Path, securedrop_app_code_contents: str -): - """ - Ensures the `securedrop-app-code` package contains all the icons. - """ - verify_static_assets(securedrop_app_code_contents, securedrop_root, "icons/*.png") - - -def test_securedrop_app_code_contains_static_javascript( - securedrop_root: Path, securedrop_app_code_contents: str -): - """ - Ensures the `securedrop-app-code` package contains all the JavaScript. - """ - verify_static_assets(securedrop_app_code_contents, securedrop_root, "js/*.js") - - [email protected]("deb, tag", deb_tags()) -def test_deb_package_lintian(host: Host, deb: Path, tag: str): - """ - Ensures lintian likes our Debian packages. - """ - c = host.run(f"lintian --tags {tag} --no-tag-display-limit {deb}") - assert len(c.stdout) == 0 - - -def test_deb_app_package_contains_https_validate_dir(securedrop_app_code_contents: str): - """ - Ensures the `securedrop-app-code` package ships with a validation - '.well-known/pki-validation' directory - """ - # well-known/pki-validation directory should exist - assert re.search( - r"^.*\./var/www/securedrop/" ".well-known/pki-validation/$", - securedrop_app_code_contents, - re.M, - ) - - -def test_control_helper_files_are_present(host: Host): - """ - Inspect the package info to get a list of helper scripts - that should be shipped with the package, e.g. postinst, prerm, etc. - Necessary due to package build logic retooling. - - Example output from package info, for reference: - - $ dpkg-deb --info securedrop-app-code_0.12.0~rc1_amd64.deb - new debian package, version 2.0. - size 13583186 bytes: control archive=11713 bytes. - 62 bytes, 2 lines conffiles - 657 bytes, 10 lines control - 26076 bytes, 298 lines md5sums - 5503 bytes, 159 lines * postinst #!/bin/bash - - Note that the actual output will have trailing whitespace, removed - from this text description to satisfy linters. - """ - wanted_files = [ - "conffiles", - "config", - "control", - "postinst", - "postrm", - "preinst", - "prerm", - ] - c = host.run("dpkg-deb --info {}".format(deb_paths["securedrop_app_code"])) - for wanted_file in wanted_files: - assert re.search( - r"^\s+?\d+ bytes,\s+\d+ lines[\s*]+" + wanted_file + r"\s+.*$", - c.stdout, - re.M, - ) - - [email protected]("deb", deb_paths.values()) -def test_jinja_files_not_present(host: Host, deb: Path): - """ - Make sure that jinja (.j2) files were not copied over - as-is into the debian packages. - """ - - c = host.run(f"dpkg-deb --contents {deb}") - # There shouldn't be any files with a .j2 ending - assert not re.search(r"^.*\.j2$", c.stdout, re.M) - - -def test_ossec_binaries_are_present_agent(host: Host): - """ - Inspect the package contents to ensure all ossec agent binaries are properly - included in the package. - """ - wanted_files = [ - "/var/ossec/bin/agent-auth", - "/var/ossec/bin/ossec-syscheckd", - "/var/ossec/bin/ossec-agentd", - "/var/ossec/bin/manage_agents", - "/var/ossec/bin/ossec-control", - "/var/ossec/bin/ossec-logcollector", - "/var/ossec/bin/util.sh", - "/var/ossec/bin/ossec-execd", - ] - c = host.run("dpkg-deb -c {}".format(deb_paths["ossec_agent"])) - for wanted_file in wanted_files: - assert re.search( - rf"^.* .{wanted_file}$", - c.stdout, - re.M, - ) - - -def test_ossec_binaries_are_present_server(host: Host): - """ - Inspect the package contents to ensure all ossec server binaries are properly - included in the package. - """ - wanted_files = [ - "/var/ossec/bin/ossec-maild", - "/var/ossec/bin/ossec-remoted", - "/var/ossec/bin/ossec-syscheckd", - "/var/ossec/bin/ossec-makelists", - "/var/ossec/bin/ossec-logtest", - "/var/ossec/bin/syscheck_update", - "/var/ossec/bin/ossec-reportd", - "/var/ossec/bin/ossec-agentlessd", - "/var/ossec/bin/manage_agents", - "/var/ossec/bin/rootcheck_control", - "/var/ossec/bin/ossec-control", - "/var/ossec/bin/ossec-dbd", - "/var/ossec/bin/ossec-csyslogd", - "/var/ossec/bin/ossec-regex", - "/var/ossec/bin/agent_control", - "/var/ossec/bin/ossec-monitord", - "/var/ossec/bin/clear_stats", - "/var/ossec/bin/ossec-logcollector", - "/var/ossec/bin/list_agents", - "/var/ossec/bin/verify-agent-conf", - "/var/ossec/bin/syscheck_control", - "/var/ossec/bin/util.sh", - "/var/ossec/bin/ossec-analysisd", - "/var/ossec/bin/ossec-execd", - "/var/ossec/bin/ossec-authd", - ] - c = host.run("dpkg-deb --contents {}".format(deb_paths["ossec_server"])) - for wanted_file in wanted_files: - assert re.search( - rf"^.* .{wanted_file}$", - c.stdout, - re.M, - ) - - -def test_config_package_contains_expected_files(host: Host) -> None: - """ - Inspect the package contents to ensure all config files are included in - the package. - """ - wanted_files = [ - "/etc/profile.d/securedrop_additions.sh", - "/opt/securedrop/20auto-upgrades", - "/opt/securedrop/50unattended-upgrades", - "/opt/securedrop/reboot-flag", - ] - c = host.run("dpkg-deb --contents {}".format(deb_paths["securedrop_config"])) - for wanted_file in wanted_files: - assert re.search( - rf"^.* .{wanted_file}$", - c.stdout, - re.M, - ) - - -def test_app_package_does_not_contain_custom_logo( - securedrop_app_code_contents: str, -) -> None: - """ - Inspect the package contents to ensure custom_logo.png is not present. This - is because custom_logo.png supersedes logo.png. - """ - assert "/var/www/static/i/custom_logo.png" not in securedrop_app_code_contents diff --git a/molecule/builder-focal/tests/test_security_updates.py b/molecule/builder-focal/tests/test_security_updates.py deleted file mode 100644 --- a/molecule/builder-focal/tests/test_security_updates.py +++ /dev/null @@ -1,46 +0,0 @@ -import os -import re -from subprocess import check_output - -import pytest - -SECUREDROP_TARGET_DISTRIBUTION = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") -testinfra_hosts = [f"docker://{SECUREDROP_TARGET_DISTRIBUTION}-sd-sec-update"] - - -def test_should_run(): - command = ["git", "describe", "--all"] - version = check_output(command).decode("utf8")[0:-1] - candidates = ( - r"(^tags/[\d]+\.[\d]+\.[\d]+-rc[\d]+)|" - r"(^tags/[\d]+\.[\d]+\.[\d]+)|" - r"(^heads/release/[\d]+\.[\d]+\.[\d]+)|" - r"(^heads/update-builder.*)" - ) - result = re.match(candidates, version) - if result: - return True - else: - return False - - [email protected](not test_should_run(), reason="Only tested for RCs and builder updates") -def test_ensure_no_updates_avail(host): - """ - Test to make sure that there are no security-updates in the - base builder container. - """ - # Filter out all the security repos to their own file - # without this change all the package updates appeared as if they were - # coming from normal ubuntu update channel (since they get posted to both) - host.run('egrep "^deb.*security" /etc/apt/sources.list > /tmp/sec.list') - - dist_upgrade_simulate = host.run( - "apt-get -s dist-upgrade " - "-oDir::Etc::Sourcelist=/tmp/sec.list " - '|grep "^Inst" |grep -i security' - ) - - # If the grep was successful that means security package updates found - # otherwise we get a non-zero exit code so no updates needed. - assert dist_upgrade_simulate.rc != 0 diff --git a/molecule/builder-focal/tests/vars.yml b/molecule/builder-focal/tests/vars.yml deleted file mode 100644 --- a/molecule/builder-focal/tests/vars.yml +++ /dev/null @@ -1,21 +0,0 @@ ---- -securedrop_version: "2.6.0~rc1" -ossec_version: "3.6.0" -keyring_version: "0.1.6" - -# These values will be interpolated with values populated above -# via helper functions in the tests. -deb_paths: - securedrop_app_code: /tmp/build/securedrop-app-code_{securedrop_version}+{securedrop_target_distribution}_amd64.deb - securedrop_ossec_agent: /tmp/build/securedrop-ossec-agent_{ossec_version}+{securedrop_version}+{securedrop_target_distribution}_all.deb - securedrop_ossec_server: /tmp/build/securedrop-ossec-server_{ossec_version}+{securedrop_version}+{securedrop_target_distribution}_all.deb - ossec_server: /tmp/build/ossec-server-{ossec_version}+{securedrop_target_distribution}-amd64.deb - ossec_agent: /tmp/build/ossec-agent-{ossec_version}+{securedrop_target_distribution}-amd64.deb - securedrop_keyring: /tmp/build/securedrop-keyring_{keyring_version}+{securedrop_version}+{securedrop_target_distribution}_all.deb - securedrop_config: /tmp/build/securedrop-config_{securedrop_version}+{securedrop_target_distribution}_all.deb - -lintian_tags: - # - non-standard-file-perm - - package-contains-vcs-control-file - - package-installs-python-bytecode - # - wrong-file-owner-uid-or-gid
Stop pinning the "builder" docker image ## Description We build our packages in a container using a custom docker image (see `molecule/builder-focal`). The way the image is currently used is that it's frozen/pinned, pushed to quay.io, and then the person building the packages will pull it down and use it, as is. But if there are any missing security updates, the build will fail after the fact and then you need to go through the hurdle of updating the builder, rebuilding packages, etc. Also during the last builder update, I noticed that the logic to detect pending security updates itself was buggy, because it simulates a dist-upgrade and sees if any packages will be pulled in from focal-security, except we don't intend to do a dist-upgrade, so it complaining that a package not in the container was a pending security update! The theory is that pinning the builder helps with reproducible builds, except it doesn't because the build isn't reproducible for other reasons. ## Proposal We just build the image on the fly. At runtime we see if there are any pending updates and if so, bail. The deployer can rebuild the image locally and restart the package building. For reproducibility, we will implement #6356, but that shouldn't block this.
2023-02-22T03:17:01Z
[]
[]
freedomofpress/securedrop
6,771
freedomofpress__securedrop-6771
[ "6770" ]
417fc935c8fa425cc40d3b65f65ff9328d02ba6a
diff --git a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py --- a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py +++ b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py @@ -71,8 +71,8 @@ def migrate_nulls() -> None: needs_migration = [] conn = op.get_bind() for table in tables: - result = conn.execute( # nosec - f"SELECT 1 FROM {table} WHERE journalist_id IS NULL;" + result = conn.execute( + f"SELECT 1 FROM {table} WHERE journalist_id IS NULL;" # nosec ).first() if result is not None: needs_migration.append(table) @@ -89,7 +89,7 @@ def migrate_nulls() -> None: # unique key violations. op.execute( sa.text( - f"UPDATE OR IGNORE {table} SET journalist_id=:journalist_id " + f"UPDATE OR IGNORE {table} SET journalist_id=:journalist_id " # nosec "WHERE journalist_id IS NULL;" ).bindparams(journalist_id=deleted_id) )
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -588,7 +588,7 @@ def test_check_for_update_when_updates_not_needed(securedrop_git_repo): github_url = ( "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" # noqa: E501 ) - latest_release = requests.get(github_url).json() + latest_release = requests.get(github_url, timeout=60).json() latest_tag = str(latest_release["tag_name"]) subprocess.check_call(["git", "checkout", latest_tag]) @@ -661,7 +661,7 @@ def test_update_with_duplicate_branch_and_tag(securedrop_git_repo): github_url = ( "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" # noqa: E501 ) - latest_release = requests.get(github_url).json() + latest_release = requests.get(github_url, timeout=60).json() latest_tag = str(latest_release["tag_name"]) # Create a branch with the same name as a tag.
New bandit failures ``` Test results: >> Issue: [B113:request_without_timeout] Requests call without timeout Severity: Medium Confidence: Low CWE: CWE-400 (https://cwe.mitre.org/data/definitions/400.html) More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b113_request_without_timeout.html Location: ./admin/tests/test_integration.py:591:21 590 ) 591 latest_release = requests.get(github_url).json() 592 latest_tag = str(latest_release["tag_name"]) -------------------------------------------------- >> Issue: [B113:request_without_timeout] Requests call without timeout Severity: Medium Confidence: Low CWE: CWE-400 (https://cwe.mitre.org/data/definitions/400.html) More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b113_request_without_timeout.html Location: ./admin/tests/test_integration.py:664:21 663 ) 664 latest_release = requests.get(github_url).json() 665 latest_tag = str(latest_release["tag_name"]) -------------------------------------------------- >> Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction. Severity: Medium Confidence: Medium CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html) More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b608_hardcoded_sql_expressions.html Location: ./securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py:75:12 74 result = conn.execute( # nosec 75 f"SELECT 1 FROM {table} WHERE journalist_id IS NULL;" 76 ).first() -------------------------------------------------- >> Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction. Severity: Medium Confidence: Low CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html) More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b608_hardcoded_sql_expressions.html Location: ./securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py:92:16 91 sa.text( 92 f"UPDATE OR IGNORE {table} SET journalist_id=:journalist_id " 93 "WHERE journalist_id IS NULL;" 94 ).bindparams(journalist_id=deleted_id) -------------------------------------------------- ```
2023-03-15T18:19:46Z
[]
[]
freedomofpress/securedrop
6,785
freedomofpress__securedrop-6785
[ "6488" ]
1295576de3737c43b64e730cc9dd891f4d5bab49
diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -250,7 +250,6 @@ def add_source() -> Tuple[Source, str]: source_app_storage=Storage.get_default(), ) source = source_user.get_db_record() - source.pending = False db.session.commit() # Generate source key diff --git a/securedrop/manage.py b/securedrop/manage.py --- a/securedrop/manage.py +++ b/securedrop/manage.py @@ -29,6 +29,7 @@ from db import db # noqa: E402 from management import SecureDropConfig, app_context # noqa: E402 from management.run import run # noqa: E402 +from management.sources import remove_pending_sources # noqa: E402 from management.submissions import ( # noqa: E402 add_check_db_disconnect_parser, add_check_fs_disconnect_parser, @@ -355,6 +356,17 @@ def get_args() -> argparse.ArgumentParser: delete_user_subp_a = subps.add_parser("delete_user", help="^") delete_user_subp_a.set_defaults(func=delete_user) + remove_pending_sources_subp = subps.add_parser( + "remove-pending-sources", help="Remove pending sources from the server." + ) + remove_pending_sources_subp.add_argument( + "--keep-most-recent", + default=100, + type=int, + help="how many of the most recent pending sources to keep", + ) + remove_pending_sources_subp.set_defaults(func=remove_pending_sources) + add_check_db_disconnect_parser(subps) add_check_fs_disconnect_parser(subps) add_delete_db_disconnect_parser(subps) diff --git a/securedrop/management/sources.py b/securedrop/management/sources.py new file mode 100644 --- /dev/null +++ b/securedrop/management/sources.py @@ -0,0 +1,58 @@ +import argparse +from typing import List + +from db import db +from encryption import EncryptionManager, GpgKeyNotFoundError +from management import app_context +from models import Source + + +def remove_pending_sources(args: argparse.Namespace) -> int: + """ + Removes pending source accounts, with the option of keeping + the n newest source accounts. + """ + n = args.keep_most_recent + sources = find_pending_sources(n) + print(f"Found {len(sources)} pending sources") + + deleted = [] + for source in sources: + try: + EncryptionManager.get_default().delete_source_key_pair(source.filesystem_id) + except GpgKeyNotFoundError: + pass + delete_pending_source(source) + deleted.append(source) + + print(f"Deleted {len(sources)} pending sources") + return 0 + + +def find_pending_sources(keep_most_recent: int) -> List[Source]: + """ + Finds all sources that are marked as pending + """ + with app_context(): + pending_sources = ( + Source.query.filter_by(pending=True) + .order_by(Source.id.desc()) + .offset(keep_most_recent) + .all() + ) + + return pending_sources + + +def delete_pending_source(source: Source) -> None: + """ + Delete a pending source from the database + """ + if source.pending: + with app_context(): + try: + db.session.delete(source) + db.session.commit() + except Exception as exc: + db.session.rollback() + print(f"ERROR: Could not remove pending source: {exc}.")
diff --git a/securedrop/tests/test_remove_pending_sources.py b/securedrop/tests/test_remove_pending_sources.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_remove_pending_sources.py @@ -0,0 +1,89 @@ +import argparse + +import manage +import pytest +from models import Source, db +from passphrases import PassphraseGenerator +from source_user import create_source_user + + [email protected]("n,m", [(10, 5), (7, 0)]) +def test_remove_pending_sources_none_pending(n, m, source_app, config, app_storage): + """remove_pending_sources() is a no-op on active sources.""" + + # Override the configuration to point at the per-test database. + data_root = config.SECUREDROP_DATA_ROOT + + with source_app.app_context(): + sources = [] + for i in range(0, n): + source_user = create_source_user( + db_session=db.session, + source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), + source_app_storage=app_storage, + ) + source = source_user.get_db_record() + source.pending = False + sources.append(source.id) + db.session.commit() + + # Make sure we have n sources. + assert db.session.query(Source).count() == n + + # If we're keeping the n most-recent sources, then remove_pending_sources() + # shouldn't remove any. + args = argparse.Namespace(data_root=data_root, verbose=True, keep_most_recent=n) + manage.setup_verbosity(args) + manage.remove_pending_sources(args) + assert db.session.query(Source).count() == n + + # If we're keeping the m most-recent sources, then remove_pending_sources() + # still shouldn't do anything, because none are pending. + args = argparse.Namespace(data_root=data_root, verbose=True, keep_most_recent=m) + manage.setup_verbosity(args) + manage.remove_pending_sources(args) + assert db.session.query(Source).count() == n + + [email protected]("n,m", [(10, 5), (7, 0)]) +def test_remove_pending_sources_all_pending(n, m, source_app, config, app_storage): + """remove_pending_sources() removes all but the most-recent m of n pending sources.""" + # Override the configuration to point at the per-test database. + data_root = config.SECUREDROP_DATA_ROOT + + with source_app.app_context(): + sources = [] + for i in range(0, n): + source_user = create_source_user( + db_session=db.session, + source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), + source_app_storage=app_storage, + ) + source = source_user.get_db_record() + sources.append(source.id) + db.session.commit() + + # Make sure we have n sources. + assert db.session.query(Source).count() == n + + # If we're keeping the n most-recent sources, then remove_pending_sources() + # shouldn't remove any. + args = argparse.Namespace(data_root=data_root, verbose=True, keep_most_recent=n) + manage.setup_verbosity(args) + manage.remove_pending_sources(args) + assert db.session.query(Source).count() == n + + # If we're keeping the m most-recent sources, then remove_pending_sources() + # should remove n - m. + args = argparse.Namespace(data_root=data_root, verbose=True, keep_most_recent=m) + manage.setup_verbosity(args) + manage.remove_pending_sources(args) + assert db.session.query(Source).count() == m + + # Specifically, the first n - m sources should be gone... + for source in sources[0 : n - m]: + assert db.session.query(Source).get(source) is None + + # ...and only the last m should remain. + for source in sources[n - m : n]: + assert db.session.query(Source).get(source) is not None
Allow for removal of "pending" source accounts ## Description When a source account is created but before a first submission, by default a "pending" flag is set. Pending accounts are not displayed in the journalist interface. If a user then exits their session and never returns to provide a submission, the account will remain in a pending state indefinitely, and cannot be removed via the Journalist Interface. On long-running high-volume instances this increases the source user count significantly, requiring admin intervention to fix. One approach to allow for the removal of unused source accounts would be to change the `pending` boolean flag to a datetime value, and purge unused accounts via a cronjob or similar after a set time (say, a month). This has the disadvantage of increasing metadata (source account creation time) about prospective sources, though the field could be set to `null` on submission, meaning that said metadata would not be stored for sources that were actually ever active. This could be mitigated somewhat by giving the datetime a resolution on the order of days or weeks. Alternatively, the fact that active source sessions without submissions would be nuked when the purge ran could just be accepted. Note that this would be moot if/when inverted flow changes land, as accounts would then only be created on first submission. So it might not be worth the effort if it was just a temporary measure. ## To do 1. [x] Add `manage.py` command 2. [ ] Add tests, especially for `--keep-most-recent`'s offset logic 3. [ ] Extract standalone script for testing purposes ## User Research Evidence long-term observations of instance behavior... ## User Stories
Today @nathandyer and I mapped out the following approach for implementing this lever: 1. Add a `securedrop.management.sources` command that: 1. Retrieves `Source`s with [`pending=True`](https://github.com/freedomofpress/securedrop/blob/d01e743d2853d42c47459163dfae05e4540344f1/securedrop/models.py#L66), except for the (parameterized) *n* most recent—that is, except those with the *n* highest `id`s. * This constraint adds a margin for recent pending sources without introducing the timestamp suggested above. 3. For each `Source` in (1), calls [`EncryptionManager.delete_source_key_pair()`](https://github.com/freedomofpress/securedrop/blob/d01e743d2853d42c47459163dfae05e4540344f1/securedrop/encryption.py#L150). 4. Deletes all `Source`s in (1). * To my eye, `Source` should have a deletion method or hook that automatically calls `EncryptionManager.delete_source_key_pair()` to avoid orphaned keys. But that's out of scope of this ticket, and a bulk operation will be more efficient anyway. 2. Once we're happy with the implementation of this command via `manage.py`, we can easily derive a standalone version for testing purposes (even just in a gist, to avoid cluttering up the branch). @nathandyer and I agreed that we'd much rather work backwards from the intended `manage.py` structure than start with a standalone script and then formalize it in `manage.py`.
2023-05-02T00:36:14Z
[]
[]
freedomofpress/securedrop
6,829
freedomofpress__securedrop-6829
[ "6489" ]
d964e5984b183f91ce9415ac37920d1d30884508
diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -6,7 +6,7 @@ import flask import werkzeug from db import db -from encryption import EncryptionManager, GpgKeyNotFoundError +from encryption import EncryptionManager from flask import Markup, abort, current_app, escape, flash, redirect, send_file, url_for from flask_babel import gettext, ngettext from journalist_app.sessions import session @@ -397,11 +397,8 @@ def delete_collection(filesystem_id: str) -> None: if os.path.exists(path): Storage.get_default().move_to_shredder(path) - # Delete the source's reply keypair, if it exists - try: - EncryptionManager.get_default().delete_source_key_pair(filesystem_id) - except GpgKeyNotFoundError: - pass + # Delete the source's reply keypair + EncryptionManager.get_default().delete_source_key_pair(filesystem_id) # Delete their entry in the db source = get_source(filesystem_id, include_deleted=True) diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -175,6 +175,13 @@ def lookup(logged_in_source: SourceUser) -> str: # Sort the replies by date replies.sort(key=operator.attrgetter("date"), reverse=True) + # If not done yet, generate a keypair to encrypt replies from the journalist + encryption_mgr = EncryptionManager.get_default() + try: + encryption_mgr.get_source_public_key(logged_in_source.filesystem_id) + except GpgKeyNotFoundError: + encryption_mgr.generate_source_key_pair(logged_in_source) + return render_template( "lookup.html", is_user_logged_in=True, @@ -305,13 +312,6 @@ def submit(logged_in_source: SourceUser) -> werkzeug.Response: normalize_timestamps(logged_in_source) - # If not done yet, generate a keypair to encrypt replies from the journalist - encryption_mgr = EncryptionManager.get_default() - try: - encryption_mgr.get_source_public_key(logged_in_source.filesystem_id) - except GpgKeyNotFoundError: - encryption_mgr.generate_source_key_pair(logged_in_source) - return redirect(url_for("main.lookup")) @view.route("/delete", methods=("POST",))
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -14,7 +14,6 @@ import pytest import version from db import db -from encryption import EncryptionManager from flaky import flaky from flask import escape, g, request, session, url_for from flask_babel import gettext @@ -119,19 +118,16 @@ def test_generate_already_logged_in(source_app): def test_create_new_source(source_app): - """Create new source, ensuring that reply key is not created at the same time""" with source_app.test_client() as app: - with patch.object(EncryptionManager, "get_source_public_key") as get_key: - resp = app.post(url_for("main.generate"), data=GENERATE_DATA) - assert resp.status_code == 200 - tab_id = next(iter(session["codenames"].keys())) - resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) - assert SessionManager.is_user_logged_in(db_session=db.session) - # should be redirected to /lookup - text = resp.data.decode("utf-8") - assert "Submit Files" in text - assert "codenames" not in session - get_key.assert_not_called() + resp = app.post(url_for("main.generate"), data=GENERATE_DATA) + assert resp.status_code == 200 + tab_id = next(iter(session["codenames"].keys())) + resp = app.post(url_for("main.create"), data={"tab_id": tab_id}, follow_redirects=True) + assert SessionManager.is_user_logged_in(db_session=db.session) + # should be redirected to /lookup + text = resp.data.decode("utf-8") + assert "Submit Files" in text + assert "codenames" not in session def test_generate_as_post(source_app): @@ -367,22 +363,18 @@ def _dummy_submission(app): ) -def test_initial_submission(source_app): +def test_initial_submission_notification(source_app): """ Regardless of the type of submission (message, file, or both), the first submission is always greeted with a notification reminding sources to check back later for replies. - - A GPG keypair for replies should also be created. """ with source_app.test_client() as app: - with patch.object(EncryptionManager, "generate_source_key_pair") as gen_key: - new_codename(app, session) - resp = _dummy_submission(app) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "Thank you for sending this information to us." in text - gen_key.assert_called_once() + new_codename(app, session) + resp = _dummy_submission(app) + assert resp.status_code == 200 + text = resp.data.decode("utf-8") + assert "Thank you for sending this information to us." in text def test_submit_message(source_app):
Generate reply key on first submission Note that this change is being reverted! ## Description When a source visits /lookup for the first time, a GPG reply key is generated. However, if the source does not submit a message, it is impossible to reply to them, as their account is flagged as `pending` and not displayed in the JI. To avoid creating keys unnecessarily, the key could be created on submission instead if it does not already exist. ## User Research Evidence Observed behavior of sd instances ## User Stories As an admin, I want to keep a manageable number of source accounts and reply keys
This is superfluous with the job to purge pending keys, and it is a potential source of race condition bugs, so I'm gonna revert the change.
2023-05-31T14:10:41Z
[]
[]
freedomofpress/securedrop
6,830
freedomofpress__securedrop-6830
[ "5914" ]
5423d1bdb9775be3fbf232de56f2ca966f83d9bc
diff --git a/admin/bootstrap.py b/admin/bootstrap.py --- a/admin/bootstrap.py +++ b/admin/bootstrap.py @@ -255,6 +255,40 @@ def install_pip_dependencies( """ Install Python dependencies via pip into virtualenv. """ + + # Ansible version 2.9.* cannot be directly upgraded and must be removed + # before attempting to install a later version - so let's check for it + # and uninstall it if we find it! + + ansible_vercheck_cmd = [ + os.path.join(VENV_DIR, "bin", "python3"), + "-c", + "from importlib.metadata import version as v; print(v('ansible'))", + ] + + ansible_uninstall_cmd = [ + os.path.join(VENV_DIR, "bin", "pip3"), + "uninstall", + "-y", + "ansible", + ] + + ansible_ver = subprocess.run( + maybe_torify() + ansible_vercheck_cmd, text=True, capture_output=True + ) + if ansible_ver.stdout.startswith("2.9"): + sdlog.info("Ansible is out-of-date, removing it.") + delete_result = subprocess.run( + maybe_torify() + ansible_uninstall_cmd, capture_output=True, text=True + ) + if delete_result.returncode != 0: + sdlog.error( + "Failed to remove old ansible version:\n" + f" return num: {delete_result.returncode}\n" + f" error text: {delete_result.stderr}\n" + "Attempting to continue." + ) + pip_install_cmd = [ os.path.join(VENV_DIR, "bin", "pip3"), "install", @@ -274,7 +308,7 @@ def install_pip_dependencies( ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) - sdlog.error("Failed to install {}. Check network" " connection and try again.".format(desc)) + sdlog.error(f"Failed to install {desc}. Check network" " connection and try again.") raise sdlog.debug(pip_output) diff --git a/install_files/ansible-base/callback_plugins/ansible_version_check.py b/install_files/ansible-base/callback_plugins/ansible_version_check.py --- a/install_files/ansible-base/callback_plugins/ansible_version_check.py +++ b/install_files/ansible-base/callback_plugins/ansible_version_check.py @@ -17,8 +17,8 @@ class CallbackModule(CallbackBase): def __init__(self): # The acceptable version range needs to be synchronized with # requirements files. - viable_start = [2, 9, 7] - viable_end = [2, 10, 0] + viable_start = [2, 11, 0] + viable_end = [2, 15, 0] ansible_version = [int(v) for v in ansible.__version__.split(".")] if not (viable_start <= ansible_version < viable_end): print_red_bold(
diff --git a/molecule/testinfra/common/test_platform.py b/molecule/testinfra/common/test_platform.py --- a/molecule/testinfra/common/test_platform.py +++ b/molecule/testinfra/common/test_platform.py @@ -10,7 +10,7 @@ def test_ansible_version(host): """ localhost = host.get_host("local://") c = localhost.check_output("ansible --version") - assert c.startswith("ansible 2.") + assert c.startswith("ansible [core 2.") def test_platform(host):
Upgrade Ansible to latest stable ## Description The Admin Workstation currently runs Ansible v2.9.7. Soon enough, we'll need to bump to the already released 2.10.x series. That's a difficult jump, and violates expectations about semver. ## Example output for complicated upgrade See the following failure message about a naive upgrade from 2.9.7 -> 2.10.7 <details> <summary> pip error output </summary> ``` $ ansible --version ansible 2.9.7 config file = /home/user/securedrop/ansible.cfg configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/user/.virtualenvs/sd/lib/python3.7/site-packages/ansible executable location = /home/user/.virtualenvs/sd/bin/ansible python version = 3.7.3 (default, Jul 25 2020, 13:03:44) [GCC 8.3.0] [user@sd-dev:~/securedrop] [sd] develop+* 6h15m51s ± $ pip install 'ansible>2.10,<2.11' Collecting ansible<2.11,>2.10 Downloading https://files.pythonhosted.org/packages/ba/22/7b58a8ba8e43159dc5cb32d97dd50e2b70b016585dbb188e9f2b61dac1e2/ansible-2.10.7.tar.gz (29.9MB) |████████████████████████████████| 29.9MB 561kB/s ERROR: Command errored out with exit status 1: command: /home/user/.virtualenvs/sd/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-312we13s/ansible/setup.py'"'"'; __file__='"'"'/tmp/pip-install-312we13s/ansible/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-312we13s/ansible/pip-egg-info cwd: /tmp/pip-install-312we13s/ansible/ Complete output (31 lines): ### ERROR ### Upgrading directly from ansible-2.9 or less to ansible-2.10 or greater with pip is known to cause problems. Please uninstall the old version found at: /home/user/.virtualenvs/sd/lib/python3.7/site-packages/ansible/__init__.py and install the new version: pip uninstall ansible pip install ansible If you have a broken installation, perhaps because ansible-base was installed before ansible was upgraded, try this to resolve it: pip install --force-reinstall ansible ansible-base If ansible is installed in a different location than you will be installing it now (for example, if the old version is installed by a system package manager to /usr/lib/python3.8/site-packages/ansible but you are installing the new version into ~/.local/lib/python3.8/site-packages/ansible with `pip install --user ansible`) or you want to install anyways and cleanup any breakage afterwards, then you may set the ANSIBLE_SKIP_CONFLICT_CHECK environment variable to ignore this check: ANSIBLE_SKIP_CONFLICT_CHECK=1 pip install --user ansible ### END ERROR ### ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 19.3.1; however, version 21.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ``` </details> The import bit: <blockquote> Upgrading directly from ansible-2.9 or less to ansible-2.10 or greater with pip is known to cause problems. Please uninstall the old version found at: /home/user/.virtualenvs/sd/lib/python3.7/site-packages/ansible/__init__.py and install the new version: pip uninstall ansible pip install ansible </blockquote> That change will require special handling of the upgrade logic in the Admin Workstation, to avoid breakage. ## Misc Looks like the Ansible project is [switching to semver](https://docs.ansible.com/ansible/latest/roadmap/COLLECTIONS_3_0.html#release-schedule), presumably due to feedback regarding the breakaging changes in 2.10: > Ansible is switching from its traditional versioning scheme to semantic versioning starting with this release. So this version is 3.0.0 instead of 2.11.0.
2023-05-31T17:25:17Z
[]
[]
freedomofpress/securedrop
6,853
freedomofpress__securedrop-6853
[ "6851" ]
3474e1324aca79c77fafc612272905c501892eaf
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -172,13 +172,16 @@ def map_locale_display_names( like Chinese, we do need the additional detail. """ + # Deduplicate before sorting. + supported_locales = sorted(list(set(config.SUPPORTED_LOCALES))) + language_locale_counts = collections.defaultdict(int) # type: Dict[str, int] - for l in sorted(config.SUPPORTED_LOCALES): + for l in supported_locales: locale = RequestLocaleInfo(l) language_locale_counts[locale.language] += 1 locale_map = collections.OrderedDict() - for l in sorted(config.SUPPORTED_LOCALES): + for l in supported_locales: if Locale.parse(l) not in usable_locales: continue
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -456,3 +456,20 @@ def test_same_lang_diff_locale(): html = resp.data.decode("utf-8") assert "português (Brasil)" in html assert "português (Portugal)" in html + + +def test_duplicate_locales(): + """ + Verify that we don't display the full locale name for duplicate locales, + whether from user input or securedrop.sdconfig's enforcement of the + fallback locale. + """ + + # ["en_US", "en_US"] alone will not display the locale switcher, which + # *does* pass through set deduplication. + test_config = create_config_for_i18n_test(supported_locales=["en_US", "en_US", "ar"]) + + app = journalist_app_module.create_app(test_config).test_client() + resp = app.get("/", follow_redirects=True) + html = resp.data.decode("utf-8") + assert "English (United States)" not in html
[2.6.0] locale switcher lists full locale name when `SUPPORTED_LOCALES` contains duplicates ## Description If the `SUPPORTED_LOCALES` list contains duplicates, including just if an administrator explicitly adds the default `en_US` locale, then the locale switcher will unnecessarily list the full locale name including the country. ## Steps to Reproduce 1. `securedrop-admin sdconfig`: explicitly include `en_US` as a supported locale 2. `securedrop-admin install` ## Expected Behavior `English` is listed in the locale switcher. ## Actual Behavior `English (United States)` is listed in the locale switcher. Courtesy of @legoktm: ![IMG_20230615_174621](https://github.com/freedomofpress/securedrop/assets/357435/7fa87841-46a6-4203-848e-a3e3b3f246b3)
2023-06-16T01:01:17Z
[]
[]
freedomofpress/securedrop
6,884
freedomofpress__securedrop-6884
[ "6817" ]
81a3c4915278a4b403868e46a75c6cfe78e9aa7c
diff --git a/redwood/build-wheel.py b/redwood/build-wheel.py new file mode 100644 --- /dev/null +++ b/redwood/build-wheel.py @@ -0,0 +1,60 @@ +#!/usr/bin/python3 +""" +Build a Python wheel containing the Rust redwood code + +Ideally we'd use maturin for this, but it has a big dependency tree +that's not really worth reviewing, so this is mostly a stop-gap until +we can use a Debian-packaged version. This is only intended to run in +the SecureDrop dev and packaging environments. + +At a high level, this script: +* Compiles the Rust code into a shared library (libredwood.so) +* Copy and rename that into the Python package structure +* Build a Python wheel using setuptools +""" +import argparse +import os +import shutil +import subprocess +import sys +import sysconfig +from pathlib import Path + +parser = argparse.ArgumentParser(description="Build a wheel") +parser.add_argument("--release", action="store_true", help="Build in release mode") +parser.add_argument("--redwood", type=Path, help="Path to redwood folder") +parser.add_argument("--target", type=Path, help="Path to target folder") +args = parser.parse_args() + +os.chdir(args.redwood) + +if args.release: + flavor = "release" + cargo_flags = ["--release"] +else: + flavor = "debug" + cargo_flags = [] + +env = {"CARGO_TARGET_DIR": str(args.target), **os.environ} + +print("Starting to build Rust code") +subprocess.check_call(["cargo", "build", "--lib", "--locked"] + cargo_flags, env=env) +print("Copying libredwood.so into package") +libredwood = args.target / flavor / "libredwood.so" +if not libredwood.exists(): + print(f"Error: Can't find libredwood.so (looked for {libredwood})") + sys.exit(1) + +so_destination = args.redwood / "redwood" / ("redwood" + sysconfig.get_config_var("EXT_SUFFIX")) +shutil.copy2(libredwood, so_destination) + +print("Building wheel") +subprocess.check_call([sys.executable, "-m", "pip", "wheel", "."]) +# Yes the wheel name is wrong (this is not a pure-Python wheel), +# but it doesn't matter, this is only an intermediate step as it will +# be immediately unpacked and installed into the virtualenv. +whl = Path("redwood-0.1.0-py3-none-any.whl") +if not whl.exists(): + print("Error: Can't find the wheel") + sys.exit(1) +print(f"Built at: {whl.absolute()}") diff --git a/redwood/redwood/__init__.py b/redwood/redwood/__init__.py new file mode 100644 --- /dev/null +++ b/redwood/redwood/__init__.py @@ -0,0 +1,6 @@ +# flake8: noqa +# Wrapper to Rust .so +from .redwood import * + +__doc__ = redwood.__doc__ +__all__ = redwood.__all__
diff --git a/builder/tests/test_securedrop_deb_package.py b/builder/tests/test_securedrop_deb_package.py --- a/builder/tests/test_securedrop_deb_package.py +++ b/builder/tests/test_securedrop_deb_package.py @@ -9,6 +9,7 @@ subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode().strip() ) DEB_PATHS = list((SECUREDROP_ROOT / "build/focal").glob("*.deb")) +SITE_PACKAGES = "/opt/venvs/securedrop-app-code/lib/python3.8/site-packages" @pytest.fixture(scope="module") @@ -69,6 +70,7 @@ def test_deb_package_contains_expected_conffiles(deb: Path): "/var/www/securedrop/.well-known/pki-validation/", "/var/www/securedrop/translations/messages.pot", "/var/www/securedrop/translations/de_DE/LC_MESSAGES/messages.mo", + f"{SITE_PACKAGES}/redwood/redwood.cpython-38-x86_64-linux-gnu.so", ], ) def test_app_code_paths(securedrop_app_code_contents: str, path: str): @@ -89,7 +91,7 @@ def test_app_code_paths(securedrop_app_code_contents: str, path: str): "/var/www/securedrop/static/.webassets-cache/", "/var/www/securedrop/static/gen/", "/var/www/securedrop/config.py", - "/var/www/static/i/custom_logo.png", + "/var/www/securedrop/static/i/custom_logo.png", ".j2", ], ) diff --git a/molecule/testinfra/app/test_smoke.py b/molecule/testinfra/app/test_smoke.py --- a/molecule/testinfra/app/test_smoke.py +++ b/molecule/testinfra/app/test_smoke.py @@ -1,6 +1,8 @@ """ Basic smoke tests that verify the apps are functioning as expected """ +import json + import pytest import testutils @@ -31,3 +33,19 @@ def test_interface_up(host, name, url, curl_flags): assert "nopenopenope" in f.content_string assert "200 OK" in response assert "Powered by" in response + + +def test_redwood(host): + """ + Verify the redwood wheel was built and installed properly and basic + functionality works + """ + response = host.run( + "/opt/venvs/securedrop-app-code/bin/python3 -c " + "'import redwood; import json; print(" + 'json.dumps(redwood.generate_source_key_pair("abcde", "test@invalid")))\'' + ) + parsed = json.loads(response.stdout) + assert "-----BEGIN PGP PUBLIC KEY BLOCK-----" in parsed[0] + assert "-----BEGIN PGP PRIVATE KEY BLOCK-----" in parsed[1] + assert len(parsed[2]) == 40
Packaging process builds Rust code Our `make build-debs` packaging process needs to build a Rust wheel and install it into the virtualenv. As part of this we need to make sure that the built wheel is fully reproducible so we aren't regressing on reproducible builds.
Just noting that in my dev Qubes VM with 6 CPU cores assigned, it takes a little over 4 minutes to build redwood in release mode. So here's what maturin is doing under the hood, as discovered by `RUST_LOG=debug maturin build -m redwood/Cargo.toml -v -r` ``` 2023-06-28T20:05:49.562717Z DEBUG maturin::project_layout: Using cargo manifest path from command line argument: "/home/user/github/freedomofpress/securedrop/redwood/Cargo.toml" 2023-06-28T20:05:49.562741Z DEBUG maturin::project_layout: Resolving cargo metadata from "/home/user/github/freedomofpress/securedrop/redwood/Cargo.toml" 2023-06-28T20:05:49.680016Z DEBUG maturin::project_layout: Found pyproject.toml at "/home/user/github/freedomofpress/securedrop/redwood/pyproject.toml" 2023-06-28T20:05:49.680486Z DEBUG maturin::project_layout: Resolving cargo metadata from "/home/user/github/freedomofpress/securedrop/redwood/Cargo.toml" 2023-06-28T20:05:49.798743Z DEBUG maturin::project_layout: Project layout resolved project_root=/home/user/github/freedomofpress/securedrop/redwood python_dir=/home/user/github/freedomofpress/securedrop/redwood rust_module=/home/user/github/freedomofpress/securedrop/redwood/redwood python_module=/home/user/github/freedomofpress/securedrop/redwood/redwood extension_name=redwood module_name=redwood 🔗 Found pyo3 bindings 2023-06-28T20:05:49.892508Z DEBUG maturin::python_interpreter: Found CPython interpreter at /home/user/github/freedomofpress/securedrop/.venv/bin/python3 🐍 Found CPython 3.8 at /home/user/github/freedomofpress/securedrop/.venv/bin/python3 📡 Using build options compatibility from pyproject.toml 2023-06-28T20:05:49.892782Z DEBUG maturin::compile: Setting PYO3_PYTHON to /home/user/github/freedomofpress/securedrop/.venv/bin/python3 2023-06-28T20:05:49.892800Z DEBUG maturin::compile: Running CARGO_ENCODED_RUSTFLAGS="-C\u{1f}link-arg=-fuse-ld=/usr/bin/mold" PYO3_ENVIRONMENT_SIGNATURE="cpython-3.8-64bit" PYO3_PYTHON="/home/user/github/freedomofpress/securedrop/.venv/bin/python3" PYTHON_SYS_EXECUTABLE="/home/user/github/freedomofpress/securedrop/.venv/bin/python3" "cargo" "rustc" "--message-format" "json-render-diagnostics" "-v" "--manifest-path" "/home/user/github/freedomofpress/securedrop/redwood/Cargo.toml" "--release" "--lib" ... 2023-06-28T20:08:25.756120Z DEBUG maturin::module_writer: Adding redwood-0.1.0.dist-info/METADATA 2023-06-28T20:08:25.756369Z DEBUG maturin::module_writer: Adding redwood-0.1.0.dist-info/WHEEL 2023-06-28T20:08:25.756691Z DEBUG maturin::module_writer: Adding redwood/__init__.py 📖 Found type stub file at redwood.pyi 2023-06-28T20:08:25.756900Z DEBUG maturin::module_writer: Adding redwood/__init__.pyi from /home/user/github/freedomofpress/securedrop/redwood/redwood.pyi 2023-06-28T20:08:25.757153Z DEBUG maturin::module_writer: Adding redwood/py.typed 2023-06-28T20:08:25.757345Z DEBUG maturin::module_writer: Adding redwood/redwood.cpython-38-x86_64-linux-gnu.so from /home/user/.cargo/target/release/maturin/libredwood.so 2023-06-28T20:08:26.382540Z DEBUG maturin::module_writer: Adding redwood-0.1.0.dist-info/RECORD 📦 Built wheel for CPython 3.8 to /home/user/.cargo/target/wheels/redwood-0.1.0-cp38-cp38-linux_x86_64.whl ``` Here's what the `__init__.py` file contains: ``` from .redwood import * __doc__ = redwood.__doc__ if hasattr(redwood, "__all__"): __all__ = redwood.__all__ ``` for reference: ```python3 >>> redwood.__all__ ['generate_source_key_pair', 'encrypt_message', 'encrypt_file', 'decrypt', 'RedwoodError'] >>> redwood.__doc__ 'A Python module implemented in Rust.' ``` I thiiiiink we could just do this ourselves?? Will keep poking. It ended up being like 40 lines of Python, which is pretty good I think! maturin does have some nice safety features, like it checks that the `PyInit_redwood` symbol is present (https://github.com/PyO3/maturin/blob/3ea1d0f165351d44f4c02afed98a226334401558/src/compile.rs#L539), so I think we should eventually switch back to it, but I think we can just wait until it lands in Debian - https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=999850 And since it's statically compiled, hopefully we'll just be able to use it directly out of unstable/testing (might run into glibc version issues?).
2023-06-27T23:56:22Z
[]
[]
freedomofpress/securedrop
6,885
freedomofpress__securedrop-6885
[ "6699" ]
2bc42f09f7cc132d55f5ba0c12d277550f3c164a
diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -228,14 +228,14 @@ def validate(self, document: Document) -> bool: class ValidateOSSECUsername(Validator): def validate(self, document: Document) -> bool: text = document.text - if text and "@" not in text and "test" != text: + if text and "@" not in text and text != "test": return True raise ValidationError(message="The SASL username should not include the domain name") class ValidateOSSECPassword(Validator): def validate(self, document: Document) -> bool: text = document.text - if len(text) >= 8 and "password123" != text: + if len(text) >= 8 and text != "password123": return True raise ValidationError(message="Password for OSSEC email account must be strong") @@ -252,7 +252,7 @@ class ValidateOSSECEmail(ValidateEmail): def validate(self, document: Document) -> bool: super().validate(document) text = document.text - if "[email protected]" != text: + if text != "[email protected]": return True raise ValidationError( message=("Must be set to something other than " "[email protected]") @@ -266,10 +266,10 @@ def validate(self, document: Document) -> bool: def __init__(self, args: argparse.Namespace) -> None: self.args = args - self.config = {} # type: Dict + self.config: dict = {} # Hold runtime configuration before save, to support # referencing other responses during validation - self._config_in_progress = {} # type: Dict + self._config_in_progress: dict = {} supported_locales = I18N_DEFAULT_LOCALES.copy() i18n_conf_path = os.path.join(args.root, I18N_CONF) @@ -279,7 +279,7 @@ def __init__(self, args: argparse.Namespace) -> None: supported_locales.update(set(i18n_conf["supported_locales"].keys())) locale_validator = SiteConfig.ValidateLocales(self.args.app_path, supported_locales) - self.desc = [ + self.desc: List[_DescEntryType] = [ ( "ssh_users", "sd", @@ -516,7 +516,7 @@ def __init__(self, args: argparse.Namespace) -> None: str.split, lambda config: True, ), - ] # type: List[_DescEntryType] + ] def load_and_update_config(self, validate: bool = True, prompt: bool = True) -> bool: if self.exists(): @@ -542,9 +542,7 @@ def user_prompt_config(self) -> Dict[str, Any]: if not condition(self._config_in_progress): self._config_in_progress[var] = "" continue - self._config_in_progress[var] = self.user_prompt_config_one( - desc, self.config.get(var) - ) # noqa: E501 + self._config_in_progress[var] = self.user_prompt_config_one(desc, self.config.get(var)) return self._config_in_progress def user_prompt_config_one(self, desc: _DescEntryType, from_config: Optional[Any]) -> Any: @@ -932,7 +930,7 @@ def check_for_updates(args: argparse.Namespace) -> Tuple[bool, str]: # relied on to determine if we're on the latest tag or not. current_tag = ( subprocess.check_output(["git", "describe"], cwd=args.root).decode("utf-8").rstrip("\n") - ) # noqa: E501 + ) # Fetch all branches git_fetch_cmd = ["git", "fetch", "--all"] @@ -945,7 +943,7 @@ def check_for_updates(args: argparse.Namespace) -> Tuple[bool, str]: .decode("utf-8") .rstrip("\n") .split("\n") - ) # noqa: E501 + ) # Do not check out any release candidate tags all_prod_tags = [x for x in all_tags if "rc" not in x] @@ -1110,8 +1108,6 @@ class ArgParseFormatterCombo( ): """Needed to combine formatting classes for help output""" - pass - parser = argparse.ArgumentParser(description=__doc__, formatter_class=ArgParseFormatterCombo) parser.add_argument( "-v", action="store_true", default=False, help="Increase verbosity on output" diff --git a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py --- a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py +++ b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py @@ -17,9 +17,7 @@ path_torrc_backup = "/etc/tor/torrc.bak" path_torrc = "/etc/tor/torrc" path_desktop = "/home/amnesia/Desktop/" -path_persistent_desktop = ( - "/lib/live/mount/persistence/TailsData_unlocked/dotfiles/Desktop/" # noqa: E501 -) +path_persistent_desktop = "/lib/live/mount/persistence/TailsData_unlocked/dotfiles/Desktop/" path_securedrop_root = "/home/amnesia/Persistent/securedrop" path_securedrop_admin_venv = os.path.join(path_securedrop_root, "admin/.venv3/bin/python") path_securedrop_admin_init = os.path.join( diff --git a/journalist_gui/journalist_gui/SecureDropUpdater.py b/journalist_gui/journalist_gui/SecureDropUpdater.py --- a/journalist_gui/journalist_gui/SecureDropUpdater.py +++ b/journalist_gui/journalist_gui/SecureDropUpdater.py @@ -12,7 +12,7 @@ from journalist_gui import resources_rc, strings, updaterUI # noqa -FLAG_LOCATION = "/home/amnesia/Persistent/.securedrop/securedrop_update.flag" # noqa +FLAG_LOCATION = "/home/amnesia/Persistent/.securedrop/securedrop_update.flag" ESCAPE_POD = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]") @@ -25,7 +25,7 @@ def password_is_set(): return True -def prevent_second_instance(app: QtWidgets.QApplication, name: str) -> None: # noqa +def prevent_second_instance(app: QtWidgets.QApplication, name: str) -> None: # Null byte triggers abstract namespace IDENTIFIER = "\0" + name diff --git a/molecule/testinfra/conftest.py b/molecule/testinfra/conftest.py --- a/molecule/testinfra/conftest.py +++ b/molecule/testinfra/conftest.py @@ -30,7 +30,7 @@ def securedrop_import_testinfra_vars(hostname, with_header=False): hostvars["securedrop_venv_site_packages"] = hostvars["securedrop_venv_site_packages"].format( "3.8" - ) # noqa: E501 + ) hostvars["python_version"] = "3.8" hostvars["apparmor_enforce_actual"] = hostvars["apparmor_enforce"]["focal"] @@ -60,7 +60,7 @@ def _prod_override(vars_key, prod_key): repo_filepath = os.path.join( os.path.dirname(__file__), "../../install_files/ansible-base/roles/install-fpf-repo/defaults/main.yml", - ) # noqa: E501 + ) if os.path.isfile(repo_filepath): with open(repo_filepath) as f: repovars = yaml.safe_load(f) @@ -74,7 +74,7 @@ def _prod_override(vars_key, prod_key): class TestVars(dict): - managed_attrs = {} # type: Dict[str, Any] + managed_attrs: Dict[str, Any] = {} def __init__(self, initial: Dict[str, Any]) -> None: self.securedrop_target_distribution = os.environ.get("SECUREDROP_TARGET_DISTRIBUTION") diff --git a/securedrop/alembic/env.py b/securedrop/alembic/env.py --- a/securedrop/alembic/env.py +++ b/securedrop/alembic/env.py @@ -17,8 +17,8 @@ try: # These imports are only needed for offline generation of automigrations. # Importing them in a prod-like environment breaks things. - from journalist_app import create_app # noqa - from sdconfig import SecureDropConfig # noqa + from journalist_app import create_app + from sdconfig import SecureDropConfig # App context is needed for autogenerated migrations sdconfig = SecureDropConfig.get_current() diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -16,7 +16,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # import collections -from typing import Dict, List, OrderedDict, Set +from typing import DefaultDict, List, OrderedDict, Set from babel.core import ( Locale, @@ -175,17 +175,17 @@ def map_locale_display_names( # Deduplicate before sorting. supported_locales = sorted(list(set(config.SUPPORTED_LOCALES))) - language_locale_counts = collections.defaultdict(int) # type: Dict[str, int] - for l in supported_locales: - locale = RequestLocaleInfo(l) + language_locale_counts: DefaultDict[str, int] = collections.defaultdict(int) + for code in supported_locales: + locale = RequestLocaleInfo(code) language_locale_counts[locale.language] += 1 locale_map = collections.OrderedDict() - for l in supported_locales: - if Locale.parse(l) not in usable_locales: + for code in supported_locales: + if Locale.parse(code) not in usable_locales: continue - locale = RequestLocaleInfo(l) + locale = RequestLocaleInfo(code) if language_locale_counts[locale.language] > 1: # Disambiguate translations for this language. locale.use_display_name = True @@ -235,9 +235,9 @@ def get_accepted_languages() -> List[str]: Convert a request's list of accepted languages into locale identifiers. """ accept_languages = [] - for l in request.accept_languages.values(): + for code in request.accept_languages.values(): try: - parsed = Locale.parse(l, "-") + parsed = Locale.parse(code, "-") accept_languages.append(str(parsed)) # We only have two Chinese translations, simplified diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py --- a/securedrop/i18n_tool.py +++ b/securedrop/i18n_tool.py @@ -211,7 +211,7 @@ def translate_desktop(self, args: argparse.Namespace) -> None: if args.compile: pos = [f for f in os.listdir(args.translations_dir) if f.endswith(".po")] - linguas = [l[:-3] for l in pos] + linguas = [lingua[:-3] for lingua in pos] content = "\n".join(linguas) + "\n" linguas_file = join(args.translations_dir, "LINGUAS") try: @@ -269,8 +269,8 @@ def sort_desktop_template(self, template: str) -> None: Sorts the lines containing the icon names. """ lines = open(template).readlines() - names = sorted(l for l in lines if l.startswith("Name")) - others = (l for l in lines if not l.startswith("Name")) + names = sorted(line for line in lines if line.startswith("Name")) + others = (line for line in lines if not line.startswith("Name")) with open(template, "w") as new_template: for line in others: new_template.write(line) @@ -439,7 +439,7 @@ def add(path: str) -> None: desktop_code = info["desktop"] path = join( LOCALE_DIR["desktop"], - f"{desktop_code}.po", # noqa: E741 + f"{desktop_code}.po", ) add(path) except KeyError: @@ -506,7 +506,7 @@ def commit_changes( ) -> None: """Check if any of the given paths have had changed staged. If so, commit them.""" self.require_git_email_name(args.root) - authors = set() # type: Set[str] + authors: Set[str] = set() cmd = ["git", "--no-pager", "diff", "--name-only", "--cached", *paths] diffs = subprocess.check_output(cmd, cwd=args.root, encoding="utf-8") @@ -592,8 +592,8 @@ def set_list_locales_parser(self, subps: _SubParsersAction) -> None: def list_locales(self, args: argparse.Namespace) -> None: if args.lines: - for l in sorted(list(self.supported_languages.keys()) + ["en_US"]): - print(l) + for lang in sorted(list(self.supported_languages.keys()) + ["en_US"]): + print(lang) elif args.python: print(sorted(list(self.supported_languages.keys()) + ["en_US"])) else: @@ -731,8 +731,7 @@ def _remove_from_content_line_with_text(text: str, content: str) -> str: # Remove the while line containing the text content_before_line = split_content[0] content_after_line = split_content[1].split("\n", maxsplit=1)[1] - updated_content = content_before_line + content_after_line - return updated_content + return content_before_line + content_after_line if __name__ == "__main__": # pragma: no cover diff --git a/securedrop/journalist_app/__init__.py b/securedrop/journalist_app/__init__.py --- a/securedrop/journalist_app/__init__.py +++ b/securedrop/journalist_app/__init__.py @@ -124,9 +124,8 @@ def setup_g() -> Optional[Response]: if request.path.split("/")[1] == "api": if request.endpoint not in _insecure_api_views and not session.logged_in(): abort(403) - else: - if request.endpoint not in _insecure_views and not session.logged_in(): - return redirect(url_for("main.login")) + elif request.endpoint not in _insecure_views and not session.logged_in(): + return redirect(url_for("main.login")) if request.method == "POST": filesystem_id = request.form.get("filesystem_id") diff --git a/securedrop/journalist_app/api.py b/securedrop/journalist_app/api.py --- a/securedrop/journalist_app/api.py +++ b/securedrop/journalist_app/api.py @@ -324,7 +324,7 @@ def seen() -> Tuple[flask.Response, int]: # gather everything to be marked seen. if any don't exist, # reject the request. - targets = set() # type: Set[Union[Submission, Reply]] + targets: Set[Union[Submission, Reply]] = set() for file_uuid in request.json.get("files", []): f = Submission.query.filter(Submission.uuid == file_uuid).one_or_none() if f is None or not f.is_file: diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -152,7 +152,7 @@ def download_single_file(filesystem_id: str, fn: str) -> werkzeug.Response: if fn.endswith("reply.gpg"): reply = Reply.query.filter(Reply.filename == fn).one() mark_seen([reply], journalist) - elif fn.endswith("-doc.gz.gpg") or fn.endswith("doc.zip.gpg"): + elif fn.endswith(("-doc.gz.gpg", "doc.zip.gpg")): submitted_file = Submission.query.filter(Submission.filename == fn).one() mark_seen([submitted_file], journalist) else: diff --git a/securedrop/journalist_app/forms.py b/securedrop/journalist_app/forms.py --- a/securedrop/journalist_app/forms.py +++ b/securedrop/journalist_app/forms.py @@ -42,10 +42,8 @@ def __call__(self, form: FlaskForm, field: Field) -> None: self.message = self.custom_message else: self.message = gettext( - 'The "{name}" field is required when "{other_name}" is set.'.format( - other_name=self.other_field_name, name=field.name - ) - ) + 'The "{name}" field is required when "{other_name}" is set.' + ).format(other_name=self.other_field_name, name=field.name) super().__call__(form, field) else: field.errors[:] = [] @@ -53,10 +51,8 @@ def __call__(self, form: FlaskForm, field: Field) -> None: else: raise ValidationError( gettext( - 'The "{other_name}" field was not found - it is required by "{name}".'.format( - other_name=self.other_field_name, name=field.name - ) - ) + 'The "{other_name}" field was not found - it is required by "{name}".' + ).format(other_name=self.other_field_name, name=field.name) ) diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -115,8 +115,7 @@ def index() -> str: source.num_unread = num_unread or 0 unstarred = [source for source, num_unread in unstarred] - response = render_template("index.html", unstarred=unstarred, starred=starred) - return response + return render_template("index.html", unstarred=unstarred, starred=starred) @view.route("/reply", methods=("POST",)) def reply() -> werkzeug.Response: diff --git a/securedrop/journalist_app/sessions.py b/securedrop/journalist_app/sessions.py --- a/securedrop/journalist_app/sessions.py +++ b/securedrop/journalist_app/sessions.py @@ -64,10 +64,7 @@ def set_uid(self, uid: int) -> None: self.uid = uid def logged_in(self) -> bool: - if self.uid is not None: - return True - else: - return False + return self.uid is not None def destroy( self, flash: Optional[Tuple[str, str]] = None, locale: Optional[str] = None @@ -169,7 +166,7 @@ def open_session(self, app: Flask, request: Request) -> Optional[ServerSideSessi msg = gettext("You have been logged out due to inactivity.") return self._new_session(is_api, initial={"_flashes": [("error", msg)]}) - def save_session( # type: ignore[override] # noqa + def save_session( # type: ignore[override] self, app: Flask, session: ServerSideSession, response: Response ) -> None: """This is called at the end of each request, just @@ -190,11 +187,10 @@ def save_session( # type: ignore[override] # noqa if session.new: session["renew_count"] = self.renew_count expires = self.lifetime - else: - if expires < (30 * 60) and session["renew_count"] > 0: - session["renew_count"] -= 1 - expires += self.lifetime - session.modified = True + elif expires < (30 * 60) and session["renew_count"] > 0: + session["renew_count"] -= 1 + expires += self.lifetime + session.modified = True conditional_cookie_kwargs = {} httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) @@ -255,7 +251,7 @@ def _get_interface(self, app: Flask) -> SessionInterface: config.setdefault("SESSION_KEY_PREFIX", "session:") config.setdefault("SESSION_HEADER_NAME", "authorization") - session_interface = SessionInterface( + return SessionInterface( config["SESSION_LIFETIME"], config["SESSION_RENEW_COUNT"], config["SESSION_REDIS"], @@ -264,8 +260,6 @@ def _get_interface(self, app: Flask) -> SessionInterface: config["SESSION_HEADER_NAME"], ) - return session_interface - # Re-export flask.session, but with the correct type information for mypy. from flask import session # noqa diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -58,9 +58,7 @@ def get_source(filesystem_id: str, include_deleted: bool = False) -> Source: query = Source.query.filter(Source.filesystem_id == filesystem_id) if not include_deleted: query = query.filter_by(deleted_at=None) - source = get_one_or_else(query, current_app.logger, abort) - - return source + return get_one_or_else(query, current_app.logger, abort) def validate_user( @@ -513,7 +511,7 @@ def col_download_unread(cols_selected: List[str]) -> werkzeug.Response: def col_download_all(cols_selected: List[str]) -> werkzeug.Response: """Download all submissions from all selected sources.""" - submissions = [] # type: List[Union[Source, Submission]] + submissions: List[Union[Source, Submission]] = [] for filesystem_id in cols_selected: id = ( Source.query.filter(Source.filesystem_id == filesystem_id) diff --git a/securedrop/manage.py b/securedrop/manage.py --- a/securedrop/manage.py +++ b/securedrop/manage.py @@ -17,13 +17,13 @@ from flask.ctx import AppContext from passphrases import PassphraseGenerator -sys.path.insert(0, "/var/www/securedrop") # noqa: E402 +sys.path.insert(0, "/var/www/securedrop") import qrcode # noqa: E402 from sqlalchemy.orm.exc import NoResultFound # noqa: E402 if not os.environ.get("SECUREDROP_ENV"): - os.environ["SECUREDROP_ENV"] = "dev" # noqa + os.environ["SECUREDROP_ENV"] = "dev" from db import db # noqa: E402 diff --git a/securedrop/management/submissions.py b/securedrop/management/submissions.py --- a/securedrop/management/submissions.py +++ b/securedrop/management/submissions.py @@ -24,9 +24,7 @@ def find_disconnected_db_submissions(path: str) -> List[Submission]: for f in files: files_in_fs[f] = os.path.abspath(os.path.join(directory, f)) - disconnected_submissions = [s for s in submissions if s.filename not in files_in_fs] - - return disconnected_submissions + return [s for s in submissions if s.filename not in files_in_fs] def check_for_disconnected_db_submissions(args: argparse.Namespace) -> None: @@ -101,11 +99,7 @@ def find_disconnected_fs_submissions(path: str) -> List[str]: filesize = os.stat(p).st_size disconnected_files_and_sizes.append((p, filesize)) - disconnected_files = [ - file for (file, size) in sorted(disconnected_files_and_sizes, key=lambda t: t[1]) - ] - - return disconnected_files + return [file for (file, size) in sorted(disconnected_files_and_sizes, key=lambda t: t[1])] def check_for_disconnected_fs_submissions(args: argparse.Namespace) -> None: diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -40,8 +40,7 @@ def get_one_or_else( return query.one() except MultipleResultsFound as e: logger.error( - "Found multiple while executing %s when one was expected: %s" - % ( + "Found multiple while executing {} when one was expected: {}".format( query, e, ) @@ -99,7 +98,7 @@ def documents_messages_count(self) -> "Dict[str, int]": def collection(self) -> "List[Union[Submission, Reply]]": """Return the list of submissions and replies for this source, sorted in ascending order by the filename/interaction count.""" - collection = [] # type: List[Union[Submission, Reply]] + collection: List[Union[Submission, Reply]] = [] collection.extend(self.submissions) collection.extend(self.replies) collection.sort(key=lambda x: int(x.filename.split("-")[0])) @@ -132,7 +131,7 @@ def to_json(self) -> "Dict[str, object]": else: starred = False - json_source = { + return { "uuid": self.uuid, "url": url_for("api.single_source", source_uuid=self.uuid), "journalist_designation": self.journalist_designation, @@ -152,7 +151,6 @@ def to_json(self) -> "Dict[str, object]": "remove_star_url": url_for("api.remove_star", source_uuid=self.uuid), "replies_url": url_for("api.all_source_replies", source_uuid=self.uuid), } - return json_source class Submission(db.Model): @@ -204,7 +202,7 @@ def to_json(self) -> "Dict[str, Any]": if m.journalist } ) - json_submission = { + return { "source_url": url_for("api.single_source", source_uuid=self.source.uuid) if self.source else None, @@ -230,7 +228,6 @@ def to_json(self) -> "Dict[str, Any]": else None, "seen_by": list(seen_by), } - return json_submission @property def seen(self) -> bool: @@ -280,7 +277,7 @@ def __repr__(self) -> str: def to_json(self) -> "Dict[str, Any]": seen_by = [r.journalist.uuid for r in SeenReply.query.filter(SeenReply.reply_id == self.id)] - json_reply = { + return { "source_url": url_for("api.single_source", source_uuid=self.source.uuid) if self.source else None, @@ -299,7 +296,6 @@ def to_json(self) -> "Dict[str, Any]": "is_deleted_by_source": self.deleted_by_source, "seen_by": seen_by, } - return json_reply class SourceStar(db.Model): @@ -701,12 +697,12 @@ def to_json(self, all_info: bool = True) -> Dict[str, Any]: """Returns a JSON representation of the journalist user. If all_info is False, potentially sensitive or extraneous fields are excluded. Note that both representations do NOT include credentials.""" - json_user = { + json_user: Dict[str, Any] = { "username": self.username, "uuid": self.uuid, "first_name": self.first_name, "last_name": self.last_name, - } # type: Dict[str, Any] + } if all_info is True: json_user["is_admin"] = self.is_admin @@ -870,10 +866,9 @@ class InstanceConfig(db.Model): def __repr__(self) -> str: return ( - "<InstanceConfig(version=%s, valid_until=%s, " - "allow_document_uploads=%s, organization_name=%s, " - "initial_message_min_len=%s, reject_message_with_codename=%s)>" - % ( + "<InstanceConfig(version={}, valid_until={}, " + "allow_document_uploads={}, organization_name={}, " + "initial_message_min_len={}, reject_message_with_codename={})>".format( self.version, self.valid_until, self.allow_document_uploads, diff --git a/securedrop/passphrases.py b/securedrop/passphrases.py --- a/securedrop/passphrases.py +++ b/securedrop/passphrases.py @@ -10,7 +10,7 @@ DicewarePassphrase = NewType("DicewarePassphrase", str) -_default_generator = None # type: Optional["PassphraseGenerator"] +_default_generator: Optional["PassphraseGenerator"] = None class InvalidWordListError(Exception): @@ -117,9 +117,9 @@ def generate_passphrase(self, preferred_language: Optional[str] = None) -> Dicew # default language words_list = self._language_to_words[self._fallback_language] - words = [ + words: List[str] = [ self._random_generator.choice(words_list) for _ in range(self.PASSPHRASE_WORDS_COUNT) - ] # type: List[str] + ] return DicewarePassphrase(" ".join(words)) diff --git a/securedrop/pretty_bad_protocol/_logger.py b/securedrop/pretty_bad_protocol/_logger.py --- a/securedrop/pretty_bad_protocol/_logger.py +++ b/securedrop/pretty_bad_protocol/_logger.py @@ -26,14 +26,14 @@ GNUPG_STATUS_LEVEL = 9 -def status(self, message, *args, **kwargs): # type: ignore[no-untyped-def] # noqa +def status(self, message, *args, **kwargs): # type: ignore[no-untyped-def] """LogRecord for GnuPG internal status messages.""" if self.isEnabledFor(GNUPG_STATUS_LEVEL): self._log(GNUPG_STATUS_LEVEL, message, args, **kwargs) @wraps(logging.Logger) -def create_logger(level=logging.NOTSET): # type: ignore[no-untyped-def] # noqa +def create_logger(level=logging.NOTSET): # type: ignore[no-untyped-def] """Create a logger for python-gnupg at a specific message level. :type level: :obj:`int` or :obj:`str` diff --git a/securedrop/pretty_bad_protocol/_meta.py b/securedrop/pretty_bad_protocol/_meta.py --- a/securedrop/pretty_bad_protocol/_meta.py +++ b/securedrop/pretty_bad_protocol/_meta.py @@ -53,7 +53,7 @@ class GPGMeta(type): set to a ``psutil.Process`` for that process. """ - def __new__(cls, name, bases, attrs): # type: ignore[no-untyped-def] # noqa + def __new__(cls, name, bases, attrs): # type: ignore[no-untyped-def] """Construct the initialiser for GPG""" log.debug("Metaclass __new__ constructor called for %r" % cls) if cls._find_agent(): @@ -63,7 +63,7 @@ def __new__(cls, name, bases, attrs): # type: ignore[no-untyped-def] # noqa return super().__new__(cls, name, bases, attrs) @classmethod - def _find_agent(cls): # type: ignore[no-untyped-def] # noqa + def _find_agent(cls): # type: ignore[no-untyped-def] """Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` @@ -132,7 +132,7 @@ class GPGBase: "packets": _parsers.ListPackets, } - def __init__( # type: ignore[no-untyped-def] # noqa + def __init__( # type: ignore[no-untyped-def] self, binary=None, home=None, @@ -224,7 +224,7 @@ def __init__( # type: ignore[no-untyped-def] # noqa # Assign our self.binary_version attribute: self._check_sane_and_get_gpg_version() - def __remove_path__(self, prog=None, at_exit=True): # type: ignore[no-untyped-def] # noqa + def __remove_path__(self, prog=None, at_exit=True): # type: ignore[no-untyped-def] """Remove the directories containing a program from the system's ``$PATH``. If ``GPGBase.binary`` is in a directory being removed, it is linked to :file:'./gpg' in the current directory. @@ -268,7 +268,7 @@ def __remove_path__(self, prog=None, at_exit=True): # type: ignore[no-untyped-d assert "PATH" not in os.environ, "OS env kept $PATH anyway!" @staticmethod - def remove_program_from_path(path, prog_base): # type: ignore[no-untyped-def] # noqa + def remove_program_from_path(path, prog_base): # type: ignore[no-untyped-def] """Remove all directories which contain a program from PATH. :param str path: The contents of the system environment's @@ -286,12 +286,11 @@ def remove_program_from_path(path, prog_base): # type: ignore[no-untyped-def] # path.remove(directory) self._removed_path_entries.append(directory) log.debug("Deleted all found instance of %s." % directory) - log.debug("PATH is now:{}{}".format(os.linesep, path)) - new_path = ":".join([p for p in path]) - return new_path + log.debug(f"PATH is now:{os.linesep}{path}") + return ":".join([p for p in path]) @staticmethod - def update_path(environment, path): # type: ignore[no-untyped-def] # noqa + def update_path(environment, path): # type: ignore[no-untyped-def] """Add paths to the string at ``os.environ['PATH']``. :param str environment: The environment mapping to update. @@ -311,7 +310,7 @@ def update_path(environment, path): # type: ignore[no-untyped-def] # noqa # register an _exithandler with the python interpreter: atexit.register(update_path, env_copy, path_copy) - def remove_symlinked_binary(symlink): # type: ignore[no-untyped-def] # noqa + def remove_symlinked_binary(symlink): # type: ignore[no-untyped-def] if os.path.islink(symlink): os.unlink(symlink) log.debug("Removed binary symlink '%s'" % symlink) @@ -319,12 +318,12 @@ def remove_symlinked_binary(symlink): # type: ignore[no-untyped-def] # noqa atexit.register(remove_symlinked_binary, new_gpg_location) @property - def default_preference_list(self): # type: ignore[no-untyped-def] # noqa + def default_preference_list(self): # type: ignore[no-untyped-def] """Get the default preference list.""" return self._prefs @default_preference_list.setter - def default_preference_list(self, prefs): # type: ignore[no-untyped-def] # noqa + def default_preference_list(self, prefs): # type: ignore[no-untyped-def] """Set the default preference list. :param str prefs: A string containing the default preferences for @@ -335,7 +334,7 @@ def default_preference_list(self, prefs): # type: ignore[no-untyped-def] # noqa self._prefs = prefs @default_preference_list.deleter - def default_preference_list(self): # type: ignore[no-untyped-def] # noqa + def default_preference_list(self): # type: ignore[no-untyped-def] """Reset the default preference list to its original state. Note that "original state" does not mean the default preference @@ -348,12 +347,12 @@ def default_preference_list(self): # type: ignore[no-untyped-def] # noqa self._prefs = "SHA512 SHA384 SHA256 AES256 CAMELLIA256 TWOFISH ZLIB ZIP" @property - def keyserver(self): # type: ignore[no-untyped-def] # noqa + def keyserver(self): # type: ignore[no-untyped-def] """Get the current keyserver setting.""" return self._keyserver @keyserver.setter - def keyserver(self, location): # type: ignore[no-untyped-def] # noqa + def keyserver(self, location): # type: ignore[no-untyped-def] """Set the default keyserver to use for sending and receiving keys. The ``location`` is sent to :func:`_parsers._check_keyserver` when @@ -368,11 +367,11 @@ def keyserver(self, location): # type: ignore[no-untyped-def] # noqa self._keyserver = location @keyserver.deleter - def keyserver(self): # type: ignore[no-untyped-def] # noqa + def keyserver(self): # type: ignore[no-untyped-def] """Reset the keyserver to the default setting.""" self._keyserver = "hkp://wwwkeys.pgp.net" - def _homedir_getter(self): # type: ignore[no-untyped-def] # noqa + def _homedir_getter(self): # type: ignore[no-untyped-def] """Get the directory currently being used as GnuPG's homedir. If unspecified, use :file:`~/.config/python-gnupg/` @@ -382,7 +381,7 @@ def _homedir_getter(self): # type: ignore[no-untyped-def] # noqa """ return self._homedir - def _homedir_setter(self, directory): # type: ignore[no-untyped-def] # noqa + def _homedir_setter(self, directory): # type: ignore[no-untyped-def] """Set the directory to use as GnuPG's homedir. If unspecified, use $HOME/.config/python-gnupg. If specified, ensure @@ -425,7 +424,7 @@ def _homedir_setter(self, directory): # type: ignore[no-untyped-def] # noqa homedir = _util.InheritableProperty(_homedir_getter, _homedir_setter) - def _generated_keys_getter(self): # type: ignore[no-untyped-def] # noqa + def _generated_keys_getter(self): # type: ignore[no-untyped-def] """Get the ``homedir`` subdirectory for storing generated keys. :rtype: str @@ -433,7 +432,7 @@ def _generated_keys_getter(self): # type: ignore[no-untyped-def] # noqa """ return self.__generated_keys - def _generated_keys_setter(self, directory): # type: ignore[no-untyped-def] # noqa + def _generated_keys_setter(self, directory): # type: ignore[no-untyped-def] """Set the directory for storing generated keys. If unspecified, use @@ -474,7 +473,7 @@ def _generated_keys_setter(self, directory): # type: ignore[no-untyped-def] # n _generated_keys = _util.InheritableProperty(_generated_keys_getter, _generated_keys_setter) - def _check_sane_and_get_gpg_version(self): # type: ignore[no-untyped-def] # noqa + def _check_sane_and_get_gpg_version(self): # type: ignore[no-untyped-def] """Check that everything runs alright, and grab the gpg binary's version number while we're at it, storing it as :data:`binary_version`. @@ -503,7 +502,7 @@ def _check_sane_and_get_gpg_version(self): # type: ignore[no-untyped-def] # noq raise RuntimeError("Got invalid version line from gpg: %s\n" % self.binary_version) log.debug("Using GnuPG version %s" % self.binary_version) - def _make_args(self, args, passphrase=False): # type: ignore[no-untyped-def] # noqa + def _make_args(self, args, passphrase=False): # type: ignore[no-untyped-def] """Make a list of command line elements for GPG. The value of ``args`` will be appended only if it passes the checks in @@ -566,7 +565,7 @@ def _make_args(self, args, passphrase=False): # type: ignore[no-untyped-def] # return cmd - def _open_subprocess(self, args=None, passphrase=False): # type: ignore[no-untyped-def] # noqa + def _open_subprocess(self, args=None, passphrase=False): # type: ignore[no-untyped-def] """Open a pipe to a GPG subprocess and return the file objects for communicating with it. @@ -587,7 +586,7 @@ def _open_subprocess(self, args=None, passphrase=False): # type: ignore[no-unty # see http://docs.python.org/2/library/subprocess.html#converting-an\ # -argument-sequence-to-a-string-on-windows cmd = shlex.split(" ".join(self._make_args(args, passphrase))) - log.debug("Sending command to GnuPG process:{}{}".format(os.linesep, cmd)) + log.debug(f"Sending command to GnuPG process:{os.linesep}{cmd}") environment = { "LANGUAGE": os.environ.get("LANGUAGE") or "en", @@ -606,7 +605,7 @@ def _open_subprocess(self, args=None, passphrase=False): # type: ignore[no-unty env=environment, ) - def _read_response(self, stream, result): # type: ignore[no-untyped-def] # noqa + def _read_response(self, stream, result): # type: ignore[no-untyped-def] """Reads all the stderr output from GPG, taking notice only of lines that begin with the magic [GNUPG:] prefix. @@ -658,14 +657,13 @@ def _read_response(self, stream, result): # type: ignore[no-untyped-def] # noqa # for some stupid reason, considered fatal: if value.find("trustdb.gpg") and value.find("No such file"): result._handle_status("NEED_TRUSTDB", "") + elif self.verbose: + log.info("%s" % line) else: - if self.verbose: - log.info("%s" % line) - else: - log.debug("%s" % line) + log.debug("%s" % line) result.stderr = "".join(lines) - def _read_data(self, stream, result): # type: ignore[no-untyped-def] # noqa + def _read_data(self, stream, result): # type: ignore[no-untyped-def] """Incrementally read from ``stream`` and store read data. All data gathered from calling ``stream.read()`` will be concatenated @@ -690,7 +688,7 @@ def _read_data(self, stream, result): # type: ignore[no-untyped-def] # noqa log.debug("Finishing reading from stream %r..." % stream.__repr__()) log.debug("Read %4d bytes total" % len(result.data)) - def _set_verbose(self, verbose): # type: ignore[no-untyped-def] # noqa + def _set_verbose(self, verbose): # type: ignore[no-untyped-def] """Check and set our :data:`verbose` attribute. The debug-level must be a string or an integer. If it is one of the allowed strings, GnuPG will translate it internally to it's @@ -715,7 +713,7 @@ def _set_verbose(self, verbose): # type: ignore[no-untyped-def] # noqa # for gpg. Default to "basic", and warn about the ambiguity. verbose = "basic" - if isinstance(verbose, str) and not (verbose in string_levels): + if isinstance(verbose, str) and verbose not in string_levels: verbose = "basic" self.verbose = verbose @@ -764,7 +762,7 @@ def _handle_io(self, args, file, result, passphrase=False, binary=False): # typ self._collect_output(p, result, writer, stdin) return result - def _recv_keys(self, keyids, keyserver=None): # type: ignore[no-untyped-def] # noqa + def _recv_keys(self, keyids, keyserver=None): # type: ignore[no-untyped-def] """Import keys from a keyserver. :param str keyids: A space-delimited string containing the keyids to @@ -776,7 +774,7 @@ def _recv_keys(self, keyids, keyserver=None): # type: ignore[no-untyped-def] # keyserver = self.keyserver args = [f"--keyserver {keyserver}", f"--recv-keys {keyids}"] - log.info("Requesting keys from {}: {}".format(keyserver, keyids)) + log.info(f"Requesting keys from {keyserver}: {keyids}") result = self._result_map["import"](self) proc = self._open_subprocess(args) @@ -784,7 +782,7 @@ def _recv_keys(self, keyids, keyserver=None): # type: ignore[no-untyped-def] # log.debug("recv_keys result: %r", result.__dict__) return result - def _sign_file( # type: ignore[no-untyped-def] # noqa + def _sign_file( # type: ignore[no-untyped-def] self, file, default_key=None, @@ -856,7 +854,7 @@ def _sign_file( # type: ignore[no-untyped-def] # noqa self._collect_output(proc, result, writer, proc.stdin) return result - def _encrypt( # type: ignore[no-untyped-def] # noqa + def _encrypt( # type: ignore[no-untyped-def] self, data, recipients, @@ -1012,8 +1010,7 @@ def _encrypt( # type: ignore[no-untyped-def] # noqa if len(recipients) >= 1: log.debug( - "GPG.encrypt() called for recipients '%s' with type '%s'" - % (recipients, type(recipients)) + f"GPG.encrypt() called for recipients '{recipients}' with type '{type(recipients)}'" ) if isinstance(recipients, (list, tuple)): @@ -1029,7 +1026,7 @@ def _encrypt( # type: ignore[no-untyped-def] # noqa log.debug("Don't know what to do with recipients: %r" % recipients) result = self._result_map["crypt"](self) - log.debug("Got data '{}' with type '{}'.".format(data, type(data))) + log.debug(f"Got data '{data}' with type '{type(data)}'.") self._handle_io(args, data, result, passphrase=passphrase, binary=True) # Avoid writing raw encrypted bytes to terminal loggers and breaking # them in that adorable way where they spew hieroglyphics until reset: diff --git a/securedrop/pretty_bad_protocol/_parsers.py b/securedrop/pretty_bad_protocol/_parsers.py --- a/securedrop/pretty_bad_protocol/_parsers.py +++ b/securedrop/pretty_bad_protocol/_parsers.py @@ -39,7 +39,7 @@ class UsageError(Exception): """Raised when incorrect usage of the API occurs..""" -def _check_keyserver(location): # type: ignore[no-untyped-def] # noqa +def _check_keyserver(location): # type: ignore[no-untyped-def] """Check that a given keyserver is a known protocol and does not contain shell escape characters. @@ -64,18 +64,17 @@ def _check_keyserver(location): # type: ignore[no-untyped-def] # noqa url = location.replace(proto, "") host, slash, extra = url.partition("/") if extra: - log.warn("URI text for {}: '{}'".format(host, extra)) + log.warn(f"URI text for {host}: '{extra}'") log.debug("Got host string for keyserver setting: '%s'" % host) host = _fix_unsafe(host) if host: log.debug("Cleaned host string: '%s'" % host) - keyserver = proto + host - return keyserver + return proto + host return None -def _check_preferences(prefs, pref_type=None): # type: ignore[no-untyped-def] # noqa +def _check_preferences(prefs, pref_type=None): # type: ignore[no-untyped-def] """Check cipher, digest, and compression preference settings. MD5 is not allowed. This is `not 1994`__. SHA1 is allowed_ grudgingly_. @@ -85,7 +84,7 @@ def _check_preferences(prefs, pref_type=None): # type: ignore[no-untyped-def] # .. _grudgingly: https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html """ if prefs is None: - return + return None cipher = frozenset( ["AES256", "AES192", "AES128", "CAMELLIA256", "CAMELLIA192", "TWOFISH", "3DES"] @@ -126,7 +125,7 @@ def _check_preferences(prefs, pref_type=None): # type: ignore[no-untyped-def] # return allowed -def _fix_unsafe(shell_input): # type: ignore[no-untyped-def] # noqa +def _fix_unsafe(shell_input): # type: ignore[no-untyped-def] """Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module. @@ -137,13 +136,12 @@ def _fix_unsafe(shell_input): # type: ignore[no-untyped-def] # noqa if len(_unsafe.findall(shell_input)) == 0: return shell_input.strip() else: - clean = "'" + shell_input.replace("'", "'\"'\"'") + "'" - return clean + return "'" + shell_input.replace("'", "'\"'\"'") + "'" except TypeError: return None -def _hyphenate(input, add_prefix=False): # type: ignore[no-untyped-def] # noqa +def _hyphenate(input, add_prefix=False): # type: ignore[no-untyped-def] """Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names. @@ -157,7 +155,7 @@ def _hyphenate(input, add_prefix=False): # type: ignore[no-untyped-def] # noqa return ret -def _is_allowed(input): # type: ignore[no-untyped-def] # noqa +def _is_allowed(input): # type: ignore[no-untyped-def] """Check that an option or argument given to GPG is in the set of allowed options, the latter being a strict subset of the set of all options known to GPG. @@ -227,7 +225,7 @@ class and its name will need to be added to this return None -def _is_hex(string): # type: ignore[no-untyped-def] # noqa +def _is_hex(string): # type: ignore[no-untyped-def] """Check that a string is hexadecimal, with alphabetic characters in either upper or lower case and without whitespace. @@ -238,7 +236,7 @@ def _is_hex(string): # type: ignore[no-untyped-def] # noqa return False -def _sanitise(*args): # type: ignore[no-untyped-def] # noqa +def _sanitise(*args): # type: ignore[no-untyped-def] """Take an arg or the key portion of a kwarg and check that it is in the set of allowed GPG options and flags, and that it has the correct type. Then, attempt to escape any unsafe characters. If an option is not @@ -269,7 +267,7 @@ def _sanitise(*args): # type: ignore[no-untyped-def] # noqa # see TODO file, tag :cleanup:sanitise: - def _check_option(arg, value): # type: ignore[no-untyped-def] # noqa + def _check_option(arg, value): # type: ignore[no-untyped-def] """Check that a single ``arg`` is an allowed option. If it is allowed, quote out any escape characters in ``value``, and @@ -313,7 +311,7 @@ def _check_option(arg, value): # type: ignore[no-untyped-def] # noqa if _is_hex(v): checked += v + " " else: - log.debug("'{} {}' not hex.".format(flag, v)) + log.debug(f"'{flag} {v}' not hex.") if (flag in hex_or_none_options) and (v is None): log.debug("Allowing '%s' for all keys" % flag) continue @@ -336,7 +334,7 @@ def _check_option(arg, value): # type: ignore[no-untyped-def] # noqa assert v is not None assert not v.isspace() except: # noqa: E722 - log.debug("Dropping {} {}".format(flag, v)) + log.debug(f"Dropping {flag} {v}") continue if flag in [ @@ -350,7 +348,7 @@ def _check_option(arg, value): # type: ignore[no-untyped-def] # noqa if (_util._is_file(val)) or ((flag == "--verify") and (val == "-")): checked += val + " " else: - log.debug("{} not file: {}".format(flag, val)) + log.debug(f"{flag} not file: {val}") elif flag in [ "--cipher-algo", @@ -395,16 +393,16 @@ def _check_option(arg, value): # type: ignore[no-untyped-def] # noqa return checked.rstrip(" ") - def is_flag(x): # type: ignore[no-untyped-def] # noqa + def is_flag(x): # type: ignore[no-untyped-def] return x.startswith("--") - def _make_filo(args_string): # type: ignore[no-untyped-def] # noqa + def _make_filo(args_string): # type: ignore[no-untyped-def] filo = arg.split(" ") filo.reverse() log.debug("_make_filo(): Converted to reverse list: %s" % filo) return filo - def _make_groups(filo): # type: ignore[no-untyped-def] # noqa + def _make_groups(filo): # type: ignore[no-untyped-def] groups = {} while len(filo) >= 1: last = filo.pop() @@ -421,26 +419,25 @@ def _make_groups(filo): # type: ignore[no-untyped-def] # noqa while len(filo) > 1 and not is_flag(filo[len(filo) - 1]): log.debug("Got value: %s" % filo[len(filo) - 1]) groups[last] += filo.pop() + " " - else: - if len(filo) == 1 and not is_flag(filo[0]): - log.debug("Got value: %s" % filo[0]) - groups[last] += filo.pop() + if len(filo) == 1 and not is_flag(filo[0]): + log.debug("Got value: %s" % filo[0]) + groups[last] += filo.pop() else: log.warn("_make_groups(): Got solitary value: %s" % last) groups["xxx"] = last return groups - def _check_groups(groups): # type: ignore[no-untyped-def] # noqa + def _check_groups(groups): # type: ignore[no-untyped-def] log.debug("Got groups: %s" % groups) checked_groups = [] for a, v in groups.items(): v = None if len(v) == 0 else v safe = _check_option(a, v) - if safe is not None and not safe.strip() == "": + if safe is not None and safe.strip() != "": log.debug("Appending option: %s" % safe) checked_groups.append(safe) else: - log.warn("Dropped option: '{} {}'".format(a, v)) + log.warn(f"Dropped option: '{a} {v}'") return checked_groups if args is not None: @@ -460,15 +457,14 @@ def _check_groups(groups): # type: ignore[no-untyped-def] # noqa arg.reverse() option_groups.update(_make_groups(arg)) else: - log.warn("Got non-str/list arg: '%s', type '%s'" % (arg, type(arg))) + log.warn(f"Got non-str/list arg: '{arg}', type '{type(arg)}'") checked = _check_groups(option_groups) - sanitised = " ".join(x for x in checked) - return sanitised + return " ".join(x for x in checked) else: log.debug("Got None for args") -def _sanitise_list(arg_list): # type: ignore[no-untyped-def] # noqa +def _sanitise_list(arg_list): # type: ignore[no-untyped-def] """A generator for iterating through a list of gpg options and sanitising them. @@ -485,7 +481,7 @@ def _sanitise_list(arg_list): # type: ignore[no-untyped-def] # noqa yield safe_arg -def _get_options_group(group=None): # type: ignore[no-untyped-def] # noqa +def _get_options_group(group=None): # type: ignore[no-untyped-def] """Get a specific group of options which are allowed.""" #: These expect a hexidecimal keyid as their argument, and can be parsed @@ -647,11 +643,11 @@ def _get_options_group(group=None): # type: ignore[no-untyped-def] # noqa none_options, ) - if group and group in locals().keys(): + if group and group in locals(): return locals()[group] -def _get_all_gnupg_options(): # type: ignore[no-untyped-def] # noqa +def _get_all_gnupg_options(): # type: ignore[no-untyped-def] """Get all GnuPG options and flags. This is hardcoded within a local scope to reduce the chance of a tampered @@ -847,11 +843,10 @@ def _get_all_gnupg_options(): # type: ignore[no-untyped-def] # noqa three_hundred_eighteen.append("--pinentry-mode") three_hundred_eighteen.append("--allow-loopback-pinentry") - gnupg_options = frozenset(three_hundred_eighteen) - return gnupg_options + return frozenset(three_hundred_eighteen) -def nodata(status_code): # type: ignore[no-untyped-def] # noqa +def nodata(status_code): # type: ignore[no-untyped-def] """Translate NODATA status codes from GnuPG to messages.""" lookup = { "1": "No armored data.", @@ -864,7 +859,7 @@ def nodata(status_code): # type: ignore[no-untyped-def] # noqa return value -def progress(status_code): # type: ignore[no-untyped-def] # noqa +def progress(status_code): # type: ignore[no-untyped-def] """Translate PROGRESS status codes from GnuPG to messages.""" lookup = { "pk_dsa": "DSA key generation", @@ -884,31 +879,31 @@ def progress(status_code): # type: ignore[no-untyped-def] # noqa class KeyExpirationInterface: """Interface that guards against misuse of --edit-key combined with --command-fd""" - def __init__(self, expiration_time, passphrase=None): # type: ignore[no-untyped-def] # noqa + def __init__(self, expiration_time, passphrase=None): # type: ignore[no-untyped-def] self._passphrase = passphrase self._expiration_time = expiration_time self._clean_key_expiration_option() - def _clean_key_expiration_option(self): # type: ignore[no-untyped-def] # noqa + def _clean_key_expiration_option(self): # type: ignore[no-untyped-def] """validates the expiration option supplied""" allowed_entry = re.findall(r"^(\d+)(|w|m|y)$", self._expiration_time) if not allowed_entry: raise UsageError("Key expiration option: %s is not valid" % self._expiration_time) - def _input_passphrase(self, _input): # type: ignore[no-untyped-def] # noqa + def _input_passphrase(self, _input): # type: ignore[no-untyped-def] if self._passphrase: - return "{}{}\n".format(_input, self._passphrase) + return f"{_input}{self._passphrase}\n" return _input - def _main_key_command(self): # type: ignore[no-untyped-def] # noqa + def _main_key_command(self): # type: ignore[no-untyped-def] main_key_input = "expire\n%s\n" % self._expiration_time return self._input_passphrase(main_key_input) - def _sub_key_command(self, sub_key_number): # type: ignore[no-untyped-def] # noqa + def _sub_key_command(self, sub_key_number): # type: ignore[no-untyped-def] sub_key_input = "key %d\nexpire\n%s\n" % (sub_key_number, self._expiration_time) return self._input_passphrase(sub_key_input) - def gpg_interactive_input(self, sub_keys_number): # type: ignore[no-untyped-def] # noqa + def gpg_interactive_input(self, sub_keys_number): # type: ignore[no-untyped-def] """processes series of inputs normally supplied on --edit-key but passed through stdin this ensures that no other --edit-key command is actually passing through. """ @@ -925,11 +920,11 @@ class KeyExpirationResult: It does not really have a job, but just to conform to the API """ - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] self._gpg = gpg self.status = "ok" - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -955,11 +950,11 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa class KeySigningResult: """Handle status messages for key singing""" - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] self._gpg = gpg self.status = "ok" - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -977,7 +972,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa self.status = "{}: {}".format(key.replace("_", " ").lower(), value) else: self.status = "failed" - raise ValueError("Key signing, unknown status message: {!r} ::{}".format(key, value)) + raise ValueError(f"Key signing, unknown status message: {key!r} ::{value}") class GenKey: @@ -987,7 +982,7 @@ class GenKey: key's fingerprint, or a status string explaining the results. """ - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] self._gpg = gpg # this should get changed to something more useful, like 'key_type' #: 'P':= primary, 'S':= subkey, 'B':= both @@ -1009,23 +1004,23 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa #: ``separate_keyring=True``. self.secring = None - def __nonzero__(self): # type: ignore[no-untyped-def] # noqa + def __nonzero__(self): # type: ignore[no-untyped-def] if self.fingerprint: return True return False __bool__ = __nonzero__ - def __str__(self): # type: ignore[no-untyped-def] # noqa + def __str__(self): # type: ignore[no-untyped-def] if self.fingerprint: return self.fingerprint + elif self.status is not None: + return self.status else: - if self.status is not None: - return self.status - else: - return False + # FIXME: we should only be returning a str + return False # noqa: PLE0307 - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -1054,7 +1049,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa "\nhttps://github.com/isislovecruft/python-gnupg/issues/137" ) self.status = "key not created" - elif key.startswith("TRUST_") or key.startswith("PKA_TRUST_") or key == "NEWSIG": + elif key.startswith(("TRUST_", "PKA_TRUST_")) or key == "NEWSIG": pass else: raise ValueError("Unknown status message: %r" % key) @@ -1068,11 +1063,11 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa class DeleteResult: """Handle status messages for --delete-keys and --delete-secret-keys""" - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] self._gpg = gpg self.status = "ok" - def __str__(self): # type: ignore[no-untyped-def] # noqa + def __str__(self): # type: ignore[no-untyped-def] return self.status problem_reason = { @@ -1081,7 +1076,7 @@ def __str__(self): # type: ignore[no-untyped-def] # noqa "3": "Ambigious specification", } - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """ Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -1114,10 +1109,10 @@ class Sign: what = None status = None - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] self._gpg = gpg - def __nonzero__(self): # type: ignore[no-untyped-def] # noqa + def __nonzero__(self): # type: ignore[no-untyped-def] """Override the determination for truthfulness evaluation. :rtype: bool @@ -1127,10 +1122,10 @@ def __nonzero__(self): # type: ignore[no-untyped-def] # noqa __bool__ = __nonzero__ - def __str__(self): # type: ignore[no-untyped-def] # noqa + def __str__(self): # type: ignore[no-untyped-def] return self.data.decode(self._gpg._encoding, self._gpg._decode_errors) - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -1189,7 +1184,7 @@ class ListKeys(list): | rvk = revocation key """ - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] super().__init__() self._gpg = gpg self.curkey = None @@ -1200,7 +1195,7 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa self.certs = {} self.revs = {} - def key(self, args): # type: ignore[no-untyped-def] # noqa + def key(self, args): # type: ignore[no-untyped-def] vars = ( """ type trust length algo keyid date expires dummy ownertrust uid @@ -1225,11 +1220,11 @@ def key(self, args): # type: ignore[no-untyped-def] # noqa pub = sec = key - def fpr(self, args): # type: ignore[no-untyped-def] # noqa + def fpr(self, args): # type: ignore[no-untyped-def] self.curkey["fingerprint"] = args[9] self.fingerprints.append(args[9]) - def uid(self, args): # type: ignore[no-untyped-def] # noqa + def uid(self, args): # type: ignore[no-untyped-def] uid = args[9] uid = ESCAPE_PATTERN.sub(lambda m: chr(int(m.group(1), 16)), uid) self.curkey["uids"].append(uid) @@ -1239,7 +1234,7 @@ def uid(self, args): # type: ignore[no-untyped-def] # noqa self.certs[uid] = set() self.uids.append(uid) - def sig(self, args): # type: ignore[no-untyped-def] # noqa + def sig(self, args): # type: ignore[no-untyped-def] vars = ( """ type trust length algo keyid date expires dummy ownertrust uid @@ -1253,21 +1248,21 @@ def sig(self, args): # type: ignore[no-untyped-def] # noqa if sig["trust"] == "!": self.certs[self.curuid].add(sig["keyid"]) - def sub(self, args): # type: ignore[no-untyped-def] # noqa + def sub(self, args): # type: ignore[no-untyped-def] subkey = [args[4], args[11]] self.curkey["subkeys"].append(subkey) - def rev(self, args): # type: ignore[no-untyped-def] # noqa + def rev(self, args): # type: ignore[no-untyped-def] self.curkey["rev"] = {"keyid": args[4], "revtime": args[5], "uid": self.curuid} - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] pass class ImportResult: """Parse GnuPG status messages for key import operations.""" - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] """Start parsing the results of a key import operation. :type gpg: :class:`gnupg.GPG` @@ -1315,7 +1310,7 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa #: imported. self.results = list() - def __nonzero__(self): # type: ignore[no-untyped-def] # noqa + def __nonzero__(self): # type: ignore[no-untyped-def] """Override the determination for truthfulness evaluation. :rtype: bool @@ -1329,7 +1324,7 @@ def __nonzero__(self): # type: ignore[no-untyped-def] # noqa __bool__ = __nonzero__ - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises ValueError: if the status message is unknown. @@ -1375,7 +1370,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa ) elif key == "IMPORT_RES": import_res = value.split() - for x in self.counts.keys(): + for x in self.counts: self.counts[x] = int(import_res.pop(0)) elif key == "KEYEXPIRED": res = {"fingerprint": None, "status": "Key expired"} @@ -1388,7 +1383,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa else: raise ValueError("Unknown status message: %r" % key) - def summary(self): # type: ignore[no-untyped-def] # noqa + def summary(self): # type: ignore[no-untyped-def] l = [] # noqa: E741 l.append("%d imported" % self.counts["imported"]) if self.counts["not_imported"]: @@ -1399,7 +1394,7 @@ def summary(self): # type: ignore[no-untyped-def] # noqa class ExportResult: """Parse GnuPG status messages for key export operations.""" - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] """Start parsing the results of a key export operation. :type gpg: :class:`gnupg.GPG` @@ -1419,7 +1414,7 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa #: exported. self.fingerprints = list() - def __nonzero__(self): # type: ignore[no-untyped-def] # noqa + def __nonzero__(self): # type: ignore[no-untyped-def] """Override the determination for truthfulness evaluation. :rtype: bool @@ -1433,7 +1428,7 @@ def __nonzero__(self): # type: ignore[no-untyped-def] # noqa __bool__ = __nonzero__ - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises ValueError: if the status message is unknown. @@ -1443,12 +1438,12 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa self.fingerprints.append(value) elif key == "EXPORT_RES": export_res = value.split() - for x in self.counts.keys(): + for x in self.counts: self.counts[x] += int(export_res.pop(0)) elif key not in informational_keys: raise ValueError("Unknown status message: %r" % key) - def summary(self): # type: ignore[no-untyped-def] # noqa + def summary(self): # type: ignore[no-untyped-def] return "%d exported" % self.counts["exported"] @@ -1501,7 +1496,7 @@ class Verify: "DECRYPTION_COMPLIANCE_MODE": DECRYPTION_COMPLIANCE_MODE, } - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] """Create a parser for verification and certification commands. :param gpg: An instance of :class:`gnupg.GPG`. @@ -1573,7 +1568,7 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa #: ``NOTATION_DATA``. self._last_notation_name = None - def __nonzero__(self): # type: ignore[no-untyped-def] # noqa + def __nonzero__(self): # type: ignore[no-untyped-def] """Override the determination for truthfulness evaluation. :rtype: bool @@ -1583,7 +1578,7 @@ def __nonzero__(self): # type: ignore[no-untyped-def] # noqa __bool__ = __nonzero__ - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -1655,7 +1650,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa # case of WARNING or ERROR) additional text. # Have fun figuring out what it means. self.status = value - log.warn("{} status emitted from gpg process: {}".format(key, value)) + log.warn(f"{key} status emitted from gpg process: {value}") elif key == "NO_PUBKEY": self.valid = False self.key_id = value @@ -1671,7 +1666,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa elif key in ("EXPKEYSIG", "REVKEYSIG"): self.valid = False self.key_id = value.split()[0] - self.status = (("%s %s") % (key[:3], key[3:])).lower() + self.status = (f"{key[:3]} {key[3:]}").lower() # This is super annoying, and bad design on the part of GnuPG, in my # opinion. # @@ -1760,7 +1755,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa else: pass else: - raise ValueError("Unknown status message: {!r} {!r}".format(key, value)) + raise ValueError(f"Unknown status message: {key!r} {value!r}") class Crypt(Verify): @@ -1768,7 +1763,7 @@ class Crypt(Verify): ``--decrypt``, and ``--decrypt-files``. """ - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] Verify.__init__(self, gpg) self._gpg = gpg #: A string containing the encrypted or decrypted data. @@ -1782,14 +1777,14 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa self.data_timestamp = None self.data_filename = None - def __nonzero__(self): # type: ignore[no-untyped-def] # noqa + def __nonzero__(self): # type: ignore[no-untyped-def] if self.ok: return True return False __bool__ = __nonzero__ - def __str__(self): # type: ignore[no-untyped-def] # noqa + def __str__(self): # type: ignore[no-untyped-def] """The str() method for a :class:`Crypt` object will automatically return the decoded data string, which stores the encryped or decrypted data. @@ -1800,7 +1795,7 @@ def __str__(self): # type: ignore[no-untyped-def] # noqa """ return self.data.decode(self._gpg._encoding, self._gpg._decode_errors) - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. @@ -1870,7 +1865,7 @@ def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa class ListPackets: """Handle status messages for --list-packets.""" - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] self._gpg = gpg #: A string describing the current processing status, or error, if one #: has occurred. @@ -1888,7 +1883,7 @@ def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa #: A list of keyid's that the message has been encrypted to. self.encrypted_to = [] - def _handle_status(self, key, value): # type: ignore[no-untyped-def] # noqa + def _handle_status(self, key, value): # type: ignore[no-untyped-def] """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. diff --git a/securedrop/pretty_bad_protocol/_trust.py b/securedrop/pretty_bad_protocol/_trust.py --- a/securedrop/pretty_bad_protocol/_trust.py +++ b/securedrop/pretty_bad_protocol/_trust.py @@ -29,19 +29,20 @@ from ._util import log -def _create_trustdb(cls): # type: ignore[no-untyped-def] # noqa +def _create_trustdb(cls): # type: ignore[no-untyped-def] """Create the trustdb file in our homedir, if it doesn't exist.""" trustdb = os.path.join(cls.homedir, "trustdb.gpg") if not os.path.isfile(trustdb): log.info( - "GnuPG complained that your trustdb file was missing. %s" - % "This is likely due to changing to a new homedir." + "GnuPG complained that your trustdb file was missing. {}".format( + "This is likely due to changing to a new homedir." + ) ) log.info("Creating trustdb.gpg file in your GnuPG homedir.") cls.fix_trustdb(trustdb) -def export_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] # noqa +def export_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] """Export ownertrust to a trustdb file. If there is already a file named :file:`trustdb.gpg` in the current GnuPG @@ -65,7 +66,7 @@ def export_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] # noqa export_proc.wait() -def import_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] # noqa +def import_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] """Import ownertrust from a trustdb file. :param str trustdb: The path to the trustdb.gpg file. If not given, @@ -86,7 +87,7 @@ def import_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] # noqa import_proc.wait() -def fix_trustdb(cls, trustdb=None): # type: ignore[no-untyped-def] # noqa +def fix_trustdb(cls, trustdb=None): # type: ignore[no-untyped-def] """Attempt to repair a broken trustdb.gpg file. GnuPG>=2.0.x has this magical-seeming flag: `--fix-trustdb`. You'd think diff --git a/securedrop/pretty_bad_protocol/_util.py b/securedrop/pretty_bad_protocol/_util.py --- a/securedrop/pretty_bad_protocol/_util.py +++ b/securedrop/pretty_bad_protocol/_util.py @@ -69,7 +69,7 @@ class GnuPGVersionError(ValueError): """Raised when we couldn't parse GnuPG's version info.""" -def _copy_data(instream, outstream): # type: ignore[no-untyped-def] # noqa +def _copy_data(instream, outstream): # type: ignore[no-untyped-def] """Copy data from one stream to another. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` or file @@ -93,7 +93,7 @@ def _copy_data(instream, outstream): # type: ignore[no-untyped-def] # noqa else: encoded = data log.debug("Sending %d bytes of data..." % sent) - log.debug("Encoded data (type {}):\n{}".format(type(encoded), encoded)) + log.debug(f"Encoded data (type {type(encoded)}):\n{encoded}") try: outstream.write(bytes(encoded)) @@ -137,12 +137,12 @@ def _copy_data(instream, outstream): # type: ignore[no-untyped-def] # noqa try: outstream.close() except OSError as ioe: - log.error("Unable to close outstream {}:\r\t{}".format(outstream, ioe)) + log.error(f"Unable to close outstream {outstream}:\r\t{ioe}") else: log.debug("Closed outstream: %d bytes sent." % sent) -def _create_if_necessary(directory): # type: ignore[no-untyped-def] # noqa +def _create_if_necessary(directory): # type: ignore[no-untyped-def] """Create the specified directory, if necessary. :param str directory: The directory to use. @@ -167,7 +167,7 @@ def _create_if_necessary(directory): # type: ignore[no-untyped-def] # noqa return True -def create_uid_email(username=None, hostname=None): # type: ignore[no-untyped-def] # noqa +def create_uid_email(username=None, hostname=None): # type: ignore[no-untyped-def] """Create an email address suitable for a UID on a GnuPG key. :param str username: The username portion of an email address. If None, @@ -195,16 +195,16 @@ def create_uid_email(username=None, hostname=None): # type: ignore[no-untyped-d else: username = username.replace(" ", "_") if (not hostname) and (username.find("@") == 0): - uid = "{}@{}".format(username, gethostname()) + uid = f"{username}@{gethostname()}" elif hostname: - uid = "{}@{}".format(username, hostname) + uid = f"{username}@{hostname}" else: uid = username return uid -def _deprefix(line, prefix, callback=None): # type: ignore[no-untyped-def] # noqa +def _deprefix(line, prefix, callback=None): # type: ignore[no-untyped-def] """Remove the prefix string from the beginning of line, if it exists. :param string line: A line, such as one output by GnuPG's status-fd. @@ -221,7 +221,7 @@ def _deprefix(line, prefix, callback=None): # type: ignore[no-untyped-def] # no try: assert line.upper().startswith("".join(prefix).upper()) except AssertionError: - log.debug("Line doesn't start with prefix '{}':\n{}".format(prefix, line)) + log.debug(f"Line doesn't start with prefix '{prefix}':\n{line}") return line else: newline = line[len(prefix) :] @@ -233,7 +233,7 @@ def _deprefix(line, prefix, callback=None): # type: ignore[no-untyped-def] # no return newline -def _find_binary(binary=None): # type: ignore[no-untyped-def] # noqa +def _find_binary(binary=None): # type: ignore[no-untyped-def] """Find the absolute path to the GnuPG binary. Also run checks that the binary is not a symlink, and check that @@ -274,7 +274,7 @@ def _find_binary(binary=None): # type: ignore[no-untyped-def] # noqa return found -def _has_readwrite(path): # type: ignore[no-untyped-def] # noqa +def _has_readwrite(path): # type: ignore[no-untyped-def] """ Determine if the real uid/gid of the executing user has read and write permissions for a directory or a file. @@ -287,7 +287,7 @@ def _has_readwrite(path): # type: ignore[no-untyped-def] # noqa return os.access(path, os.R_OK | os.W_OK) -def _is_file(filename): # type: ignore[no-untyped-def] # noqa +def _is_file(filename): # type: ignore[no-untyped-def] """Check that the size of the thing which is supposed to be a filename has size greater than zero, without following symbolic links or using :func:os.path.isfile. @@ -299,7 +299,7 @@ def _is_file(filename): # type: ignore[no-untyped-def] # noqa try: statinfo = os.lstat(filename) log.debug( - "lstat(%r) with type=%s gave us %r" % (repr(filename), type(filename), repr(statinfo)) + f"lstat({repr(filename)!r}) with type={type(filename)} gave us {repr(statinfo)!r}" ) if not (statinfo.st_size > 0): raise ValueError("'%s' appears to be an empty file!" % filename) @@ -315,7 +315,7 @@ def _is_file(filename): # type: ignore[no-untyped-def] # noqa return False -def _is_stream(input): # type: ignore[no-untyped-def] # noqa +def _is_stream(input): # type: ignore[no-untyped-def] """Check that the input is a byte stream. :param input: An object provided for reading from or writing to. @@ -325,7 +325,7 @@ def _is_stream(input): # type: ignore[no-untyped-def] # noqa return isinstance(input, tuple(_STREAMLIKE_TYPES)) -def _is_list_or_tuple(instance): # type: ignore[no-untyped-def] # noqa +def _is_list_or_tuple(instance): # type: ignore[no-untyped-def] """Check that ``instance`` is a list or tuple. :param instance: The object to type check. @@ -341,7 +341,7 @@ def _is_list_or_tuple(instance): # type: ignore[no-untyped-def] # noqa ) -def _make_binary_stream(thing, encoding=None, armor=True): # type: ignore[no-untyped-def] # noqa +def _make_binary_stream(thing, encoding=None, armor=True): # type: ignore[no-untyped-def] """Encode **thing**, then make it stream/file-like. :param thing: The thing to turn into a encoded stream. @@ -355,7 +355,7 @@ def _make_binary_stream(thing, encoding=None, armor=True): # type: ignore[no-un return BytesIO(thing) -def _next_year(): # type: ignore[no-untyped-def] # noqa +def _next_year(): # type: ignore[no-untyped-def] """Get the date of today plus one year. :rtype: str @@ -368,12 +368,12 @@ def _next_year(): # type: ignore[no-untyped-def] # noqa return "-".join((next_year, month, day)) -def _now(): # type: ignore[no-untyped-def] # noqa +def _now(): # type: ignore[no-untyped-def] """Get a timestamp for right now, formatted according to ISO 8601.""" return datetime.isoformat(datetime.now()) -def _separate_keyword(line): # type: ignore[no-untyped-def] # noqa +def _separate_keyword(line): # type: ignore[no-untyped-def] """Split the line, and return (first_word, the_rest).""" try: first, rest = line.split(None, 1) @@ -383,7 +383,7 @@ def _separate_keyword(line): # type: ignore[no-untyped-def] # noqa return first, rest -def _threaded_copy_data(instream, outstream): # type: ignore[no-untyped-def] # noqa +def _threaded_copy_data(instream, outstream): # type: ignore[no-untyped-def] """Copy data from one stream to another in a separate thread. Wraps ``_copy_data()`` in a :class:`threading.Thread`. @@ -423,7 +423,7 @@ def _which(executable, flags=os.X_OK, abspath_only=False, disallow_symlinks=Fals they were found. """ - def _can_allow(p): # type: ignore[no-untyped-def] # noqa + def _can_allow(p): # type: ignore[no-untyped-def] if not os.access(p, flags): return False if abspath_only and not os.path.abspath(p): @@ -450,7 +450,7 @@ def _can_allow(p): # type: ignore[no-untyped-def] # noqa return result -def _write_passphrase(stream, passphrase, encoding): # type: ignore[no-untyped-def] # noqa +def _write_passphrase(stream, passphrase, encoding): # type: ignore[no-untyped-def] """Write the passphrase from memory to the GnuPG process' stdin. :type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO` @@ -474,7 +474,7 @@ def __init__(self, fget=None, fset=None, fdel=None, doc=None): # type: ignore[n self.fdel = fdel self.__doc__ = doc - def __get__(self, obj, objtype=None): # type: ignore[no-untyped-def] # noqa + def __get__(self, obj, objtype=None): # type: ignore[no-untyped-def] if obj is None: return self if self.fget is None: @@ -484,7 +484,7 @@ def __get__(self, obj, objtype=None): # type: ignore[no-untyped-def] # noqa else: return getattr(obj, self.fget.__name__)() - def __set__(self, obj, value): # type: ignore[no-untyped-def] # noqa + def __set__(self, obj, value): # type: ignore[no-untyped-def] if self.fset is None: raise AttributeError("can't set attribute") if self.fset.__name__ == "<lambda>" or not self.fset.__name__: @@ -492,7 +492,7 @@ def __set__(self, obj, value): # type: ignore[no-untyped-def] # noqa else: getattr(obj, self.fset.__name__)(value) - def __delete__(self, obj): # type: ignore[no-untyped-def] # noqa + def __delete__(self, obj): # type: ignore[no-untyped-def] if self.fdel is None: raise AttributeError("can't delete attribute") if self.fdel.__name__ == "<lambda>" or not self.fdel.__name__: diff --git a/securedrop/pretty_bad_protocol/gnupg.py b/securedrop/pretty_bad_protocol/gnupg.py --- a/securedrop/pretty_bad_protocol/gnupg.py +++ b/securedrop/pretty_bad_protocol/gnupg.py @@ -32,7 +32,7 @@ import re import textwrap import time -from codecs import open as open +from codecs import open #: see :pep:`328` http://docs.python.org/2.5/whatsnew/pep-328.html from . import _trust, _util @@ -52,7 +52,7 @@ class GPG(GPGBase): #: '--list-sigs' to: _batch_limit = 25 - def __init__( # type: ignore[no-untyped-def] # noqa + def __init__( # type: ignore[no-untyped-def] self, binary=None, homedir=None, @@ -176,34 +176,34 @@ def __init__( # type: ignore[no-untyped-def] # noqa self.use_agent = None @functools.wraps(_trust._create_trustdb) - def create_trustdb(self): # type: ignore[no-untyped-def] # noqa + def create_trustdb(self): # type: ignore[no-untyped-def] _trust._create_trustdb(self) # For backward compatibility with python-gnupg<=1.3.1: _create_trustdb = create_trustdb @functools.wraps(_trust.fix_trustdb) - def fix_trustdb(self, trustdb=None): # type: ignore[no-untyped-def] # noqa + def fix_trustdb(self, trustdb=None): # type: ignore[no-untyped-def] _trust.fix_trustdb(self) # For backward compatibility with python-gnupg<=1.3.1: _fix_trustdb = fix_trustdb @functools.wraps(_trust.import_ownertrust) - def import_ownertrust(self, trustdb=None): # type: ignore[no-untyped-def] # noqa + def import_ownertrust(self, trustdb=None): # type: ignore[no-untyped-def] _trust.import_ownertrust(self) # For backward compatibility with python-gnupg<=1.3.1: _import_ownertrust = import_ownertrust @functools.wraps(_trust.export_ownertrust) - def export_ownertrust(self, trustdb=None): # type: ignore[no-untyped-def] # noqa + def export_ownertrust(self, trustdb=None): # type: ignore[no-untyped-def] _trust.export_ownertrust(self) # For backward compatibility with python-gnupg<=1.3.1: _export_ownertrust = export_ownertrust - def sign(self, data, **kwargs): # type: ignore[no-untyped-def] # noqa + def sign(self, data, **kwargs): # type: ignore[no-untyped-def] """Create a signature for a message string or file. Note that this method is not for signing other keys. (In GnuPG's @@ -236,7 +236,7 @@ def sign(self, data, **kwargs): # type: ignore[no-untyped-def] # noqa The default, if unspecified, is ``'SHA512'``. """ if "default_key" in kwargs: - log.info("Signing message '%r' with keyid: %s" % (data, kwargs["default_key"])) + log.info("Signing message '{!r}' with keyid: {}".format(data, kwargs["default_key"])) else: log.warn("No 'default_key' given! Using first key on secring.") @@ -247,11 +247,11 @@ def sign(self, data, **kwargs): # type: ignore[no-untyped-def] # noqa result = self._sign_file(stream, **kwargs) stream.close() else: - log.warn("Unable to sign message '%s' with type %s" % (data, type(data))) + log.warn(f"Unable to sign message '{data}' with type {type(data)}") result = None return result - def verify(self, data): # type: ignore[no-untyped-def] # noqa + def verify(self, data): # type: ignore[no-untyped-def] """Verify the signature on the contents of the string ``data``. >>> gpg = GPG(homedir="doctests") @@ -271,7 +271,7 @@ def verify(self, data): # type: ignore[no-untyped-def] # noqa f.close() return result - def verify_file(self, file, sig_file=None): # type: ignore[no-untyped-def] # noqa + def verify_file(self, file, sig_file=None): # type: ignore[no-untyped-def] """Verify the signature on the contents of a file or file-like object. Can handle embedded signatures as well as detached signatures. If using detached signatures, the file containing the @@ -309,7 +309,7 @@ def verify_file(self, file, sig_file=None): # type: ignore[no-untyped-def] # no sig_fh.close() return result - def import_keys(self, key_data): # type: ignore[no-untyped-def] # noqa + def import_keys(self, key_data): # type: ignore[no-untyped-def] """ Import the key_data into our keyring. @@ -355,7 +355,7 @@ def import_keys(self, key_data): # type: ignore[no-untyped-def] # noqa data.close() return result - def recv_keys(self, *keyids, **kwargs): # type: ignore[no-untyped-def] # noqa + def recv_keys(self, *keyids, **kwargs): # type: ignore[no-untyped-def] """Import keys from a keyserver. >>> gpg = gnupg.GPG(homedir="doctests") @@ -435,10 +435,10 @@ def export_keys(self, keyids, secret=False, subkeys=False): # type: ignore[no-u # stdout, stderr = p.communicate() result = self._result_map["export"](self) self._collect_output(p, result, stdin=p.stdin) - log.debug("Exported:{}{!r}".format(os.linesep, result.fingerprints)) + log.debug(f"Exported:{os.linesep}{result.fingerprints!r}") return result.data.decode(self._encoding, self._decode_errors) - def list_keys(self, secret=False): # type: ignore[no-untyped-def] # noqa + def list_keys(self, secret=False): # type: ignore[no-untyped-def] """List the keys currently in the keyring. The GnuPG option '--show-photos', according to the GnuPG manual, "does @@ -480,7 +480,7 @@ def list_keys(self, secret=False): # type: ignore[no-untyped-def] # noqa self._parse_keys(result) return result - def list_packets(self, raw_data): # type: ignore[no-untyped-def] # noqa + def list_packets(self, raw_data): # type: ignore[no-untyped-def] """List the packet contents of a file.""" args = ["--list-packets"] result = self._result_map["packets"](self) @@ -523,7 +523,7 @@ def sign_key(self, keyid, default_key=None, passphrase=None): # type: ignore[no self._collect_output(p, result, stdin=p.stdin) return result - def list_sigs(self, *keyids): # type: ignore[no-untyped-def] # noqa + def list_sigs(self, *keyids): # type: ignore[no-untyped-def] """Get the signatures for each of the ``keyids``. >>> import gnupg @@ -538,7 +538,7 @@ def list_sigs(self, *keyids): # type: ignore[no-untyped-def] # noqa """ return self._process_keys(keyids) - def check_sigs(self, *keyids): # type: ignore[no-untyped-def] # noqa + def check_sigs(self, *keyids): # type: ignore[no-untyped-def] """Validate the signatures for each of the ``keyids``. :rtype: dict @@ -547,7 +547,7 @@ def check_sigs(self, *keyids): # type: ignore[no-untyped-def] # noqa """ return self._process_keys(keyids, check_sig=True) - def _process_keys(self, keyids, check_sig=False): # type: ignore[no-untyped-def] # noqa + def _process_keys(self, keyids, check_sig=False): # type: ignore[no-untyped-def] if len(keyids) > self._batch_limit: raise ValueError( @@ -568,7 +568,7 @@ def _process_keys(self, keyids, check_sig=False): # type: ignore[no-untyped-def self._parse_keys(result) return result - def _parse_keys(self, result): # type: ignore[no-untyped-def] # noqa + def _parse_keys(self, result): # type: ignore[no-untyped-def] lines = result.data.decode(self._encoding, self._decode_errors).splitlines() valid_keywords = "pub uid sec fpr sub sig rev".split() for line in lines: @@ -626,7 +626,7 @@ def expire(self, keyid, expiration_time="1y", passphrase=None, expire_subkeys=Tr self._collect_output(p, result, stdin=p.stdin) return result - def gen_key(self, input): # type: ignore[no-untyped-def] # noqa + def gen_key(self, input): # type: ignore[no-untyped-def] """Generate a GnuPG key through batch file key generation. See :meth:`GPG.gen_key_input()` for creating the control input. @@ -653,21 +653,19 @@ def gen_key(self, input): # type: ignore[no-untyped-def] # noqa if not os.path.exists(d): os.makedirs(d) - if self.temp_keyring: - if os.path.isfile(self.temp_keyring): - prefix = os.path.join(self.temp_keyring, fpr) - try: - os.rename(self.temp_keyring, prefix + ".pubring") - except OSError as ose: - log.error(str(ose)) - - if self.temp_secring: - if os.path.isfile(self.temp_secring): - prefix = os.path.join(self.temp_secring, fpr) - try: - os.rename(self.temp_secring, prefix + ".secring") - except OSError as ose: - log.error(str(ose)) + if self.temp_keyring and os.path.isfile(self.temp_keyring): + prefix = os.path.join(self.temp_keyring, fpr) + try: + os.rename(self.temp_keyring, prefix + ".pubring") + except OSError as ose: + log.error(str(ose)) + + if self.temp_secring and os.path.isfile(self.temp_secring): + prefix = os.path.join(self.temp_secring, fpr) + try: + os.rename(self.temp_secring, prefix + ".secring") + except OSError as ose: + log.error(str(ose)) log.info("Key created. Fingerprint: %s" % fpr) key.keyring = self.temp_keyring @@ -865,8 +863,9 @@ def gen_key_input(self, separate_keyring=False, save_batchfile=False, testing=Fa parms.setdefault("Key-Type", "default") log.debug( - "GnuPG v%s detected: setting default key type to %s." - % (self.binary_version, parms["Key-Type"]) + "GnuPG v{} detected: setting default key type to {}.".format( + self.binary_version, parms["Key-Type"] + ) ) parms.setdefault("Key-Length", 4096) parms.setdefault("Name-Real", "Autogenerated Key") @@ -884,9 +883,8 @@ def gen_key_input(self, separate_keyring=False, save_batchfile=False, testing=Fa for key, val in list(kwargs.items()): key = key.replace("_", "-").title() # to set 'cert', 'Key-Usage' must be blank string - if key not in ("Key-Usage", "Subkey-Usage"): - if str(val).strip(): - parms[key] = val + if key not in ("Key-Usage", "Subkey-Usage") and str(val).strip(): + parms[key] = val # if Key-Type is 'default', make Subkey-Type also be 'default' if parms["Key-Type"] == "default": @@ -903,16 +901,15 @@ def gen_key_input(self, separate_keyring=False, save_batchfile=False, testing=Fa # Key-Type must come first, followed by length out = "Key-Type: %s\n" % parms.pop("Key-Type") out += "Key-Length: %d\n" % parms.pop("Key-Length") - if "Subkey-Type" in parms.keys(): + if "Subkey-Type" in parms: out += "Subkey-Type: %s\n" % parms.pop("Subkey-Type") - else: - if default_type: - out += "Subkey-Type: default\n" - if "Subkey-Length" in parms.keys(): + elif default_type: + out += "Subkey-Type: default\n" + if "Subkey-Length" in parms: out += "Subkey-Length: %s\n" % parms.pop("Subkey-Length") for key, val in list(parms.items()): - out += "{}: {}\n".format(key, val) + out += f"{key}: {val}\n" # There is a problem where, in the batch files, if the '%%pubring' # and '%%secring' are given as any static string, i.e. 'pubring.gpg', @@ -973,7 +970,7 @@ def gen_key_input(self, separate_keyring=False, save_batchfile=False, testing=Fa return out - def encrypt(self, data, *recipients, **kwargs): # type: ignore[no-untyped-def] # noqa + def encrypt(self, data, *recipients, **kwargs): # type: ignore[no-untyped-def] """Encrypt the message contained in ``data`` to ``recipients``. :param str data: The file or bytestream to encrypt. @@ -1066,7 +1063,7 @@ def encrypt(self, data, *recipients, **kwargs): # type: ignore[no-untyped-def] stream.close() return result - def decrypt(self, message, **kwargs): # type: ignore[no-untyped-def] # noqa + def decrypt(self, message, **kwargs): # type: ignore[no-untyped-def] """Decrypt the contents of a string or file-like object ``message``. :type message: file or str or :class:`io.BytesIO` @@ -1104,11 +1101,11 @@ def decrypt_file(self, filename, always_trust=False, passphrase=None, output=Non class GPGUtilities: """Extra tools for working with GnuPG.""" - def __init__(self, gpg): # type: ignore[no-untyped-def] # noqa + def __init__(self, gpg): # type: ignore[no-untyped-def] """Initialise extra utility functions.""" self._gpg = gpg - def find_key_by_email(self, email, secret=False): # type: ignore[no-untyped-def] # noqa + def find_key_by_email(self, email, secret=False): # type: ignore[no-untyped-def] """Find user's key based on their email address. :param str email: The email address to search for. @@ -1120,7 +1117,7 @@ def find_key_by_email(self, email, secret=False): # type: ignore[no-untyped-def return key raise LookupError("GnuPG public key for email %s not found!" % email) - def find_key_by_subkey(self, subkey): # type: ignore[no-untyped-def] # noqa + def find_key_by_subkey(self, subkey): # type: ignore[no-untyped-def] """Find a key by a fingerprint of one of its subkeys. :param str subkey: The fingerprint of the subkey to search for. @@ -1131,7 +1128,7 @@ def find_key_by_subkey(self, subkey): # type: ignore[no-untyped-def] # noqa return key raise LookupError("GnuPG public key for subkey %s not found!" % subkey) - def send_keys(self, keyserver, *keyids): # type: ignore[no-untyped-def] # noqa + def send_keys(self, keyserver, *keyids): # type: ignore[no-untyped-def] """Send keys to a keyserver.""" result = self._result_map["list"](self) log.debug("send_keys: %r", keyids) @@ -1143,7 +1140,7 @@ def send_keys(self, keyserver, *keyids): # type: ignore[no-untyped-def] # noqa data.close() return result - def encrypted_to(self, raw_data): # type: ignore[no-untyped-def] # noqa + def encrypted_to(self, raw_data): # type: ignore[no-untyped-def] """Return the key to which raw_data is encrypted to.""" # TODO: make this support multiple keys. result = self._gpg.list_packets(raw_data) @@ -1154,15 +1151,15 @@ def encrypted_to(self, raw_data): # type: ignore[no-untyped-def] # noqa except: # noqa: E722 return self.find_key_by_subkey(result.key) - def is_encrypted_sym(self, raw_data): # type: ignore[no-untyped-def] # noqa + def is_encrypted_sym(self, raw_data): # type: ignore[no-untyped-def] result = self._gpg.list_packets(raw_data) return bool(result.need_passphrase_sym) - def is_encrypted_asym(self, raw_data): # type: ignore[no-untyped-def] # noqa + def is_encrypted_asym(self, raw_data): # type: ignore[no-untyped-def] result = self._gpg.list_packets(raw_data) return bool(result.key) - def is_encrypted(self, raw_data): # type: ignore[no-untyped-def] # noqa + def is_encrypted(self, raw_data): # type: ignore[no-untyped-def] return self.is_encrypted_asym(raw_data) or self.is_encrypted_sym(raw_data) diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -102,9 +102,8 @@ def setup_g() -> Optional[werkzeug.Response]: @ignore_static def check_tor2web() -> Optional[werkzeug.Response]: # TODO: expand header checking logic to catch modern tor2web proxies - if "X-tor2web" in request.headers: - if request.path != url_for("info.tor2web_warning"): - return redirect(url_for("info.tor2web_warning")) + if "X-tor2web" in request.headers and request.path != url_for("info.tor2web_warning"): + return redirect(url_for("info.tor2web_warning")) return None @app.errorhandler(404) diff --git a/securedrop/source_app/decorators.py b/securedrop/source_app/decorators.py --- a/securedrop/source_app/decorators.py +++ b/securedrop/source_app/decorators.py @@ -36,7 +36,7 @@ def ignore_static(f: Callable) -> Callable: @wraps(f) def decorated_function(*args: Any, **kwargs: Any) -> Any: if request.path.startswith("/static"): - return # don't execute the decorated function + return None # don't execute the decorated function return f(*args, **kwargs) return decorated_function diff --git a/securedrop/source_app/forms.py b/securedrop/source_app/forms.py --- a/securedrop/source_app/forms.py +++ b/securedrop/source_app/forms.py @@ -1,6 +1,7 @@ import wtforms from flask import abort from flask_babel import lazy_gettext as gettext +from flask_babel import ngettext from flask_wtf import FlaskForm from models import InstanceConfig, Submission from passphrases import PassphraseGenerator @@ -17,12 +18,11 @@ class LoginForm(FlaskForm): Length( 1, PassphraseGenerator.MAX_PASSPHRASE_LENGTH, - message=gettext( - "Field must be between 1 and " - "{max_codename_len} characters long.".format( - max_codename_len=PassphraseGenerator.MAX_PASSPHRASE_LENGTH - ) - ), + message=ngettext( + "Field must be between 1 and {max_codename_len} character long.", + "Field must be between 1 and {max_codename_len} characters long.", + PassphraseGenerator.MAX_PASSPHRASE_LENGTH, + ).format(max_codename_len=PassphraseGenerator.MAX_PASSPHRASE_LENGTH), ), # Make sure to allow dashes since some words in the wordlist have them Regexp(r"[\sA-Za-z0-9-]+$", message=gettext("Invalid input.")), diff --git a/securedrop/source_app/info.py b/securedrop/source_app/info.py --- a/securedrop/source_app/info.py +++ b/securedrop/source_app/info.py @@ -1,4 +1,4 @@ -from io import BytesIO # noqa +from io import BytesIO import flask import werkzeug diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -340,7 +340,7 @@ def batch_delete(logged_in_source: SourceUser) -> werkzeug.Response: Reply.query.filter(Reply.source_id == logged_in_source.db_record_id) .filter(Reply.deleted_by_source == False) .all() - ) # noqa + ) if len(replies) == 0: current_app.logger.error("Found no replies when at least one was " "expected") return redirect(url_for(".lookup")) diff --git a/securedrop/specialstrings.py b/securedrop/specialstrings.py --- a/securedrop/specialstrings.py +++ b/securedrop/specialstrings.py @@ -1,7 +1,8 @@ +# ruff: noqa strings = [ """This is a test message without markup!""", """This is a test message with markup and characters such as \\, \\, \', \" and ". """ - + """<strong>This text should not be bold</strong>!""", # noqa: W605, E501 + + """<strong>This text should not be bold</strong>!""", """~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%""", """Ω≈ç√∫˜µ≤≥÷ åß∂ƒ©˙∆˚¬…æ @@ -10,26 +11,26 @@ ¸˛Ç◊ı˜Â¯˘¿ ÅÍÎÏ˝ÓÔÒÚÆ☃ Œ„´‰ˇÁ¨ˆØ∏”""", - """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$""", # noqa: W605, E501 - """............................................................................................................................ .""", # noqa: W605, E501 - """thisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwit💩houtspacesordashes""", # noqa: W605, E501 - """😍😍😍😍🔥🔥🔥🔥🔥🖧Thelastwas3networkedcomuters📟📸longwordwit💩houtspacesordashes""", # noqa: W605, E501 + """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$""", + """............................................................................................................................ .""", + """thisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwit💩houtspacesordashes""", + """😍😍😍😍🔥🔥🔥🔥🔥🖧Thelastwas3networkedcomuters📟📸longwordwit💩houtspacesordashes""", """WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW""", - """.................................................................................................................................""", # noqa: W605, E501 + """.................................................................................................................................""", """https://github.com/freedomofpress/securedrop-client/pull/1050""", """~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%^&*()_+{}|:"<>?~!@#$%""", """Ω≈ç√∫˜µ≤≥÷åß∂ƒ©˙∆˚¬…æœ∑´®†¥¨ˆøπ“‘""", "🌈️", - """..................................................................................................................................""", # noqa: W605, E501, - """$........................................................................................................................................................................................................................................................""", # noqa: W605, E501 - """Ω≈ç√∫˜µ≤≥÷åß∂ƒ©˙∆˚¬æœ∑®†¥¨ˆøπ“‘Ω≈ç√∫˜µ≤≥÷åß∂ƒ©˙∆........................................................................................................................................................""", # noqa: W605, E501 - """data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gBbRmlsZSBzb3VyY2U6IGh0dHBzOi8vY29tbW9ucy53aWtpbWVkaWEub3JnL3dpa2kvRmlsZTpMb3dfcHJlc3N1cmVfc3lzdGVtX292ZXJfSWNlbGFuZC5qcGf/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAHgAioDASIAAhEBAxEB/8QAHAAAAQUBAQEAAAAAAAAAAAAABQIDBAYHAQAI/8QAQRAAAgECBQIEBQEHAgUDBQEBAQIDBBEABRIhMQZBEyJRYQcUMnGBkRUjQlKhscHR8CQzYnLhQ4LxCBYlU5I0sv/EABkBAQEBAQEBAAAAAAAAAAAAAAABAgMEBf/EACMRAQEAAgICAwEBAQEBAAAAAAABAhEhMRJBAyJRYRMycbH/2gAMAwEAAhEDEQA/APpUxmxI27YSF7qdibXOFVMrHSXlWKmAuWJsW9/17YQpLNZbhD7WsP8AXFQkgs5JIO1wLYkRwBIQH1M3JW9gPvjsDxIY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6xpa0O4EkVSFVysRYLpffewsb84zly1hdPoWkchdLm6ngE3tiSpCnT4iJfe3JwJyzMKeopEkp2SRGYBZopPEQj7i+DFGfGpBIDEojJvIhs35v+O2ObqVGpv5buD6Kf74eEYt3/AP6x6HxU1ENdAbXP1H8dsP8Aip/KcB//2Q==""", # noqa: W605, E501 + """..................................................................................................................................""", # , + """$........................................................................................................................................................................................................................................................""", + """Ω≈ç√∫˜µ≤≥÷åß∂ƒ©˙∆˚¬æœ∑®†¥¨ˆøπ“‘Ω≈ç√∫˜µ≤≥÷åß∂ƒ©˙∆........................................................................................................................................................""", + """data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gBbRmlsZSBzb3VyY2U6IGh0dHBzOi8vY29tbW9ucy53aWtpbWVkaWEub3JnL3dpa2kvRmlsZTpMb3dfcHJlc3N1cmVfc3lzdGVtX292ZXJfSWNlbGFuZC5qcGf/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAHgAioDASIAAhEBAxEB/8QAHAAAAQUBAQEAAAAAAAAAAAAABQIDBAYHAQAI/8QAQRAAAgECBQIEBQEHAgUDBQEBAQIDBBEABRIhMQZBEyJRYQcUMnGBkRUjQlKhscHR8CQzYnLhQ4LxCBYlU5I0sv/EABkBAQEBAQEBAAAAAAAAAAAAAAABAgMEBf/EACMRAQEAAgICAwEBAQEBAAAAAAABAhEhMRJBAyJRYRMycbH/2gAMAwEAAhEDEQA/APpUxmxI27YSF7qdibXOFVMrHSXlWKmAuWJsW9/17YQpLNZbhD7WsP8AXFQkgs5JIO1wLYkRwBIQH1M3JW9gPvjsDxIY0uDI1z62GOzSXRS1sQckRY0sAGbbjDPhPKGC7FrBfsOTh8r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CnT4iJfe3JwJyzMKeopEkp2SRGYBZopPEQj7i+DFGfGpBIDEojJvIhs35v+O2ObqVGpv5buD6Kf74eEYt3/AP6x6HxU1ENdAbXP1H8dsP8Aip/KcB//2Q==""", """thisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashes thisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashes thisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashesthisisalongwordwithoutspacesordashes -""", # noqa: W605, E501 +""", """Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a neque vitae diam blandit porttitor id in leo. Fusce varius urna a suscipit euismod. Praesent dapibus, dui vehicula accumsan ornare, augue felis maximus metus, quis faucibus magna libero id lectus. Sed lobortis vestibulum finibus. Integer dui lorem, porttitor dapibus malesuada in, vestibulum id tellus. Phasellus sollicitudin orci nunc, sed fringilla odio lobortis commodo. Duis rutrum nunc justo, sit amet dictum nulla aliquam at. Fusce non nisi mauris. Maecenas et auctor purus, lacinia elementum velit. Mauris congue est ac tortor auctor hendrerit. Fusce ac sollicitudin augue. Etiam imperdiet purus quis risus ultrices, ut iaculis ante convallis. Fusce eros massa, laoreet nec augue nec, aliquam finibus elit. Praesent ullamcorper dignissim odio, id gravida dui sollicitudin at. Nunc eget laoreet diam. Nam vitae mauris dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis nibh nec dapibus egestas. Sed ut sodales dui. Cras facilisis ex quis quam maximus euismod. Vestibulum sed ullamcorper orci, nec tempor orci. Sed felis est, luctus mollis dolor eu, mattis ornare leo. Aliquam interdum ac tortor quis facilisis. Donec hendrerit ullamcorper orci vitae facilisis. Morbi odio justo, fringilla sed fermentum vitae, pellentesque eget ante. Etiam elementum tincidunt sapien in interdum. In hac habitasse platea dictumst. Suspendisse non metus non risus congue luctus. @@ -109,15 +110,15 @@ Donec non ipsum sit amet mauris mattis tincidunt ut a leo. Quisque volutpat eget elit quis suscipit. Mauris id nulla varius, suscipit nulla vel, tincidunt augue. Nulla tristique augue diam, et malesuada tellus hendrerit a. Sed lobortis, nulla nec pulvinar tempus, est mi molestie urna, efficitur gravida metus odio ac eros. Sed at porttitor lectus, eget aliquam lectus. Proin at pretium diam. Phasellus commodo rutrum nisl, et maximus enim rutrum ac. Morbi magna ligula, elementum eget mauris eget, gravida molestie turpis. Nunc gravida, lorem ut volutpat malesuada, neque mi sodales massa, ut malesuada erat leo eu nisi. Duis ac turpis nec risus ullamcorper suscipit. Duis quis ante gravida, hendrerit mauris quis, congue tellus. Suspendisse lacinia non nisl at gravida. Nam a mi turpis. Maecenas ac mollis nisi. Maecenas dolor magna, semper ac faucibus non, sollicitudin et nisi. Suspendisse ut sapien elit. Suspendisse commodo lacus in augue tempor ullamcorper. Proin euismod augue eu ipsum cursus fringilla. Nunc vitae tortor tellus. -""", # noqa: W605, E501 - """............................................................................................................................ .""", # noqa: W605, E501 +""", + """............................................................................................................................ .""", """Date Ticker Type Amount Details 03/27/2020 warning Purchase $500,001 - $1,000,000 View 03/31/2020 warning Purchase $250,001 - $500,000 View 03/27/2020 warning Purchase $100,001 - $250,000 View 03/18/2020 warning Purchase $500,001 - $1,000,000 View -""", # noqa: W605, E501 - """؁؂؃؄؅؜۝܏᠎​‌‍‎‏‪‫‬‭‮⁠⁡⁢⁣⁤⁦⁧⁨⁩""", # noqa: W605, E501 +""", + """؁؂؃؄؅؜۝܏᠎​‌‍‎‏‪‫‬‭‮⁠⁡⁢⁣⁤⁦⁧⁨⁩""", """田中さんにあげて下さい パーティーへ行かないか 和製漢語 @@ -127,8 +128,8 @@ 社會科學院語學研究所 울란바토르 𠜎𠜱𠝹𠱓𠱸𠲖𠳏 -""", # noqa: W605, E501 - """𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆""", # noqa: W605, E501 +""", + """𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆""", """ The quick brown fox jumps over the lazy dog 𝐓𝐡𝐞 𝐪𝐮𝐢𝐜𝐤 𝐛𝐫𝐨𝐰𝐧 𝐟𝐨𝐱 𝐣𝐮𝐦𝐩𝐬 𝐨𝐯𝐞𝐫 𝐭𝐡𝐞 𝐥𝐚𝐳𝐲 𝐝𝐨𝐠 @@ -137,5 +138,5 @@ 𝓣𝓱𝓮 𝓺𝓾𝓲𝓬𝓴 𝓫𝓻𝓸𝔀𝓷 𝓯𝓸𝔁 𝓳𝓾𝓶𝓹𝓼 𝓸𝓿𝓮𝓻 𝓽𝓱𝓮 𝓵𝓪𝔃𝔂 𝓭𝓸𝓰 𝕋𝕙𝕖 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨𝕟 𝕗𝕠𝕩 𝕛𝕦𝕞𝕡𝕤 𝕠𝕧𝕖𝕣 𝕥𝕙𝕖 𝕝𝕒𝕫𝕪 𝕕𝕠𝕘 𝚃𝚑𝚎 𝚚𝚞𝚒𝚌𝚔 𝚋𝚛𝚘𝚠𝚗 𝚏𝚘𝚡 𝚓𝚞𝚖𝚙𝚜 𝚘𝚟𝚎𝚛 𝚝𝚑𝚎 𝚕𝚊𝚣𝚢 𝚍𝚘𝚐 -⒯⒣⒠ ⒬⒰⒤⒞⒦ ⒝⒭⒪⒲⒩ ⒡⒪⒳ ⒥⒰⒨⒫⒮ ⒪⒱⒠⒭ ⒯⒣⒠ ⒧⒜⒵⒴ ⒟⒪⒢""", # noqa: W605, E501 +⒯⒣⒠ ⒬⒰⒤⒞⒦ ⒝⒭⒪⒲⒩ ⒡⒪⒳ ⒥⒰⒨⒫⒮ ⒪⒱⒠⒭ ⒯⒣⒠ ⒧⒜⒵⒴ ⒟⒪⒢""", ] diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -7,6 +7,8 @@ import zipfile from hashlib import sha256 from pathlib import Path +from tempfile import _TemporaryFileWrapper +from typing import IO, List, Optional, Type, Union import rm from encryption import EncryptionManager @@ -15,22 +17,15 @@ from sdconfig import SecureDropConfig from secure_tempfile import SecureTemporaryFile from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import Session, sessionmaker from werkzeug.utils import secure_filename from worker import create_queue if typing.TYPE_CHECKING: - # flake8 can not understand type annotation yet. - # That is why all type annotation relative import - # statements has to be marked as noqa. - # http://flake8.pycqa.org/en/latest/user/error-codes.html?highlight=f401 - from tempfile import _TemporaryFileWrapper # type: ignore # noqa: F401 - from typing import IO, List, Optional, Type, Union # noqa: F401 + # Break circular import + from models import Reply, Submission - from models import Reply, Submission # noqa: F401 - from sqlalchemy.orm import Session # noqa: F401 - -_default_storage: typing.Optional["Storage"] = None +_default_storage: Optional["Storage"] = None VALIDATE_FILENAME = re.compile( @@ -43,8 +38,6 @@ class PathException(Exception): can be bad when it is not absolute or not normalized. """ - pass - class TooManyFilesException(Exception): """An exception raised by path_without_filesystem_id when too many @@ -53,8 +46,6 @@ class TooManyFilesException(Exception): journalist_designations. """ - pass - class NoFileFoundException(Exception): """An exception raised by path_without_filesystem_id when a file could @@ -62,16 +53,12 @@ class NoFileFoundException(Exception): This is likely due to an admin manually deleting files from the server. """ - pass - class NotEncrypted(Exception): """An exception raised if a file expected to be encrypted client-side is actually plaintext. """ - pass - def safe_renames(old: str, new: str) -> None: """safe_renames(old, new) @@ -313,7 +300,7 @@ def save_file_submission( filesystem_id: str, count: int, journalist_filename: str, - filename: typing.Optional[str], + filename: Optional[str], stream: "IO[bytes]", ) -> str: diff --git a/securedrop/two_factor.py b/securedrop/two_factor.py --- a/securedrop/two_factor.py +++ b/securedrop/two_factor.py @@ -58,8 +58,7 @@ def __init__(self, secret_as_base32: str) -> None: ) def generate(self, counter: int) -> str: - token = self._hotp.generate(counter).decode("ascii") - return token + return self._hotp.generate(counter).decode("ascii") def verify(self, token: str, counter: int) -> int: """Validate an HOTP-generated token and return the counter value that succeeded.""" @@ -115,12 +114,10 @@ def __init__(self, secret_as_base32: str) -> None: ) def generate(self, time: datetime) -> str: - token = self._totp.generate(time.timestamp()).decode("ascii") - return token + return self._totp.generate(time.timestamp()).decode("ascii") def now(self) -> str: - token = self._totp.generate(datetime.utcnow().timestamp()).decode("ascii") - return token + return self._totp.generate(datetime.utcnow().timestamp()).decode("ascii") def verify(self, token: str, time: datetime) -> None: # Also check the given token against the previous and next valid tokens, to compensate diff --git a/securedrop/upload-screenshots.py b/securedrop/upload-screenshots.py --- a/securedrop/upload-screenshots.py +++ b/securedrop/upload-screenshots.py @@ -120,7 +120,7 @@ def get_existing_screenshots(self) -> List[Dict[str, str]]: # API results are paginated, so we must loop through a set of results and # concatenate them. - screenshots = [] # type: List[Dict[str, str]] + screenshots: List[Dict[str, str]] = [] request_count = 0 while next_screenshots_url is not None: response = self.session.get(next_screenshots_url) diff --git a/securedrop/worker.py b/securedrop/worker.py --- a/securedrop/worker.py +++ b/securedrop/worker.py @@ -15,8 +15,7 @@ def create_queue(name: str, timeout: int = 3600) -> Queue: If ``name`` is omitted, ``config.RQ_WORKER_NAME`` is used. """ - q = Queue(name=name, connection=Redis(), default_timeout=timeout) - return q + return Queue(name=name, connection=Redis(), default_timeout=timeout) def rq_workers(queue: Queue = None) -> List[Worker]:
diff --git a/admin/tests/test_integration.py b/admin/tests/test_integration.py --- a/admin/tests/test_integration.py +++ b/admin/tests/test_integration.py @@ -152,48 +152,46 @@ def verify_username_prompt(child): def verify_reboot_prompt(child): child.expect(rb"Daily reboot time of the server \(24\-hour clock\):", timeout=2) - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "4" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "4" def verify_ipv4_appserver_prompt(child): - child.expect(rb"Local IPv4 address for the Application Server\:", timeout=2) # noqa: E501 + child.expect(rb"Local IPv4 address for the Application Server\:", timeout=2) # Expected default - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "10.20.2.2" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "10.20.2.2" def verify_ipv4_monserver_prompt(child): child.expect(rb"Local IPv4 address for the Monitor Server\:", timeout=2) # Expected default - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "10.20.3.2" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "10.20.3.2" def verify_hostname_app_prompt(child): child.expect(rb"Hostname for Application Server\:", timeout=2) - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "app" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "app" def verify_hostname_mon_prompt(child): child.expect(rb"Hostname for Monitor Server\:", timeout=2) - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "mon" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "mon" def verify_dns_prompt(child): child.expect(rb"DNS server\(s\):", timeout=2) - assert ( - ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "8.8.8.8 8.8.4.4" - ) # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "8.8.8.8 8.8.4.4" def verify_app_gpg_key_prompt(child): child.expect( rb"Local filepath to public key for SecureDrop Application GPG public key\:", timeout=2 - ) # noqa: E501 + ) def verify_https_prompt(child): child.expect( rb"Whether HTTPS should be enabled on Source Interface \(requires EV cert\)\:", timeout=2 - ) # noqa: E501 + ) def verify_https_cert_prompt(child): @@ -205,64 +203,54 @@ def verify_https_cert_key_prompt(child): def verify_https_cert_chain_file_prompt(child): - child.expect(rb"Local filepath to HTTPS certificate chain file\:", timeout=2) # noqa: E501 + child.expect(rb"Local filepath to HTTPS certificate chain file\:", timeout=2) def verify_app_gpg_fingerprint_prompt(child): - child.expect( - rb"Full fingerprint for the SecureDrop Application GPG Key\:", timeout=2 - ) # noqa: E501 + child.expect(rb"Full fingerprint for the SecureDrop Application GPG Key\:", timeout=2) def verify_ossec_gpg_key_prompt(child): - child.expect(rb"Local filepath to OSSEC alerts GPG public key\:", timeout=2) # noqa: E501 + child.expect(rb"Local filepath to OSSEC alerts GPG public key\:", timeout=2) def verify_ossec_gpg_fingerprint_prompt(child): - child.expect( - rb"Full fingerprint for the OSSEC alerts GPG public key\:", timeout=2 - ) # noqa: E501 + child.expect(rb"Full fingerprint for the OSSEC alerts GPG public key\:", timeout=2) def verify_admin_email_prompt(child): - child.expect(rb"Admin email address for receiving OSSEC alerts\:", timeout=2) # noqa: E501 + child.expect(rb"Admin email address for receiving OSSEC alerts\:", timeout=2) def verify_journalist_gpg_key_prompt(child): - child.expect( - rb"Local filepath to journalist alerts GPG public key \(optional\)\:", timeout=2 - ) # noqa: E501 + child.expect(rb"Local filepath to journalist alerts GPG public key \(optional\)\:", timeout=2) def verify_journalist_fingerprint_prompt(child): child.expect( rb"Full fingerprint for the journalist alerts GPG public key \(optional\)\:", timeout=2 - ) # noqa: E501 + ) def verify_journalist_email_prompt(child): - child.expect( - rb"Email address for receiving journalist alerts \(optional\)\:", timeout=2 - ) # noqa: E501 + child.expect(rb"Email address for receiving journalist alerts \(optional\)\:", timeout=2) def verify_smtp_relay_prompt(child): child.expect(rb"SMTP relay for sending OSSEC alerts\:", timeout=2) # Expected default - assert ( - ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "smtp.gmail.com" - ) # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "smtp.gmail.com" def verify_smtp_port_prompt(child): child.expect(rb"SMTP port for sending OSSEC alerts\:", timeout=2) - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "587" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "587" def verify_sasl_domain_prompt(child): child.expect(rb"SASL domain for sending OSSEC alerts\:", timeout=2) # Expected default - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "gmail.com" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "gmail.com" def verify_sasl_username_prompt(child): @@ -275,11 +263,11 @@ def verify_sasl_password_prompt(child): def verify_ssh_over_lan_prompt(child): child.expect(rb"will be available over LAN only\:", timeout=2) - assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "yes" # noqa: E501 + assert ANSI_ESCAPE.sub("", child.buffer.decode("utf-8")).strip() == "yes" def verify_locales_prompt(child): - child.expect(rb"Space separated list of additional locales to support") # noqa: E501 + child.expect(rb"Space separated list of additional locales to support") def verify_install_has_valid_config(): @@ -361,7 +349,7 @@ def test_sdconfig_on_first_run(): with open( os.path.join(SD_DIR, "install_files/ansible-base/group_vars/all/site-specific") - ) as fobj: # noqa: E501 + ) as fobj: data = fobj.read() assert data == OUTPUT1 @@ -427,9 +415,9 @@ def test_sdconfig_enable_journalist_alerts(): with open( os.path.join(SD_DIR, "install_files/ansible-base/group_vars/all/site-specific") - ) as fobj: # noqa: E501 + ) as fobj: data = fobj.read() - assert JOURNALIST_ALERT_OUTPUT == data + assert data == JOURNALIST_ALERT_OUTPUT verify_install_has_valid_config() @@ -500,9 +488,9 @@ def test_sdconfig_enable_https_on_source_interface(): with open( os.path.join(SD_DIR, "install_files/ansible-base/group_vars/all/site-specific") - ) as fobj: # noqa: E501 + ) as fobj: data = fobj.read() - assert HTTPS_OUTPUT == data + assert data == HTTPS_OUTPUT verify_install_has_valid_config() @@ -522,7 +510,7 @@ def test_sdconfig_enable_https_on_source_interface(): """ [email protected] [email protected]() def securedrop_git_repo(tmpdir): cwd = os.getcwd() os.chdir(str(tmpdir)) @@ -585,9 +573,7 @@ def test_check_for_update_when_updates_needed(securedrop_git_repo): @flaky(max_runs=3) def test_check_for_update_when_updates_not_needed(securedrop_git_repo): # Determine latest production tag using GitHub release object - github_url = ( - "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" # noqa: E501 - ) + github_url = "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" latest_release = requests.get(github_url, timeout=60).json() latest_tag = str(latest_release["tag_name"]) @@ -658,9 +644,7 @@ def test_update_with_duplicate_branch_and_tag(securedrop_git_repo): gpgdir = os.path.join(os.path.expanduser("~"), ".gnupg") set_reliable_keyserver(gpgdir) - github_url = ( - "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" # noqa: E501 - ) + github_url = "https://api.github.com/repos/freedomofpress/securedrop/releases/latest" latest_release = requests.get(github_url, timeout=60).json() latest_tag = str(latest_release["tag_name"]) diff --git a/admin/tests/test_securedrop-admin-setup.py b/admin/tests/test_securedrop-admin-setup.py --- a/admin/tests/test_securedrop-admin-setup.py +++ b/admin/tests/test_securedrop-admin-setup.py @@ -45,7 +45,7 @@ def test_run_command(self): assert output_line.strip() == b"something" lines = [] - with pytest.raises(subprocess.CalledProcessError): + with pytest.raises(subprocess.CalledProcessError): # noqa: PT012 for output_line in bootstrap.run_command( ["sh", "-c", "echo in stdout ; echo in stderr >&2 ; false"] ): @@ -71,9 +71,8 @@ def test_install_pip_dependencies_fail(self, caplog): subprocess, "check_output", side_effect=subprocess.CalledProcessError(returncode=2, cmd="", output=b"failed"), - ): - with pytest.raises(subprocess.CalledProcessError): - bootstrap.install_pip_dependencies(args) + ), pytest.raises(subprocess.CalledProcessError): + bootstrap.install_pip_dependencies(args) assert "Failed to install" in caplog.text def test_python3_buster_venv_deleted_in_bullseye(self, tmpdir, caplog): @@ -110,26 +109,27 @@ def test_venv_cleanup_subprocess_exception(self, tmpdir, caplog): venv_path = str(tmpdir) python_lib_path = os.path.join(venv_path, "lib/python3.7") os.makedirs(python_lib_path) - with mock.patch("bootstrap.is_tails", return_value=True): - with mock.patch( - "subprocess.check_output", side_effect=subprocess.CalledProcessError(1, ":o") - ): - bootstrap.clean_up_old_tails_venv(venv_path) - assert os.path.exists(venv_path) + with mock.patch("bootstrap.is_tails", return_value=True), mock.patch( + "subprocess.check_output", side_effect=subprocess.CalledProcessError(1, ":o") + ): + bootstrap.clean_up_old_tails_venv(venv_path) + assert os.path.exists(venv_path) def test_envsetup_cleanup(self, tmpdir, caplog): venv = os.path.join(str(tmpdir), "empty_dir") args = "" - with pytest.raises(subprocess.CalledProcessError): - with mock.patch( - "subprocess.check_output", side_effect=self.side_effect_venv_bootstrap(venv) - ): - bootstrap.envsetup(args, venv) - assert not os.path.exists(venv) - assert "Cleaning up virtualenv" in caplog.text + with pytest.raises(subprocess.CalledProcessError), mock.patch( + "subprocess.check_output", side_effect=self.side_effect_venv_bootstrap(venv) + ): + bootstrap.envsetup(args, venv) + assert not os.path.exists(venv) + assert "Cleaning up virtualenv" in caplog.text def side_effect_venv_bootstrap(self, venv_path): # emulate the venv being created, and raise exception to simulate # failure in virtualenv creation - os.makedirs(venv_path) - raise subprocess.CalledProcessError(1, ":o") + def func(*args, **kwargs): + os.makedirs(venv_path) + raise subprocess.CalledProcessError(1, ":o") + + return func diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -196,7 +196,7 @@ def test_check_for_updates_if_most_recent_tag_is_rc(self, tmpdir, caplog): assert tag == "0.6.1" @pytest.mark.parametrize( - "git_output, expected_rv", + ("git_output", "expected_rv"), [ (b"* develop\n", "develop"), (b" develop\n" b"* release/1.7.0\n", "release/1.7.0"), @@ -473,10 +473,10 @@ def test_no_signature_on_update(self, tmpdir, caplog): def test_exit_codes(self, tmpdir): """Ensure that securedrop-admin returns the correct exit codes for success or failure.""" - with mock.patch("securedrop_admin.install_securedrop", return_value=True): + with mock.patch("securedrop_admin.install_securedrop", return_value=0): with pytest.raises(SystemExit) as e: securedrop_admin.main(["--root", str(tmpdir), "install"]) - assert e.value.code == securedrop_admin.EXIT_SUCCESS + assert e.value.code == securedrop_admin.EXIT_SUCCESS with mock.patch( "securedrop_admin.install_securedrop", @@ -484,12 +484,12 @@ def test_exit_codes(self, tmpdir): ): with pytest.raises(SystemExit) as e: securedrop_admin.main(["--root", str(tmpdir), "install"]) - assert e.value.code == securedrop_admin.EXIT_SUBPROCESS_ERROR + assert e.value.code == securedrop_admin.EXIT_SUBPROCESS_ERROR with mock.patch("securedrop_admin.install_securedrop", side_effect=KeyboardInterrupt): with pytest.raises(SystemExit) as e: securedrop_admin.main(["--root", str(tmpdir), "install"]) - assert e.value.code == securedrop_admin.EXIT_INTERRUPT + assert e.value.code == securedrop_admin.EXIT_INTERRUPT class TestSiteConfig: @@ -647,7 +647,7 @@ def test_sanitize_fingerprint(self, tmpdir): root=tmpdir, ) site_config = securedrop_admin.SiteConfig(args) - assert "ABC" == site_config.sanitize_fingerprint(" A bc") + assert site_config.sanitize_fingerprint(" A bc") == "ABC" def test_validate_int(self): validator = securedrop_admin.SiteConfig.ValidateInt() @@ -981,11 +981,11 @@ def auto_prompt(prompt, default, **kwargs): value = "VALUE" assert value == site_config.validated_input("", value, lambda: True, None) assert value.lower() == site_config.validated_input("", value, lambda: True, str.lower) - assert "yes" == site_config.validated_input("", True, lambda: True, None) - assert "no" == site_config.validated_input("", False, lambda: True, None) - assert "1234" == site_config.validated_input("", 1234, lambda: True, None) - assert "a b" == site_config.validated_input("", ["a", "b"], lambda: True, None) - assert "{}" == site_config.validated_input("", {}, lambda: True, None) + assert site_config.validated_input("", True, lambda: True, None) == "yes" + assert site_config.validated_input("", False, lambda: True, None) == "no" + assert site_config.validated_input("", 1234, lambda: True, None) == "1234" + assert site_config.validated_input("", ["a", "b"], lambda: True, None) == "a b" + assert site_config.validated_input("", {}, lambda: True, None) == "{}" def test_load(self, tmpdir, caplog): args = argparse.Namespace( @@ -1053,7 +1053,7 @@ def test_find_or_generate_new_torv3_keys_first_run(tmpdir, capsys): "mon_ssh_private_key", ] for key in expected_keys: - assert key in v3_onion_service_keys.keys() + assert key in v3_onion_service_keys def test_find_or_generate_new_torv3_keys_subsequent_run(tmpdir, capsys): diff --git a/builder/tests/test_ossec_package.py b/builder/tests/test_ossec_package.py --- a/builder/tests/test_ossec_package.py +++ b/builder/tests/test_ossec_package.py @@ -29,7 +29,7 @@ def test_ossec_binaries_are_present_agent(): contents = subprocess.check_output(["dpkg-deb", "-c", str(path)]).decode() for wanted_file in wanted_files: assert re.search( - r"^.* .{}$".format(wanted_file), + rf"^.* .{wanted_file}$", contents, re.M, ) @@ -71,7 +71,7 @@ def test_ossec_binaries_are_present_server(): contents = subprocess.check_output(["dpkg-deb", "-c", str(path)]).decode() for wanted_file in wanted_files: assert re.search( - r"^.* .{}$".format(wanted_file), + rf"^.* .{wanted_file}$", contents, re.M, ) diff --git a/builder/tests/test_securedrop_deb_package.py b/builder/tests/test_securedrop_deb_package.py --- a/builder/tests/test_securedrop_deb_package.py +++ b/builder/tests/test_securedrop_deb_package.py @@ -65,11 +65,11 @@ def test_deb_package_contains_expected_conffiles(deb: Path): @pytest.mark.parametrize( "path", - ( + [ "/var/www/securedrop/.well-known/pki-validation/", "/var/www/securedrop/translations/messages.pot", "/var/www/securedrop/translations/de_DE/LC_MESSAGES/messages.mo", - ), + ], ) def test_app_code_paths(securedrop_app_code_contents: str, path: str): """ @@ -80,18 +80,18 @@ def test_app_code_paths(securedrop_app_code_contents: str, path: str): assert True return - assert False, "not found" + pytest.fail("not found") @pytest.mark.parametrize( "path", - ( + [ "/var/www/securedrop/static/.webassets-cache/", "/var/www/securedrop/static/gen/", "/var/www/securedrop/config.py", "/var/www/static/i/custom_logo.png", ".j2", - ), + ], ) def test_app_code_paths_missing(securedrop_app_code_contents: str, path: str): """ @@ -99,4 +99,4 @@ def test_app_code_paths_missing(securedrop_app_code_contents: str, path: str): """ for line in securedrop_app_code_contents.splitlines(): if line.endswith(path): - assert False, line + pytest.fail(f"found {line}") diff --git a/journalist_gui/test_gui.py b/journalist_gui/test_gui.py --- a/journalist_gui/test_gui.py +++ b/journalist_gui/test_gui.py @@ -59,9 +59,9 @@ def test_same_name(self, mock_msgbox, mock_exit): def test_unknown_kernel_error(self, mock_msgbox, mock_exit): mock_socket = self.socket_mock_generator(131) # crazy unexpected error with mock.patch("journalist_gui.SecureDropUpdater.socket", new=mock_socket): + prevent_second_instance(self.mock_app, "name1") with pytest.raises(OSError): prevent_second_instance(self.mock_app, "name1") - prevent_second_instance(self.mock_app, "name1") class AppTestCase(unittest.TestCase): @@ -92,20 +92,20 @@ def test_window_is_a_fixed_size(self): def test_clicking_install_later_exits_the_application(self): QTest.mouseClick(self.window.pushButton, Qt.LeftButton) - self.assertFalse(self.window.isVisible()) + assert not self.window.isVisible() def test_progress_bar_begins_at_zero(self): - self.assertEqual(self.window.progressBar.value(), 0) + assert self.window.progressBar.value() == 0 def test_default_tab(self): - self.assertEqual(self.window.tabWidget.currentIndex(), 0) + assert self.window.tabWidget.currentIndex() == 0 def test_output_tab(self): tab = self.window.tabWidget.tabBar() QTest.mouseClick(tab, Qt.LeftButton) - self.assertEqual( - self.window.tabWidget.currentIndex(), self.window.tabWidget.indexOf(self.window.tab_2) + assert self.window.tabWidget.currentIndex() == self.window.tabWidget.indexOf( + self.window.tab_2 ) @mock.patch("subprocess.check_output", return_value=b"Python dependencies for securedrop-admin") @@ -115,8 +115,8 @@ def test_setupThread(self, check_output): self.window.setup_thread.run() # Call run directly mock_open.assert_called_once_with(FLAG_LOCATION, "a") - self.assertEqual(self.window.update_success, True) - self.assertEqual(self.window.progressBar.value(), 70) + assert self.window.update_success == True + assert self.window.progressBar.value() == 70 @mock.patch("subprocess.check_output", return_value=b"Failed to install pip dependencies") def test_setupThread_failure(self, check_output): @@ -125,16 +125,16 @@ def test_setupThread_failure(self, check_output): self.window.setup_thread.run() # Call run directly mock_open.assert_called_once_with(FLAG_LOCATION, "a") - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.progressBar.value(), 0) - self.assertEqual(self.window.failure_reason, strings.update_failed_generic_reason) + assert self.window.update_success == False + assert self.window.progressBar.value() == 0 + assert self.window.failure_reason == strings.update_failed_generic_reason @mock.patch("subprocess.check_output", return_value=b"Signature verification successful") def test_updateThread(self, check_output): with mock.patch.object(self.window, "setup_thread", return_value=MagicMock()): self.window.update_thread.run() # Call run directly - self.assertEqual(self.window.update_success, True) - self.assertEqual(self.window.progressBar.value(), 50) + assert self.window.update_success == True + assert self.window.progressBar.value() == 50 @mock.patch( "subprocess.check_output", @@ -143,8 +143,8 @@ def test_updateThread(self, check_output): def test_updateThread_failure(self, check_output): with mock.patch.object(self.window, "setup_thread", return_value=MagicMock()): self.window.update_thread.run() # Call run directly - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, strings.update_failed_sig_failure) + assert self.window.update_success == False + assert self.window.failure_reason == strings.update_failed_sig_failure @mock.patch( "subprocess.check_output", @@ -153,8 +153,8 @@ def test_updateThread_failure(self, check_output): def test_updateThread_generic_failure(self, check_output): with mock.patch.object(self.window, "setup_thread", return_value=MagicMock()): self.window.update_thread.run() # Call run directly - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, strings.update_failed_generic_reason) + assert self.window.update_success == False + assert self.window.failure_reason == strings.update_failed_generic_reason def test_get_sudo_password_when_password_provided(self): expected_password = "password" @@ -162,13 +162,13 @@ def test_get_sudo_password_when_password_provided(self): with mock.patch.object(QInputDialog, "getText", return_value=[expected_password, True]): sudo_password = self.window.get_sudo_password() - self.assertEqual(sudo_password, expected_password) + assert sudo_password == expected_password def test_get_sudo_password_when_password_not_provided(self): test_password = "" with mock.patch.object(QInputDialog, "getText", return_value=[test_password, False]): - self.assertIsNone(self.window.get_sudo_password()) + assert self.window.get_sudo_password() is None @mock.patch("pexpect.spawn") def test_tailsconfigThread_no_failures(self, pt): @@ -182,8 +182,8 @@ def test_tailsconfigThread_no_failures(self, pt): self.window.tails_thread.run() mock_remove.assert_called_once_with(FLAG_LOCATION) - self.assertIn("failed=0", self.window.output) - self.assertEqual(self.window.update_success, True) + assert "failed=0" in self.window.output + assert self.window.update_success == True @mock.patch("pexpect.spawn") def test_tailsconfigThread_generic_failure(self, pt): @@ -192,9 +192,9 @@ def test_tailsconfigThread_generic_failure(self, pt): before.decode.side_effect = ["SUDO: ", "failed=10 ERROR!!!!!"] child.before = before self.window.tails_thread.run() - self.assertNotIn("failed=0", self.window.output) - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_generic_reason) + assert "failed=0" not in self.window.output + assert self.window.update_success == False + assert self.window.failure_reason == strings.tailsconfig_failed_generic_reason @mock.patch("pexpect.spawn") def test_tailsconfigThread_sudo_password_is_wrong(self, pt): @@ -203,9 +203,9 @@ def test_tailsconfigThread_sudo_password_is_wrong(self, pt): before.decode.return_value = "stuff[sudo via ansible, key=blahblahblah" child.before = before self.window.tails_thread.run() - self.assertNotIn("failed=0", self.window.output) - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_sudo_password) + assert "failed=0" not in self.window.output + assert self.window.update_success == False + assert self.window.failure_reason == strings.tailsconfig_failed_sudo_password @mock.patch("pexpect.spawn") def test_tailsconfigThread_timeout(self, pt): @@ -214,9 +214,9 @@ def test_tailsconfigThread_timeout(self, pt): before.decode.side_effect = ["some data", pexpect.exceptions.TIMEOUT(1)] child.before = before self.window.tails_thread.run() - self.assertNotIn("failed=0", self.window.output) - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_timeout) + assert "failed=0" not in self.window.output + assert self.window.update_success == False + assert self.window.failure_reason == strings.tailsconfig_failed_timeout @mock.patch("pexpect.spawn") def test_tailsconfigThread_some_other_subprocess_error(self, pt): @@ -227,9 +227,9 @@ def test_tailsconfigThread_some_other_subprocess_error(self, pt): ) child.before = before self.window.tails_thread.run() - self.assertNotIn("failed=0", self.window.output) - self.assertEqual(self.window.update_success, False) - self.assertEqual(self.window.failure_reason, strings.tailsconfig_failed_generic_reason) + assert "failed=0" not in self.window.output + assert self.window.update_success == False + assert self.window.failure_reason == strings.tailsconfig_failed_generic_reason def test_tails_status_success(self): result = {"status": True, "output": "successful.", "failure_reason": ""} @@ -239,7 +239,7 @@ def test_tails_status_success(self): # We do remove the flag file if the update does finish mock_remove.assert_called_once_with(FLAG_LOCATION) - self.assertEqual(self.window.progressBar.value(), 100) + assert self.window.progressBar.value() == 100 def test_tails_status_failure(self): result = {"status": False, "output": "successful.", "failure_reason": "42"} @@ -249,14 +249,14 @@ def test_tails_status_failure(self): # We do not remove the flag file if the update does not finish mock_remove.assert_not_called() - self.assertEqual(self.window.progressBar.value(), 0) + assert self.window.progressBar.value() == 0 @mock.patch("journalist_gui.SecureDropUpdater.QtWidgets.QMessageBox") def test_no_update_without_password(self, mock_msgbox): with mock.patch("journalist_gui.SecureDropUpdater.password_is_set", return_value=False): self.window.update_securedrop() - self.assertEqual(self.window.pushButton.isEnabled(), True) - self.assertEqual(self.window.pushButton_2.isEnabled(), False) + assert self.window.pushButton.isEnabled() == True + assert self.window.pushButton_2.isEnabled() == False if __name__ == "__main__": diff --git a/molecule/testinfra/app-code/test_securedrop_app_code.py b/molecule/testinfra/app-code/test_securedrop_app_code.py --- a/molecule/testinfra/app-code/test_securedrop_app_code.py +++ b/molecule/testinfra/app-code/test_securedrop_app_code.py @@ -52,7 +52,7 @@ def test_unwanted_packages_absent(host, package): assert not host.package(package).is_installed [email protected]_in_prod [email protected]_in_prod() def test_securedrop_application_test_locale(host): """ Ensure both SecureDrop DEFAULT_LOCALE and SUPPORTED_LOCALES are present. @@ -66,7 +66,7 @@ def test_securedrop_application_test_locale(host): assert "\nSUPPORTED_LOCALES = ['el', 'ar', 'en_US']\n" in securedrop_config.content_string [email protected]_in_prod [email protected]_in_prod() def test_securedrop_application_test_journalist_key(host): """ Ensure the SecureDrop Application GPG public key file is present. diff --git a/molecule/testinfra/app/apache/test_apache_journalist_interface.py b/molecule/testinfra/app/apache/test_apache_journalist_interface.py --- a/molecule/testinfra/app/apache/test_apache_journalist_interface.py +++ b/molecule/testinfra/app/apache/test_apache_journalist_interface.py @@ -7,7 +7,7 @@ testinfra_hosts = [securedrop_test_vars.app_hostname] [email protected]("header, value", securedrop_test_vars.wanted_apache_headers.items()) [email protected](("header", "value"), securedrop_test_vars.wanted_apache_headers.items()) def test_apache_headers_journalist_interface(host, header, value): """ Test for expected headers in Document Interface vhost config. diff --git a/molecule/testinfra/app/apache/test_apache_source_interface.py b/molecule/testinfra/app/apache/test_apache_source_interface.py --- a/molecule/testinfra/app/apache/test_apache_source_interface.py +++ b/molecule/testinfra/app/apache/test_apache_source_interface.py @@ -7,7 +7,7 @@ testinfra_hosts = [securedrop_test_vars.app_hostname] [email protected]("header, value", securedrop_test_vars.wanted_apache_headers.items()) [email protected](("header", "value"), securedrop_test_vars.wanted_apache_headers.items()) def test_apache_headers_source_interface(host, header, value): """ Test for expected headers in Source Interface vhost config. diff --git a/molecule/testinfra/app/test_app_network.py b/molecule/testinfra/app/test_app_network.py --- a/molecule/testinfra/app/test_app_network.py +++ b/molecule/testinfra/app/test_app_network.py @@ -9,7 +9,7 @@ testinfra_hosts = [securedrop_test_vars.app_hostname] [email protected]_in_prod [email protected]_in_prod() def test_app_iptables_rules(host): local = host.get_host("local://") diff --git a/molecule/testinfra/app/test_appenv.py b/molecule/testinfra/app/test_appenv.py --- a/molecule/testinfra/app/test_appenv.py +++ b/molecule/testinfra/app/test_appenv.py @@ -15,7 +15,7 @@ def test_app_pip_deps(host, exp_pip_pkg): assert result.stdout.strip() == exp_pip_pkg["version"] [email protected]_in_prod [email protected]_in_prod() def test_app_wsgi(host): """ensure logging is enabled for source interface in staging""" f = host.file("/var/www/source.wsgi") @@ -35,14 +35,14 @@ def test_pidfile(host): @pytest.mark.parametrize( - "app_dir,owner", - ( + ("app_dir", "owner"), + [ ("/var/www/securedrop", "root"), ("/var/lib/securedrop", "www-data"), ("/var/lib/securedrop/store", "www-data"), ("/var/lib/securedrop/keys", "www-data"), ("/var/lib/securedrop/tmp", "www-data"), - ), + ], ) def test_app_directories(host, app_dir, owner): """ensure securedrop app directories exist with correct permissions""" @@ -87,7 +87,7 @@ def test_supervisor_not_installed(host): assert host.package("supervisor").is_installed is False [email protected]_in_prod [email protected]_in_prod() def test_gpg_key_in_keyring(host): """ensure test gpg key is present in app keyring""" with host.sudo(sdvars.securedrop_user): @@ -105,7 +105,7 @@ def test_ensure_logo(host): assert f.group == "root" [email protected]("user", ("root", "www-data")) [email protected]("user", ["root", "www-data"]) def test_empty_crontabs(host, user): """Ensure root + www-data crontabs are empty""" with host.sudo(): diff --git a/molecule/testinfra/app/test_ossec_agent.py b/molecule/testinfra/app/test_ossec_agent.py --- a/molecule/testinfra/app/test_ossec_agent.py +++ b/molecule/testinfra/app/test_ossec_agent.py @@ -39,7 +39,7 @@ def test_ossec_agent_installed(host): # Permissions don't match between Ansible and OSSEC deb packages postinst. [email protected] [email protected]() def test_ossec_keyfile_present(host): """ensure client keyfile for ossec-agent is present""" pattern = "^1024 {} {} [0-9a-f]{{64}}$".format( diff --git a/molecule/testinfra/app/test_smoke.py b/molecule/testinfra/app/test_smoke.py --- a/molecule/testinfra/app/test_smoke.py +++ b/molecule/testinfra/app/test_smoke.py @@ -9,12 +9,12 @@ @pytest.mark.parametrize( - "name,url,curl_flags", - ( + ("name", "url", "curl_flags"), + [ # We pass -L to follow the redirect from / to /login ("journalist", "http://localhost:8080/", "L"), ("source", "http://localhost:80/", ""), - ), + ], ) def test_interface_up(host, name, url, curl_flags): """ diff --git a/molecule/testinfra/app/test_tor_config.py b/molecule/testinfra/app/test_tor_config.py --- a/molecule/testinfra/app/test_tor_config.py +++ b/molecule/testinfra/app/test_tor_config.py @@ -68,7 +68,7 @@ def test_tor_torrc_sandbox(host): assert not f.contains("^.*Sandbox.*$") [email protected]_in_prod [email protected]_in_prod() def test_tor_v2_onion_url_file_absent(host): v2_url_filepath = "/var/lib/securedrop/source_v2_url" with host.sudo(): @@ -76,7 +76,7 @@ def test_tor_v2_onion_url_file_absent(host): assert not f.exists [email protected]_in_prod [email protected]_in_prod() def test_tor_v3_onion_url_readable_by_app(host): v3_url_filepath = "/var/lib/securedrop/source_v3_url" with host.sudo(): diff --git a/molecule/testinfra/app/test_tor_hidden_services.py b/molecule/testinfra/app/test_tor_hidden_services.py --- a/molecule/testinfra/app/test_tor_hidden_services.py +++ b/molecule/testinfra/app/test_tor_hidden_services.py @@ -8,7 +8,7 @@ # Prod Tor services may have unexpected configs # TODO: read from admin workstation site-specific file if available [email protected]_in_prod [email protected]_in_prod() @pytest.mark.parametrize("tor_service", sdvars.tor_services) def test_tor_service_directories(host, tor_service): """ @@ -22,7 +22,7 @@ def test_tor_service_directories(host, tor_service): assert f.group == "debian-tor" [email protected]_in_prod [email protected]_in_prod() @pytest.mark.parametrize("tor_service", sdvars.tor_services) def test_tor_service_hostnames(host, tor_service): """ @@ -57,7 +57,7 @@ def test_tor_service_hostnames(host, tor_service): assert re.search(f"^{ths_hostname_regex_v3}$", f.content_string) [email protected]_in_prod [email protected]_in_prod() @pytest.mark.parametrize("tor_service", sdvars.tor_services) def test_tor_services_config(host, tor_service): """ diff --git a/molecule/testinfra/common/test_automatic_updates.py b/molecule/testinfra/common/test_automatic_updates.py --- a/molecule/testinfra/common/test_automatic_updates.py +++ b/molecule/testinfra/common/test_automatic_updates.py @@ -81,7 +81,7 @@ def test_sources_list(host, repo): } [email protected]("k, v", apt_config_options.items()) [email protected](("k", "v"), apt_config_options.items()) def test_unattended_upgrades_config(host, k, v): """ Ensures the apt and unattended-upgrades config is correct only under Ubuntu Focal diff --git a/molecule/testinfra/common/test_user_config.py b/molecule/testinfra/common/test_user_config.py --- a/molecule/testinfra/common/test_user_config.py +++ b/molecule/testinfra/common/test_user_config.py @@ -88,7 +88,7 @@ def test_tmux_installed(host): assert host.package("tmux").is_installed [email protected]_in_prod [email protected]_in_prod() def test_sudoers_tmux_env_deprecated(host): """ Previous version of the Ansible config set the tmux config diff --git a/molecule/testinfra/mon/test_mon_network.py b/molecule/testinfra/mon/test_mon_network.py --- a/molecule/testinfra/mon/test_mon_network.py +++ b/molecule/testinfra/mon/test_mon_network.py @@ -9,7 +9,7 @@ testinfra_hosts = [securedrop_test_vars.monitor_hostname] [email protected]_in_prod [email protected]_in_prod() def test_mon_iptables_rules(host): local = host.get_host("local://") @@ -54,7 +54,7 @@ def test_mon_iptables_rules(host): assert iptables_expected == iptables [email protected]_in_prod [email protected]_in_prod() @pytest.mark.parametrize( "ossec_service", [ diff --git a/molecule/testinfra/mon/test_ossec_server.py b/molecule/testinfra/mon/test_ossec_server.py --- a/molecule/testinfra/mon/test_ossec_server.py +++ b/molecule/testinfra/mon/test_ossec_server.py @@ -32,7 +32,7 @@ def test_ossec_service_start_style(host): # Permissions don't match between Ansible and OSSEC deb packages postinst. [email protected] [email protected]() @pytest.mark.parametrize( "keyfile", [ @@ -59,7 +59,7 @@ def test_ossec_keyfiles(host, keyfile): # Permissions don't match between Ansible and OSSEC deb packages postinst. [email protected] [email protected]() def test_procmail_log(host): """ Ensure procmail log file exist with proper ownership. diff --git a/molecule/testinfra/ossec/test_journalist_mail.py b/molecule/testinfra/ossec/test_journalist_mail.py --- a/molecule/testinfra/ossec/test_journalist_mail.py +++ b/molecule/testinfra/ossec/test_journalist_mail.py @@ -11,7 +11,7 @@ class TestBase: @pytest.fixture(autouse=True) - def only_mon_staging_sudo(self, host): + def only_mon_staging_sudo(self, host): # noqa: PT004 if host.backend.host != "mon-staging": pytest.skip() diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -104,7 +104,7 @@ def setup_journalist_key_and_gpg_folder() -> Generator[Tuple[str, Path], None, N shutil.rmtree(tmp_gpg_dir, ignore_errors=True) [email protected](scope="function") [email protected]() def config( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, str], @@ -124,7 +124,7 @@ def config( yield config [email protected](scope="function") [email protected]() def alembic_config(config: SecureDropConfig) -> Generator[Path, None, None]: base_dir = path.join(path.dirname(__file__), "..") migrations_dir = path.join(base_dir, "alembic") @@ -153,12 +153,12 @@ def alembic_config(config: SecureDropConfig) -> Generator[Path, None, None]: os.environ["SECUREDROP_ENV"] = previous_env_value [email protected](scope="function") [email protected]() def app_storage(config: SecureDropConfig) -> "Storage": return Storage(str(config.STORE_DIR), str(config.TEMP_DIR)) [email protected](scope="function") [email protected]() def source_app(config: SecureDropConfig, app_storage: Storage) -> Generator[Flask, None, None]: with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = app_storage @@ -173,7 +173,7 @@ def source_app(config: SecureDropConfig, app_storage: Storage) -> Generator[Flas db.drop_all() [email protected](scope="function") [email protected]() def journalist_app(config: SecureDropConfig, app_storage: Storage) -> Generator[Flask, None, None]: with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = app_storage @@ -188,7 +188,7 @@ def journalist_app(config: SecureDropConfig, app_storage: Storage) -> Generator[ db.drop_all() [email protected](scope="function") [email protected]() def test_journo(journalist_app: Flask) -> Dict[str, Any]: with journalist_app.app_context(): user, password = utils.db_helper.init_journalist(is_admin=False) @@ -206,7 +206,7 @@ def test_journo(journalist_app: Flask) -> Dict[str, Any]: } [email protected](scope="function") [email protected]() def test_admin(journalist_app: Flask) -> Dict[str, Any]: with journalist_app.app_context(): user, password = utils.db_helper.init_journalist(is_admin=True) @@ -221,7 +221,7 @@ def test_admin(journalist_app: Flask) -> Dict[str, Any]: } [email protected](scope="function") [email protected]() def test_source(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: with journalist_app.app_context(): passphrase = PassphraseGenerator.get_default().generate_passphrase() @@ -243,7 +243,7 @@ def test_source(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: } [email protected](scope="function") [email protected]() def test_submissions(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: with journalist_app.app_context(): source, codename = utils.db_helper.init_source(app_storage) @@ -257,7 +257,7 @@ def test_submissions(journalist_app: Flask, app_storage: Storage) -> Dict[str, A } [email protected](scope="function") [email protected]() def test_files(journalist_app, test_journo, app_storage): with journalist_app.app_context(): source, codename = utils.db_helper.init_source(app_storage) @@ -273,7 +273,7 @@ def test_files(journalist_app, test_journo, app_storage): } [email protected](scope="function") [email protected]() def test_files_deleted_journalist(journalist_app, test_journo, app_storage): with journalist_app.app_context(): source, codename = utils.db_helper.init_source(app_storage) @@ -292,7 +292,7 @@ def test_files_deleted_journalist(journalist_app, test_journo, app_storage): } [email protected](scope="function") [email protected]() def journalist_api_token(journalist_app, test_journo): with journalist_app.test_client() as app: valid_token = TOTP(test_journo["otp_secret"]).now() diff --git a/securedrop/tests/functional/app_navigators/journalist_app_nav.py b/securedrop/tests/functional/app_navigators/journalist_app_nav.py --- a/securedrop/tests/functional/app_navigators/journalist_app_nav.py +++ b/securedrop/tests/functional/app_navigators/journalist_app_nav.py @@ -118,7 +118,7 @@ def journalist_downloads_first_message( lambda: self.driver.find_element_by_css_selector("table#submissions") ) submissions = self.driver.find_elements_by_css_selector("#submissions a") - assert 1 == len(submissions) + assert len(submissions) == 1 file_url = submissions[0].get_attribute("href") # Downloading files with Selenium is tricky because it cannot automate @@ -208,16 +208,14 @@ def journalist_confirms_delete_selected(self) -> None: ActionChains(self.driver).move_to_element(confirm_btn).click().perform() def get_submission_checkboxes_on_current_page(self): - checkboxes = self.driver.find_elements_by_name("doc_names_selected") - return checkboxes + return self.driver.find_elements_by_name("doc_names_selected") def count_submissions_on_current_page(self) -> int: return len(self.get_submission_checkboxes_on_current_page()) def get_sources_on_index_page(self): assert self.is_on_journalist_homepage() - sources = self.driver.find_elements_by_class_name("code-name") - return sources + return self.driver.find_elements_by_class_name("code-name") def count_sources_on_index_page(self) -> int: return len(self.get_sources_on_index_page()) diff --git a/securedrop/tests/functional/app_navigators/source_app_nav.py b/securedrop/tests/functional/app_navigators/source_app_nav.py --- a/securedrop/tests/functional/app_navigators/source_app_nav.py +++ b/securedrop/tests/functional/app_navigators/source_app_nav.py @@ -128,8 +128,7 @@ def message_submitted(): return notification.text # Return the confirmation notification - notification_text = self.nav_helper.wait_for(message_submitted) - return notification_text + return self.nav_helper.wait_for(message_submitted) def source_submits_a_file(self, file_content: str = "S3cr3t f1l3") -> None: # Write the content to a file diff --git a/securedrop/tests/functional/conftest.py b/securedrop/tests/functional/conftest.py --- a/securedrop/tests/functional/conftest.py +++ b/securedrop/tests/functional/conftest.py @@ -21,14 +21,14 @@ # Function-scoped so that tests can be run in parallel if needed [email protected](scope="function") [email protected]() def firefox_web_driver() -> WebDriver: with get_web_driver(web_driver_type=WebDriverTypeEnum.FIREFOX) as web_driver: yield web_driver # Function-scoped so that tests can be run in parallel if needed [email protected](scope="function") [email protected]() def tor_browser_web_driver() -> WebDriver: with get_web_driver(web_driver_type=WebDriverTypeEnum.TOR_BROWSER) as web_driver: yield web_driver @@ -216,7 +216,7 @@ def sd_servers( yield sd_servers_result [email protected](scope="function") [email protected]() def sd_servers_with_clean_state( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, Path], @@ -239,7 +239,7 @@ def sd_servers_with_clean_state( yield sd_servers_result [email protected](scope="function") [email protected]() def sd_servers_with_submitted_file( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, Path], diff --git a/securedrop/tests/functional/pageslayout/accessibility.py b/securedrop/tests/functional/pageslayout/accessibility.py --- a/securedrop/tests/functional/pageslayout/accessibility.py +++ b/securedrop/tests/functional/pageslayout/accessibility.py @@ -92,7 +92,7 @@ def sniff_accessibility_issues(driver: WebDriver, locale: str, test_name: str) - """ # 1. Retrieve/compute required data - with open(f"/usr/local/lib/node_modules/html_codesniffer/build/HTMLCS.js") as htmlcs: + with open("/usr/local/lib/node_modules/html_codesniffer/build/HTMLCS.js") as htmlcs: html_codesniffer = htmlcs.read() errors_dir = _ACCESSIBILITY_DIR / locale / "errors" diff --git a/securedrop/tests/functional/pageslayout/test_journalist.py b/securedrop/tests/functional/pageslayout/test_journalist.py --- a/securedrop/tests/functional/pageslayout/test_journalist.py +++ b/securedrop/tests/functional/pageslayout/test_journalist.py @@ -21,7 +21,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestJournalistLayout: def test_login_index_and_edit(self, locale, sd_servers, firefox_web_driver): # Given an SD server diff --git a/securedrop/tests/functional/pageslayout/test_journalist_account.py b/securedrop/tests/functional/pageslayout/test_journalist_account.py --- a/securedrop/tests/functional/pageslayout/test_journalist_account.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_account.py @@ -24,7 +24,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestJournalistLayoutAccount: def test_account_edit_and_set_hotp_secret( self, locale, sd_servers_with_clean_state, firefox_web_driver diff --git a/securedrop/tests/functional/pageslayout/test_journalist_admin.py b/securedrop/tests/functional/pageslayout/test_journalist_admin.py --- a/securedrop/tests/functional/pageslayout/test_journalist_admin.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_admin.py @@ -28,7 +28,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestAdminLayoutAddAndEditUser: def test_admin_adds_user_hotp_and_edits_hotp( self, locale, sd_servers_with_clean_state, firefox_web_driver @@ -219,7 +219,7 @@ def _retry_2fa_pop_ups( @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestAdminLayoutEditConfig: def test_admin_changes_logo(self, locale, sd_servers_with_clean_state, firefox_web_driver): # Given an SD server diff --git a/securedrop/tests/functional/pageslayout/test_journalist_col.py b/securedrop/tests/functional/pageslayout/test_journalist_col.py --- a/securedrop/tests/functional/pageslayout/test_journalist_col.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_col.py @@ -37,8 +37,8 @@ def _create_source_and_submission_and_delete_source_key(config_in_use: SecureDro EncryptionManager.get_default().delete_source_key_pair(source_user.filesystem_id) [email protected](scope="function") -def _sd_servers_with_deleted_source_key( [email protected]() +def sd_servers_with_deleted_source_key( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, Path], ) -> Generator[SdServersFixtureResult, None, None]: @@ -64,7 +64,7 @@ def _sd_servers_with_deleted_source_key( @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestJournalistLayoutCol: def test_col_with_and_without_documents( self, locale, sd_servers_with_submitted_file, firefox_web_driver @@ -105,19 +105,19 @@ def submission_deleted() -> None: journ_app_nav.nav_helper.wait_for(submission_deleted) save_static_data(journ_app_nav.driver, locale, "journalist-col_no_document") - def test_col_has_no_key(self, locale, _sd_servers_with_deleted_source_key, firefox_web_driver): + def test_col_has_no_key(self, locale, sd_servers_with_deleted_source_key, firefox_web_driver): # Given an SD server with an already-submitted file, but the source's key was deleted # And a journalist logging into the journalist interface locale_with_commas = locale.replace("_", "-") journ_app_nav = JournalistAppNavigator( - journalist_app_base_url=_sd_servers_with_deleted_source_key.journalist_app_base_url, + journalist_app_base_url=sd_servers_with_deleted_source_key.journalist_app_base_url, web_driver=firefox_web_driver, accept_languages=locale_with_commas, ) journ_app_nav.journalist_logs_in( - username=_sd_servers_with_deleted_source_key.journalist_username, - password=_sd_servers_with_deleted_source_key.journalist_password, - otp_secret=_sd_servers_with_deleted_source_key.journalist_otp_secret, + username=sd_servers_with_deleted_source_key.journalist_username, + password=sd_servers_with_deleted_source_key.journalist_password, + otp_secret=sd_servers_with_deleted_source_key.journalist_otp_secret, ) # Take a screenshot of the source's page after their key was deleted diff --git a/securedrop/tests/functional/pageslayout/test_journalist_delete.py b/securedrop/tests/functional/pageslayout/test_journalist_delete.py --- a/securedrop/tests/functional/pageslayout/test_journalist_delete.py +++ b/securedrop/tests/functional/pageslayout/test_journalist_delete.py @@ -21,7 +21,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestJournalistLayoutDelete: def test_delete_none(self, locale, sd_servers_with_submitted_file, firefox_web_driver): # Given an SD server with a file submitted by a source diff --git a/securedrop/tests/functional/pageslayout/test_source.py b/securedrop/tests/functional/pageslayout/test_source.py --- a/securedrop/tests/functional/pageslayout/test_source.py +++ b/securedrop/tests/functional/pageslayout/test_source.py @@ -21,7 +21,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestSourceLayout: def test(self, locale, sd_servers_with_clean_state, tor_browser_web_driver): # Given a source user accessing the app from their browser diff --git a/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py b/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py --- a/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py +++ b/securedrop/tests/functional/pageslayout/test_source_layout_torbrowser.py @@ -22,7 +22,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestSourceLayoutTorBrowser: def test_index_and_logout(self, locale, sd_servers): # Given a source user accessing the app from their browser diff --git a/securedrop/tests/functional/pageslayout/test_source_session_layout.py b/securedrop/tests/functional/pageslayout/test_source_session_layout.py --- a/securedrop/tests/functional/pageslayout/test_source_session_layout.py +++ b/securedrop/tests/functional/pageslayout/test_source_session_layout.py @@ -13,7 +13,7 @@ @pytest.fixture(scope="session") -def _sd_servers_with_short_timeout( +def sd_servers_with_short_timeout( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, str], ) -> Generator[SdServersFixtureResult, None, None]: @@ -35,14 +35,14 @@ def _sd_servers_with_short_timeout( @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestSourceAppSessionTimeout: - def test_source_session_timeout(self, locale, _sd_servers_with_short_timeout): + def test_source_session_timeout(self, locale, sd_servers_with_short_timeout): # Given an SD server with a very short session timeout # And a source user accessing the source app from their browser locale_with_commas = locale.replace("_", "-") with SourceAppNavigator.using_tor_browser_web_driver( - source_app_base_url=_sd_servers_with_short_timeout.source_app_base_url, + source_app_base_url=sd_servers_with_short_timeout.source_app_base_url, accept_languages=locale_with_commas, ) as navigator: diff --git a/securedrop/tests/functional/pageslayout/test_source_static_pages.py b/securedrop/tests/functional/pageslayout/test_source_static_pages.py --- a/securedrop/tests/functional/pageslayout/test_source_static_pages.py +++ b/securedrop/tests/functional/pageslayout/test_source_static_pages.py @@ -6,7 +6,7 @@ from version import __version__ [email protected] [email protected]() class TestSourceAppStaticPages: @pytest.mark.parametrize("locale", list_locales()) def test_notfound(self, locale, sd_servers): diff --git a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py --- a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py +++ b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py @@ -7,7 +7,7 @@ @pytest.mark.parametrize("locale", list_locales()) [email protected] [email protected]() class TestSubmitAndRetrieveFile: def test_submit_and_retrieve_happy_path( self, locale, sd_servers_with_clean_state, tor_browser_web_driver, firefox_web_driver @@ -109,7 +109,7 @@ def _journalist_stars_and_unstars_single_message(journ_app_nav: JournalistAppNav def message_starred(): starred = journ_app_nav.driver.find_elements_by_id("starred-source-link-1") - assert 1 == len(starred) + assert len(starred) == 1 journ_app_nav.nav_helper.wait_for(message_starred) diff --git a/securedrop/tests/functional/test_admin_interface.py b/securedrop/tests/functional/test_admin_interface.py --- a/securedrop/tests/functional/test_admin_interface.py +++ b/securedrop/tests/functional/test_admin_interface.py @@ -167,7 +167,7 @@ def _create_second_journalist(config_in_use: SecureDropConfig) -> None: db_session_for_sd_servers.commit() [email protected](scope="function") [email protected]() def sd_servers_with_second_journalist( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, Path], diff --git a/securedrop/tests/functional/test_journalist.py b/securedrop/tests/functional/test_journalist.py --- a/securedrop/tests/functional/test_journalist.py +++ b/securedrop/tests/functional/test_journalist.py @@ -374,8 +374,8 @@ def one_source_no_files(): journ_app_nav.nav_helper.wait_for(one_source_no_files) [email protected](scope="function") -def _sd_servers_with_missing_file( [email protected]() +def sd_servers_with_missing_file( setup_journalist_key_and_gpg_folder: Tuple[str, Path], setup_rqworker: Tuple[str, Path], ) -> Generator[SdServersFixtureResult, None, None]: @@ -406,17 +406,17 @@ class TestJournalistMissingFile: """Test error handling when a message file has been deleted from disk but remains in the database. Ref #4787.""" - def test_download_source_unread(self, _sd_servers_with_missing_file, firefox_web_driver): + def test_download_source_unread(self, sd_servers_with_missing_file, firefox_web_driver): # Given an SD server with a submission whose file was deleted from disk # And a journalist logged into the journalist interface journ_app_nav = JournalistAppNavigator( - journalist_app_base_url=_sd_servers_with_missing_file.journalist_app_base_url, + journalist_app_base_url=sd_servers_with_missing_file.journalist_app_base_url, web_driver=firefox_web_driver, ) journ_app_nav.journalist_logs_in( - username=_sd_servers_with_missing_file.journalist_username, - password=_sd_servers_with_missing_file.journalist_password, - otp_secret=_sd_servers_with_missing_file.journalist_otp_secret, + username=sd_servers_with_missing_file.journalist_username, + password=sd_servers_with_missing_file.journalist_password, + otp_secret=sd_servers_with_missing_file.journalist_otp_secret, ) # When the journalist clicks on the source's "n unread" button @@ -441,19 +441,17 @@ def _journalist_sees_missing_file_error_message(journ_app_nav: JournalistAppNavi assert notification.text in error_msg - def test_select_source_and_download_all( - self, _sd_servers_with_missing_file, firefox_web_driver - ): + def test_select_source_and_download_all(self, sd_servers_with_missing_file, firefox_web_driver): # Given an SD server with a submission whose file was deleted from disk # And a journalist logged into the journalist interface journ_app_nav = JournalistAppNavigator( - journalist_app_base_url=_sd_servers_with_missing_file.journalist_app_base_url, + journalist_app_base_url=sd_servers_with_missing_file.journalist_app_base_url, web_driver=firefox_web_driver, ) journ_app_nav.journalist_logs_in( - username=_sd_servers_with_missing_file.journalist_username, - password=_sd_servers_with_missing_file.journalist_password, - otp_secret=_sd_servers_with_missing_file.journalist_otp_secret, + username=sd_servers_with_missing_file.journalist_username, + password=sd_servers_with_missing_file.journalist_password, + otp_secret=sd_servers_with_missing_file.journalist_otp_secret, ) # When the journalist selects the source and then clicks the "Download" button @@ -467,18 +465,18 @@ def test_select_source_and_download_all( journ_app_nav.is_on_journalist_homepage() def test_select_source_and_download_unread( - self, _sd_servers_with_missing_file, firefox_web_driver + self, sd_servers_with_missing_file, firefox_web_driver ): # Given an SD server with a submission whose file was deleted from disk # And a journalist logged into the journalist interface journ_app_nav = JournalistAppNavigator( - journalist_app_base_url=_sd_servers_with_missing_file.journalist_app_base_url, + journalist_app_base_url=sd_servers_with_missing_file.journalist_app_base_url, web_driver=firefox_web_driver, ) journ_app_nav.journalist_logs_in( - username=_sd_servers_with_missing_file.journalist_username, - password=_sd_servers_with_missing_file.journalist_password, - otp_secret=_sd_servers_with_missing_file.journalist_otp_secret, + username=sd_servers_with_missing_file.journalist_username, + password=sd_servers_with_missing_file.journalist_password, + otp_secret=sd_servers_with_missing_file.journalist_otp_secret, ) # When the journalist selects the source then clicks the "Download Unread" button @@ -491,17 +489,17 @@ def test_select_source_and_download_unread( self._journalist_sees_missing_file_error_message(journ_app_nav) journ_app_nav.is_on_journalist_homepage() - def test_download_message(self, _sd_servers_with_missing_file, firefox_web_driver): + def test_download_message(self, sd_servers_with_missing_file, firefox_web_driver): # Given an SD server with a submission whose file was deleted from disk # And a journalist logged into the journalist interface journ_app_nav = JournalistAppNavigator( - journalist_app_base_url=_sd_servers_with_missing_file.journalist_app_base_url, + journalist_app_base_url=sd_servers_with_missing_file.journalist_app_base_url, web_driver=firefox_web_driver, ) journ_app_nav.journalist_logs_in( - username=_sd_servers_with_missing_file.journalist_username, - password=_sd_servers_with_missing_file.journalist_password, - otp_secret=_sd_servers_with_missing_file.journalist_otp_secret, + username=sd_servers_with_missing_file.journalist_username, + password=sd_servers_with_missing_file.journalist_password, + otp_secret=sd_servers_with_missing_file.journalist_otp_secret, ) # When the journalist clicks on the individual message from the source page @@ -512,7 +510,7 @@ def test_download_message(self, _sd_servers_with_missing_file, firefox_web_drive lambda: journ_app_nav.driver.find_element_by_css_selector("table#submissions") ) submissions = journ_app_nav.driver.find_elements_by_css_selector("#submissions a") - assert 1 == len(submissions) + assert len(submissions) == 1 file_link = submissions[0] file_link.click() @@ -528,18 +526,18 @@ def _journalist_is_on_collection_page(journ_app_nav: JournalistAppNavigator) -> ) def test_select_message_and_download_selected( - self, _sd_servers_with_missing_file, firefox_web_driver + self, sd_servers_with_missing_file, firefox_web_driver ): # Given an SD server with a submission whose file was deleted from disk # And a journalist logged into the journalist interface journ_app_nav = JournalistAppNavigator( - journalist_app_base_url=_sd_servers_with_missing_file.journalist_app_base_url, + journalist_app_base_url=sd_servers_with_missing_file.journalist_app_base_url, web_driver=firefox_web_driver, ) journ_app_nav.journalist_logs_in( - username=_sd_servers_with_missing_file.journalist_username, - password=_sd_servers_with_missing_file.journalist_password, - otp_secret=_sd_servers_with_missing_file.journalist_otp_secret, + username=sd_servers_with_missing_file.journalist_username, + password=sd_servers_with_missing_file.journalist_password, + otp_secret=sd_servers_with_missing_file.journalist_otp_secret, ) # When the journalist selects the individual message from the source page # and clicks "Download Selected" diff --git a/securedrop/tests/functional/test_source_cancels.py b/securedrop/tests/functional/test_source_cancels.py --- a/securedrop/tests/functional/test_source_cancels.py +++ b/securedrop/tests/functional/test_source_cancels.py @@ -31,4 +31,4 @@ def test_source_cancels_at_submit_page(self, sd_servers, tor_browser_web_driver) # And the right message is displayed heading = source_app_nav.driver.find_element_by_id("submit-heading") - assert "Submit Files or Messages" == heading.text + assert heading.text == "Submit Files or Messages" diff --git a/securedrop/tests/functional/test_source_designation_collision.py b/securedrop/tests/functional/test_source_designation_collision.py --- a/securedrop/tests/functional/test_source_designation_collision.py +++ b/securedrop/tests/functional/test_source_designation_collision.py @@ -7,7 +7,7 @@ @pytest.fixture(scope="session") -def _sd_servers_with_designation_collisions(setup_journalist_key_and_gpg_folder, setup_rqworker): +def sd_servers_with_designation_collisions(setup_journalist_key_and_gpg_folder, setup_rqworker): """Spawn source and journalist apps that can only generate a single journalist designation.""" # Generate a config that can only generate a single journalist designation folder_for_fixture_path = Path("/tmp/sd-tests/functional-designation-collisions") @@ -36,9 +36,9 @@ def _sd_servers_with_designation_collisions(setup_journalist_key_and_gpg_folder, class TestSourceAppDesignationCollision: - def test(self, _sd_servers_with_designation_collisions, tor_browser_web_driver): + def test(self, sd_servers_with_designation_collisions, tor_browser_web_driver): navigator = SourceAppNavigator( - source_app_base_url=_sd_servers_with_designation_collisions.source_app_base_url, + source_app_base_url=sd_servers_with_designation_collisions.source_app_base_url, web_driver=tor_browser_web_driver, ) diff --git a/securedrop/tests/functional/test_source_warnings.py b/securedrop/tests/functional/test_source_warnings.py --- a/securedrop/tests/functional/test_source_warnings.py +++ b/securedrop/tests/functional/test_source_warnings.py @@ -7,7 +7,7 @@ from tests.functional.web_drivers import _FIREFOX_PATH [email protected] [email protected]() def orbot_web_driver(sd_servers): # Create new profile and driver with the orbot user agent orbot_user_agent = "Mozilla/5.0 (Android; Mobile; rv:52.0) Gecko/20100101 Firefox/52.0" diff --git a/securedrop/tests/migrations/migration_15ac9509fc68.py b/securedrop/tests/migrations/migration_15ac9509fc68.py --- a/securedrop/tests/migrations/migration_15ac9509fc68.py +++ b/securedrop/tests/migrations/migration_15ac9509fc68.py @@ -180,4 +180,3 @@ def check_downgrade(self): """We don't need to check anything on this downgrade because the migration drops all the tables. Thus, there is nothing to do. """ - pass diff --git a/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py b/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py --- a/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py +++ b/securedrop/tests/migrations/migration_2d0ce3ee5bdc.py @@ -77,8 +77,7 @@ def extract(app): GROUP BY j.id ORDER BY j.id """ - res = list(db.session.execute(text(sql))) - return res + return list(db.session.execute(text(sql))) class UpgradeTester(Helper): diff --git a/securedrop/tests/migrations/migration_2e24fc7536e8.py b/securedrop/tests/migrations/migration_2e24fc7536e8.py --- a/securedrop/tests/migrations/migration_2e24fc7536e8.py +++ b/securedrop/tests/migrations/migration_2e24fc7536e8.py @@ -109,11 +109,9 @@ def load_data(self): """This function loads data into the database and filesystem. It is executed before the downgrade. """ - pass def check_downgrade(self): """This function is run after the downgrade and verifies the state of the database or filesystem. It MUST raise an exception if the check fails. """ - pass diff --git a/securedrop/tests/migrations/migration_35513370ba0d.py b/securedrop/tests/migrations/migration_35513370ba0d.py --- a/securedrop/tests/migrations/migration_35513370ba0d.py +++ b/securedrop/tests/migrations/migration_35513370ba0d.py @@ -71,9 +71,7 @@ def check_downgrade(self): """ After downgrade, using `deleted_at` in a query should raise an exception """ - with self.app.app_context(): - with pytest.raises(sqlalchemy.exc.OperationalError): - sources = db.engine.execute( - sqlalchemy.text("SELECT * FROM sources WHERE deleted_at IS NOT NULL") - ).fetchall() - assert len(sources) == 0 + with self.app.app_context(), pytest.raises(sqlalchemy.exc.OperationalError): + db.engine.execute( + sqlalchemy.text("SELECT * FROM sources WHERE deleted_at IS NOT NULL") + ).fetchall() diff --git a/securedrop/tests/migrations/migration_92fba0be98e9.py b/securedrop/tests/migrations/migration_92fba0be98e9.py --- a/securedrop/tests/migrations/migration_92fba0be98e9.py +++ b/securedrop/tests/migrations/migration_92fba0be98e9.py @@ -58,11 +58,7 @@ def check_downgrade(self): """ After downgrade, using `organization_name` in a query should raise an exception """ - with self.app.app_context(): - with pytest.raises(sqlalchemy.exc.OperationalError): - configs = db.engine.execute( - sqlalchemy.text( - "SELECT * FROM instance_config WHERE organization_name IS NOT NULL" - ) - ).fetchall() - assert len(configs) == 0 + with self.app.app_context(), pytest.raises(sqlalchemy.exc.OperationalError): + db.engine.execute( + sqlalchemy.text("SELECT * FROM instance_config WHERE organization_name IS NOT NULL") + ).fetchall() diff --git a/securedrop/tests/migrations/migration_b060f38c0c31.py b/securedrop/tests/migrations/migration_b060f38c0c31.py --- a/securedrop/tests/migrations/migration_b060f38c0c31.py +++ b/securedrop/tests/migrations/migration_b060f38c0c31.py @@ -35,8 +35,8 @@ class UpgradeTester: """ source_count = 10 - original_sources = {} # type: Dict[str, Any] - source_submissions = {} # type: Dict[str, Any] + original_sources: Dict[str, Any] = {} + source_submissions: Dict[str, Any] = {} def __init__(self, config): self.config = config @@ -57,7 +57,7 @@ def load_data(self): self.source_submissions[s.id] = db.engine.execute( text("SELECT * FROM submissions WHERE source_id = :source_id"), - **{"source_id": s.id}, + source_id=s.id, ).fetchall() def add_source(self): @@ -101,7 +101,7 @@ def check_upgrade(self): source_submissions = db.engine.execute( text("SELECT * FROM submissions WHERE source_id = :source_id"), - **{"source_id": source.id}, + source_id=source.id, ).fetchall() assert source_submissions == self.source_submissions[source.id] @@ -112,8 +112,8 @@ class DowngradeTester: """ source_count = 10 - original_sources = {} # type: Dict[str, Any] - source_submissions = {} # type: Dict[str, Any] + original_sources: Dict[str, Any] = {} + source_submissions: Dict[str, Any] = {} def __init__(self, config): self.config = config @@ -156,7 +156,7 @@ def load_data(self): self.source_submissions[s.id] = db.engine.execute( text("SELECT * FROM submissions WHERE source_id = :source_id"), - **{"source_id": s.id}, + source_id=s.id, ).fetchall() def check_downgrade(self): @@ -177,6 +177,6 @@ def check_downgrade(self): source_submissions = db.engine.execute( text("SELECT * FROM submissions WHERE source_id = :source_id"), - **{"source_id": source.id}, + source_id=source.id, ).fetchall() assert source_submissions == self.source_submissions[source.id] diff --git a/securedrop/tests/migrations/migration_b58139cfdc8c.py b/securedrop/tests/migrations/migration_b58139cfdc8c.py --- a/securedrop/tests/migrations/migration_b58139cfdc8c.py +++ b/securedrop/tests/migrations/migration_b58139cfdc8c.py @@ -127,7 +127,6 @@ def __init__(self, config): self.storage = Storage(str(config.STORE_DIR), str(config.TEMP_DIR)) def load_data(self): - global DATA with mock.patch("store.Storage.get_default") as mock_storage_global: mock_storage_global.return_value = self.storage with self.app.app_context(): @@ -159,7 +158,6 @@ def check_upgrade(self): log file in `/tmp/`. The other part of the migration, creating a table, cannot be tested regardless. """ - pass class DowngradeTester(Helper): diff --git a/securedrop/tests/migrations/migration_b7f98cfd6a70.py b/securedrop/tests/migrations/migration_b7f98cfd6a70.py --- a/securedrop/tests/migrations/migration_b7f98cfd6a70.py +++ b/securedrop/tests/migrations/migration_b7f98cfd6a70.py @@ -86,11 +86,9 @@ def load_data(self): """This function loads data into the database and filesystem. It is executed before the downgrade. """ - pass def check_downgrade(self): """This function is run after the downgrade and verifies the state of the database or filesystem. It MUST raise an exception if the check fails. """ - pass diff --git a/securedrop/tests/migrations/migration_e0a525cbab83.py b/securedrop/tests/migrations/migration_e0a525cbab83.py --- a/securedrop/tests/migrations/migration_e0a525cbab83.py +++ b/securedrop/tests/migrations/migration_e0a525cbab83.py @@ -121,7 +121,7 @@ def check_upgrade(self): assert len(replies) == self.JOURNO_NUM - 1 for reply in replies: - assert reply.deleted_by_source == False # noqa + assert reply.deleted_by_source == False class DowngradeTester: diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -22,7 +22,7 @@ WHITESPACE_REGEX = re.compile(r"\s+") [email protected](scope="function") [email protected]() def _reset_db(config: SecureDropConfig) -> None: # The config fixture creates all the models in the DB, but most alembic tests expect an # empty DB, so we reset the DB via this fixture diff --git a/securedrop/tests/test_encryption.py b/securedrop/tests/test_encryption.py --- a/securedrop/tests/test_encryption.py +++ b/securedrop/tests/test_encryption.py @@ -3,7 +3,7 @@ from datetime import datetime from pathlib import Path -import pytest as pytest +import pytest from db import db from encryption import EncryptionManager, GpgDecryptError, GpgEncryptError, GpgKeyNotFoundError from passphrases import PassphraseGenerator diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -42,7 +42,7 @@ def create_config_for_i18n_test( default_locale: str = "en_US", translation_dirs: Path = DEFAULT_SECUREDROP_ROOT / "translations", ) -> SecureDropConfig: - tmp_root_for_test = Path(f"/tmp/sd-tests/test_i18n") + tmp_root_for_test = Path("/tmp/sd-tests/test_i18n") tmp_root_for_test.mkdir(exist_ok=True, parents=True) i18n_config = SecureDropConfigFactory.create( @@ -210,7 +210,7 @@ def verify_i18n(app): assert not_translated == gettext(not_translated) with app.test_request_context(): - assert "" == render_template("locales.html") + assert render_template("locales.html") == "" with app.test_client() as c: c.get("/") @@ -236,7 +236,7 @@ def verify_i18n(app): def test_i18n(): - translation_dirs = Path(f"/tmp/sd-tests/test_i18n/translations") + translation_dirs = Path("/tmp/sd-tests/test_i18n/translations") translation_dirs.mkdir(exist_ok=True, parents=True) test_config = create_config_for_i18n_test( supported_locales=["ar", "en_US", "fr_FR", "nb_NO", "zh_Hans"], @@ -305,7 +305,7 @@ def test_parse_locale_set(): assert parse_locale_set([FALLBACK_LOCALE]) == {Locale.parse(FALLBACK_LOCALE)} [email protected] # #6873 [email protected]() # #6873 def test_no_usable_fallback_locale(): """ The apps fail if neither the default nor the fallback locale is usable. @@ -321,7 +321,7 @@ def test_no_usable_fallback_locale(): source_app.create_app(test_config) [email protected] # #6873 [email protected]() # #6873 def test_unusable_default_but_usable_fallback_locale(caplog): """ The apps start even if the default locale is unusable, as along as the fallback locale is diff --git a/securedrop/tests/test_i18n_tool.py b/securedrop/tests/test_i18n_tool.py --- a/securedrop/tests/test_i18n_tool.py +++ b/securedrop/tests/test_i18n_tool.py @@ -309,7 +309,7 @@ def test_update_from_weblate(self, tmpdir, caplog): subprocess.check_call(["git", "checkout", "-b", "i18n", "master"], **k) def r(): - return "".join([str(l) for l in caplog.records]) + return "".join([str(record) for record in caplog.records]) # # de_DE is not amount the supported languages, it is not taken diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -1,7 +1,5 @@ -# flake8: noqa: E741 import base64 import binascii -import io import os import random import time @@ -792,7 +790,8 @@ def test_user_edits_password_expires_session(journalist_app, test_journo): ins.assert_redirects(resp, url_for("main.login")) # verify the session was expired after the password was changed - assert session.uid is None and session.user is None + assert session.uid is None + assert session.user is None @flaky(rerun_filter=utils.flaky_filter_xfail) @@ -1652,7 +1651,7 @@ def test_admin_add_user_too_short_username(config, journalist_app, test_admin, l @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize( - "locale, secret", + ("locale", "secret"), ( (locale, "a" * i) for locale in get_test_locales() @@ -1695,7 +1694,7 @@ def test_admin_add_user_yubikey_odd_length(config, journalist_app, test_admin, l @flaky(rerun_filter=utils.flaky_filter_xfail) @pytest.mark.parametrize( - "locale, secret", + ("locale", "secret"), ((locale, " " * i) for locale in get_test_locales() for i in range(3)), ) def test_admin_add_user_yubikey_blank_secret(config, journalist_app, test_admin, locale, secret): @@ -1722,7 +1721,7 @@ def test_admin_add_user_yubikey_blank_secret(config, journalist_app, test_admin, ) assert page_language(resp.data) == language_tag(locale) - msgids = ['The "otp_secret" field is required when "is_hotp" is set.'] + msgids = ["The &#34;otp_secret&#34; field is required when &#34;is_hotp&#34; is set."] with xfail_untranslated_messages(config, locale, msgids): # Should redirect to the token verification page assert gettext(msgids[0]) in resp.data.decode("utf-8") @@ -3018,7 +3017,7 @@ def test_render_locales( journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder worker_name, _ = setup_rqworker config_with_fr_locale = SecureDropConfigFactory.create( - SECUREDROP_DATA_ROOT=Path(f"/tmp/sd-tests/render_locales"), + SECUREDROP_DATA_ROOT=Path("/tmp/sd-tests/render_locales"), GPG_KEY_DIR=gpg_key_dir, JOURNALIST_KEY=journalist_key_fingerprint, SUPPORTED_LOCALES=["en_US", "fr_FR"], @@ -3099,7 +3098,7 @@ def test_download_selected_submissions_and_replies( ).one_or_none() if not seen_file and not seen_message and not seen_reply: - assert False + pytest.fail("no seen_file and no seen_message and no seen_reply") # The items not selected are absent from the zipfile not_selected_submissions = set(submissions).difference(selected_submissions) @@ -3173,7 +3172,7 @@ def test_download_selected_submissions_and_replies_previously_seen( ).one_or_none() if not seen_file and not seen_message and not seen_reply: - assert False + pytest.fail("no seen_file and no seen_message and no seen_reply") # The items not selected are absent from the zipfile not_selected_submissions = set(submissions).difference(selected_submissions) @@ -3251,7 +3250,7 @@ def test_download_selected_submissions_previously_downloaded( ) [email protected](scope="function") [email protected]() def selected_missing_files(journalist_app, test_source, app_storage): """Fixture for the download tests with missing files in storage.""" source = Source.query.get(test_source["id"]) @@ -3264,7 +3263,7 @@ def selected_missing_files(journalist_app, test_source, app_storage): for file in msg_files: file.unlink() - yield selected + return selected def test_download_selected_submissions_missing_files( @@ -3400,20 +3399,19 @@ def test_download_unread_all_sources(journalist_app, test_journo, app_storage): ).one_or_none() if not seen_file and not seen_message: - assert False + pytest.fail("no seen_file and no seen_message") # Check that the zip file does not contain any seen data or replies + zipf = zipfile.ZipFile(BytesIO(resp.data)) for item in seen_files + seen_messages + seen_replies + unseen_replies: + path = os.path.join( + "unread", + source.journalist_designation, + "{}_{}".format(item.filename.split("-")[0], source.last_updated.date()), + item.filename, + ) with pytest.raises(KeyError): - zipinfo = zipfile.ZipFile(BytesIO(resp.data)).getinfo( - os.path.join( - "unread", - source.journalist_designation, - "{}_{}".format(item.filename.split("-")[0], source.last_updated.date()), - item.filename, - ) - ) - assert zipinfo + zipf.getinfo(path) def test_download_all_selected_sources(journalist_app, test_journo, app_storage): @@ -3475,20 +3473,19 @@ def test_download_all_selected_sources(journalist_app, test_journo, app_storage) ).one_or_none() if not seen_file and not seen_message: - assert False + pytest.fail("no seen_file and no seen_message") # Check that the zip file does not contain any replies + zipf = zipfile.ZipFile(BytesIO(resp.data)) for item in seen_replies + unseen_replies: + path = os.path.join( + "unread", + source.journalist_designation, + "{}_{}".format(item.filename.split("-")[0], source.last_updated.date()), + item.filename, + ) with pytest.raises(KeyError): - zipinfo = zipfile.ZipFile(BytesIO(resp.data)).getinfo( - os.path.join( - "unread", - source.journalist_designation, - "{}_{}".format(item.filename.split("-")[0], source.last_updated.date()), - item.filename, - ) - ) - assert zipinfo + zipf.getinfo(path) def test_single_source_is_successfully_starred(journalist_app, test_journo, test_source): diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -601,8 +601,8 @@ def test_authorized_user_can_delete_source_conversation( source_id = test_files["source"].id # Submissions and Replies both exist - assert not Submission.query.filter(source_id == source_id).all() == [] - assert not Reply.query.filter(source_id == source_id).all() == [] + assert Submission.query.filter(source_id == source_id).all() != [] + assert Reply.query.filter(source_id == source_id).all() != [] response = app.delete( url_for("api.source_conversation", source_uuid=uuid), @@ -616,7 +616,7 @@ def test_authorized_user_can_delete_source_conversation( assert Reply.query.filter(source_id == source_id).all() == [] # Source still exists - assert not Source.query.filter(uuid == uuid).all() == [] + assert Source.query.filter(uuid == uuid).all() != [] def test_source_conversation_does_not_support_get( diff --git a/securedrop/tests/test_remove_pending_sources.py b/securedrop/tests/test_remove_pending_sources.py --- a/securedrop/tests/test_remove_pending_sources.py +++ b/securedrop/tests/test_remove_pending_sources.py @@ -7,7 +7,7 @@ from source_user import create_source_user [email protected]("n,m", [(10, 5), (7, 0)]) [email protected](("n", "m"), [(10, 5), (7, 0)]) def test_remove_pending_sources_none_pending(n, m, source_app, config, app_storage): """remove_pending_sources() is a no-op on active sources.""" @@ -45,7 +45,7 @@ def test_remove_pending_sources_none_pending(n, m, source_app, config, app_stora assert db.session.query(Source).count() == n [email protected]("n,m", [(10, 5), (7, 0)]) [email protected](("n", "m"), [(10, 5), (7, 0)]) def test_remove_pending_sources_all_pending(n, m, source_app, config, app_storage): """remove_pending_sources() removes all but the most-recent m of n pending sources.""" # Override the configuration to point at the per-test database. diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -1,4 +1,3 @@ -# flake8: noqa: E741 import gzip import os import re @@ -14,19 +13,16 @@ import pytest import version from db import db -from flaky import flaky from flask import escape, g, request, session, url_for -from flask_babel import gettext from journalist_app.utils import delete_collection from models import InstanceConfig, Reply, Source from passphrases import PassphraseGenerator from source_app import api as source_app_api -from source_app import get_logo_url, session_manager +from source_app import get_logo_url from source_app.session_manager import SessionManager from . import utils from .utils.db_helper import new_codename, submit -from .utils.i18n import get_test_locales, language_tag, page_language, xfail_untranslated_messages from .utils.instrument import InstrumentedApp GENERATE_DATA = {"tor2web_check": 'href="fake.onion"'} @@ -769,12 +765,12 @@ def test_normalize_timestamps(source_app, app_storage): assert "Thanks! We received your message" in text # only two of the source's three submissions should have files in the store - assert 3 == len(source.submissions) + assert len(source.submissions) == 3 submission_paths = [ Path(app_storage.path(source.filesystem_id, s.filename)) for s in source.submissions ] extant_paths = [p for p in submission_paths if p.exists()] - assert 2 == len(extant_paths) + assert len(extant_paths) == 2 # verify that the deleted file has not been recreated assert not first_submission_path.exists() diff --git a/securedrop/tests/test_source_utils.py b/securedrop/tests/test_source_utils.py --- a/securedrop/tests/test_source_utils.py +++ b/securedrop/tests/test_source_utils.py @@ -65,13 +65,13 @@ def test_fit_codenames_into_cookie(config): @pytest.mark.parametrize( - "message,expected", - ( + ("message", "expected"), + [ ("Foo", False), ("codename", True), (" codename ", True), ("foocodenamebar", False), - ), + ], ) def test_codename_detected(message, expected): assert codename_detected(message, "codename") is expected diff --git a/securedrop/tests/test_store.py b/securedrop/tests/test_store.py --- a/securedrop/tests/test_store.py +++ b/securedrop/tests/test_store.py @@ -20,7 +20,7 @@ from tests import utils [email protected](scope="function") [email protected]() def test_storage() -> Generator[Storage, None, None]: # Setup the filesystem for the storage object with TemporaryDirectory() as data_dir_name: @@ -115,28 +115,25 @@ def test_verify_path_not_absolute(test_storage): def test_verify_in_store_dir(test_storage): - with pytest.raises(store.PathException) as e: - path = test_storage.storage_path + "_backup" + path = test_storage.storage_path + "_backup" + with pytest.raises(store.PathException, match="Path not valid in store: "): test_storage.verify(path) - assert e.message == f"Path not valid in store: {path}" def test_verify_store_path_not_absolute(test_storage): - with pytest.raises(store.PathException) as e: + with pytest.raises(store.PathException, match="Path not valid in store: "): test_storage.verify("..") - assert e.message == "Path not valid in store: .." def test_verify_rejects_symlinks(test_storage): """ Test that verify rejects paths involving links outside the store. """ + link = os.path.join(test_storage.storage_path, "foo") try: - link = os.path.join(test_storage.storage_path, "foo") os.symlink("/foo", link) - with pytest.raises(store.PathException) as e: + with pytest.raises(store.PathException, match="Path not valid in store: "): test_storage.verify(link) - assert e.message == f"Path not valid in store: {link}" finally: os.unlink(link) @@ -189,9 +186,8 @@ def test_verify_invalid_filename_in_sourcedir_raises_exception(test_storage): test_storage.storage_path, "example-filesystem-id", "NOTVALID.gpg" ) - with pytest.raises(store.PathException) as e: + with pytest.raises(store.PathException, match="Path not valid in store: "): test_storage.verify(file_path) - assert e.message == f"Path not valid in store: {file_path}" def test_get_zip(journalist_app, test_source, app_storage, config): @@ -278,9 +274,9 @@ def _wait_for_redis_worker(job: Job, timeout: int = 60) -> None: if job.result == redis_success_return_value: return elif job.result not in (None, redis_success_return_value): - assert False, "Redis worker failed!" + pytest.fail("Redis worker failed!") time.sleep(0.1) - assert False, "Redis worker timed out!" + pytest.fail("Redis worker timed out!") @pytest.mark.parametrize("db_model", [Submission, Reply]) diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -16,22 +16,22 @@ def verify_rel_datetime_format(app): c.get("/") assert session.get("locale") == "en_US" result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1)) - assert "January 1, 2016 at 1:01:01 AM UTC" == result + assert result == "January 1, 2016 at 1:01:01 AM UTC" result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1), fmt="yyyy") - assert "2016" == result + assert result == "2016" test_time = datetime.utcnow() - timedelta(hours=2) result = template_filters.rel_datetime_format(test_time, relative=True) - assert "2 hours ago" == result + assert result == "2 hours ago" c.get("/?l=fr_FR") assert session.get("locale") == "fr_FR" result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1)) - assert "1 janvier 2016 à 01:01:01 TU" == result + assert result == "1 janvier 2016 à 01:01:01 TU" result = template_filters.rel_datetime_format(datetime(2016, 1, 1, 1, 1, 1), fmt="yyyy") - assert "2016" == result + assert result == "2016" test_time = datetime.utcnow() - timedelta(hours=2) result = template_filters.rel_datetime_format(test_time, relative=True) @@ -42,31 +42,31 @@ def verify_filesizeformat(app): with app.test_client() as c: c.get("/") assert session.get("locale") == "en_US" - assert "1 byte" == template_filters.filesizeformat(1) - assert "2 bytes" == template_filters.filesizeformat(2) + assert template_filters.filesizeformat(1) == "1 byte" + assert template_filters.filesizeformat(2) == "2 bytes" value = 1024 * 3 - assert "3 kB" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3 kB" value *= 1024 - assert "3 MB" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3 MB" value *= 1024 - assert "3 GB" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3 GB" value *= 1024 - assert "3 TB" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3 TB" value *= 1024 - assert "3,072 TB" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3,072 TB" c.get("/?l=fr_FR") assert session.get("locale") == "fr_FR" - assert "1\xa0octet" == template_filters.filesizeformat(1) - assert "2\xa0octets" == template_filters.filesizeformat(2) + assert template_filters.filesizeformat(1) == "1\xa0octet" + assert template_filters.filesizeformat(2) == "2\xa0octets" value = 1024 * 3 - assert "3\u202fko" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3\u202fko" value *= 1024 - assert "3\u202fMo" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3\u202fMo" value *= 1024 - assert "3\u202fGo" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3\u202fGo" value *= 1024 - assert "3\u202fTo" == template_filters.filesizeformat(value) + assert template_filters.filesizeformat(value) == "3\u202fTo" value *= 1024 assert "072\u202fTo" in template_filters.filesizeformat(value) @@ -102,9 +102,11 @@ def do_test(create_app): ] ) - for l in ("en_US", "fr_FR"): + for lang in ("en_US", "fr_FR"): pot = Path(test_config.TEMP_DIR) / "messages.pot" - subprocess.check_call(["pybabel", "init", "-i", pot, "-d", test_config.TEMP_DIR, "-l", l]) + subprocess.check_call( + ["pybabel", "init", "-i", pot, "-d", test_config.TEMP_DIR, "-l", lang] + ) app = create_app(test_config) with app.app_context(): diff --git a/securedrop/tests/test_two_factor.py b/securedrop/tests/test_two_factor.py --- a/securedrop/tests/test_two_factor.py +++ b/securedrop/tests/test_two_factor.py @@ -51,7 +51,7 @@ def test_verify_within_look_ahead_window(self) -> None: hotp.verify(self._VALID_TOKEN, counter) @pytest.mark.parametrize( - "token, counter", + ("token", "counter"), [ pytest.param(_VALID_TOKEN, _VALID_TOKEN_COUNTER + 10), pytest.param(_VALID_TOKEN, 12345), @@ -102,7 +102,7 @@ def test_generate(self) -> None: assert token == self._VALID_TOKEN @pytest.mark.parametrize( - "token, verification_timestamp", + ("token", "verification_timestamp"), [ # Ensure the token is valid at the exact time pytest.param(_VALID_TOKEN, _VALID_TOKEN_GENERATED_AT), @@ -122,7 +122,7 @@ def test_verify(self, token: str, verification_timestamp: int) -> None: totp.verify(token, verification_time) @pytest.mark.parametrize( - "token, verification_timestamp", + ("token", "verification_timestamp"), [ # Ensure the token is invalid at a totally wrong time pytest.param(_VALID_TOKEN, 123456), diff --git a/securedrop/tests/test_two_factor_in_apps.py b/securedrop/tests/test_two_factor_in_apps.py --- a/securedrop/tests/test_two_factor_in_apps.py +++ b/securedrop/tests/test_two_factor_in_apps.py @@ -94,25 +94,24 @@ def test_rejects_user_with_invalid_otp_secret(self, journalist_app, otp_secret): db.session.commit() # When they try to login - with journalist_app.test_client() as app: - with InstrumentedApp(app) as ins: - resp = app.post( - url_for("main.login"), - data={ - "username": new_username, - "password": password, - "token": "705334", - }, - follow_redirects=True, - ) + with journalist_app.test_client() as app, InstrumentedApp(app) as ins: + resp = app.post( + url_for("main.login"), + data={ + "username": new_username, + "password": password, + "token": "705334", + }, + follow_redirects=True, + ) - # It fails and they didn't get a session - assert resp.status_code == 200 - assert session.get_user() is None + # It fails and they didn't get a session + assert resp.status_code == 200 + assert session.get_user() is None - # And the corresponding error messages was displayed - assert len(ins.flashed_messages) == 1 - assert "2FA details are invalid" in ins.flashed_messages[0][0] + # And the corresponding error messages was displayed + assert len(ins.flashed_messages) == 1 + assert "2FA details are invalid" in ins.flashed_messages[0][0] def test_can_login_after_regenerating_hotp(self, journalist_app, test_journo): # Given a journalist logged into the journalist app @@ -144,19 +143,18 @@ def test_can_login_after_regenerating_hotp(self, journalist_app, test_journo): app.get("/logout") # When they later try to login using a 2fa token based on their new HOTP secret - with journalist_app.test_client() as app: - with InstrumentedApp(journalist_app) as ins: - resp = app.post( - "/login", - data=dict( - username=test_journo["username"], - password=test_journo["password"], - token=HOTP(b32_otp_secret).generate(1), - ), - ) + with journalist_app.test_client() as app, InstrumentedApp(journalist_app) as ins: + resp = app.post( + "/login", + data=dict( + username=test_journo["username"], + password=test_journo["password"], + token=HOTP(b32_otp_secret).generate(1), + ), + ) - # Then it succeeds - ins.assert_redirects(resp, "/") + # Then it succeeds + ins.assert_redirects(resp, "/") class TestTwoFactorInAdminApp: diff --git a/securedrop/tests/test_wsgi.py b/securedrop/tests/test_wsgi.py --- a/securedrop/tests/test_wsgi.py +++ b/securedrop/tests/test_wsgi.py @@ -6,7 +6,7 @@ import pytest [email protected]("filename", ("journalist.wsgi", "source.wsgi")) [email protected]("filename", ["journalist.wsgi", "source.wsgi"]) def test_wsgi(filename): """ Verify that all setup code and imports in the wsgi files work diff --git a/securedrop/tests/utils/__init__.py b/securedrop/tests/utils/__init__.py --- a/securedrop/tests/utils/__init__.py +++ b/securedrop/tests/utils/__init__.py @@ -12,8 +12,9 @@ def flaky_filter_xfail(err, *args): If the test is expected to fail, let's not run it again. """ - return "_pytest.outcomes.XFailed" == "{}.{}".format( - err[0].__class__.__module__, err[0].__class__.__qualname__ + return ( + f"{err[0].__class__.__module__}.{err[0].__class__.__qualname__}" + == "_pytest.outcomes.XFailed" )
Add pyupgrade to our toolchain ## Description pyupgrade is a tool that automatically rewrites code to use modern syntax. https://github.com/asottile/pyupgrade has a detailed list with examples. This would be similar to black/isort, in which we'd have a command like `make pyupgrade` that applies all the changes, and then another like `make pyupgrade-check` which verifies there are no unapplied changes. Note that black should always run after pyupgrade changes things. ## User Stories * As a developer, I want to automatically update Python code to modern patterns/syntax so I don't have to do it manually
@legoktm I can work on this if you'd like. I'm relatively new and don't have professional experience yet but I do open source sometimes and I've worked with `make` and `black` before, for example. Let me know! Hi @phershbe, thanks for your interest! I want to get input from other team members before we move ahead with this, that will probably take (or not) a week if you don't mind waiting, or I can suggest another task for you to work on now! @legoktm Yeah, of course, I'm not on any kind of timeline, I'm simply here to help and to practice. Thank you for offering another task ... I'm kind of intimated by a lot of stuff, any other easy tasks off the top of your head? I was looking at https://github.com/freedomofpress/securedrop/issues/6641. @phershbe: yep, that is (I think!) relatively straightforward (parsing the flask version out of requirements.txt). I'd also suggest #2484 (some code deletion), and #6515 (porting some regex checks to Python/flask).
2023-07-05T21:41:35Z
[]
[]
freedomofpress/securedrop
6,892
freedomofpress__securedrop-6892
[ "6799" ]
604562233f979ff5d4c6056678429dd32093503d
diff --git a/securedrop/alembic/versions/811334d7105f_sequoia_pgp.py b/securedrop/alembic/versions/811334d7105f_sequoia_pgp.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/811334d7105f_sequoia_pgp.py @@ -0,0 +1,30 @@ +"""sequoia_pgp + +Revision ID: 811334d7105f +Revises: c5a02eb52f2d +Create Date: 2023-06-29 18:19:59.314380 + +""" +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "811334d7105f" +down_revision = "c5a02eb52f2d" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("sources", schema=None) as batch_op: + batch_op.add_column(sa.Column("pgp_fingerprint", sa.String(length=40), nullable=True)) + batch_op.add_column(sa.Column("pgp_public_key", sa.Text(), nullable=True)) + batch_op.add_column(sa.Column("pgp_secret_key", sa.Text(), nullable=True)) + + +def downgrade() -> None: + # We do NOT drop the columns here, because doing so would break any + # source that had its key pair stored here. If a downgrade is needed for + # whatever reason, the extra columns will just be ignored, and the sources + # will still be temporarily broken, but there will be no data loss. + pass diff --git a/securedrop/encryption.py b/securedrop/encryption.py --- a/securedrop/encryption.py +++ b/securedrop/encryption.py @@ -1,16 +1,18 @@ import os import re import typing -from datetime import date -from io import BytesIO, StringIO +from io import BytesIO from pathlib import Path -from typing import Dict, List, Optional +from typing import BinaryIO, Dict, Optional import pretty_bad_protocol as gnupg from redis import Redis from sdconfig import SecureDropConfig +import redwood + if typing.TYPE_CHECKING: + from models import Source from source_user import SourceUser # To fix https://github.com/freedomofpress/securedrop/issues/78 @@ -33,28 +35,20 @@ class GpgDecryptError(Exception): class EncryptionManager: - - GPG_KEY_TYPE = "RSA" - GPG_KEY_LENGTH = 4096 - - # All reply keypairs will be "created" on the same day SecureDrop (then - # Strongbox) was publicly released for the first time. - # https://www.newyorker.com/news/news-desk/strongbox-and-aaron-swartz - DEFAULT_KEY_CREATION_DATE = date(2013, 5, 14) - - # '0' is the magic value that tells GPG's batch key generation not - # to set an expiration date. - DEFAULT_KEY_EXPIRATION_DATE = "0" + """EncryptionManager provides a high-level interface for each PGP operation we do""" REDIS_FINGERPRINT_HASH = "sd/crypto-util/fingerprints" REDIS_KEY_HASH = "sd/crypto-util/keys" - SOURCE_KEY_NAME = "Source Key" SOURCE_KEY_UID_RE = re.compile(r"(Source|Autogenerated) Key <[-A-Za-z0-9+/=_]+>") - def __init__(self, gpg_key_dir: Path, journalist_key_fingerprint: str) -> None: + def __init__(self, gpg_key_dir: Path, journalist_pub_key: Path) -> None: self._gpg_key_dir = gpg_key_dir - self._journalist_key_fingerprint = journalist_key_fingerprint + self.journalist_pub_key = journalist_pub_key + if not self.journalist_pub_key.exists(): + raise RuntimeError( + f"The journalist public key does not exist at {self.journalist_pub_key}" + ) self._redis = Redis(decode_responses=True) # Instantiate the "main" GPG binary @@ -71,15 +65,6 @@ def __init__(self, gpg_key_dir: Path, journalist_key_fingerprint: str) -> None: binary="gpg2", homedir=str(self._gpg_key_dir), options=["--yes", "--trust-model direct"] ) - # Ensure that the journalist public key has been previously imported in GPG - try: - self.get_journalist_public_key() - except GpgKeyNotFoundError: - raise OSError( - f"The journalist public key with fingerprint {journalist_key_fingerprint}" - f" has not been imported into GPG." - ) - @classmethod def get_default(cls) -> "EncryptionManager": global _default_encryption_mgr @@ -87,27 +72,22 @@ def get_default(cls) -> "EncryptionManager": config = SecureDropConfig.get_current() _default_encryption_mgr = cls( gpg_key_dir=config.GPG_KEY_DIR, - journalist_key_fingerprint=config.JOURNALIST_KEY, + journalist_pub_key=(config.SECUREDROP_DATA_ROOT / "journalist.pub"), ) return _default_encryption_mgr - def generate_source_key_pair(self, source_user: "SourceUser") -> None: - gen_key_input = self._gpg.gen_key_input( - passphrase=source_user.gpg_secret, - name_email=source_user.filesystem_id, - key_type=self.GPG_KEY_TYPE, - key_length=self.GPG_KEY_LENGTH, - name_real=self.SOURCE_KEY_NAME, - creation_date=self.DEFAULT_KEY_CREATION_DATE.isoformat(), - expire_date=self.DEFAULT_KEY_EXPIRATION_DATE, - ) - new_key = self._gpg.gen_key(gen_key_input) - - # Store the newly-created key's fingerprint in Redis for faster lookups - self._save_key_fingerprint_to_redis(source_user.filesystem_id, str(new_key)) - def delete_source_key_pair(self, source_filesystem_id: str) -> None: - source_key_fingerprint = self.get_source_key_fingerprint(source_filesystem_id) + """ + Try to delete the source's key from the filesystem. If it's not found, either: + (a) it doesn't exist or + (b) the source is Sequoia-based and has its key stored in Source.pgp_public_key, + which will be deleted when the Source instance itself is deleted. + """ + try: + source_key_fingerprint = self.get_source_key_fingerprint(source_filesystem_id) + except GpgKeyNotFoundError: + # If the source is entirely Sequoia-based, there is nothing to delete + return # The subkeys keyword argument deletes both secret and public keys self._gpg_for_key_deletion.delete_keys(source_key_fingerprint, secret=True, subkeys=True) @@ -116,7 +96,7 @@ def delete_source_key_pair(self, source_filesystem_id: str) -> None: self._redis.hdel(self.REDIS_FINGERPRINT_HASH, source_filesystem_id) def get_journalist_public_key(self) -> str: - return self._get_public_key(self._journalist_key_fingerprint) + return self.journalist_pub_key.read_text() def get_source_public_key(self, source_filesystem_id: str) -> str: source_key_fingerprint = self.get_source_key_fingerprint(source_filesystem_id) @@ -134,35 +114,42 @@ def get_source_key_fingerprint(self, source_filesystem_id: str) -> str: return source_key_fingerprint def encrypt_source_message(self, message_in: str, encrypted_message_path_out: Path) -> None: - message_as_stream = StringIO(message_in) - self._encrypt( + redwood.encrypt_message( # A submission is only encrypted for the journalist key - using_keys_with_fingerprints=[self._journalist_key_fingerprint], - plaintext_in=message_as_stream, - ciphertext_path_out=encrypted_message_path_out, + recipients=[self.get_journalist_public_key()], + plaintext=message_in, + destination=encrypted_message_path_out, ) - def encrypt_source_file(self, file_in: typing.IO, encrypted_file_path_out: Path) -> None: - self._encrypt( + def encrypt_source_file(self, file_in: BinaryIO, encrypted_file_path_out: Path) -> None: + redwood.encrypt_stream( # A submission is only encrypted for the journalist key - using_keys_with_fingerprints=[self._journalist_key_fingerprint], - plaintext_in=file_in, - ciphertext_path_out=encrypted_file_path_out, + recipients=[self.get_journalist_public_key()], + plaintext=file_in, + destination=encrypted_file_path_out, ) def encrypt_journalist_reply( - self, for_source_with_filesystem_id: str, reply_in: str, encrypted_reply_path_out: Path + self, for_source: "Source", reply_in: str, encrypted_reply_path_out: Path ) -> None: - source_key_fingerprint = self.get_source_key_fingerprint(for_source_with_filesystem_id) - reply_as_stream = StringIO(reply_in) - self._encrypt( + redwood.encrypt_message( # A reply is encrypted for both the journalist key and the source key - using_keys_with_fingerprints=[source_key_fingerprint, self._journalist_key_fingerprint], - plaintext_in=reply_as_stream, - ciphertext_path_out=encrypted_reply_path_out, + recipients=[for_source.public_key, self.get_journalist_public_key()], + plaintext=reply_in, + destination=encrypted_reply_path_out, ) def decrypt_journalist_reply(self, for_source_user: "SourceUser", ciphertext_in: bytes) -> str: + """Decrypt a reply sent by a journalist.""" + # TODO: Avoid making a database query here + for_source = for_source_user.get_db_record() + if for_source.pgp_secret_key is not None: + return redwood.decrypt( + ciphertext_in, + secret_key=for_source.pgp_secret_key, + passphrase=for_source_user.gpg_secret, + ).decode() + # TODO: Migrate gpg-stored secret keys to database storage for Sequoia ciphertext_as_stream = BytesIO(ciphertext_in) out = self._gpg.decrypt_file(ciphertext_as_stream, passphrase=for_source_user.gpg_secret) if not out.ok: @@ -170,27 +157,6 @@ def decrypt_journalist_reply(self, for_source_user: "SourceUser", ciphertext_in: return out.data.decode("utf-8") - def _encrypt( - self, - using_keys_with_fingerprints: List[str], - plaintext_in: typing.IO, - ciphertext_path_out: Path, - ) -> None: - # Remove any spaces from provided fingerprints GPG outputs fingerprints - # with spaces for readability, but requires the spaces to be removed - # when using fingerprints to specify recipients. - sanitized_key_fingerprints = [fpr.replace(" ", "") for fpr in using_keys_with_fingerprints] - - out = self._gpg.encrypt( - plaintext_in, - *sanitized_key_fingerprints, - output=str(ciphertext_path_out), - always_trust=True, - armor=False, - ) - if not out.ok: - raise GpgEncryptError(out.stderr) - def _get_source_key_details(self, source_filesystem_id: str) -> Dict[str, str]: for key in self._gpg.list_keys(): for uid in key["uids"]: diff --git a/securedrop/journalist_app/col.py b/securedrop/journalist_app/col.py --- a/securedrop/journalist_app/col.py +++ b/securedrop/journalist_app/col.py @@ -2,7 +2,7 @@ import werkzeug from db import db -from encryption import EncryptionManager, GpgKeyNotFoundError +from encryption import GpgKeyNotFoundError from flask import ( Blueprint, Markup, @@ -56,13 +56,11 @@ def remove_star(filesystem_id: str) -> werkzeug.Response: def col(filesystem_id: str) -> str: form = ReplyForm() source = get_source(filesystem_id) - try: - EncryptionManager.get_default().get_source_public_key(filesystem_id) - source.has_key = True - except GpgKeyNotFoundError: - source.has_key = False + has_key = source.public_key is not None - return render_template("col.html", filesystem_id=filesystem_id, source=source, form=form) + return render_template( + "col.html", filesystem_id=filesystem_id, source=source, has_key=has_key, form=form + ) @view.route("/delete/<filesystem_id>", methods=("POST",)) def delete_single(filesystem_id: str) -> werkzeug.Response: diff --git a/securedrop/journalist_app/main.py b/securedrop/journalist_app/main.py --- a/securedrop/journalist_app/main.py +++ b/securedrop/journalist_app/main.py @@ -143,7 +143,7 @@ def reply() -> werkzeug.Response: g.source.interaction_count, g.source.journalist_filename ) EncryptionManager.get_default().encrypt_journalist_reply( - for_source_with_filesystem_id=g.filesystem_id, + for_source=g.source, reply_in=form.message.data, encrypted_reply_path_out=Path(Storage.get_default().path(g.filesystem_id, filename)), ) diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -221,7 +221,7 @@ def add_reply( record_source_interaction(source) fname = f"{source.interaction_count}-{source.journalist_filename}-reply.gpg" EncryptionManager.get_default().encrypt_journalist_reply( - for_source_with_filesystem_id=source.filesystem_id, + for_source=source, reply_in=next(replies), encrypted_reply_path_out=Path(Storage.get_default().path(source.filesystem_id, fname)), ) @@ -252,9 +252,6 @@ def add_source() -> Tuple[Source, str]: source = source_user.get_db_record() db.session.commit() - # Generate source key - EncryptionManager.get_default().generate_source_key_pair(source_user) - return source, codename diff --git a/securedrop/models.py b/securedrop/models.py --- a/securedrop/models.py +++ b/securedrop/models.py @@ -22,7 +22,7 @@ from flask_babel import gettext, ngettext from markupsafe import Markup from passphrases import PassphraseGenerator -from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, LargeBinary, String +from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, LargeBinary, String, Text from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Query, backref, relationship from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound @@ -70,9 +70,24 @@ class Source(db.Model): # when deletion of the source was requested deleted_at = Column(DateTime) - def __init__(self, filesystem_id: str, journalist_designation: str) -> None: + # PGP key material + pgp_public_key = Column(Text, nullable=True) + pgp_secret_key = Column(Text, nullable=True) + pgp_fingerprint = Column(String(40), nullable=True) + + def __init__( + self, + filesystem_id: str, + journalist_designation: str, + public_key: str, + secret_key: str, + fingerprint: str, + ) -> None: self.filesystem_id = filesystem_id self.journalist_designation = journalist_designation + self.pgp_public_key = public_key + self.pgp_secret_key = secret_key + self.pgp_fingerprint = fingerprint self.uuid = str(uuid.uuid4()) def __repr__(self) -> str: @@ -105,14 +120,18 @@ def collection(self) -> "List[Union[Submission, Reply]]": return collection @property - def fingerprint(self) -> "Optional[str]": + def fingerprint(self) -> Optional[str]: + if self.pgp_fingerprint is not None: + return self.pgp_fingerprint try: return EncryptionManager.get_default().get_source_key_fingerprint(self.filesystem_id) except GpgKeyNotFoundError: return None @property - def public_key(self) -> "Optional[str]": + def public_key(self) -> Optional[str]: + if self.pgp_public_key: + return self.pgp_public_key try: return EncryptionManager.get_default().get_source_public_key(self.filesystem_id) except GpgKeyNotFoundError: diff --git a/securedrop/secure_tempfile.py b/securedrop/secure_tempfile.py --- a/securedrop/secure_tempfile.py +++ b/securedrop/secure_tempfile.py @@ -8,7 +8,6 @@ from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers.modes import CTR -from pretty_bad_protocol._util import _STREAMLIKE_TYPES class SecureTemporaryFile(_TemporaryFileWrapper): @@ -134,9 +133,3 @@ def close(self) -> None: # Since tempfile._TemporaryFileWrapper.close() does other cleanup, # (i.e. deleting the temp file on disk), we need to call it also. super().close() - - -# python-gnupg will not recognize our SecureTemporaryFile as a stream-like type -# and will attempt to call encode on it, thinking it's a string-like type. To -# avoid this we append it the list of stream-like types. -_STREAMLIKE_TYPES.append(_TemporaryFileWrapper) diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -7,7 +7,7 @@ import store import werkzeug from db import db -from encryption import EncryptionManager, GpgKeyNotFoundError +from encryption import EncryptionManager from flask import ( Blueprint, abort, @@ -43,6 +43,8 @@ ) from store import Storage +import redwood + def make_blueprint(config: SecureDropConfig) -> Blueprint: view = Blueprint("main", __name__) @@ -161,7 +163,8 @@ def lookup(logged_in_source: SourceUser) -> str: with open(reply_path, "rb") as f: contents = f.read() decrypted_reply = EncryptionManager.get_default().decrypt_journalist_reply( - for_source_user=logged_in_source, ciphertext_in=contents + for_source_user=logged_in_source, + ciphertext_in=contents, ) reply.decrypted = decrypted_reply except UnicodeDecodeError: @@ -175,13 +178,6 @@ def lookup(logged_in_source: SourceUser) -> str: # Sort the replies by date replies.sort(key=operator.attrgetter("date"), reverse=True) - # If not done yet, generate a keypair to encrypt replies from the journalist - encryption_mgr = EncryptionManager.get_default() - try: - encryption_mgr.get_source_public_key(logged_in_source.filesystem_id) - except GpgKeyNotFoundError: - encryption_mgr.generate_source_key_pair(logged_in_source) - return render_template( "lookup.html", is_user_logged_in=True, @@ -356,20 +352,33 @@ def batch_delete(logged_in_source: SourceUser) -> werkzeug.Response: @view.route("/login", methods=("GET", "POST")) def login() -> Union[str, werkzeug.Response]: form = LoginForm() - if form.validate_on_submit(): - try: - SessionManager.log_user_in( - db_session=db.session, - supplied_passphrase=DicewarePassphrase(request.form["codename"].strip()), - ) - except InvalidPassphraseError: - current_app.logger.info("Login failed for invalid codename") - flash_msg("error", None, gettext("Sorry, that is not a recognized codename.")) - else: - # Success: a valid passphrase was supplied - return redirect(url_for(".lookup", from_login="1")) - - return render_template("login.html", form=form) + if not form.validate_on_submit(): + return render_template("login.html", form=form) + try: + source_user = SessionManager.log_user_in( + db_session=db.session, + supplied_passphrase=DicewarePassphrase(request.form["codename"].strip()), + ) + except InvalidPassphraseError: + current_app.logger.info("Login failed for invalid codename") + flash_msg("error", None, gettext("Sorry, that is not a recognized codename.")) + return render_template("login.html", form=form) + # Success: a valid passphrase was supplied and the source was logged-in + source = source_user.get_db_record() + if source.fingerprint is None: + # This legacy source didn't have a PGP keypair generated yet, + # do it now. + public_key, secret_key, fingerprint = redwood.generate_source_key_pair( + source_user.gpg_secret, source_user.filesystem_id + ) + source.pgp_public_key = public_key + source.pgp_secret_key = secret_key + source.pgp_fingerprint = fingerprint + db.session.add(source) + db.session.commit() + # TODO: Migrate GPG secret key here too + + return redirect(url_for(".lookup", from_login="1")) @view.route("/logout") def logout() -> Union[str, werkzeug.Response]: diff --git a/securedrop/source_user.py b/securedrop/source_user.py --- a/securedrop/source_user.py +++ b/securedrop/source_user.py @@ -12,6 +12,8 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session +import redwood + if TYPE_CHECKING: from passphrases import DicewarePassphrase from store import Storage @@ -99,9 +101,18 @@ def create_source_user( # Could not generate a designation that is not already used raise SourceDesignationCollisionError() + # Generate PGP keys + public_key, secret_key, fingerprint = redwood.generate_source_key_pair( + gpg_secret, filesystem_id + ) + # Store the source in the DB source_db_record = models.Source( - filesystem_id=filesystem_id, journalist_designation=valid_designation + filesystem_id=filesystem_id, + journalist_designation=valid_designation, + public_key=public_key, + secret_key=secret_key, + fingerprint=fingerprint, ) db_session.add(source_db_record) try: diff --git a/securedrop/store.py b/securedrop/store.py --- a/securedrop/store.py +++ b/securedrop/store.py @@ -8,7 +8,7 @@ from hashlib import sha256 from pathlib import Path from tempfile import _TemporaryFileWrapper -from typing import IO, List, Optional, Type, Union +from typing import BinaryIO, List, Optional, Type, Union import rm from encryption import EncryptionManager @@ -301,7 +301,7 @@ def save_file_submission( count: int, journalist_filename: str, filename: Optional[str], - stream: "IO[bytes]", + stream: BinaryIO, ) -> str: if filename is not None:
diff --git a/molecule/testinfra/app-code/test_securedrop_app_code.py b/molecule/testinfra/app-code/test_securedrop_app_code.py --- a/molecule/testinfra/app-code/test_securedrop_app_code.py +++ b/molecule/testinfra/app-code/test_securedrop_app_code.py @@ -72,15 +72,15 @@ def test_securedrop_application_test_journalist_key(host): Ensure the SecureDrop Application GPG public key file is present. This is a test-only pubkey provided in the repository strictly for testing. """ - pubkey_file = host.file(f"{securedrop_test_vars.securedrop_data}/test_journalist_key.pub") + pubkey_file = host.file(f"{securedrop_test_vars.securedrop_data}/journalist.pub") # sudo is only necessary when testing against app hosts, since the # permissions are tighter. Let's elevate privileges so we're sure # we can read the correct file attributes and test them. with host.sudo(): assert pubkey_file.is_file assert pubkey_file.user == "root" - assert pubkey_file.group == "root" - assert pubkey_file.mode == 0o644 + assert pubkey_file.group == "www-data" + assert pubkey_file.mode == 0o640 # Let's make sure the corresponding fingerprint is specified # in the SecureDrop app configuration. diff --git a/molecule/testinfra/app/test_smoke.py b/molecule/testinfra/app/test_smoke.py --- a/molecule/testinfra/app/test_smoke.py +++ b/molecule/testinfra/app/test_smoke.py @@ -11,14 +11,15 @@ @pytest.mark.parametrize( - ("name", "url", "curl_flags"), + ("name", "url", "curl_flags", "expected"), [ # We pass -L to follow the redirect from / to /login - ("journalist", "http://localhost:8080/", "L"), - ("source", "http://localhost:80/", ""), + ("journalist", "http://localhost:8080/", "L", "Powered by"), + ("source", "http://localhost:80/", "", "Powered by"), + ("source", "http://localhost:80/public-key", "", "-----BEGIN PGP PUBLIC KEY BLOCK-----"), ], ) -def test_interface_up(host, name, url, curl_flags): +def test_interface_up(host, name, url, curl_flags, expected): """ Ensure the respective interface is up with HTTP 200 if not, we try our best to grab the error log and print it via an intentionally failed @@ -32,7 +33,7 @@ def test_interface_up(host, name, url, curl_flags): if f.exists: assert "nopenopenope" in f.content_string assert "200 OK" in response - assert "Powered by" in response + assert expected in response def test_redwood(host): diff --git a/securedrop/tests/conftest.py b/securedrop/tests/conftest.py --- a/securedrop/tests/conftest.py +++ b/securedrop/tests/conftest.py @@ -9,7 +9,6 @@ from pathlib import Path from typing import Any, Dict, Generator, Tuple from unittest import mock -from unittest.mock import PropertyMock from uuid import uuid4 import pretty_bad_protocol as gnupg @@ -17,7 +16,6 @@ import pytest import sdconfig from db import db -from encryption import EncryptionManager from flask import Flask, url_for from journalist_app import create_app as create_journalist_app from passphrases import PassphraseGenerator @@ -91,14 +89,11 @@ def setup_journalist_key_and_gpg_folder() -> Generator[Tuple[str, Path], None, N gpg = gnupg.GPG("gpg2", homedir=str(tmp_gpg_dir)) journalist_public_key_path = Path(__file__).parent / "files" / "test_journalist_key.pub" journalist_public_key = journalist_public_key_path.read_text() + # TODO: we don't need the journalist pub key in the keyring anymore, but include + # it anyways to match a legacy prod keyring. journalist_key_fingerprint = gpg.import_keys(journalist_public_key).fingerprints[0] - # Reduce source GPG key length to speed up tests at the expense of security - with mock.patch.object( - EncryptionManager, "GPG_KEY_LENGTH", PropertyMock(return_value=1024) - ): - - yield journalist_key_fingerprint, tmp_gpg_dir + yield journalist_key_fingerprint, tmp_gpg_dir finally: shutil.rmtree(tmp_gpg_dir, ignore_errors=True) @@ -230,7 +225,6 @@ def test_source(journalist_app: Flask, app_storage: Storage) -> Dict[str, Any]: source_passphrase=passphrase, source_app_storage=app_storage, ) - EncryptionManager.get_default().generate_source_key_pair(source_user) source = source_user.get_db_record() return { "source_user": source_user, diff --git a/securedrop/tests/factories.py b/securedrop/tests/factories.py --- a/securedrop/tests/factories.py +++ b/securedrop/tests/factories.py @@ -106,5 +106,10 @@ def create( config.TEMP_DIR.mkdir(parents=True) config.STORE_DIR.mkdir(parents=True) + # Copy the journalist public key into DATA_ROOT + shutil.copy2( + Path(__file__).parent / "files/test_journalist_key.pub", + config.SECUREDROP_DATA_ROOT / "journalist.pub", + ) # All done return config diff --git a/securedrop/tests/files/test_journalist_key.sec b/securedrop/tests/files/test_journalist_key.sec --- a/securedrop/tests/files/test_journalist_key.sec +++ b/securedrop/tests/files/test_journalist_key.sec @@ -1,6 +1,6 @@ -----BEGIN PGP PRIVATE KEY BLOCK----- -lQcYBFJZi2ABEACZJJA53+pEAdkZyD99nxB995ZVTBw60SQ/6E/gws4kInv+YS7t +lQdGBFJZi2ABEACZJJA53+pEAdkZyD99nxB995ZVTBw60SQ/6E/gws4kInv+YS7t wSMXGa5bR4SD9voWxzLgyulqbM93jUFKn5GcsSh2O/lxAvEDKsPmXCRP1eBg3pjU +8DRLm0TEFiywC+w6HF4PsOh+JlBWafUfL3vwrGKTXvrlKBsosvDmoogLjkMWomM KBF/97OKyQiMQf1BDJqZ88nScJEqwo0xz0PfcB04GAtfR7N6Qa8HpFc0VDQcILFB @@ -11,122 +11,124 @@ ak+Y8aolHDt6a785eF0AaAtgbPX4THMum/CNMksHO0PBBqxR+C9z7WSHXFHvv+8B CyIBiMZSK/j8PMJT1X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jWShxQBXeMRv/UXiaF1GZwdzkjl +CO3DEE8Tm0bQJapVxF2mF0Yr9KCldoOp3jeuwQESaXtvkst5cZV9RVzFkLdaiSVb +yWKbdeQYKKlqFk8wjOYkrTIpKD9re3/gCJbavJlRXMbC3Ne4qEg16ZsPuDUwqPcq +2Ak4UDa2KLJp3z41xmtrJ9gSMvGyJtY9OsrFb0vHmctTLnS0dqHVZLs8MoMNVaVV +SsFmUiAl7rbC70JcLI4y8g+r6fwQKtX5VEBzDWE1iCIIWiKXCqPpUclJvoWqdMNN +Yjdggj/P1q2LHDBJE3/Uh7xyiSSfw04beaU1o//3Yl4XuzKCrIABHzwnGitSg0U9 +7/hokYdFLqPpsMrNVZ3eT9MzwQDFOosg5A3RcI9n9yIdRlcNSjafqN9qqnxNYjTv +LloWhuJBg9y110tyO63CVZWB3/5A2nEr/y3f4Yr2AY/lpXGgO+hGGdh7bvI= +=kBsg -----END PGP PRIVATE KEY BLOCK----- diff --git a/securedrop/tests/functional/app_navigators/journalist_app_nav.py b/securedrop/tests/functional/app_navigators/journalist_app_nav.py --- a/securedrop/tests/functional/app_navigators/journalist_app_nav.py +++ b/securedrop/tests/functional/app_navigators/journalist_app_nav.py @@ -1,22 +1,20 @@ import base64 import gzip -import tempfile from binascii import unhexlify from random import randint from typing import Callable, Dict, Iterable, Optional, Tuple import requests import two_factor -from encryption import EncryptionManager from selenium.common.exceptions import NoSuchElementException from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support import expected_conditions +from tests import utils from tests.functional.app_navigators._nav_helper import NavigationHelper from tests.functional.tor_utils import proxies_for_url -from tests.test_encryption import import_journalist_private_key class JournalistAppNavigator: @@ -98,20 +96,7 @@ def _download_content_at_url(url: str, cookies: Dict[str, str]) -> bytes: data += chunk return data - @staticmethod - def _unzip_content(raw_content: bytes) -> str: - with tempfile.TemporaryFile() as fp: - fp.write(raw_content) - fp.seek(0) - - gzf = gzip.GzipFile(mode="rb", fileobj=fp) - content = gzf.read() - - return content.decode("utf-8") - - def journalist_downloads_first_message( - self, encryption_mgr_to_use_for_decryption: EncryptionManager - ) -> str: + def journalist_downloads_first_message(self) -> str: # Select the first submission from the first source in the page self.journalist_selects_the_first_source() self.nav_helper.wait_for( @@ -136,15 +121,13 @@ def cookie_string_from_selenium_cookies( cks = cookie_string_from_selenium_cookies(self.driver.get_cookies()) raw_content = self._download_content_at_url(file_url, cks) - with import_journalist_private_key(encryption_mgr_to_use_for_decryption): - decryption_result = encryption_mgr_to_use_for_decryption._gpg.decrypt(raw_content) - + decryption_result = utils.decrypt_as_journalist(raw_content) if file_url.endswith(".gz.gpg"): - decrypted_message = self._unzip_content(decryption_result.data) + decrypted_message = gzip.decompress(decryption_result) else: - decrypted_message = decryption_result.data.decode("utf-8") + decrypted_message = decryption_result - return decrypted_message + return decrypted_message.decode() def journalist_selects_the_first_source(self) -> None: self.driver.find_element_by_css_selector("#un-starred-source-link-1").click() diff --git a/securedrop/tests/functional/conftest.py b/securedrop/tests/functional/conftest.py --- a/securedrop/tests/functional/conftest.py +++ b/securedrop/tests/functional/conftest.py @@ -275,7 +275,6 @@ def create_source_and_submission(config_in_use: SecureDropConfig) -> Tuple[Sourc """ # This function will be called in a separate Process that runs the app # Hence the late imports - from encryption import EncryptionManager from models import Submission from passphrases import PassphraseGenerator from source_user import create_source_user @@ -291,7 +290,6 @@ def create_source_and_submission(config_in_use: SecureDropConfig) -> Tuple[Sourc source_app_storage=Storage.get_default(), ) source_db_record = source_user.get_db_record() - EncryptionManager.get_default().generate_source_key_pair(source_user) # Create a file submission from this source source_db_record.interaction_count += 1 diff --git a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py --- a/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py +++ b/securedrop/tests/functional/pageslayout/test_submit_and_retrieve_file.py @@ -1,5 +1,4 @@ import pytest -from encryption import EncryptionManager from selenium.common.exceptions import NoSuchElementException from tests.functional.app_navigators.journalist_app_nav import JournalistAppNavigator from tests.functional.app_navigators.source_app_nav import SourceAppNavigator @@ -48,13 +47,7 @@ def test_submit_and_retrieve_happy_path( # And when they try to download the file # Then it succeeds and the journalist sees the correct content - apps_sd_config = sd_servers_with_clean_state.config_in_use - retrieved_message = journ_app_nav.journalist_downloads_first_message( - encryption_mgr_to_use_for_decryption=EncryptionManager( - gpg_key_dir=apps_sd_config.GPG_KEY_DIR, - journalist_key_fingerprint=apps_sd_config.JOURNALIST_KEY, - ) - ) + retrieved_message = journ_app_nav.journalist_downloads_first_message() assert retrieved_message == submitted_content # And when they reply to the source, it succeeds diff --git a/securedrop/tests/functional/test_submit_and_retrieve_message.py b/securedrop/tests/functional/test_submit_and_retrieve_message.py --- a/securedrop/tests/functional/test_submit_and_retrieve_message.py +++ b/securedrop/tests/functional/test_submit_and_retrieve_message.py @@ -1,4 +1,3 @@ -from encryption import EncryptionManager from tests.functional.app_navigators.journalist_app_nav import JournalistAppNavigator from tests.functional.app_navigators.source_app_nav import SourceAppNavigator @@ -37,11 +36,5 @@ def test_submit_and_retrieve_happy_path( # And they try to download the message # Then it succeeds and the journalist sees correct message - servers_sd_config = sd_servers_with_clean_state.config_in_use - retrieved_message = journ_app_nav.journalist_downloads_first_message( - encryption_mgr_to_use_for_decryption=EncryptionManager( - gpg_key_dir=servers_sd_config.GPG_KEY_DIR, - journalist_key_fingerprint=servers_sd_config.JOURNALIST_KEY, - ) - ) + retrieved_message = journ_app_nav.journalist_downloads_first_message() assert retrieved_message == submitted_message diff --git a/securedrop/tests/migrations/migration_811334d7105f.py b/securedrop/tests/migrations/migration_811334d7105f.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_811334d7105f.py @@ -0,0 +1,105 @@ +import uuid + +from db import db +from journalist_app import create_app +from sqlalchemy import text + + +class UpgradeTester: + def __init__(self, config): + self.config = config + self.app = create_app(self.config) + self.uuid = str(uuid.uuid4()) + + def load_data(self): + """Create a source""" + with self.app.app_context(): + source = { + "uuid": self.uuid, + "filesystem_id": "5678", + "journalist_designation": "alienated licensee", + "interaction_count": 0, + } + sql = """\ + INSERT INTO sources (uuid, filesystem_id, journalist_designation, + interaction_count) + VALUES (:uuid, :filesystem_id, :journalist_designation, + :interaction_count)""" + db.engine.execute(text(sql), **source) + + def check_upgrade(self): + """Verify PGP fields can be queried and modified""" + with self.app.app_context(): + query_sql = """\ + SELECT pgp_fingerprint, pgp_public_key, pgp_secret_key + FROM sources + WHERE uuid = :uuid""" + source = db.engine.execute( + text(query_sql), + uuid=self.uuid, + ).fetchone() + # Fields are set to NULL by default + assert source == (None, None, None) + update_sql = """\ + UPDATE sources + SET pgp_fingerprint=:pgp_fingerprint, pgp_public_key=:pgp_public_key, + pgp_secret_key=:pgp_secret_key + WHERE uuid = :uuid""" + db.engine.execute( + text(update_sql), + pgp_fingerprint="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + pgp_public_key="a public key!", + pgp_secret_key="a secret key!", + uuid=self.uuid, + ) + source = db.engine.execute(text(query_sql), uuid=self.uuid).fetchone() + # Fields are the values we set them to + assert source == ( + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "a public key!", + "a secret key!", + ) + + +class DowngradeTester: + def __init__(self, config): + self.config = config + self.app = create_app(self.config) + self.uuid = str(uuid.uuid4()) + + def load_data(self): + """Create a source with a PGP key pair stored""" + with self.app.app_context(): + source = { + "uuid": self.uuid, + "filesystem_id": "1234", + "journalist_designation": "mucky pine", + "interaction_count": 0, + "pgp_fingerprint": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "pgp_public_key": "very public", + "pgp_secret_key": "very secret", + } + sql = """\ + INSERT INTO sources (uuid, filesystem_id, journalist_designation, + interaction_count, pgp_fingerprint, pgp_public_key, pgp_secret_key) + VALUES (:uuid, :filesystem_id, :journalist_designation, + :interaction_count, :pgp_fingerprint, :pgp_public_key, :pgp_secret_key)""" + db.engine.execute(text(sql), **source) + + def check_downgrade(self): + """Verify the downgrade does nothing, i.e. the PGP fields are still there""" + with self.app.app_context(): + sql = """\ + SELECT pgp_fingerprint, pgp_public_key, pgp_secret_key + FROM sources + WHERE uuid = :uuid""" + source = db.engine.execute( + text(sql), + uuid=self.uuid, + ).fetchone() + print(source) + assert source == ( + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "very public", + "very secret", + ) diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -137,6 +137,8 @@ def test_alembic_migration_up_and_down(alembic_config, config, migration, _reset @pytest.mark.parametrize("migration", ALL_MIGRATIONS) def test_schema_unchanged_after_up_then_downgrade(alembic_config, config, migration, _reset_db): + if migration == "811334d7105f": + pytest.skip("811334d7105f_sequoia_pgp doesn't delete columns on downgrade") # Create the app here. Using a fixture will init the database. app = create_app(config) diff --git a/securedrop/tests/test_encryption.py b/securedrop/tests/test_encryption.py --- a/securedrop/tests/test_encryption.py +++ b/securedrop/tests/test_encryption.py @@ -1,69 +1,30 @@ -import typing -from contextlib import contextmanager -from datetime import datetime from pathlib import Path import pytest from db import db -from encryption import EncryptionManager, GpgDecryptError, GpgEncryptError, GpgKeyNotFoundError +from encryption import EncryptionManager, GpgDecryptError, GpgKeyNotFoundError from passphrases import PassphraseGenerator from source_user import create_source_user +from tests import utils + +from redwood import RedwoodError class TestEncryptionManager: def test_get_default(self, config): + # Given an encryption manager encryption_mgr = EncryptionManager.get_default() assert encryption_mgr - assert encryption_mgr.get_journalist_public_key() - - def test_generate_source_key_pair( - self, setup_journalist_key_and_gpg_folder, source_app, app_storage - ): - # Given a source user - with source_app.app_context(): - source_user = create_source_user( - db_session=db.session, - source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), - source_app_storage=app_storage, - ) - - # And an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) - - # When using the encryption manager to generate a key pair for this source user + # When using the encryption manager to fetch the journalist public key # It succeeds - encryption_mgr.generate_source_key_pair(source_user) - - # And the newly-created key's fingerprint was added to Redis - fingerprint_in_redis = encryption_mgr._redis.hget( - encryption_mgr.REDIS_FINGERPRINT_HASH, source_user.filesystem_id - ) - assert fingerprint_in_redis - source_key_fingerprint = encryption_mgr.get_source_key_fingerprint( - source_user.filesystem_id - ) - assert fingerprint_in_redis == source_key_fingerprint - - # And the user's newly-generated public key can be retrieved - assert encryption_mgr.get_source_public_key(source_user.filesystem_id) - - # And the key has a hardcoded creation date to avoid leaking information about when sources - # first created their account - source_key_details = encryption_mgr._get_source_key_details(source_user.filesystem_id) - assert source_key_details - creation_date = _parse_gpg_date_string(source_key_details["date"]) - assert creation_date.date() == EncryptionManager.DEFAULT_KEY_CREATION_DATE - - # And the user's key does not expire - assert source_key_details["expires"] == "" + journalist_pub_key = encryption_mgr.get_journalist_public_key() + assert journalist_pub_key.startswith("-----BEGIN PGP PUBLIC KEY BLOCK----") - def test_get_source_public_key(self, test_source): - # Given a source user with a key pair in the default encryption manager + def test_get_gpg_source_public_key(self, test_source): + # Given a source user with a key pair in the gpg keyring source_user = test_source["source_user"] encryption_mgr = EncryptionManager.get_default() + utils.create_legacy_gpg_key(encryption_mgr, source_user, test_source["source"]) # When using the encryption manager to fetch the source user's public key # It succeeds @@ -80,35 +41,21 @@ def test_get_source_public_key(self, test_source): # And the public key was saved to Redis assert encryption_mgr._redis.hget(encryption_mgr.REDIS_KEY_HASH, source_key_fingerprint) - def test_get_journalist_public_key(self, setup_journalist_key_and_gpg_folder): - # Given an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) - - # When using the encryption manager to fetch the journalist public key - # It succeeds - journalist_pub_key = encryption_mgr.get_journalist_public_key() - assert journalist_pub_key - assert journalist_pub_key.startswith("-----BEGIN PGP PUBLIC KEY BLOCK----") - - def test_get_source_public_key_wrong_id(self, setup_journalist_key_and_gpg_folder): + def test_get_gpg_source_public_key_wrong_id(self, test_source): # Given an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) + encryption_mgr = EncryptionManager.get_default() # When using the encryption manager to fetch a key for an invalid filesystem id # It fails with pytest.raises(GpgKeyNotFoundError): encryption_mgr.get_source_public_key("1234test") - def test_delete_source_key_pair(self, source_app, test_source): - # Given a source user with a key pair in the default encryption manager + def test_delete_gpg_source_key_pair(self, source_app, test_source): + # Given a source user with a key pair in the gpg keyring source_user = test_source["source_user"] encryption_mgr = EncryptionManager.get_default() + utils.create_legacy_gpg_key(encryption_mgr, source_user, test_source["source"]) + assert encryption_mgr.get_source_public_key(source_user.filesystem_id) # When using the encryption manager to delete this source user's key pair # It succeeds @@ -124,27 +71,17 @@ def test_delete_source_key_pair(self, source_app, test_source): with pytest.raises(GpgKeyNotFoundError): encryption_mgr._get_source_key_details(source_user.filesystem_id) - def test_delete_source_key_pair_on_journalist_key(self, setup_journalist_key_and_gpg_folder): - # Given an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) - - # When trying to delete the journalist key via the encryption manager - # It fails - with pytest.raises(GpgKeyNotFoundError): - encryption_mgr.delete_source_key_pair(journalist_key_fingerprint) - def test_delete_source_key_pair_pinentry_status_is_handled( self, source_app, test_source, mocker, capsys ): """ Regression test for https://github.com/freedomofpress/securedrop/issues/4294 """ - # Given a source user with a key pair in the default encryption manager + # Given a source user with a key pair in the gpg keyring source_user = test_source["source_user"] encryption_mgr = EncryptionManager.get_default() + utils.create_legacy_gpg_key(encryption_mgr, source_user, test_source["source"]) + assert encryption_mgr.get_source_public_key(source_user.filesystem_id) # And a gpg binary that will trigger the issue described in #4294 mocker.patch( @@ -164,12 +101,9 @@ def test_delete_source_key_pair_pinentry_status_is_handled( captured = capsys.readouterr() assert "ValueError: Unknown status message: 'PINENTRY_LAUNCHED'" not in captured.err - def test_encrypt_source_message(self, setup_journalist_key_and_gpg_folder, tmp_path): + def test_encrypt_source_message(self, config, tmp_path): # Given an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) + encryption_mgr = EncryptionManager.get_default() # And a message to be submitted by a source message = "s3cr3t message" @@ -183,91 +117,131 @@ def test_encrypt_source_message(self, setup_journalist_key_and_gpg_folder, tmp_p # And the output file contains the encrypted data encrypted_message = encrypted_message_path.read_bytes() - assert encrypted_message + assert encrypted_message.startswith(b"-----BEGIN PGP MESSAGE-----") # And the journalist is able to decrypt the message - with import_journalist_private_key(encryption_mgr): - decrypted_message = encryption_mgr._gpg.decrypt(encrypted_message).data - assert decrypted_message.decode() == message + decrypted_message = utils.decrypt_as_journalist(encrypted_message).decode() + assert decrypted_message == message - # And the source or anyone else is NOT able to decrypt the message - # For GPG 2.1+, a non-null passphrase _must_ be passed to decrypt() - assert not encryption_mgr._gpg.decrypt(encrypted_message, passphrase="test 123").ok - - def test_encrypt_source_file(self, setup_journalist_key_and_gpg_folder, tmp_path): + def test_encrypt_source_file(self, config, tmp_path): # Given an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) + encryption_mgr = EncryptionManager.get_default() # And a file to be submitted by a source - we use this python file file_to_encrypt_path = Path(__file__) - with file_to_encrypt_path.open() as file_to_encrypt: - # When the source tries to encrypt the file - # It succeeds - encrypted_file_path = tmp_path / "file.gpg" + # When the source tries to encrypt the file + # It succeeds + encrypted_file_path = tmp_path / "file.gpg" + with file_to_encrypt_path.open("rb") as fh: encryption_mgr.encrypt_source_file( - file_in=file_to_encrypt, + file_in=fh, encrypted_file_path_out=encrypted_file_path, ) - # And the output file contains the encrypted data - encrypted_file = encrypted_file_path.read_bytes() - assert encrypted_file + # And the output file contains the encrypted data + encrypted_file = encrypted_file_path.read_bytes() + assert encrypted_file.startswith(b"-----BEGIN PGP MESSAGE-----") # And the journalist is able to decrypt the file - with import_journalist_private_key(encryption_mgr): - decrypted_file = encryption_mgr._gpg.decrypt(encrypted_file).data - assert decrypted_file.decode() == file_to_encrypt_path.read_text() - - # And the source or anyone else is NOT able to decrypt the file - # For GPG 2.1+, a non-null passphrase _must_ be passed to decrypt() - assert not encryption_mgr._gpg.decrypt(encrypted_file, passphrase="test 123").ok + decrypted_file = utils.decrypt_as_journalist(encrypted_file) + assert decrypted_file == file_to_encrypt_path.read_bytes() def test_encrypt_and_decrypt_journalist_reply( self, source_app, test_source, tmp_path, app_storage ): - # Given a source user with a key pair in the default encryption manager + # Given a source user source_user1 = test_source["source_user"] + source1 = test_source["source"] encryption_mgr = EncryptionManager.get_default() - # And another source with a key pair in the default encryption manager + # And another source user with source_app.app_context(): source_user2 = create_source_user( db_session=db.session, source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), source_app_storage=app_storage, ) - encryption_mgr.generate_source_key_pair(source_user2) + source_user2.get_db_record() # When the journalist tries to encrypt a reply to source1 # It succeeds journalist_reply = "s3cr3t message" encrypted_reply_path = tmp_path / "reply.gpg" encryption_mgr.encrypt_journalist_reply( - for_source_with_filesystem_id=source_user1.filesystem_id, + for_source=source1, reply_in=journalist_reply, encrypted_reply_path_out=encrypted_reply_path, ) # And the output file contains the encrypted data encrypted_reply = encrypted_reply_path.read_bytes() - assert encrypted_reply + assert encrypted_reply.startswith(b"-----BEGIN PGP MESSAGE-----") # And source1 is able to decrypt the reply decrypted_reply = encryption_mgr.decrypt_journalist_reply( - for_source_user=source_user1, ciphertext_in=encrypted_reply + for_source_user=source_user1, + ciphertext_in=encrypted_reply, ) - assert decrypted_reply assert decrypted_reply == journalist_reply # And source2 is NOT able to decrypt the reply - with pytest.raises(GpgDecryptError): + with pytest.raises(RedwoodError): encryption_mgr.decrypt_journalist_reply( - for_source_user=source_user2, ciphertext_in=encrypted_reply + for_source_user=source_user2, + ciphertext_in=encrypted_reply, + ) + + # And the journalist is able to decrypt their own reply + decrypted_reply_for_journalist = utils.decrypt_as_journalist(encrypted_reply) + assert decrypted_reply_for_journalist.decode() == journalist_reply + + def test_gpg_encrypt_and_decrypt_journalist_reply( + self, source_app, test_source, tmp_path, app_storage + ): + # Given a source user with a key pair in the gpg keyring + source_user1 = test_source["source_user"] + source1 = test_source["source"] + encryption_mgr = EncryptionManager.get_default() + utils.create_legacy_gpg_key(encryption_mgr, source_user1, source1) + + # And another source with a key pair in the gpg keyring + with source_app.app_context(): + source_user2 = create_source_user( + db_session=db.session, + source_passphrase=PassphraseGenerator.get_default().generate_passphrase(), + source_app_storage=app_storage, + ) + source2 = source_user2.get_db_record() + utils.create_legacy_gpg_key(encryption_mgr, source_user2, source2) + + # When the journalist tries to encrypt a reply to source1 + # It succeeds + journalist_reply = "s3cr3t message" + encrypted_reply_path = tmp_path / "reply.gpg" + encryption_mgr.encrypt_journalist_reply( + for_source=source1, + reply_in=journalist_reply, + encrypted_reply_path_out=encrypted_reply_path, + ) + + # And the output file contains the encrypted data + encrypted_reply = encrypted_reply_path.read_bytes() + assert encrypted_reply.startswith(b"-----BEGIN PGP MESSAGE-----") + + # And source1 is able to decrypt the reply + decrypted_reply = encryption_mgr.decrypt_journalist_reply( + for_source_user=source_user1, + ciphertext_in=encrypted_reply, ) + assert decrypted_reply == journalist_reply + + # And source2 is NOT able to decrypt the reply + with pytest.raises(GpgDecryptError): + encryption_mgr.decrypt_journalist_reply( + for_source_user=source_user2, + ciphertext_in=encrypted_reply, + ) # Amd the reply can't be decrypted without providing the source1's gpg secret result = encryption_mgr._gpg.decrypt( @@ -278,77 +252,5 @@ def test_encrypt_and_decrypt_journalist_reply( assert not result.ok # And the journalist is able to decrypt their reply - with import_journalist_private_key(encryption_mgr): - decrypted_reply_for_journalist = encryption_mgr._gpg.decrypt( - # For GPG 2.1+, a non-null passphrase _must_ be passed to decrypt() - encrypted_reply, - passphrase="test 123", - ).data - assert decrypted_reply_for_journalist.decode() == journalist_reply - - def test_encrypt_fails(self, setup_journalist_key_and_gpg_folder, tmp_path): - # Given an encryption manager - journalist_key_fingerprint, gpg_key_dir = setup_journalist_key_and_gpg_folder - encryption_mgr = EncryptionManager( - gpg_key_dir=gpg_key_dir, journalist_key_fingerprint=journalist_key_fingerprint - ) - - # When trying to encrypt some data without providing any recipient - # It fails and the right exception is raised - with pytest.raises(GpgEncryptError) as exc: - encryption_mgr._encrypt( - using_keys_with_fingerprints=[], - plaintext_in="test", - ciphertext_path_out=tmp_path / "encrypt_fails", - ) - assert "no terminal at all requested" in str(exc) - - -def _parse_gpg_date_string(date_string: str) -> datetime: - """Parse a date string returned from `gpg --with-colons --list-keys` into a datetime. - - The format of the date strings is complicated; see gnupg doc/DETAILS for a - full explanation. - - Key details: - - The creation date of the key is given in UTC. - - the date is usually printed in seconds since epoch, however, we are - migrating to an ISO 8601 format (e.g. "19660205T091500"). A simple - way to detect the new format is to scan for the 'T'. - """ - if "T" in date_string: - dt = datetime.strptime(date_string, "%Y%m%dT%H%M%S") - else: - dt = datetime.utcfromtimestamp(int(date_string)) - return dt - - -@contextmanager -def import_journalist_private_key( - encryption_mgr: EncryptionManager, -) -> typing.Generator[None, None, None]: - """Import the journalist secret key so the encryption_mgr can decrypt data for the journalist. - - The journalist secret key is removed at the end of this context manager in order to not impact - other decryption-related tests. - """ - # Import the journalist private key - journalist_private_key_path = Path(__file__).parent / "files" / "test_journalist_key.sec" - encryption_mgr._gpg.import_keys(journalist_private_key_path.read_text()) - journalist_secret_key_fingerprint = "C1C4E16BB24E4F4ABF37C3A6C3E7C4C0A2201B2A" - - yield - - # Make sure to remove the journalist private key to not impact the other tests - encryption_mgr._gpg_for_key_deletion.delete_keys( - fingerprints=journalist_secret_key_fingerprint, secret=True, subkeys=False - ) - - # Double check that the journalist private key was removed - is_journalist_secret_key_available = False - for key in encryption_mgr._gpg.list_keys(secret=True): - for uid in key["uids"]: - if "SecureDrop Test" in uid: - is_journalist_secret_key_available = True - break - assert not is_journalist_secret_key_available + decrypted_reply_for_journalist = utils.decrypt_as_journalist(encrypted_reply).decode() + assert decrypted_reply_for_journalist == journalist_reply diff --git a/securedrop/tests/test_integration.py b/securedrop/tests/test_integration.py --- a/securedrop/tests/test_integration.py +++ b/securedrop/tests/test_integration.py @@ -15,7 +15,6 @@ from source_app.session_manager import SessionManager from store import Storage from tests import utils -from tests.test_encryption import import_journalist_private_key from tests.utils import login_journalist from two_factor import TOTP @@ -78,11 +77,8 @@ def test_submit_message(journalist_app, source_app, test_journo, app_storage): resp = app.get(submission_url) assert resp.status_code == 200 - encryption_mgr = EncryptionManager.get_default() - with import_journalist_private_key(encryption_mgr): - decryption_result = encryption_mgr._gpg.decrypt(resp.data) - assert decryption_result.ok - assert decryption_result.data.decode("utf-8") == test_msg + decryption_result = utils.decrypt_as_journalist(resp.data).decode() + assert decryption_result == test_msg # delete submission resp = app.get(col_url) @@ -175,12 +171,8 @@ def test_submit_file(journalist_app, source_app, test_journo, app_storage): resp = app.get(submission_url) assert resp.status_code == 200 - encryption_mgr = EncryptionManager.get_default() - with import_journalist_private_key(encryption_mgr): - decrypted_data = encryption_mgr._gpg.decrypt(resp.data) - assert decrypted_data.ok - - sio = BytesIO(decrypted_data.data) + decrypted_data = utils.decrypt_as_journalist(resp.data) + sio = BytesIO(decrypted_data) with gzip.GzipFile(mode="rb", fileobj=sio) as gzip_file: unzipped_decrypted_data = gzip_file.read() mtime = gzip_file.mtime @@ -225,7 +217,7 @@ def assertion(): utils.asynchronous.wait_for_assertion(assertion) -def _helper_test_reply(journalist_app, source_app, test_journo, test_reply, expected_success=True): +def _helper_test_reply(journalist_app, source_app, test_journo, test_reply): test_msg = "This is a test message." with source_app.test_client() as app: @@ -260,8 +252,6 @@ def _helper_test_reply(journalist_app, source_app, test_journo, test_reply, expe resp = app.get(col_url) assert resp.status_code == 200 - assert EncryptionManager.get_default().get_source_key_fingerprint(filesystem_id) - # Create 2 replies to test deleting on journalist and source interface with journalist_app.test_client() as app: login_journalist( @@ -275,11 +265,8 @@ def _helper_test_reply(journalist_app, source_app, test_journo, test_reply, expe ) assert resp.status_code == 200 - if not expected_success: - pass - else: - text = resp.data.decode("utf-8") - assert "The source will receive your reply" in text + text = resp.data.decode("utf-8") + assert "The source will receive your reply" in text resp = app.get(col_url) text = resp.data.decode("utf-8") @@ -304,8 +291,10 @@ def _helper_test_reply(journalist_app, source_app, test_journo, test_reply, expe zf = zipfile.ZipFile(BytesIO(resp.data), "r") data = zf.read(zf.namelist()[0]) - _can_decrypt_with_journalist_secret_key(data) - _can_decrypt_with_source_secret_key(data, source_user.gpg_secret) + journalist_decrypted = utils.decrypt_as_journalist(data).decode() + assert journalist_decrypted == test_reply + source_decrypted = EncryptionManager.get_default().decrypt_journalist_reply(source_user, data) + assert source_decrypted == test_reply # Test deleting reply on the journalist interface last_reply_number = len(soup.select('input[name="doc_names_selected"]')) - 1 @@ -318,22 +307,18 @@ def _helper_test_reply(journalist_app, source_app, test_journo, test_reply, expe assert resp.status_code == 200 text = resp.data.decode("utf-8") - if not expected_success: - # there should be no reply - assert "You have received a reply." not in text - else: - assert "You have received a reply. To protect your identity" in text - assert test_reply in text, text - soup = BeautifulSoup(text, "html.parser") - msgid = soup.select('form > input[name="reply_filename"]')[0]["value"] - resp = app.post( - "/delete", - data=dict(filesystem_id=filesystem_id, reply_filename=msgid), - follow_redirects=True, - ) - assert resp.status_code == 200 - text = resp.data.decode("utf-8") - assert "Reply deleted" in text + assert "You have received a reply. To protect your identity" in text + assert test_reply in text, text + soup = BeautifulSoup(text, "html.parser") + msgid = soup.select('form > input[name="reply_filename"]')[0]["value"] + resp = app.post( + "/delete", + data=dict(filesystem_id=filesystem_id, reply_filename=msgid), + follow_redirects=True, + ) + assert resp.status_code == 200 + text = resp.data.decode("utf-8") + assert "Reply deleted" in text app.get("/logout") @@ -367,26 +352,6 @@ def assertion(): utils.asynchronous.wait_for_assertion(assertion) -def _can_decrypt_with_journalist_secret_key(msg: bytes) -> None: - encryption_mgr = EncryptionManager.get_default() - with import_journalist_private_key(encryption_mgr): - # For GPG 2.1+, a non null passphrase _must_ be passed to decrypt() - decryption_result = encryption_mgr._gpg.decrypt(msg, passphrase="dummy passphrase") - - assert decryption_result.ok, "Could not decrypt msg with key, gpg says: {}".format( - decryption_result.stderr - ) - - -def _can_decrypt_with_source_secret_key(msg: bytes, source_gpg_secret: str) -> None: - encryption_mgr = EncryptionManager.get_default() - decryption_result = encryption_mgr._gpg.decrypt(msg, passphrase=source_gpg_secret) - - assert decryption_result.ok, "Could not decrypt msg with key, gpg says: {}".format( - decryption_result.stderr - ) - - def test_reply_normal(journalist_app, source_app, test_journo): """Test for regression on #1360 (failure to encode bytes before calling gpg functions). @@ -398,7 +363,6 @@ def test_reply_normal(journalist_app, source_app, test_journo): source_app, test_journo, "This is a test reply.", - True, ) @@ -418,7 +382,6 @@ def test_unicode_reply_with_ansi_env(journalist_app, source_app, test_journo): source_app, test_journo, "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ", - True, ) diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -41,7 +41,6 @@ from tests import utils from tests.factories import SecureDropConfigFactory from tests.functional.db_session import get_database_session -from tests.utils import login_journalist from tests.utils.i18n import ( get_plural_tests, get_test_locales, @@ -52,6 +51,8 @@ from tests.utils.instrument import InstrumentedApp from two_factor import TOTP +from .utils import create_legacy_gpg_key, login_journalist + # Smugly seed the RNG for deterministic testing random.seed(r"¯\_(ツ)_/¯") @@ -2867,10 +2868,15 @@ def test_delete_collection_updates_db(journalist_app, test_journo, test_source, assert not seen_reply -def test_delete_source_deletes_source_key(journalist_app, test_source, test_journo, app_storage): - """Verify that when a source is deleted, the PGP key that corresponds +def test_delete_source_deletes_gpg_source_key( + journalist_app, test_source, test_journo, app_storage +): + """Verify that when a legacy source is deleted, the GPG key that corresponds to them is also deleted.""" + encryption_mgr = EncryptionManager.get_default() + create_legacy_gpg_key(encryption_mgr, test_source["source_user"], test_source["source"]) + with journalist_app.app_context(): source = Source.query.get(test_source["id"]) journo = Journalist.query.get(test_journo["id"]) @@ -2879,7 +2885,6 @@ def test_delete_source_deletes_source_key(journalist_app, test_source, test_jour utils.db_helper.reply(app_storage, journo, source, 2) # Source key exists - encryption_mgr = EncryptionManager.get_default() assert encryption_mgr.get_source_key_fingerprint(test_source["filesystem_id"]) journalist_app_module.utils.delete_collection(test_source["filesystem_id"]) diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -1,16 +1,16 @@ import json import random from datetime import datetime +from pathlib import Path from uuid import UUID, uuid4 from db import db from encryption import EncryptionManager from flask import url_for from models import Journalist, Reply, Source, SourceStar, Submission +from tests.utils.api_helper import get_api_headers from two_factor import TOTP -from .utils.api_helper import get_api_headers - random.seed("◔ ⌣ ◔") @@ -767,7 +767,7 @@ def test_unencrypted_replies_get_rejected( def test_authorized_user_can_add_reply( - journalist_app, journalist_api_token, test_source, test_journo, app_storage + journalist_app, journalist_api_token, test_source, test_journo, app_storage, tmp_path ): with journalist_app.test_client() as app: source_id = test_source["source"].id @@ -776,12 +776,15 @@ def test_authorized_user_can_add_reply( # First we must encrypt the reply, or it will get rejected # by the server. encryption_mgr = EncryptionManager.get_default() - source_key = encryption_mgr.get_source_key_fingerprint(test_source["source"].filesystem_id) - reply_content = encryption_mgr._gpg.encrypt("This is a plaintext reply", source_key).data + reply_path = tmp_path / "message.gpg" + encryption_mgr.encrypt_journalist_reply( + test_source["source"], "This is a plaintext reply", reply_path + ) + reply_content = reply_path.read_text() response = app.post( url_for("api.all_source_replies", source_uuid=uuid), - data=json.dumps({"reply": reply_content.decode("utf-8")}), + data=json.dumps({"reply": reply_content}), headers=get_api_headers(journalist_api_token), ) assert response.status_code == 201 @@ -809,10 +812,9 @@ def test_authorized_user_can_add_reply( source.interaction_count, source.journalist_filename ) - expected_filepath = app_storage.path(source.filesystem_id, expected_filename) + expected_filepath = Path(app_storage.path(source.filesystem_id, expected_filename)) - with open(expected_filepath, "rb") as fh: - saved_content = fh.read() + saved_content = expected_filepath.read_text() assert reply_content == saved_content diff --git a/securedrop/tests/test_pretty_bad_protocol.py b/securedrop/tests/test_pretty_bad_protocol.py --- a/securedrop/tests/test_pretty_bad_protocol.py +++ b/securedrop/tests/test_pretty_bad_protocol.py @@ -30,7 +30,7 @@ def test_gpg_export_keys(tmp_path): message = "GPG to Sequoia-PGP, yippe!" ciphertext = tmp_path / "encrypted.asc" redwood.encrypt_message([public_key], message, ciphertext) - decrypted = redwood.decrypt(ciphertext.read_bytes(), secret_key, passphrase) + decrypted = redwood.decrypt(ciphertext.read_bytes(), secret_key, passphrase).decode() assert decrypted == message # Test some failure cases for exporting the secret key: diff --git a/securedrop/tests/test_redwood.py b/securedrop/tests/test_redwood.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_redwood.py @@ -0,0 +1,38 @@ +# Integration tests for the redwood Python/Sequoia bridge + +import pytest +from secure_tempfile import SecureTemporaryFile + +import redwood + +PASSPHRASE = "correcthorsebatterystaple" +SECRET_MESSAGE = "Rust-in-Python is really great 🦀" + + [email protected](scope="session") +def key_pair(): + return redwood.generate_source_key_pair(PASSPHRASE, "[email protected]") + + +def test_encrypt_stream(tmp_path, key_pair): + (public_key, secret_key, fingerprint) = key_pair + iterations = 100_000 # force a good amount of chunks + file = tmp_path / "file.asc" + with SecureTemporaryFile("/tmp") as stf: + for _ in range(iterations): + stf.write(SECRET_MESSAGE.encode()) + + redwood.encrypt_stream([public_key], stf, file) + ciphertext = file.read_bytes() + actual = redwood.decrypt(ciphertext, secret_key, PASSPHRASE) + assert (SECRET_MESSAGE * iterations) == actual.decode() + + +def test_encrypt_stream_bad(tmp_path, key_pair): + (public_key, secret_key, fingerprint) = key_pair + not_stream = SECRET_MESSAGE.encode() + file = tmp_path / "file.asc" + with pytest.raises( + redwood.RedwoodError, match="AttributeError: 'bytes' object has no attribute 'read'" + ): + redwood.encrypt_stream([public_key], not_stream, file) diff --git a/securedrop/tests/test_secure_tempfile.py b/securedrop/tests/test_secure_tempfile.py --- a/securedrop/tests/test_secure_tempfile.py +++ b/securedrop/tests/test_secure_tempfile.py @@ -1,7 +1,6 @@ import os import pytest -from pretty_bad_protocol._util import _is_stream from secure_tempfile import SecureTemporaryFile MESSAGE = "410,757,864,530" @@ -78,10 +77,6 @@ def test_file_is_removed_from_disk(): assert not os.path.exists(f.filepath) -def test_SecureTemporaryFile_is_a_STREAMLIKE_TYPE(): - assert _is_stream(SecureTemporaryFile("/tmp")) - - def test_buffered_read(): f = SecureTemporaryFile("/tmp") msg = MESSAGE * 1000 diff --git a/securedrop/tests/utils/__init__.py b/securedrop/tests/utils/__init__.py --- a/securedrop/tests/utils/__init__.py +++ b/securedrop/tests/utils/__init__.py @@ -1,10 +1,20 @@ +import datetime +from pathlib import Path + import flask import models from db import db +from encryption import EncryptionManager from flask.testing import FlaskClient +from source_user import SourceUser from tests.utils import asynchronous, db_helper # noqa: F401 from two_factor import TOTP +import redwood + +JOURNALIST_SECRET_KEY_PATH = Path(__file__).parent.parent / "files" / "test_journalist_key.sec" +JOURNALIST_SECRET_KEY = JOURNALIST_SECRET_KEY_PATH.read_text() + def flaky_filter_xfail(err, *args): """ @@ -56,3 +66,40 @@ def login_journalist( assert session.get_user() is not None _reset_journalist_last_token(username) + + +def decrypt_as_journalist(ciphertext: bytes) -> bytes: + return redwood.decrypt( + ciphertext=ciphertext, + secret_key=JOURNALIST_SECRET_KEY, + passphrase="correcthorsebatterystaple", + ) + + +def create_legacy_gpg_key( + manager: EncryptionManager, source_user: SourceUser, source: models.Source +) -> None: + """Create a GPG key for the source, so we can test pre-Sequoia behavior""" + # All reply keypairs will be "created" on the same day SecureDrop (then + # Strongbox) was publicly released for the first time. + # https://www.newyorker.com/news/news-desk/strongbox-and-aaron-swartz + default_key_creation_date = datetime.date(2013, 5, 14) + gen_key_input = manager._gpg.gen_key_input( + passphrase=source_user.gpg_secret, + name_email=source_user.filesystem_id, + key_type="RSA", + key_length=4096, + name_real="Source Key", + creation_date=default_key_creation_date.isoformat(), + # '0' is the magic value that tells GPG's batch key generation not + # to set an expiration date. + expire_date="0", + ) + manager._gpg.gen_key(gen_key_input) + + # Delete the Sequoia-generated keys + source.pgp_public_key = None + source.pgp_fingerprint = None + source.pgp_secret_key = None + db.session.add(source) + db.session.commit() diff --git a/securedrop/tests/utils/db_helper.py b/securedrop/tests/utils/db_helper.py --- a/securedrop/tests/utils/db_helper.py +++ b/securedrop/tests/utils/db_helper.py @@ -74,7 +74,7 @@ def reply(storage, journalist, source, num_replies): fname = f"{source.interaction_count}-{source.journalist_filename}-reply.gpg" EncryptionManager.get_default().encrypt_journalist_reply( - for_source_with_filesystem_id=source.filesystem_id, + for_source=source, reply_in=str(os.urandom(1)), encrypted_reply_path_out=storage.path(source.filesystem_id, fname), ) @@ -104,7 +104,6 @@ def init_source(storage): source_passphrase=passphrase, source_app_storage=storage, ) - EncryptionManager.get_default().generate_source_key_pair(source_user) return source_user.get_db_record(), passphrase
New source creation uses Sequoia As part of our work to migrate to Sequoia, the first step is to have new source creation generate a PGP key pair using Sequoia, and then use those keys for encryption/decryption. This work will include: * Writing Sequoia bindings for Python * Converting key storage to be in the database * Switching over new source creation to use those functions and store said keys in the database. Most of this work already exists in the oxidize branch
What is coming in this PR: * Storing journalist public key out of the GPG keyring - including a hopefully not too hacky postinst migration * DB schema change, adding 3 columns to the source table * Changing all the EncryptionManager.encrypt_* functions to use redwood, and sometimes the decrypt function * Actually switching the new source creation to Sequoia Honestly I've spent most of the time getting tests to pass, including: * Getting rid of all `EncryptionManager._gpg` direct calls and fixing all the other `EncryptionManager` calls really. * Encrypting the journalist test key with a passphrase because Sequoia wants that Except some tests are failing with `redwood.RedwoodError: OpenPgp(Missing session key: No session key decrypted)` in my new `utils.decrypt_as_journalist()` function. I'm trying to get everything else passing before I dive into this one. The missing session key issue seems to be with encrypting a message for multiple recipients. Here's a pure-Rust test case that fails: ```rust #[test] fn test_multiple_recipients() { // Generate 2 keys let (public_key1, secret_key1, _fingerprint1) = generate_source_key_pair( "correcthorsebatterystaple", "[email protected]", ) .unwrap(); let (public_key2, secret_key2, _fingerprint2) = generate_source_key_pair( "correcthorsebatterystaple", "[email protected]", ) .unwrap(); let tmp = NamedTempFile::new().unwrap(); // Encrypt a message encrypt_message( vec![public_key1, public_key2], "Rust is great 🦀".to_string(), tmp.path().to_path_buf(), ) .unwrap(); let ciphertext = std::fs::read_to_string(tmp.path()).unwrap(); // Verify ciphertext looks like an encrypted message assert!(ciphertext.starts_with("-----BEGIN PGP MESSAGE-----\n")); // Decrypt as key 1 let plaintext = decrypt( ciphertext.clone().into_bytes(), secret_key1, "correcthorsebatterystaple".to_string(), ) .unwrap(); // Verify message is what we put in originally assert_eq!("Rust is great 🦀", &plaintext); // Decrypt as key 2 let plaintext = decrypt( ciphertext.into_bytes(), secret_key2, "correcthorsebatterystaple".to_string(), ) .unwrap(); // <-- fails here // Verify message is what we put in originally assert_eq!("Rust is great 🦀", &plaintext); } ```
2023-07-21T18:17:46Z
[]
[]
freedomofpress/securedrop
6,928
freedomofpress__securedrop-6928
[ "6796" ]
1016f4817b993bfd4826df1f410f1ba66d184746
diff --git a/admin/bootstrap.py b/admin/bootstrap.py --- a/admin/bootstrap.py +++ b/admin/bootstrap.py @@ -29,6 +29,16 @@ DIR = os.path.dirname(os.path.realpath(__file__)) VENV_DIR = os.path.join(DIR, ".venv3") +# Space-separated list of apt dependencies +APT_DEPENDENCIES_STR = "python3-virtualenv \ + python3-yaml \ + python3-pip \ + virtualenv \ + libffi-dev \ + libssl-dev \ + libpython3-dev \ + sq-keyring-linter" + def setup_logger(verbose: bool = False) -> None: """Configure logging handler""" @@ -95,6 +105,37 @@ def checkenv(args: argparse.Namespace) -> None: sys.exit(1) +def is_missing_dependency() -> bool: + """ + Check if there are any missing apt dependencies. + This applies to existing Tails systems where `securedrop-setup` may not have been + run recently. + """ + # apt-cache -q0 policy $dependency1 $dependency2 $dependency3 | grep "Installed: (none)" + apt_query = f"apt-cache -q0 policy {APT_DEPENDENCIES_STR}".split(" ") + grep_command = ["grep", "Installed: (none)"] + + try: + sdlog.info("Checking apt dependencies are installed") + apt_process = subprocess.Popen(apt_query, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + grep_process = subprocess.Popen( + grep_command, stdin=apt_process.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + + # Wait for the process to complete before checking the returncode + grep_process.communicate() + returncode = grep_process.returncode + + # If the above command returns 0, then one or more packages are not installed. + return returncode == 0 + + except subprocess.CalledProcessError as e: + sdlog.error("Error checking apt dependencies") + sdlog.debug(e.output) + raise + + def maybe_torify() -> List[str]: if is_tails(): return ["torify"] @@ -117,15 +158,8 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: "sudo", "su", "-c", - "apt-get update && \ - apt-get -q -o=Dpkg::Use-Pty=0 install -y \ - python3-virtualenv \ - python3-yaml \ - python3-pip \ - virtualenv \ - libffi-dev \ - libssl-dev \ - libpython3-dev", + f"apt-get update && \ + apt-get -q -o=Dpkg::Use-Pty=0 install -y {APT_DEPENDENCIES_STR}", ] try: @@ -133,6 +167,7 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: # of progress during long-running command. for output_line in run_command(apt_command): print(output_line.decode("utf-8").rstrip()) + except subprocess.CalledProcessError: # Tails supports apt persistence, which was used by SecureDrop # under Tails 2.x. If updates are being applied, don't try to pile @@ -158,11 +193,13 @@ def envsetup(args: argparse.Namespace, virtualenv_dir: str = VENV_DIR) -> None: # clean up old Tails venv on major upgrades clean_up_old_tails_venv(virtualenv_dir) + # Check apt dependencies and ensure all are present. + if is_missing_dependency(): + install_apt_dependencies(args) + # virtualenv doesnt exist? Install dependencies and create if not os.path.exists(virtualenv_dir): - install_apt_dependencies(args) - # Technically you can create a virtualenv from within python # but pip can only be run over Tor on Tails, and debugging that # along with instaling a third-party dependency is not worth diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -599,11 +599,23 @@ def validate_gpg_keys(self) -> bool: ) except subprocess.CalledProcessError as e: sdlog.debug(e.output) - raise FingerprintException( - f"fingerprint {fingerprint} " - + "does not match " - + f"the public key {public_key}" - ) + message = f"{fingerprint}: Fingerprint validation failed" + + # The validation script returns different error codes depending on what + # the cause of the validation failure was. See `admin/bin/validate-gpg-key.sh` + if e.returncode == 1: + message = ( + f"fingerprint {fingerprint} does not match " + + f"the public key {public_key}" + ) + elif e.returncode == 2: + message = ( + f"fingerprint {fingerprint} " + + "failed sq-keyring-linter check. You may be using an older key that " + + "needs to be updated. Please contact your SecureDrop administrator, or " + + "https://support.freedom.press for assistance." + ) + raise FingerprintException(message) return True def validate_journalist_alert_email(self) -> bool:
diff --git a/admin/tests/files/ossec.pub b/admin/tests/files/ossec.pub --- a/admin/tests/files/ossec.pub +++ b/admin/tests/files/ossec.pub @@ -1,5 +1,4 @@ -----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2.0.19 (GNU/Linux) mQINBFJZi2ABEACZJJA53+pEAdkZyD99nxB995ZVTBw60SQ/6E/gws4kInv+YS7t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RAbm90YXRpb25zLnNlcXVv +aWEtcGdwLm9yZ2Rb2iH8Npxse74z0qFlR0n6Isi6GLMBTedHZ0PCht2yAhsMFiEE +ZaG1/xlbVjU8xj3/zEDvEignFEEAAJPuD/9ywPYGKfr+d809LSd+6kUO2dinMrGM +5ETb79LQQKCh2u0jF+nvSEs8TIjT+bowGnys27Ih5BqNDOE229sVZ8x7QWEbEc1W +YO2hLZZ2KS5bCBB17aSwXIqhFw7z5bNOPu9BxEOx47T8zg3DJP6VeXnszKl/eD5D +C2L+L27red4OWIvndU9jZC3aoHLUbJf38pagsp2KwTjOl0bMyMkcffWuNZKHFAFd +4xG/9ReJoXUZnB3OSOUI7cMQTxObRtAlqlXEXaYXRiv0oKV2g6neN67BARJpe2+S +y3lxlX1FXMWQt1qJJVvJYpt15BgoqWoWTzCM5iStMikoP2t7f+AIltq8mVFcxsLc +17ioSDXpmw+4NTCo9yrYCThQNrYosmnfPjXGa2sn2BIy8bIm1j06ysVvS8eZy1Mu +dLR2odVkuzwygw1VpVVKwWZSICXutsLvQlwsjjLyD6vp/BAq1flUQHMNYTWIIgha +IpcKo+lRyUm+hap0w01iN2CCP8/WrYscMEkTf9SHvHKJJJ/DTht5pTWj//diXhe7 +MoKsgAEfPCcaK1KDRT3v+GiRh0Uuo+mwys1Vnd5P0zPBAMU6iyDkDdFwj2f3Ih1G +Vw1KNp+o32qqfE1iNO8uWhaG4kGD3LXXS3I7rcJVlYHf/kDacSv/Ld/hivYBj+Wl +caA76EYZ2Htu8g== +=LPJh -----END PGP PUBLIC KEY BLOCK----- diff --git a/admin/tests/files/test_journalist_key.pub b/admin/tests/files/test_journalist_key.pub --- a/admin/tests/files/test_journalist_key.pub +++ b/admin/tests/files/test_journalist_key.pub @@ -1,5 +1,4 @@ -----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2.0.19 (GNU/Linux) mQINBFJZi2ABEACZJJA53+pEAdkZyD99nxB995ZVTBw60SQ/6E/gws4kInv+YS7t wSMXG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YXRpb25zLnNlcXVv +aWEtcGdwLm9yZ2Rb2iH8Npxse74z0qFlR0n6Isi6GLMBTedHZ0PCht2yAhsMFiEE +ZaG1/xlbVjU8xj3/zEDvEignFEEAAJPuD/9ywPYGKfr+d809LSd+6kUO2dinMrGM +5ETb79LQQKCh2u0jF+nvSEs8TIjT+bowGnys27Ih5BqNDOE229sVZ8x7QWEbEc1W +YO2hLZZ2KS5bCBB17aSwXIqhFw7z5bNOPu9BxEOx47T8zg3DJP6VeXnszKl/eD5D +C2L+L27red4OWIvndU9jZC3aoHLUbJf38pagsp2KwTjOl0bMyMkcffWuNZKHFAFd +4xG/9ReJoXUZnB3OSOUI7cMQTxObRtAlqlXEXaYXRiv0oKV2g6neN67BARJpe2+S +y3lxlX1FXMWQt1qJJVvJYpt15BgoqWoWTzCM5iStMikoP2t7f+AIltq8mVFcxsLc +17ioSDXpmw+4NTCo9yrYCThQNrYosmnfPjXGa2sn2BIy8bIm1j06ysVvS8eZy1Mu +dLR2odVkuzwygw1VpVVKwWZSICXutsLvQlwsjjLyD6vp/BAq1flUQHMNYTWIIgha +IpcKo+lRyUm+hap0w01iN2CCP8/WrYscMEkTf9SHvHKJJJ/DTht5pTWj//diXhe7 +MoKsgAEfPCcaK1KDRT3v+GiRh0Uuo+mwys1Vnd5P0zPBAMU6iyDkDdFwj2f3Ih1G +Vw1KNp+o32qqfE1iNO8uWhaG4kGD3LXXS3I7rcJVlYHf/kDacSv/Ld/hivYBj+Wl +caA76EYZ2Htu8g== +=LPJh -----END PGP PUBLIC KEY BLOCK----- diff --git a/admin/tests/files/weak_test_key_should_fail_sqlinter.asc b/admin/tests/files/weak_test_key_should_fail_sqlinter.asc new file mode 100644 --- /dev/null +++ b/admin/tests/files/weak_test_key_should_fail_sqlinter.asc @@ -0,0 +1,20 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mI0EZOPgWwEEALRtUxob9g8IYRBVGZfsIM79e7OuqCUNnnpcNkNZ4tiKyd8yjjfD +2t4OZ5WAv7VuseDThwGnDoCUJ3ZZXtKTtJITtYvtHsQox3BZoz5wSWRSJDO8npKU +Zv0j7Dy8uqv0n69J402+3Fq9mELyekH9/j29UqLdUTzRQgH+ZkXAH27DABEBAAG0 +O0JBREtFWSAoU2hvdWxkIGZhaWwgc3Eta2V5cmluZy1saW50ZXIpIDxCQURLRVlA +Tk9SRVBMWS5ORVQ+iM4EEwEKADgWIQRA8cF7fngm2rQLFK53hrAA5tCnbgUCZOPg +WwIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRB3hrAA5tCnboiIA/oDjkPm +fhg9/2XdylpdB0WhY55vNLweSyQW6tWEgoL4IMl2HJx38WiMsNbqgWfsw/cLHrRW +eQfPJiB4n8jbucSFmutO9nlKT+yN/G1eVrSikz0nZ4OlLtW5Jy2T70LVzo3Lb6fE +Ve9zkVp+AaOxgsxlLj8aEX8E9tdD7EdmMKSJIbiNBGTj4FsBBACt+L8aGNutQfqK +iqqtwncUGBWdXNZgy+2SCmNF6QGwj0m8AlgBjERfbeBcYo3Mw2PIPM1r5UlXFiMy +blF32L7kZGxy5ETYaADHilGoJHCubtpBH4hDRsmt9OKydFSQvE01+CHLmAfiXBzx +KK48B2nVTseLIPhdxOW15GGd9QwLNwARAQABiLYEGAEKACAWIQRA8cF7fngm2rQL +FK53hrAA5tCnbgUCZOPgWwIbDAAKCRB3hrAA5tCnbqQ1A/9JSda8nzav4lgBw8co +dbB0s9AdvGymtlTWLUFdfHRaNYwHInUtXIagDhgJNLaa75xd/WNLvvjPcV3SoaOC +hGVDM/BkMb87VxjeYgHzKdN5MxMrPvITS5Y0EGB0ITvG1MTqHWalhY99pyRqeCRA +2BWLtQSMMPWQxML48db4EtfTQw== +=rpbe +-----END PGP PUBLIC KEY BLOCK----- \ No newline at end of file diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -716,6 +716,21 @@ def test_validate_gpg_key(self, tmpdir, caplog): site_config.validate_gpg_keys() assert "FAIL does not match" in str(e) + # Test a key with matching fingerprint but that fails sq-keyring-linter + invalid_config = { + # Correct key fingerprint but weak 1024-bit RSA key with SHA-1 self signature + "securedrop_app_gpg_public_key": "weak_test_key_should_fail_sqlinter.asc", + "securedrop_app_gpg_fingerprint": "40F1C17B7E7826DAB40B14AE7786B000E6D0A76E", + "ossec_alert_gpg_public_key": "test_journalist_key.pub", + "ossec_gpg_fpr": "65A1B5FF195B56353CC63DFFCC40EF1228271441", + "journalist_alert_gpg_public_key": "test_journalist_key.pub", + "journalist_gpg_fpr": "65A1B5FF195B56353CC63DFFCC40EF1228271441", + } + site_config.config = invalid_config + with pytest.raises(securedrop_admin.FingerprintException) as e: + site_config.validate_gpg_keys() + assert "failed sq-keyring-linter check" in str(e) + def test_journalist_alert_email(self, tmpdir): args = argparse.Namespace( site_config="INVALID", diff --git a/install_files/ansible-base/roles/app/files/test_journalist_key.pub b/install_files/ansible-base/roles/app/files/test_journalist_key.pub --- a/install_files/ansible-base/roles/app/files/test_journalist_key.pub +++ b/install_files/ansible-base/roles/app/files/test_journalist_key.pub @@ -1,5 +1,4 @@ -----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2.0.19 (GNU/Linux) mQINBFJZi2ABEACZJJA53+pEAdkZyD99nxB995ZVTBw60SQ/6E/gws4kInv+YS7t wSMXGa5bR4SD9voWxzLgyulqbM93jUFKn5GcsSh2O/lxAvEDKsPmXCRP1eBg3pjU @@ -25,28 +24,56 @@ iNl4NCgd26iRgTLhfMXpTjRyOb2RvFdzLByDEWIbvu5kCh247UFYSL0llk+suNh3 cm0mOUdL1nZuEo4EyEF1dq+1opMfDMF98q0660wZdwvwUQIXBt/yK3FH0BGA66ai R78Z4pH1JqtYvzfDJx+XP8O2N9GYGd7kpak/5C2BTJzLVyzagB1yi8SmiYna5yQj EqW5Txeq0GGd2H4KtUETUevU4x0Rw3luHToaDd9d5sioF48o87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sp2KwTjOl0bMyMkcffWuNZKHFAFd +4xG/9ReJoXUZnB3OSOUI7cMQTxObRtAlqlXEXaYXRiv0oKV2g6neN67BARJpe2+S +y3lxlX1FXMWQt1qJJVvJYpt15BgoqWoWTzCM5iStMikoP2t7f+AIltq8mVFcxsLc +17ioSDXpmw+4NTCo9yrYCThQNrYosmnfPjXGa2sn2BIy8bIm1j06ysVvS8eZy1Mu +dLR2odVkuzwygw1VpVVKwWZSICXutsLvQlwsjjLyD6vp/BAq1flUQHMNYTWIIgha +IpcKo+lRyUm+hap0w01iN2CCP8/WrYscMEkTf9SHvHKJJJ/DTht5pTWj//diXhe7 +MoKsgAEfPCcaK1KDRT3v+GiRh0Uuo+mwys1Vnd5P0zPBAMU6iyDkDdFwj2f3Ih1G +Vw1KNp+o32qqfE1iNO8uWhaG4kGD3LXXS3I7rcJVlYHf/kDacSv/Ld/hivYBj+Wl +caA76EYZ2Htu8g== +=LPJh -----END PGP PUBLIC KEY BLOCK-----
Have securedrop-admin reject Submission Keys with SHA-1 signatures ## Description securedrop-admin should reject Submission Keys that have SHA-1 signatures https://sequoia-pgp.org/blog/2023/02/01/202302-happy-sha1-day/ We should install `sq-keyring-linter` as part of the Tails Admin Workstation setup, and then check the key in https://github.com/freedomofpress/securedrop/blob/develop/admin/bin/validate-gpg-key.sh, erroring if it fails the linter
We currently run [all the pubkeys](https://github.com/freedomofpress/securedrop/blob/ba04ad7000f8e11474397dfb054c46e726c0383b/admin/securedrop_admin/__init__.py#L583-L586) (submission key, ossec alert key, journalist key if applicable) through our validation script. Question for team: Should we fail on _any_ key using SHA-1 in its binding signature, or just on the Submission Key?
2023-08-21T22:29:53Z
[]
[]
freedomofpress/securedrop
6,946
freedomofpress__securedrop-6946
[ "6800" ]
c52eb9e04693ac784b4f67bd81f4f4a6297c5994
diff --git a/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py b/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py new file mode 100644 --- /dev/null +++ b/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py @@ -0,0 +1,96 @@ +"""PGP public keys + +Revision ID: 17c559a7a685 +Revises: 811334d7105f +Create Date: 2023-09-21 12:33:56.550634 + +""" + +import traceback + +import pretty_bad_protocol as gnupg +import sqlalchemy as sa +from alembic import op +from encryption import EncryptionManager +from sdconfig import SecureDropConfig + +import redwood + +# revision identifiers, used by Alembic. +revision = "17c559a7a685" +down_revision = "811334d7105f" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """ + Migrate public keys from the GPG keyring into the SQLite database + + We iterate over all the secret keys in the keyring and see if we + can identify the corresponding Source record. If we can, and it + doesn't already have key material migrated, export the key and + save it in the database. + """ + config = SecureDropConfig.get_current() + gpg = gnupg.GPG( + binary="gpg2", + homedir=str(config.GPG_KEY_DIR), + options=["--pinentry-mode loopback", "--trust-model direct"], + ) + # Source keys all have a secret key, so we can filter on that + for keyinfo in gpg.list_keys(secret=True): + if len(keyinfo["uids"]) > 1: + # Source keys should only have one UID + continue + uid = keyinfo["uids"][0] + search = EncryptionManager.SOURCE_KEY_UID_RE.search(uid) + if not search: + # Didn't match at all + continue + filesystem_id = search.group(2) + # Check that it's a valid ID + conn = op.get_bind() + result = conn.execute( + sa.text( + """ + SELECT pgp_public_key, pgp_fingerprint + FROM sources + WHERE filesystem_id=:filesystem_id + """ + ).bindparams(filesystem_id=filesystem_id) + ).first() + if result != (None, None): + # Either not in the database or there's already some data in the DB. + # In any case, skip. + continue + fingerprint = keyinfo["fingerprint"] + try: + public_key = gpg.export_keys(fingerprint) + redwood.is_valid_public_key(public_key) + except: # noqa: E722 + # Exporting the key failed in some manner + traceback.print_exc() + continue + + # Save to database + op.execute( + sa.text( + """ + UPDATE sources + SET pgp_public_key=:pgp_public_key, pgp_fingerprint=:pgp_fingerprint + WHERE filesystem_id=:filesystem_id + """ + ).bindparams( + pgp_public_key=public_key, + pgp_fingerprint=fingerprint, + filesystem_id=filesystem_id, + ) + ) + + +def downgrade() -> None: + """ + This is a non-destructive operation, so it's not worth implementing a + migration from database storage to GPG. + """ diff --git a/securedrop/encryption.py b/securedrop/encryption.py --- a/securedrop/encryption.py +++ b/securedrop/encryption.py @@ -40,7 +40,7 @@ class EncryptionManager: REDIS_FINGERPRINT_HASH = "sd/crypto-util/fingerprints" REDIS_KEY_HASH = "sd/crypto-util/keys" - SOURCE_KEY_UID_RE = re.compile(r"(Source|Autogenerated) Key <[-A-Za-z0-9+/=_]+>") + SOURCE_KEY_UID_RE = re.compile(r"(Source|Autogenerated) Key <([-A-Za-z0-9+/=_]+)>") def __init__(self, gpg_key_dir: Path, journalist_pub_key: Path) -> None: self._gpg_key_dir = gpg_key_dir diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -239,7 +239,7 @@ def add_reply( db.session.commit() -def add_source() -> Tuple[Source, str]: +def add_source(use_gpg: bool = False) -> Tuple[Source, str]: """ Adds a single source. """ @@ -250,6 +250,26 @@ def add_source() -> Tuple[Source, str]: source_app_storage=Storage.get_default(), ) source = source_user.get_db_record() + if use_gpg: + manager = EncryptionManager.get_default() + gen_key_input = manager._gpg.gen_key_input( + passphrase=source_user.gpg_secret, + name_email=source_user.filesystem_id, + key_type="RSA", + key_length=4096, + name_real="Source Key", + creation_date="2013-05-14", + # '0' is the magic value that tells GPG's batch key generation not + # to set an expiration date. + expire_date="0", + ) + manager._gpg.gen_key(gen_key_input) + + # Delete the Sequoia-generated keys + source.pgp_public_key = None + source.pgp_fingerprint = None + source.pgp_secret_key = None + db.session.add(source) db.session.commit() return source, codename @@ -323,7 +343,7 @@ def add_sources(args: argparse.Namespace, journalists: Tuple[Journalist, ...]) - ) for i in range(1, args.source_count + 1): - source, codename = add_source() + source, codename = add_source(use_gpg=args.gpg) for _ in range(args.messages_per_source): submit_message(source, secrets.choice(journalists) if seen_message_count > 0 else None) @@ -450,6 +470,12 @@ def parse_arguments() -> argparse.Namespace: "--seed", help=("Random number seed (for reproducible datasets)"), ) + parser.add_argument( + "--gpg", + help="Create sources with a key pair stored in GPG", + action="store_true", + default=False, + ) return parser.parse_args()
diff --git a/securedrop/tests/migrations/migration_17c559a7a685.py b/securedrop/tests/migrations/migration_17c559a7a685.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/migrations/migration_17c559a7a685.py @@ -0,0 +1,116 @@ +import uuid + +import pretty_bad_protocol as gnupg +from db import db +from journalist_app import create_app +from sqlalchemy import text + +import redwood + + +class UpgradeTester: + def __init__(self, config): + """This function MUST accept an argument named `config`. + You will likely want to save a reference to the config in your + class so you can access the database later. + """ + self.config = config + self.app = create_app(self.config) + self.gpg = gnupg.GPG( + binary="gpg2", + homedir=str(config.GPG_KEY_DIR), + options=["--pinentry-mode loopback", "--trust-model direct"], + ) + self.fingerprint = None + # random, chosen by fair dice roll + self.filesystem_id = ( + "HAR5WIY3C4K3MMIVLYXER7DMTYCL5PWZEPNOCR2AIBCVWXDZQDMDFUHEFJM" + "Z3JW5D6SLED3YKCBDAKNMSIYOKWEJK3ZRJT3WEFT3S5Q=" + ) + + def load_data(self): + """Create a source and GPG key pair""" + with self.app.app_context(): + source = { + "uuid": str(uuid.uuid4()), + "filesystem_id": self.filesystem_id, + "journalist_designation": "psychic webcam", + "interaction_count": 0, + } + sql = """\ + INSERT INTO sources (uuid, filesystem_id, journalist_designation, + interaction_count) + VALUES (:uuid, :filesystem_id, :journalist_designation, + :interaction_count)""" + db.engine.execute(text(sql), **source) + # Generate the GPG key pair + gen_key_input = self.gpg.gen_key_input( + passphrase="correct horse battery staple", + name_email=self.filesystem_id, + key_type="RSA", + key_length=4096, + name_real="Source Key", + creation_date="2013-05-14", + expire_date="0", + ) + key = self.gpg.gen_key(gen_key_input) + self.fingerprint = str(key.fingerprint) + + def check_upgrade(self): + """Verify PGP fields have been populated""" + with self.app.app_context(): + query_sql = """\ + SELECT pgp_fingerprint, pgp_public_key, pgp_secret_key + FROM sources + WHERE filesystem_id = :filesystem_id""" + source = db.engine.execute( + text(query_sql), + filesystem_id=self.filesystem_id, + ).fetchone() + assert source[0] == self.fingerprint + assert redwood.is_valid_public_key(source[1]) == self.fingerprint + assert source[2] is None + + +class DowngradeTester: + def __init__(self, config): + self.config = config + self.app = create_app(self.config) + self.uuid = str(uuid.uuid4()) + + def load_data(self): + """Create a source with a PGP key pair already migrated""" + with self.app.app_context(): + source = { + "uuid": self.uuid, + "filesystem_id": "1234", + "journalist_designation": "mucky pine", + "interaction_count": 0, + "pgp_fingerprint": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "pgp_public_key": "very public", + "pgp_secret_key": None, + } + sql = """\ + INSERT INTO sources (uuid, filesystem_id, journalist_designation, + interaction_count, pgp_fingerprint, pgp_public_key, pgp_secret_key) + VALUES (:uuid, :filesystem_id, :journalist_designation, + :interaction_count, :pgp_fingerprint, :pgp_public_key, :pgp_secret_key)""" + db.engine.execute(text(sql), **source) + + def check_downgrade(self): + """Verify the downgrade does nothing, i.e. the two PGP fields are still populated""" + with self.app.app_context(): + sql = """\ + SELECT pgp_fingerprint, pgp_public_key, pgp_secret_key + FROM sources + WHERE uuid = :uuid""" + source = db.engine.execute( + text(sql), + uuid=self.uuid, + ).fetchone() + print(source) + assert source == ( + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "very public", + None, + )
One-time migration of sources' public keys and fingerprints from gpg to database-backed storage As part of our work to migrate to Sequoia, we will perform a one-time, alembic migration of sources' public keys and fingerprints from the gpg keyring and into the new database backed storage (added in https://github.com/freedomofpress/securedrop/issues/6799). This will iterate over each source, fetch the armored public key out of the gpg keyring, get the fingerprint, and store both in the database.
2023-09-21T13:51:55Z
[]
[]
freedomofpress/securedrop
6,954
freedomofpress__securedrop-6954
[ "6917" ]
fa0c61c38de4069385a52eecc4fe93f1346a3c5b
diff --git a/securedrop/i18n.py b/securedrop/i18n.py --- a/securedrop/i18n.py +++ b/securedrop/i18n.py @@ -211,11 +211,11 @@ def get_locale(config: SecureDropConfig) -> str: - config.DEFAULT_LOCALE - config.FALLBACK_LOCALE """ - preferences = [] + preferences: List[str] = [] if session and session.get("locale"): - preferences.append(session.get("locale")) + preferences.append(session["locale"]) if request.args.get("l"): - preferences.insert(0, request.args.get("l")) + preferences.insert(0, request.args["l"]) if not preferences: preferences.extend(get_accepted_languages()) preferences.append(config.DEFAULT_LOCALE) diff --git a/securedrop/i18n_tool.py b/securedrop/i18n_tool.py deleted file mode 100755 --- a/securedrop/i18n_tool.py +++ /dev/null @@ -1,738 +0,0 @@ -#!/opt/venvs/securedrop-app-code/bin/python - -import argparse -import glob -import json -import logging -import os -import re -import signal -import subprocess -import sys -import textwrap -from argparse import _SubParsersAction -from os.path import abspath, dirname, join, realpath -from pathlib import Path -from typing import Dict, List, Optional, Set - -import version - -logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") -log = logging.getLogger(__name__) - -I18N_CONF = os.path.join(os.path.dirname(__file__), "i18n.json") - -# Map components of the "securedrop" Weblate project (keys) to their filesystem -# paths (values) relative to the repository root. -LOCALE_DIR = { - "securedrop": "securedrop/translations", - "desktop": "install_files/ansible-base/roles/tails-config/templates", -} - - -class I18NTool: - # - # The database of support language, indexed by the language code - # used by weblate (i.e. whatever shows as CODE in - # https://weblate.securedrop.org/projects/securedrop/securedrop/CODE/ - # is the index of the SUPPORTED_LANGUAGES database below. - # - # name: English name of the language to the documentation, not for - # display in the interface. - # desktop: The language code used for desktop icons. - # - with open(I18N_CONF) as i18n_conf: - conf = json.load(i18n_conf) - supported_languages = conf["supported_locales"] - release_tag_re = re.compile(r"^\d+\.\d+\.\d+$") - translated_commit_re = re.compile("Translated using Weblate") - updated_commit_re = re.compile(r"(?:updated from| (?:revision|commit):) (\w+)") - - def file_is_modified(self, path: str) -> bool: - return bool(subprocess.call(["git", "-C", dirname(path), "diff", "--quiet", path])) - - def ensure_i18n_remote(self, args: argparse.Namespace) -> None: - """ - Make sure we have a git remote for the i18n repo. - """ - - k = {"cwd": args.root} - if "i18n" not in subprocess.check_output(["git", "remote"], encoding="utf-8", **k): - subprocess.check_call(["git", "remote", "add", "i18n", args.url], **k) - subprocess.check_call(["git", "fetch", "i18n"], **k) - - def translate_messages(self, args: argparse.Namespace) -> None: - messages_file = Path(args.translations_dir).absolute() / "messages.pot" - - if args.extract_update: - if not os.path.exists(args.translations_dir): - os.makedirs(args.translations_dir) - sources = args.sources.split(",") - subprocess.check_call( - [ - "pybabel", - "extract", - "--charset=utf-8", - "--mapping", - args.mapping, - "--output", - messages_file, - "--project=SecureDrop", - "--version", - args.version, - "[email protected]", - "--copyright-holder=Freedom of the Press Foundation", - "--add-comments=Translators:", - "--strip-comments", - "--add-location=never", - "--no-wrap", - *sources, - ] - ) - - msg_file_content = messages_file.read_text() - updated_content = _remove_from_content_line_with_text( - text='"POT-Creation-Date:', content=msg_file_content - ) - messages_file.write_text(updated_content) - - if ( - self.file_is_modified(str(messages_file)) - and len(os.listdir(args.translations_dir)) > 1 - ): - tglob = f"{args.translations_dir}/*/LC_MESSAGES/*.po" - for translation in glob.iglob(tglob): - subprocess.check_call( - [ - "msgattrib", - "--no-fuzzy", - "--output-file", - translation, - translation, - ] - ) - subprocess.check_call( - [ - "msgmerge", - "--previous", - "--update", - "--no-fuzzy-matching", - "--no-wrap", - translation, - messages_file, - ] - ) - log.warning(f"messages translations updated in {messages_file}") - else: - log.warning("messages translations are already up to date") - - if args.compile and len(os.listdir(args.translations_dir)) > 1: - # Suppress all pybabel to hide warnings (e.g. - # https://github.com/python-babel/babel/issues/566) and verbose "compiling..." messages - subprocess.run( - ["pybabel", "compile", "--directory", args.translations_dir], - check=True, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) - - def translate_desktop(self, args: argparse.Namespace) -> None: - messages_file = Path(args.translations_dir).absolute() / "desktop.pot" - - if args.extract_update: - sources = args.sources.split(",") - xgettext_flags = [] - - # First extract from JavaScript sources via Babel ("xgettext - # --language=JavaScript" can't parse gettext as exposed by GNOME - # JavaScript): - js_sources = [source for source in sources if ".js" in source] - if js_sources: - xgettext_flags.append("--join-existing") - subprocess.check_call( - [ - "pybabel", - "extract", - "--charset=utf-8", - "--mapping", - args.mapping, - "--output", - "desktop.pot", - "--project=SecureDrop", - "--version", - args.version, - "[email protected]", - "--copyright-holder=Freedom of the Press Foundation", - "--add-comments=Translators:", - "--strip-comments", - "--add-location=never", - "--no-wrap", - *js_sources, - ], - cwd=args.translations_dir, - ) - - # Then extract from desktop templates via xgettext in appending - # "--join-existing" mode: - desktop_sources = [source for source in sources if ".js" not in source] - subprocess.check_call( - [ - "xgettext", - *xgettext_flags, - "--output=desktop.pot", - "--language=Desktop", - "--keyword", - "--keyword=Name", - "--package-version", - args.version, - "[email protected]", - "--copyright-holder=Freedom of the Press Foundation", - *desktop_sources, - ], - cwd=args.translations_dir, - ) - msg_file_content = messages_file.read_text() - updated_content = _remove_from_content_line_with_text( - text='"POT-Creation-Date:', content=msg_file_content - ) - messages_file.write_text(updated_content) - - if self.file_is_modified(str(messages_file)): - for f in os.listdir(args.translations_dir): - if not f.endswith(".po"): - continue - po_file = os.path.join(args.translations_dir, f) - subprocess.check_call( - ["msgmerge", "--no-fuzzy-matching", "--update", po_file, messages_file] - ) - log.warning(f"messages translations updated in {messages_file}") - else: - log.warning("desktop translations are already up to date") - - if args.compile: - pos = [f for f in os.listdir(args.translations_dir) if f.endswith(".po")] - linguas = [lingua[:-3] for lingua in pos] - content = "\n".join(linguas) + "\n" - linguas_file = join(args.translations_dir, "LINGUAS") - try: - open(linguas_file, "w").write(content) - - # First, compile each message catalog for normal gettext use. - # We have to iterate over them, rather than using "pybabel - # compile --directory", in order to replicate gettext's - # standard "{locale}/LC_MESSAGES/{domain}.mo" structure (like - # "securedrop/translations"). - locale_dir = os.path.join(args.translations_dir, "locale") - for po in pos: - locale = po.replace(".po", "") - output_dir = os.path.join(locale_dir, locale, "LC_MESSAGES") - subprocess.run(["mkdir", "--parents", output_dir], check=True) - subprocess.run( - [ - "msgfmt", - "--output-file", - os.path.join(output_dir, "messages.mo"), - po, - ], - check=True, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - cwd=args.translations_dir, - ) - - # Then use msgfmt to update the desktop files as usual. - desktop_sources = [ - source for source in args.sources.split(",") if ".js" not in source - ] - for source in desktop_sources: - target = source.rstrip(".in") - subprocess.check_call( - [ - "msgfmt", - "--desktop", - "--template", - source, - "-o", - target, - "-d", - ".", - ], - cwd=args.translations_dir, - ) - self.sort_desktop_template(join(args.translations_dir, target)) - finally: - if os.path.exists(linguas_file): - os.unlink(linguas_file) - - def sort_desktop_template(self, template: str) -> None: - """ - Sorts the lines containing the icon names. - """ - lines = open(template).readlines() - names = sorted(line for line in lines if line.startswith("Name")) - others = (line for line in lines if not line.startswith("Name")) - with open(template, "w") as new_template: - for line in others: - new_template.write(line) - for line in names: - new_template.write(line) - - def set_translate_parser( - self, parser: argparse.ArgumentParser, translations_dir: str, sources: str - ) -> None: - parser.add_argument( - "--extract-update", - action="store_true", - help=("extract strings to translate and " "update existing translations"), - ) - parser.add_argument("--compile", action="store_true", help="compile translations") - parser.add_argument( - "--translations-dir", - default=translations_dir, - help=f"Base directory for translation files (default {translations_dir})", - ) - parser.add_argument( - "--version", - default=version.__version__, - help=( - "SecureDrop version " - "to store in pot files (default {})".format(version.__version__) - ), - ) - parser.add_argument( - "--sources", - default=sources, - help=f"Source files and directories to extract (default {sources})", - ) - - def set_translate_messages_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser( - "translate-messages", help=("Update and compile " "source and template translations") - ) - translations_dir = join(dirname(realpath(__file__)), "translations") - sources = ".,source_templates,journalist_templates" - self.set_translate_parser(parser, translations_dir, sources) - mapping = "babel.cfg" - parser.add_argument( - "--mapping", - default=mapping, - help=f"Mapping of files to consider (default {mapping})", - ) - parser.set_defaults(func=self.translate_messages) - - def set_translate_desktop_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser( - "translate-desktop", help=("Update and compile " "desktop icons translations") - ) - translations_dir = join( - dirname(realpath(__file__)), - "..", - LOCALE_DIR["desktop"], - ) - sources = ",".join( - [ - "desktop-journalist-icon.j2.in", - "desktop-source-icon.j2.in", - "extension.js.in", - ] - ) - mapping = join(dirname(realpath(__file__)), "babel.cfg") - parser.add_argument( - "--mapping", - default=mapping, - help=f"Mapping of files to consider (default {mapping})", - ) - self.set_translate_parser(parser, translations_dir, sources) - parser.set_defaults(func=self.translate_desktop) - - @staticmethod - def require_git_email_name(git_dir: str) -> bool: - cmd = ( - "git -C {d} config --get user.name > /dev/null && " - "git -C {d} config --get user.email > /dev/null".format(d=git_dir) - ) - # nosemgrep: python.lang.security.audit.subprocess-shell-true.subprocess-shell-true - if subprocess.call(cmd, shell=True): # nosec - if "docker" in open("/proc/1/cgroup").read(): - log.error( - "remember ~/.gitconfig does not exist " - "in the dev-shell Docker container, " - "only .git/config does" - ) - raise Exception(cmd + " returned false, please set name and email") - return True - - def update_docs(self, args: argparse.Namespace) -> None: - l10n_content = ".. GENERATED BY i18n_tool.py DO NOT EDIT:\n\n" - for (code, info) in sorted(self.supported_languages.items()): - l10n_content += "* " + info["name"] + " (``" + code + "``)\n" - includes = abspath(join(args.docs_repo_dir, "docs/includes")) - l10n_txt = join(includes, "l10n.txt") - open(l10n_txt, mode="w").write(l10n_content) - self.require_git_email_name(includes) - if self.file_is_modified(l10n_txt): - subprocess.check_call(["git", "add", "l10n.txt"], cwd=includes) - msg = "docs: update the list of supported languages" - subprocess.check_call(["git", "commit", "-m", msg, "l10n.txt"], cwd=includes) - log.warning(l10n_txt + " updated") - git_show_out = subprocess.check_output(["git", "show"], encoding="utf-8", cwd=includes) - log.warning(git_show_out) - else: - log.warning(l10n_txt + " already up to date") - - def set_update_docs_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser("update-docs", help=("Update the documentation")) - parser.add_argument( - "--docs-repo-dir", - required=True, - help=("root directory of the SecureDrop documentation repository"), - ) - parser.set_defaults(func=self.update_docs) - - def update_from_weblate(self, args: argparse.Namespace) -> None: - """ - Pull in updated translations from the i18n repo. - """ - self.ensure_i18n_remote(args) - - # Check out *all* remote changes to the LOCALE_DIRs. - subprocess.check_call( - [ - "git", - "checkout", - args.target, - "--", - *LOCALE_DIR.values(), - ], - cwd=args.root, - ) - - # Use the LOCALE_DIR corresponding to the "securedrop" component to - # determine which locales are present. - locale_dir = os.path.join(args.root, LOCALE_DIR["securedrop"]) - locales = self.translated_locales(locale_dir) - if args.supported_languages: - codes = args.supported_languages.split(",") - locales = {code: locales[code] for code in locales if code in codes} - - # Then iterate over all locales present and decide which to stage and commit. - for code, path in locales.items(): - paths = [] - - def add(path: str) -> None: - """ - Add the file to the git index. - """ - subprocess.check_call(["git", "add", path], cwd=args.root) - paths.append(path) - - # Any translated locale may have changes that need to be staged from the - # securedrop/securedrop component. - add(path) - - # Only supported locales may have changes that need to be staged from the - # securedrop/desktop component, because the link between the two components - # is defined in I18N_CONF when a language is marked supported. - try: - info = self.supported_languages[code] - name = info["name"] - desktop_code = info["desktop"] - path = join( - LOCALE_DIR["desktop"], - f"{desktop_code}.po", - ) - add(path) - except KeyError: - log.info( - f"{code} has translations but is not marked as supported; " - f"skipping desktop translation" - ) - name = code - - # Try to commit changes for this locale no matter what, even if it turns out to be a - # no-op. - self.commit_changes(args, code, name, paths) - - def translators( - self, args: argparse.Namespace, path: str, since_commit: Optional[str] - ) -> Set[str]: - """ - Return the set of people who've modified a file in Weblate. - - Extracts all the authors of translation changes to the given - path since the given commit. Translation changes are - identified by the presence of "Translated using Weblate" in - the commit message. - """ - - log_command = ["git", "--no-pager", "-C", args.root, "log", "--format=%aN\x1e%s\x1e%H"] - - if since_commit: - since = self.get_commit_timestamp(args.root, since_commit) - log_command.extend(["--since", since]) - - log_command.extend([args.target, "--", path]) - - # NB. We use an explicit str.split("\n") here because str.splitlines() splits on a - # set of characters that includes the \x1e "record separator" we pass to "git log - # --format" in log_command. See #6648. - log_lines = subprocess.check_output(log_command, encoding="utf-8").strip().split("\n") - path_changes = [c.split("\x1e") for c in log_lines] - path_changes = [ - c - for c in path_changes - if len(c) > 1 and c[2] != since_commit and self.translated_commit_re.match(c[1]) - ] - log.debug("Path changes for %s: %s", path, path_changes) - translators = {c[0] for c in path_changes} - log.debug("Translators for %s: %s", path, translators) - return translators - - def get_path_commits(self, root: str, path: str) -> List[str]: - """ - Returns the list of commit hashes involving the path, most recent first. - """ - cmd = ["git", "--no-pager", "log", "--format=%H", path] - return subprocess.check_output(cmd, encoding="utf-8", cwd=root).splitlines() - - def translated_locales(self, path: str) -> Dict[str, str]: - """Return a dictionary of all locale directories present in `path`, where the keys - are the base (directory) names and the values are the full paths.""" - p = Path(path) - return {x.name: str(x) for x in p.iterdir() if x.is_dir()} - - def commit_changes( - self, args: argparse.Namespace, code: str, name: str, paths: List[str] - ) -> None: - """Check if any of the given paths have had changed staged. If so, commit them.""" - self.require_git_email_name(args.root) - authors: Set[str] = set() - cmd = ["git", "--no-pager", "diff", "--name-only", "--cached", *paths] - diffs = subprocess.check_output(cmd, cwd=args.root, encoding="utf-8") - - # If nothing was changed, "git commit" will return nonzero as a no-op. - if len(diffs) == 0: - return - - # for each modified file, find the last commit made by this - # function, then collect all the contributors since that - # commit, so they can be credited in this one. if no commit - # with the right message is found, just use the most recent - # commit that touched the file. - for path in paths: - path_commits = self.get_path_commits(args.root, path) - since_commit = None - for path_commit in path_commits: - commit_message = subprocess.check_output( - ["git", "--no-pager", "show", path_commit], - encoding="utf-8", - cwd=args.root, - ) - m = self.updated_commit_re.search(commit_message) - if m: - since_commit = m.group(1) - break - log.debug("Crediting translators of %s since %s", path, since_commit) - authors |= self.translators(args, path, since_commit) - - authors_as_str = "\n ".join(sorted(authors)) - - current = subprocess.check_output( - ["git", "rev-parse", args.target], cwd=args.root, encoding="utf-8" - ) - message = textwrap.dedent( - """ - l10n: updated {name} ({code}) - - contributors: - {authors} - - updated from: - repo: {remote} - commit: {current} - """ - ).format(remote=args.url, name=name, authors=authors_as_str, code=code, current=current) - subprocess.check_call(["git", "commit", "-m", message, *paths], cwd=args.root) - log.debug(f"Committing with this message: {message}") - - def set_update_from_weblate_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser("update-from-weblate", help=("Import translations from weblate")) - root = join(dirname(realpath(__file__)), "..") - parser.add_argument( - "--root", - default=root, - help=("root of the SecureDrop git repository" " (default {})".format(root)), - ) - url = "https://github.com/freedomofpress/securedrop-i18n" - parser.add_argument( - "--url", default=url, help=("URL of the weblate repository" " (default {})".format(url)) - ) - parser.add_argument( - "--target", - default="i18n/i18n", - help=( - "Commit on i18n branch at which to stop gathering translator contributions " - "(default: i18n/i18n)" - ), - ) - parser.add_argument( - "--supported-languages", help="comma separated list of supported languages" - ) - parser.set_defaults(func=self.update_from_weblate) - - def set_list_locales_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser("list-locales", help="List supported locales") - parser.add_argument( - "--python", - action="store_true", - help=("Print the locales as a Python list suitable for config.py"), - ) - parser.add_argument("--lines", action="store_true", help=("List one locale per line")) - parser.set_defaults(func=self.list_locales) - - def list_locales(self, args: argparse.Namespace) -> None: - if args.lines: - for lang in sorted(list(self.supported_languages.keys()) + ["en_US"]): - print(lang) - elif args.python: - print(sorted(list(self.supported_languages.keys()) + ["en_US"])) - else: - print(" ".join(sorted(list(self.supported_languages.keys()) + ["en_US"]))) - - def set_list_translators_parser(self, subps: _SubParsersAction) -> None: - parser = subps.add_parser("list-translators", help=("List contributing translators")) - root = join(dirname(realpath(__file__)), "..") - parser.add_argument( - "--root", - default=root, - help=("root of the SecureDrop git repository" " (default {})".format(root)), - ) - url = "https://github.com/freedomofpress/securedrop-i18n" - parser.add_argument( - "--url", default=url, help=("URL of the weblate repository" " (default {})".format(url)) - ) - parser.add_argument( - "--target", - default="i18n/i18n", - help=( - "Commit on i18n branch at which to stop gathering translator contributions " - "(default: i18n/i18n)" - ), - ) - parser.add_argument( - "--since", - help=( - "Gather translator contributions from the time of this commit " - "(default: last release tag)" - ), - ) - parser.add_argument( - "--all", - action="store_true", - help=( - "List everyone who's ever contributed, instead of just since the last " - "release or specified commit." - ), - ) - parser.set_defaults(func=self.list_translators) - - def get_last_release(self, root: str) -> str: - """ - Returns the last release tag, e.g. 1.5.0. - """ - tags = ( - subprocess.check_output(["git", "-C", root, "tag", "--list"]) - .decode("utf-8") - .splitlines() - ) - release_tags = sorted([t.strip() for t in tags if self.release_tag_re.match(t)]) - if not release_tags: - raise ValueError("Could not find a release tag!") - return release_tags[-1] - - def get_commit_timestamp(self, root: str, commit: Optional[str]) -> str: - """ - Returns the UNIX timestamp of the given commit. - """ - cmd = ["git", "-C", root, "log", "-n", "1", "--pretty=format:%ct"] - if commit: - cmd.append(commit) - - timestamp = subprocess.check_output(cmd) - return timestamp.decode("utf-8").strip() - - def list_translators(self, args: argparse.Namespace) -> None: - self.ensure_i18n_remote(args) - app_template = "{}/{}/LC_MESSAGES/messages.po" - desktop_template = LOCALE_DIR["desktop"] + "/{}.po" - since = None - if args.all: - print("Listing all translators who have ever helped") - else: - since = args.since if args.since else self.get_last_release(args.root) - print(f"Listing translators who have helped since {since}") - for code, info in sorted(self.supported_languages.items()): - translators = set() - paths = [ - app_template.format(LOCALE_DIR["securedrop"], code), - desktop_template.format(info["desktop"]), - ] - for path in paths: - try: - t = self.translators(args, path, since) - translators.update(t) - except Exception as e: - print(f"Could not check git history of {path}: {e}", file=sys.stderr) - print( - "{} ({}):{}".format( - code, - info["name"], - "\n {}\n".format("\n ".join(sorted(translators))) if translators else "\n", - ) - ) - - def get_args(self) -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog=__file__, description="i18n tool for SecureDrop.") - parser.set_defaults(func=lambda args: parser.print_help()) - - parser.add_argument("-v", "--verbose", action="store_true") - subps = parser.add_subparsers() - - self.set_translate_messages_parser(subps) - self.set_translate_desktop_parser(subps) - self.set_update_docs_parser(subps) - self.set_update_from_weblate_parser(subps) - self.set_list_translators_parser(subps) - self.set_list_locales_parser(subps) - - return parser - - def setup_verbosity(self, args: argparse.Namespace) -> None: - if args.verbose: - logging.getLogger("sh.command").setLevel(logging.INFO) - log.setLevel(logging.DEBUG) - else: - log.setLevel(logging.INFO) - - def main(self, argv: List[str]) -> int: - try: - args = self.get_args().parse_args(argv) - self.setup_verbosity(args) - return args.func(args) - except KeyboardInterrupt: - return signal.SIGINT - - -def _remove_from_content_line_with_text(text: str, content: str) -> str: - # Split where the text is located; assume there is only one instance of the text - split_content = content.split(text) - assert len(split_content) == 2 - - # Remove the while line containing the text - content_before_line = split_content[0] - content_after_line = split_content[1].split("\n", maxsplit=1)[1] - return content_before_line + content_after_line - - -if __name__ == "__main__": # pragma: no cover - sys.exit(I18NTool().main(sys.argv[1:]))
diff --git a/securedrop/tests/test_i18n.py b/securedrop/tests/test_i18n.py --- a/securedrop/tests/test_i18n.py +++ b/securedrop/tests/test_i18n.py @@ -21,7 +21,6 @@ from typing import List import i18n -import i18n_tool import journalist_app as journalist_app_module import pytest import source_app @@ -247,22 +246,31 @@ def test_i18n(): i18n_dir = Path(__file__).absolute().parent / "i18n" sources = [str(i18n_dir / "code.py"), str(i18n_dir / "template.html")] - i18n_tool.I18NTool().main( + pot = i18n_dir / "messages.pot" + subprocess.check_call( [ - "--verbose", - "translate-messages", + "pybabel", + "extract", "--mapping", str(i18n_dir / "babel.cfg"), - "--translations-dir", - str(translation_dirs), - "--sources", - ",".join(sources), - "--extract-update", + "--output", + pot, + *sources, ] ) - pot = translation_dirs / "messages.pot" - subprocess.check_call(["pybabel", "init", "-i", pot, "-d", translation_dirs, "-l", "en_US"]) + subprocess.check_call( + [ + "pybabel", + "init", + "--input-file", + pot, + "--output-dir", + translation_dirs, + "--locale", + "en_US", + ] + ) for (locale, translated_msg) in ( ("fr_FR", "code bonjour"), @@ -271,7 +279,18 @@ def test_i18n(): ("nb_NO", "code norwegian"), ("es_ES", "code spanish"), ): - subprocess.check_call(["pybabel", "init", "-i", pot, "-d", translation_dirs, "-l", locale]) + subprocess.check_call( + [ + "pybabel", + "init", + "--input-file", + pot, + "--output-dir", + translation_dirs, + "--locale", + locale, + ] + ) # Populate the po file with a translation po_file = translation_dirs / locale / "LC_MESSAGES" / "messages.po" @@ -281,15 +300,18 @@ def test_i18n(): msgstr=translated_msg, ) - i18n_tool.I18NTool().main( - [ - "--verbose", - "translate-messages", - "--translations-dir", - str(translation_dirs), - "--compile", - ] - ) + subprocess.check_call( + [ + "pybabel", + "compile", + "--directory", + translation_dirs, + "--locale", + locale, + "--input-file", + po_file, + ] + ) # Use our config (and not an app fixture) because the i18n module # grabs values at init time and we can't inject them later. diff --git a/securedrop/tests/test_i18n_tool.py b/securedrop/tests/test_i18n_tool.py deleted file mode 100644 --- a/securedrop/tests/test_i18n_tool.py +++ /dev/null @@ -1,442 +0,0 @@ -import os -import shutil -import signal -import subprocess -import time -from os.path import abspath, dirname, exists, getmtime, join, realpath -from pathlib import Path -from unittest.mock import patch - -import i18n_tool -import pytest -from tests.test_i18n import set_msg_translation_in_po_file - - -class TestI18NTool: - def setup(self): - self.dir = abspath(dirname(realpath(__file__))) - - def test_main(self, tmpdir, caplog): - with pytest.raises(SystemExit): - i18n_tool.I18NTool().main(["--help"]) - - tool = i18n_tool.I18NTool() - with patch.object(tool, "setup_verbosity", side_effect=KeyboardInterrupt): - assert ( - tool.main(["translate-messages", "--translations-dir", str(tmpdir)]) - == signal.SIGINT - ) - - def test_translate_desktop_l10n(self, tmpdir): - in_files = {} - for what in ("source", "journalist"): - in_files[what] = join(str(tmpdir), what + ".desktop.in") - shutil.copy(join(self.dir, "i18n/" + what + ".desktop.in"), in_files[what]) - i18n_tool.I18NTool().main( - [ - "--verbose", - "translate-desktop", - "--translations-dir", - str(tmpdir), - "--sources", - in_files["source"], - "--extract-update", - ] - ) - messages_file = join(str(tmpdir), "desktop.pot") - assert exists(messages_file) - with open(messages_file) as fobj: - pot = fobj.read() - assert "SecureDrop Source Interfaces" in pot - # pretend this happened a few seconds ago - few_seconds_ago = time.time() - 60 - os.utime(messages_file, (few_seconds_ago, few_seconds_ago)) - - i18n_file = join(str(tmpdir), "source.desktop") - - # Extract+update but do not compile - old_messages_mtime = getmtime(messages_file) - assert not exists(i18n_file) - i18n_tool.I18NTool().main( - [ - "--verbose", - "translate-desktop", - "--translations-dir", - str(tmpdir), - "--sources", - ",".join(list(in_files.values())), - "--extract-update", - ] - ) - assert not exists(i18n_file) - current_messages_mtime = getmtime(messages_file) - assert old_messages_mtime < current_messages_mtime - - for locale, translation in [ - ("fr_FR", "SOURCE FR"), - # Regression test for #4192; bug when adding Romanian as an accepted language - ("ro", "SOURCE RO"), - ]: - po_file = Path(tmpdir) / f"{locale}.po" - subprocess.check_call( - [ - "msginit", - "--no-translator", - "--locale", - locale, - "--output", - po_file, - "--input", - messages_file, - ] - ) - set_msg_translation_in_po_file( - po_file=po_file, - msgid_to_translate="SecureDrop Source Interfaces", - msgstr=translation, - ) - - # Compile but do not extract+update - old_messages_mtime = current_messages_mtime - i18n_tool.I18NTool().main( - [ - "--verbose", - "translate-desktop", - "--translations-dir", - str(tmpdir), - "--sources", - ",".join(list(in_files.values()) + ["BOOM"]), - "--compile", - ] - ) - assert old_messages_mtime == getmtime(messages_file) - with open(po_file) as fobj: - po = fobj.read() - assert "SecureDrop Source Interfaces" in po - assert "SecureDrop Journalist Interfaces" not in po - with open(i18n_file) as fobj: - i18n = fobj.read() - assert "SOURCE FR" in i18n - - def test_translate_messages_l10n(self, tmpdir): - source = [ - join(self.dir, "i18n/code.py"), - join(self.dir, "i18n/template.html"), - ] - args = [ - "--verbose", - "translate-messages", - "--translations-dir", - str(tmpdir), - "--mapping", - join(self.dir, "i18n/babel.cfg"), - "--sources", - ",".join(source), - "--extract-update", - "--compile", - ] - i18n_tool.I18NTool().main(args) - messages_file = join(str(tmpdir), "messages.pot") - assert exists(messages_file) - with open(messages_file, "rb") as fobj: - pot = fobj.read() - assert b"code hello i18n" in pot - assert b"template hello i18n" in pot - - locale = "en_US" - locale_dir = join(str(tmpdir), locale) - subprocess.check_call( - [ - "pybabel", - "init", - "-i", - messages_file, - "-d", - str(tmpdir), - "-l", - locale, - ] - ) - - # Add a dummy translation - po_file = Path(locale_dir) / "LC_MESSAGES/messages.po" - for msgid in ["code hello i18n", "template hello i18n"]: - set_msg_translation_in_po_file( - po_file=po_file, - msgid_to_translate=msgid, - msgstr=msgid, - ) - - mo_file = join(locale_dir, "LC_MESSAGES/messages.mo") - assert not exists(mo_file) - i18n_tool.I18NTool().main(args) - assert exists(mo_file) - with open(mo_file, mode="rb") as fobj: - mo = fobj.read() - assert b"code hello i18n" in mo - assert b"template hello i18n" in mo - - def test_translate_messages_compile_arg(self, tmpdir): - args = [ - "--verbose", - "translate-messages", - "--translations-dir", - str(tmpdir), - "--mapping", - join(self.dir, "i18n/babel.cfg"), - ] - i18n_tool.I18NTool().main( - args - + [ - "--sources", - join(self.dir, "i18n/code.py"), - "--extract-update", - ] - ) - messages_file = join(str(tmpdir), "messages.pot") - assert exists(messages_file) - with open(messages_file) as fobj: - pot = fobj.read() - assert "code hello i18n" in pot - - locale = "en_US" - locale_dir = join(str(tmpdir), locale) - po_file = join(locale_dir, "LC_MESSAGES/messages.po") - subprocess.check_call( - ["pybabel", "init", "-i", messages_file, "-d", str(tmpdir), "-l", locale] - ) - assert exists(po_file) - # pretend this happened a few seconds ago - few_seconds_ago = time.time() - 60 - os.utime(po_file, (few_seconds_ago, few_seconds_ago)) - - mo_file = join(locale_dir, "LC_MESSAGES/messages.mo") - - # - # Extract+update but do not compile - # - old_po_mtime = getmtime(po_file) - assert not exists(mo_file) - i18n_tool.I18NTool().main( - args - + [ - "--sources", - join(self.dir, "i18n/code.py"), - "--extract-update", - ] - ) - assert not exists(mo_file) - current_po_mtime = getmtime(po_file) - assert old_po_mtime < current_po_mtime - - # - # Translation would occur here - let's fake it - set_msg_translation_in_po_file( - po_file=Path(po_file), - msgid_to_translate="code hello i18n", - msgstr="code hello i18n", - ) - - # - # Compile but do not extract+update - # - source = [ - join(self.dir, "i18n/code.py"), - join(self.dir, "i18n/template.html"), - ] - current_po_mtime = getmtime(po_file) - i18n_tool.I18NTool().main( - args - + [ - "--sources", - ",".join(source), - "--compile", - ] - ) - assert current_po_mtime == getmtime(po_file) - with open(mo_file, mode="rb") as fobj: - mo = fobj.read() - assert b"code hello i18n" in mo - assert b"template hello i18n" not in mo - - def test_require_git_email_name(self, tmpdir): - k = {"cwd": str(tmpdir)} - subprocess.check_call(["git", "init"], **k) - with pytest.raises(Exception) as excinfo: - i18n_tool.I18NTool.require_git_email_name(str(tmpdir)) - assert "please set name" in str(excinfo.value) - - subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) - subprocess.check_call(["git", "config", "user.name", "Your Name"], **k) - assert i18n_tool.I18NTool.require_git_email_name(str(tmpdir)) - - def test_update_docs(self, tmpdir, caplog): - k = {"cwd": str(tmpdir)} - subprocess.check_call(["git", "init"], **k) - subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) - subprocess.check_call(["git", "config", "user.name", "Your Name"], **k) - os.makedirs(join(str(tmpdir), "docs/includes")) - subprocess.check_call(["touch", "docs/includes/l10n.txt"], **k) - subprocess.check_call(["git", "add", "docs/includes/l10n.txt"], **k) - subprocess.check_call(["git", "commit", "-m", "init"], **k) - - i18n_tool.I18NTool().main(["--verbose", "update-docs", "--docs-repo-dir", str(tmpdir)]) - assert "l10n.txt updated" in caplog.text - caplog.clear() - i18n_tool.I18NTool().main(["--verbose", "update-docs", "--docs-repo-dir", str(tmpdir)]) - assert "l10n.txt already up to date" in caplog.text - - def test_update_from_weblate(self, tmpdir, caplog): - d = str(tmpdir) - for repo in ("i18n", "securedrop"): - os.mkdir(join(d, repo)) - k = {"cwd": join(d, repo)} - subprocess.check_call(["git", "init"], **k) - subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) - subprocess.check_call(["git", "config", "user.name", "Loïc Nordhøy"], **k) - subprocess.check_call(["touch", "README.md"], **k) - subprocess.check_call(["git", "add", "README.md"], **k) - subprocess.check_call(["git", "commit", "-m", "README", "README.md"], **k) - for o in os.listdir(join(self.dir, "i18n")): - f = join(self.dir, "i18n", o) - if os.path.isfile(f): - shutil.copyfile(f, join(d, "i18n", o)) - else: - shutil.copytree(f, join(d, "i18n", o)) - k = {"cwd": join(d, "i18n")} - subprocess.check_call(["git", "add", "securedrop", "install_files"], **k) - subprocess.check_call(["git", "commit", "-m", "init", "-a"], **k) - subprocess.check_call(["git", "checkout", "-b", "i18n", "master"], **k) - - def r(): - return "".join([str(record) for record in caplog.records]) - - # - # de_DE is not amount the supported languages, it is not taken - # into account despite the fact that it exists in weblate. - # - caplog.clear() - i18n_tool.I18NTool().main( - [ - "--verbose", - "update-from-weblate", - "--root", - join(str(tmpdir), "securedrop"), - "--url", - join(str(tmpdir), "i18n"), - "--supported-languages", - "nl", - ] - ) - assert "l10n: updated Dutch (nl)" in r() - assert "l10n: updated German (de_DE)" not in r() - - # - # de_DE is added but there is no change in the nl translation - # therefore nothing is done for nl - # - caplog.clear() - i18n_tool.I18NTool().main( - [ - "--verbose", - "update-from-weblate", - "--root", - join(str(tmpdir), "securedrop"), - "--url", - join(str(tmpdir), "i18n"), - "--supported-languages", - "nl,de_DE", - ] - ) - assert "l10n: updated Dutch (nl)" not in r() - assert "l10n: updated German (de_DE)" in r() - - # - # nothing new for nl or de_DE: nothing is done - # - caplog.clear() - i18n_tool.I18NTool().main( - [ - "--verbose", - "update-from-weblate", - "--root", - join(str(tmpdir), "securedrop"), - "--url", - join(str(tmpdir), "i18n"), - "--supported-languages", - "nl,de_DE", - ] - ) - assert "l10n: updated Dutch (nl)" not in r() - assert "l10n: updated German (de_DE)" not in r() - message = subprocess.check_output( - ["git", "--no-pager", "-C", "securedrop", "show"], - cwd=d, - encoding="utf-8", - ) - assert "Loïc" in message - - # an update is done to nl in weblate - i18n_dir = Path(d) / "i18n" - po_file = i18n_dir / "securedrop/translations/nl/LC_MESSAGES/messages.po" - content = po_file.read_text() - text_to_update = "inactiviteit" - assert text_to_update in content - updated_content = content.replace(text_to_update, "INACTIVITEIT") - po_file.write_text(updated_content) - - k = {"cwd": join(d, "i18n")} - subprocess.check_call(["git", "add", str(po_file)], **k) - subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) - subprocess.check_call(["git", "config", "user.name", "Someone Else"], **k) - subprocess.check_call( - ["git", "commit", "-m", "Translated using Weblate", str(po_file)], **k - ) - - k = {"cwd": join(d, "securedrop")} - subprocess.check_call(["git", "config", "user.email", "[email protected]"], **k) - subprocess.check_call(["git", "config", "user.name", "Someone Else"], **k) - - # - # the nl translation update from weblate is copied - # over. - # - caplog.clear() - i18n_tool.I18NTool().main( - [ - "--verbose", - "update-from-weblate", - "--root", - join(str(tmpdir), "securedrop"), - "--url", - join(str(tmpdir), "i18n"), - "--supported-languages", - "nl,de_DE", - ] - ) - assert "l10n: updated Dutch (nl)" in r() - assert "l10n: updated German (de_DE)" not in r() - - # The translator is credited in Git history. - message = subprocess.check_output( - ["git", "--no-pager", "-C", "securedrop", "show"], - cwd=d, - encoding="utf-8", - ) - assert "Someone Else" in message - assert "Loïc" not in message - - # The "list-translators" command correctly reads the translator from Git history. - caplog.clear() - i18n_tool.I18NTool().main( - [ - "--verbose", - "list-translators", - "--all", - "--root", - join(str(tmpdir), "securedrop"), - "--url", - join(str(tmpdir), "i18n"), - ] - ) - assert "Someone Else" in caplog.text diff --git a/securedrop/tests/test_template_filters.py b/securedrop/tests/test_template_filters.py --- a/securedrop/tests/test_template_filters.py +++ b/securedrop/tests/test_template_filters.py @@ -2,7 +2,6 @@ from datetime import datetime, timedelta from pathlib import Path -import i18n_tool import journalist_app import source_app import template_filters @@ -87,23 +86,24 @@ def do_test(create_app): test_config = create_config_for_i18n_test(supported_locales=["en_US", "fr_FR"]) i18n_dir = Path(__file__).absolute().parent / "i18n" - i18n_tool.I18NTool().main( + pot = Path(test_config.TEMP_DIR) / "messages.pot" + subprocess.check_call( [ - "--verbose", - "translate-messages", + "pybabel", + "extract", "--mapping", str(i18n_dir / "babel.cfg"), - "--translations-dir", - str(test_config.TEMP_DIR), - "--sources", + "--output", + pot, str(i18n_dir / "code.py"), - "--extract-update", - "--compile", ] ) + # To be able to test template filters for a given language, its message + # catalog must exist, but it doesn't have to contain any actual + # translations. So we can just initialize it based on the template created + # by "pybabel extract". for lang in ("en_US", "fr_FR"): - pot = Path(test_config.TEMP_DIR) / "messages.pot" subprocess.check_call( ["pybabel", "init", "-i", pot, "-d", test_config.TEMP_DIR, "-l", lang] )
streamline functions currently provided by `i18n_tool.py` - [x] Adapt `securedrop-client`'s `make extract-strings` target - Can this be generalized in `securedrop-tooling`? - Does this let us combine the `securedrop/{securedrop,desktop}` Weblate components? (This might violate the "No side effects" constraint.) - [x] Enforce in CI (`make check-strings`) - Can this be generalized in `securedrop-tooling`? - Per <https://github.com/freedomofpress/securedrop-engineering/pull/30#issuecomment-1633171470>: - [x] Reimplement "Compile `.po` catalogs → `.mo` machine objects" as `make compile-translations` - ~`make update-docs` → https://github.com/freedomofpress/securedrop-docs/blob/main/docs/includes/l10n.txt~ - Counterpoint: https://github.com/freedomofpress/securedrop/issues/6917#issuecomment-1689091116 - freedomofpress/securedrop-docs#503 - ~~freedomofpress/securedrop-client#1280~~ - Counterpoint: https://github.com/freedomofpress/securedrop/issues/6917#issuecomment-1690762840
2023-09-28T22:18:07Z
[]
[]
freedomofpress/securedrop
6,972
freedomofpress__securedrop-6972
[ "6802" ]
fd110093483552c06a377dc4716828b1f15a3bab
diff --git a/securedrop/encryption.py b/securedrop/encryption.py --- a/securedrop/encryption.py +++ b/securedrop/encryption.py @@ -113,6 +113,12 @@ def get_source_key_fingerprint(self, source_filesystem_id: str) -> str: self._save_key_fingerprint_to_redis(source_filesystem_id, source_key_fingerprint) return source_key_fingerprint + def get_source_secret_key(self, fingerprint: str, passphrase: str) -> str: + secret_key = self._gpg.export_keys(fingerprint, secret=True, passphrase=passphrase) + if not secret_key: + raise GpgKeyNotFoundError() + return secret_key + def encrypt_source_message(self, message_in: str, encrypted_message_path_out: Path) -> None: redwood.encrypt_message( # A submission is only encrypted for the journalist key diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -7,7 +7,7 @@ import store import werkzeug from db import db -from encryption import EncryptionManager +from encryption import EncryptionManager, GpgKeyNotFoundError from flask import ( Blueprint, abort, @@ -376,7 +376,30 @@ def login() -> Union[str, werkzeug.Response]: source.pgp_fingerprint = fingerprint db.session.add(source) db.session.commit() - # TODO: Migrate GPG secret key here too + elif source.pgp_secret_key is None: + # Need to migrate the secret key out of GPG + encryption_mgr = EncryptionManager.get_default() + try: + secret_key = encryption_mgr.get_source_secret_key( + source.fingerprint, source_user.gpg_secret + ) + except GpgKeyNotFoundError: + # Don't fail here, but it's likely decryption of journalist + # messages will fail. + secret_key = None + if secret_key: + source.pgp_secret_key = secret_key + db.session.add(source) + db.session.commit() + # Let's optimistically delete the GPG key from the keyring + # if *everything* has been migrated. If this fails it's OK, + # since we still try to delete from the keyring on source + # deletion too. + if source.pgp_fingerprint and source.pgp_public_key: + try: + encryption_mgr.delete_source_key_pair(source.filesystem_id) + except: # noqa: E722 + pass return redirect(url_for(".lookup", from_login="1"))
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -13,6 +13,7 @@ import pytest import version from db import db +from encryption import EncryptionManager, GpgKeyNotFoundError from flask import escape, g, request, session, url_for from journalist_app.utils import delete_collection from models import InstanceConfig, Reply, Source @@ -20,6 +21,7 @@ from source_app import api as source_app_api from source_app import get_logo_url from source_app.session_manager import SessionManager +from source_user import create_source_user import redwood @@ -345,6 +347,62 @@ def test_login_with_missing_reply_files(source_app, app_storage): assert SessionManager.is_user_logged_in(db_session=db.session) +def test_login_no_pgp_keypair(source_app, app_storage): + """ + Test the on-demand creation of a keypair when none exists + """ + source, codename = utils.db_helper.init_source(app_storage) + source.pgp_fingerprint = None + source.pgp_public_key = None + source.pgp_secret_key = None + db.session.add(source) + db.session.commit() + # And there's no legacy GPG key hiding in the background + assert source.fingerprint is None + with source_app.test_client() as app: + resp = app.post(url_for("main.login"), data=dict(codename=codename), follow_redirects=True) + assert resp.status_code == 200 + assert SessionManager.is_user_logged_in(db_session=db.session) + # Now check to see PGP fields are populated + assert len(source.pgp_fingerprint) == 40 + assert redwood.is_valid_public_key(source.pgp_public_key) + assert source.pgp_secret_key.startswith("-----BEGIN PGP PRIVATE KEY BLOCK-----") + + +def test_login_gpg_secret_key_migration(source_app, app_storage): + """ + Test the on-demand migration of GPG secret keys to database-backed storage + """ + # First create a source that is backed by a GPG key + passphrase = PassphraseGenerator.get_default().generate_passphrase() + source_user = create_source_user( + db_session=db.session, + source_passphrase=passphrase, + source_app_storage=app_storage, + ) + source = source_user.get_db_record() + encryption_mgr = EncryptionManager.get_default() + utils.create_legacy_gpg_key(encryption_mgr, source_user, source) + # Copy the fingerprint and public key to DB storage, like the alembic migration does + source.pgp_fingerprint = source.fingerprint + source.pgp_public_key = source.public_key + source.pgp_secret_key = None + db.session.add(source) + db.session.commit() + # Now log in + with source_app.test_client() as app: + resp = app.post( + url_for("main.login"), data=dict(codename=passphrase), follow_redirects=True + ) + assert resp.status_code == 200 + assert SessionManager.is_user_logged_in(db_session=db.session) + # Now check to see PGP secret key is populated + assert source.pgp_secret_key.startswith("-----BEGIN PGP PRIVATE KEY BLOCK-----") + # And the GPG key has been deleted + with pytest.raises(GpgKeyNotFoundError): + encryption_mgr.get_source_key_fingerprint(source.filesystem_id) + + def _dummy_submission(app): """ Helper to make a submission (content unimportant), mostly useful in
On-demand migration of sources' private keys to database-backed storage upon login As part of our work to migrate to Sequoia, we will migrate sources' private keys on-demand when they log in to the database-backed storage. As discussed in #6499, gpg stores keys in their own encrypted format, and we need the source's passphrase to unlock them, so we can't do it offline (like the public key migration). The plan is that when a source logs in, we'll see that they don't have a private key in the database, so we'll try to export their private key from gpg and then store it in the database in the armored and encrypted OpenPGP format.
Likely the main work here is that pretty_bad_protocol (AFAICT) doesn't already have a function to export private keys, so that will need to be done as part of this task, whether in p_b_p or just separately and directly calling GPG. > Likely the main work here is that pretty_bad_protocol (AFAICT) doesn't already have a function to export private keys, so that will need to be done as part of this task, whether in p_b_p This is implemented in #6907.
2023-10-05T03:00:05Z
[]
[]
freedomofpress/securedrop
6,975
freedomofpress__securedrop-6975
[ "6977", "6977" ]
41cf6a3d6d75f9e488183bdb55ec57542f82b145
diff --git a/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py b/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py --- a/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py +++ b/securedrop/alembic/versions/17c559a7a685_pgp_public_keys.py @@ -32,7 +32,12 @@ def upgrade() -> None: doesn't already have key material migrated, export the key and save it in the database. """ - config = SecureDropConfig.get_current() + try: + config = SecureDropConfig.get_current() + except ModuleNotFoundError: + # Fresh install, nothing to migrate + return + gpg = gnupg.GPG( binary="gpg2", homedir=str(config.GPG_KEY_DIR), diff --git a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py --- a/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py +++ b/securedrop/alembic/versions/2e24fc7536e8_make_journalist_id_non_nullable.py @@ -5,24 +5,15 @@ Create Date: 2022-01-12 19:31:06.186285 """ -import os import uuid import argon2 import sqlalchemy as sa import two_factor from alembic import op - -# raise the errors if we're not in production -raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" - -try: - from models import ARGON2_PARAMS - from passphrases import PassphraseGenerator -except: # noqa - if raise_errors: - raise - +from models import ARGON2_PARAMS +from passphrases import PassphraseGenerator +from sdconfig import SecureDropConfig # revision identifiers, used by Alembic. revision = "2e24fc7536e8" @@ -98,6 +89,14 @@ def migrate_nulls() -> None: def upgrade() -> None: + try: + # While this migration doesn't use SecureDrop config directly, + # it's transitively used via PassphraseGenerator + SecureDropConfig.get_current() + except ModuleNotFoundError: + # Fresh install, nothing to migrate + return + migrate_nulls() with op.batch_alter_table("journalist_login_attempt", schema=None) as batch_op: diff --git a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py --- a/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py +++ b/securedrop/alembic/versions/3da3fcab826a_delete_orphaned_submissions.py @@ -7,22 +7,12 @@ Create Date: 2018-11-25 19:40:25.873292 """ -import os import sqlalchemy as sa from alembic import op - -# raise the errors if we're not in production -raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" - -try: - from journalist_app import create_app - from sdconfig import SecureDropConfig - from store import NoFileFoundException, Storage, TooManyFilesException -except ImportError: - # This is a fresh install, and config.py has not been created yet. - if raise_errors: - raise +from journalist_app import create_app +from sdconfig import SecureDropConfig +from store import NoFileFoundException, Storage, TooManyFilesException # revision identifiers, used by Alembic. revision = "3da3fcab826a" @@ -43,69 +33,70 @@ def raw_sql_grab_orphaned_objects(table_name: str) -> str: def upgrade() -> None: + try: + config = SecureDropConfig.get_current() + except ModuleNotFoundError: + # Fresh install, nothing to migrate + return + conn = op.get_bind() submissions = conn.execute(sa.text(raw_sql_grab_orphaned_objects("submissions"))).fetchall() replies = conn.execute(sa.text(raw_sql_grab_orphaned_objects("replies"))).fetchall() - try: - config = SecureDropConfig.get_current() - app = create_app(config) - with app.app_context(): - for submission in submissions: - try: - conn.execute( - sa.text( - """ - DELETE FROM submissions + app = create_app(config) + with app.app_context(): + for submission in submissions: + try: + conn.execute( + sa.text( + """ + DELETE FROM submissions + WHERE id=:id + """ + ).bindparams(id=submission.id) + ) + + path = Storage.get_default().path_without_filesystem_id(submission.filename) + Storage.get_default().move_to_shredder(path) + except NoFileFoundException: + # The file must have been deleted by the admin, remove the row + conn.execute( + sa.text( + """ + DELETE FROM submissions + WHERE id=:id + """ + ).bindparams(id=submission.id) + ) + except TooManyFilesException: + pass + + for reply in replies: + try: + conn.execute( + sa.text( + """ + DELETE FROM replies WHERE id=:id """ - ).bindparams(id=submission.id) - ) - - path = Storage.get_default().path_without_filesystem_id(submission.filename) - Storage.get_default().move_to_shredder(path) - except NoFileFoundException: - # The file must have been deleted by the admin, remove the row - conn.execute( - sa.text( - """ - DELETE FROM submissions + ).bindparams(id=reply.id) + ) + + path = Storage.get_default().path_without_filesystem_id(reply.filename) + Storage.get_default().move_to_shredder(path) + except NoFileFoundException: + # The file must have been deleted by the admin, remove the row + conn.execute( + sa.text( + """ + DELETE FROM replies WHERE id=:id """ - ).bindparams(id=submission.id) - ) - except TooManyFilesException: - pass - - for reply in replies: - try: - conn.execute( - sa.text( - """ - DELETE FROM replies - WHERE id=:id - """ - ).bindparams(id=reply.id) - ) - - path = Storage.get_default().path_without_filesystem_id(reply.filename) - Storage.get_default().move_to_shredder(path) - except NoFileFoundException: - # The file must have been deleted by the admin, remove the row - conn.execute( - sa.text( - """ - DELETE FROM replies - WHERE id=:id - """ - ).bindparams(id=reply.id) - ) - except TooManyFilesException: - pass - except: # noqa - if raise_errors: - raise + ).bindparams(id=reply.id) + ) + except TooManyFilesException: + pass def downgrade() -> None: diff --git a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py --- a/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py +++ b/securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py @@ -3,23 +3,14 @@ Revises: f2833ac34bb6 Create Date: 2019-04-02 10:45:05.178481 """ -import os import sqlalchemy as sa from alembic import op - -# raise the errors if we're not in production -raise_errors = os.environ.get("SECUREDROP_ENV", "prod") != "prod" - -try: - from journalist_app import create_app - from models import Reply, Submission - from sdconfig import SecureDropConfig - from store import Storage, queued_add_checksum_for_file - from worker import create_queue -except: # noqa - if raise_errors: - raise +from journalist_app import create_app +from models import Reply, Submission +from sdconfig import SecureDropConfig +from store import Storage, queued_add_checksum_for_file +from worker import create_queue # revision identifiers, used by Alembic. revision = "b58139cfdc8c" @@ -47,47 +38,48 @@ def upgrade() -> None: try: config = SecureDropConfig.get_current() - app = create_app(config) + except ModuleNotFoundError: + # Fresh install, nothing to migrate + return + + app = create_app(config) - # we need an app context for the rq worker extension to work properly - with app.app_context(): - conn = op.get_bind() - query = sa.text( - """SELECT submissions.id, sources.filesystem_id, submissions.filename - FROM submissions - INNER JOIN sources - ON submissions.source_id = sources.id - """ + # we need an app context for the rq worker extension to work properly + with app.app_context(): + conn = op.get_bind() + query = sa.text( + """SELECT submissions.id, sources.filesystem_id, submissions.filename + FROM submissions + INNER JOIN sources + ON submissions.source_id = sources.id + """ + ) + for (sub_id, filesystem_id, filename) in conn.execute(query): + full_path = Storage.get_default().path(filesystem_id, filename) + create_queue(config.RQ_WORKER_NAME).enqueue( + queued_add_checksum_for_file, + Submission, + int(sub_id), + full_path, + app.config["SQLALCHEMY_DATABASE_URI"], ) - for (sub_id, filesystem_id, filename) in conn.execute(query): - full_path = Storage.get_default().path(filesystem_id, filename) - create_queue(config.RQ_WORKER_NAME).enqueue( - queued_add_checksum_for_file, - Submission, - int(sub_id), - full_path, - app.config["SQLALCHEMY_DATABASE_URI"], - ) - query = sa.text( - """SELECT replies.id, sources.filesystem_id, replies.filename - FROM replies - INNER JOIN sources - ON replies.source_id = sources.id - """ + query = sa.text( + """SELECT replies.id, sources.filesystem_id, replies.filename + FROM replies + INNER JOIN sources + ON replies.source_id = sources.id + """ + ) + for (rep_id, filesystem_id, filename) in conn.execute(query): + full_path = Storage.get_default().path(filesystem_id, filename) + create_queue(config.RQ_WORKER_NAME).enqueue( + queued_add_checksum_for_file, + Reply, + int(rep_id), + full_path, + app.config["SQLALCHEMY_DATABASE_URI"], ) - for (rep_id, filesystem_id, filename) in conn.execute(query): - full_path = Storage.get_default().path(filesystem_id, filename) - create_queue(config.RQ_WORKER_NAME).enqueue( - queued_add_checksum_for_file, - Reply, - int(rep_id), - full_path, - app.config["SQLALCHEMY_DATABASE_URI"], - ) - except: # noqa - if raise_errors: - raise def downgrade() -> None:
diff --git a/securedrop/tests/test_alembic.py b/securedrop/tests/test_alembic.py --- a/securedrop/tests/test_alembic.py +++ b/securedrop/tests/test_alembic.py @@ -1,8 +1,11 @@ import os import re +import shutil import subprocess from collections import OrderedDict +from contextlib import contextmanager from os import path +from typing import Generator import pytest from alembic.config import Config as AlembicConfig @@ -129,10 +132,12 @@ def test_alembic_head_matches_db_models(journalist_app, alembic_config, config): assert_schemas_equal(alembic_schema, models_schema) [email protected]("use_config_py", [True, False]) @pytest.mark.parametrize("migration", ALL_MIGRATIONS) -def test_alembic_migration_up_and_down(alembic_config, config, migration, _reset_db): - upgrade(alembic_config, migration) - downgrade(alembic_config, "base") +def test_alembic_migration_up_and_down(alembic_config, config, use_config_py, migration, _reset_db): + with use_config(use_config_py): + upgrade(alembic_config, migration) + downgrade(alembic_config, "base") @pytest.mark.parametrize("migration", ALL_MIGRATIONS) @@ -213,3 +218,14 @@ def test_downgrade_with_data(alembic_config, config, migration, _reset_db): # Make sure it applied "cleanly" for some definition of clean downgrade_tester.check_downgrade() + + +@contextmanager +def use_config(use: bool) -> Generator: + if not use: + shutil.move("config.py", "config.py.moved") + try: + yield + finally: + if not use: + shutil.move("config.py.moved", "config.py")
alembic tests should run a variant without config.py As we learned in https://github.com/freedomofpress/securedrop/issues/6976 / https://github.com/freedomofpress/securedrop/pull/6975, migrations need to work in a fresh install, where there's no config.py yet. The alembic tests that run each migration up and down should have a variant that does that somehow. alembic tests should run a variant without config.py As we learned in https://github.com/freedomofpress/securedrop/issues/6976 / https://github.com/freedomofpress/securedrop/pull/6975, migrations need to work in a fresh install, where there's no config.py yet. The alembic tests that run each migration up and down should have a variant that does that somehow.
2023-10-05T20:49:31Z
[]
[]
freedomofpress/securedrop
7,029
freedomofpress__securedrop-7029
[ "7025" ]
4c883e1c55fcec6f2192e22baad8720e999f2148
diff --git a/securedrop/source_app/main.py b/securedrop/source_app/main.py --- a/securedrop/source_app/main.py +++ b/securedrop/source_app/main.py @@ -7,7 +7,7 @@ import store import werkzeug from db import db -from encryption import EncryptionManager, GpgKeyNotFoundError +from encryption import EncryptionManager, GpgDecryptError, GpgKeyNotFoundError from flask import ( Blueprint, abort, @@ -44,6 +44,7 @@ from store import Storage import redwood +from redwood import RedwoodError def make_blueprint(config: SecureDropConfig) -> Blueprint: @@ -171,6 +172,8 @@ def lookup(logged_in_source: SourceUser) -> str: current_app.logger.error("Could not decode reply %s" % reply.filename) except FileNotFoundError: current_app.logger.error("Reply file missing: %s" % reply.filename) + except (GpgDecryptError, RedwoodError) as e: + current_app.logger.error(f"Could not decrypt reply {reply.filename}: {str(e)}") else: reply.date = datetime.utcfromtimestamp(os.stat(reply_path).st_mtime) replies.append(reply)
diff --git a/securedrop/tests/test_source.py b/securedrop/tests/test_source.py --- a/securedrop/tests/test_source.py +++ b/securedrop/tests/test_source.py @@ -13,7 +13,7 @@ import pytest import version from db import db -from encryption import EncryptionManager, GpgKeyNotFoundError +from encryption import EncryptionManager, GpgDecryptError, GpgKeyNotFoundError from flask import escape, g, request, session, url_for from journalist_app.utils import delete_collection from models import InstanceConfig, Reply, Source @@ -347,6 +347,34 @@ def test_login_with_missing_reply_files(source_app, app_storage): assert SessionManager.is_user_logged_in(db_session=db.session) +def test_login_with_undecryptable_reply_files(source_app, app_storage): + """ + Test that source can log in when replies are present but cannot be decrypted + """ + source, codename = utils.db_helper.init_source(app_storage) + journalist, _ = utils.db_helper.init_journalist() + replies = utils.db_helper.reply(app_storage, journalist, source, 1) + assert len(replies) > 0 + reply_file_path = Path(app_storage.path(source.filesystem_id, replies[0].filename)) + assert reply_file_path.exists() + + with mock.patch("encryption.EncryptionManager.decrypt_journalist_reply") as repMock: + repMock.side_effect = GpgDecryptError() + with source_app.test_client() as app: + resp = app.get(url_for("main.login")) + assert resp.status_code == 200 + text = resp.data.decode("utf-8") + assert "Enter Codename" in text + + resp = app.post( + url_for("main.login"), data=dict(codename=codename), follow_redirects=True + ) + assert resp.status_code == 200 + text = resp.data.decode("utf-8") + assert "Submit Files" in text + assert SessionManager.is_user_logged_in(db_session=db.session) + + def test_login_no_pgp_keypair(source_app, app_storage): """ Test the on-demand creation of a keypair when none exists
When a source's reply secret key is unavailable, but there are replies encrypted with it, the source can't log in ## Description ## Steps to Reproduce - create a source in the SI and submit a file, then log out - reply to the source from the JI - delete the source's reply keypair - attempt to log in as the source ## Expected Behavior - source logs in but encrypted replies are not available ## Actual Behavior - the source gets an error page and the following errors are thrown in source logs: ``` [Wed Oct 25 02:27:52.095767 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] File "/var/www/securedrop/encryption.py", line 210, in decrypt_journalist_reply [Wed Oct 25 02:27:52.095848 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] raise GpgDecryptError(out.stderr) [Wed Oct 25 02:27:52.095906 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] encryption.GpgDecryptError: [GNUPG:] ENC_TO 311FF89D40A5FAC9 1 0 [Wed Oct 25 02:27:52.095963 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] ENC_TO 2FB6D22BADC72E83 1 0 [Wed Oct 25 02:27:52.096057 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] KEY_CONSIDERED 7ECA271BA6894A7EBAE6414C4EE9B0B8EF362114 0 [Wed Oct 25 02:27:52.096117 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] gpg: encrypted with 4096-bit RSA key, ID 2FB6D22BADC72E83, created 2022-09-23 [Wed Oct 25 02:27:52.096183 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] "SD test submission key" [Wed Oct 25 02:27:52.096268 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] NO_SECKEY 2FB6D22BADC72E83 [Wed Oct 25 02:27:52.096327 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] gpg: encrypted with RSA key, ID 311FF89D40A5FAC9 [Wed Oct 25 02:27:52.096384 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] NO_SECKEY 311FF89D40A5FAC9 [Wed Oct 25 02:27:52.096475 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] BEGIN_DECRYPTION [Wed Oct 25 02:27:52.096534 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] DECRYPTION_FAILED [Wed Oct 25 02:27:52.096601 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] gpg: decryption failed: No secret key [Wed Oct 25 02:27:52.096679 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] [GNUPG:] END_DECRYPTION [Wed Oct 25 02:27:52.096737 2023] [wsgi:error] [pid 134751:tid 132485121509120] [remote 127.0.0.1:52012] ``` Please provide screenshots where appropriate. ## Comments Suggestions to fix, any other relevant information.
This should be an impossible state to end up in - if there's no key pair, you shouldn't have been able to leave a reply since there's no key to encrypt the message to. This is also an irrecoverable state, because even if we generate a new key pair, the message is encrypted to the old key pair so it can never be decrypted by the source. So, we could display a nicer error page or just hide the replies upon decryption failure, but I think letting the error bubble up is appropriate for an impossible state in normal operation. Plus I think if decryption fails in general, that is bad and we should be erroring out instead of trying to recover. Unless I'm missing something, I suggest wontfix. The repro involves the keypair being unavailable *after* the reply was created, so it's very unlikely but not impossible. The replies are not recoverable but the source's passphrase would still be valid otherwise. Also, as it stands this is a silent error - a source just gets a message that there was a problem with no indication of what went wrong and no obvious next step (the only link on the error page asks them to "look up another codename", which makes no sense in this context). If the instance is configured correctly SI logging is disabled, which means admins aren't alerted either. Given that the next release starts the process of removing GPG keypairs in favour of Sequioa and DB storage, the remote chance of the keychain getting into a broken state and a source's private key not being available for migration seems like it would be higher. Improving the error page is the most basic response in this case - I don't agree that WONTFIX is justified. With an upgrade to 2.7.0-rc2 this gets even more fun. Since there's no public key to migrate the sources' relevant db fields are null, which means that if they try to log in a new key is generated for them. With that key in place, the JI displays a reply box for the source and replies can be sent. But the source still can't log in, so they can't read the replies encrypted with the new key. I think my mental model is that if a source's key pair goes missing it's equivalent to half of their DB row being zeroed out, which is just irrecoverable corruption IMO. No objection to adding/improving a dedicated error page. > Given that the next release starts the process of removing GPG keypairs in favour of Sequioa and DB storage, the remote chance of the keychain getting into a broken state and a source's private key not being available for migration seems like it would be higher. Yeah, that seems right. Though we'd hope that people are regularly deleting sources, so the act of deleting a GPG key pair isn't an aberration. I do think we could use with more guards around the secret key export (some equivalent to `is_valid_public_key()` and verifying the passphrase can unlock it), which I can sketch out. I think the scenario that's bugging me here is if there are incomplete or borked keyrings in prod instances right now, or if (somehow!) the Sequoia migration leaves the keyring in the state above. Once we're on 2.7.0 and all keys are migrated then yep, the only way this happens is if the db is corrupted or manually edited to drop keys. This is less about data consistency than it is about UX for sources, though. Through that lens, a message that (some) replies can't be decrypted seems better than an opaque error that cuts them off from using an existing passphrase.
2023-10-26T14:53:08Z
[]
[]
freedomofpress/securedrop
7,035
freedomofpress__securedrop-7035
[ "7030" ]
3a665de636bef589403863fa6a02562fde45a24d
diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -1,9 +1,13 @@ +import sys + from encryption import EncryptionManager, GpgKeyNotFoundError from execution import asynchronous from journalist_app import create_app from models import Source from sdconfig import SecureDropConfig +import redwood + config = SecureDropConfig.get_current() # app is imported by journalist.wsgi app = create_app(config) @@ -21,10 +25,28 @@ def prime_keycache() -> None: pass -prime_keycache() +def validate_journalist_key() -> None: + """Verify the journalist PGP key is valid""" + encryption_mgr = EncryptionManager.get_default() + # First check that we can read it + try: + journalist_key = encryption_mgr.get_journalist_public_key() + except Exception as e: + print(f"ERROR: Unable to read journalist public key: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Unable to read journalist public key: {e}") + sys.exit(1) + # And then what we read is valid + try: + redwood.is_valid_public_key(journalist_key) + except redwood.RedwoodError as e: + print(f"ERROR: Journalist public key is not valid: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Journalist public key is not valid: {e}") + sys.exit(1) if __name__ == "__main__": # pragma: no cover + validate_journalist_key() + prime_keycache() debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host app.run(debug=debug, host="0.0.0.0", port=8081)
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -17,6 +17,7 @@ from flaky import flaky from flask import escape, g, url_for from flask_babel import gettext, ngettext +from journalist import validate_journalist_key from journalist_app.sessions import session from journalist_app.utils import mark_seen from models import ( @@ -51,6 +52,8 @@ from tests.utils.instrument import InstrumentedApp from two_factor import TOTP +from redwood import RedwoodError + from .utils import create_legacy_gpg_key, login_journalist # Smugly seed the RNG for deterministic testing @@ -3772,3 +3775,20 @@ def test_journalist_deletion(journalist_app, app_storage): assert len(SeenReply.query.filter_by(journalist_id=deleted.id).all()) == 2 # And there are no login attempts assert JournalistLoginAttempt.query.all() == [] + + +def test_validate_journalist_key(config, capsys): + # The test key passes validation + validate_journalist_key() + # Reading the key file fails + with patch( + "encryption.EncryptionManager.get_journalist_public_key", side_effect=RuntimeError("err") + ): + with pytest.raises(SystemExit): + validate_journalist_key() + assert capsys.readouterr().err == "ERROR: Unable to read journalist public key: err\n" + # Key fails validation + with patch("redwood.is_valid_public_key", side_effect=RedwoodError("err")): + with pytest.raises(SystemExit): + validate_journalist_key() + assert capsys.readouterr().err == "ERROR: Journalist public key is not valid: err\n"
determine post-upgrade failure-mode for a SHA-1-signed submission key ## Description After #6948 (for #6399), redwood will refuse to encrypt to a submission key with a SHA-1 signature. After #6928, `securedrop-admin sdconfig` will reject a submission key with a SHA-1 signature. This check guarantees that new and reconfigured instances will comply with #6948. What will happen to an instance with a SHA-1-signed signature after upgrading to v2.7.0? ## Possible approaches | Option | Documentation changes | Code changes | Implication | | --- | --- | --- | --- | | Fail open, but log | optional | ✓ | Admin must monitor logs and/or OSSEC alerts. | | Fail open, but document | ✓ | ✗ | Admin must monitor release notes or check documentation. | | Fail closed | optional | ✓[1] | Admin can contact us for help. | **Notes:** 1. @legoktm observes that, without a code change to handle this case, Apache will come back up after reboot even if the `postinst` script fails under `unattended-upgrades`.
For context, we expect this to be a pretty rare issue given that if people followed our documentation, they should not have generated a SHA-1 submission key. The submission key is currently stored in the GPG keyring, so we export it to disk for Sequoia to read (and for SecureDrop to serve) in the postinst: ```bash export_journalist_public_key() { # config.py is root-writable, so it's safe to run it as root to extract the fingerprint journalist_pub="/var/lib/securedrop/journalist.pub" # If the journalist.pub file doesn't exist if ! test -f $journalist_pub; then # And we have a config.py (during initial install it won't exist yet) if test -f /var/www/securedrop/config.py; then # n.b. based on sdconfig.py, this should work with very old config.py files. fingerprint=$(cd /var/www/securedrop; python3 -c "import config; print(config.JOURNALIST_KEY)") # Set up journalist.pub as root/www-data 640 before writing to it. touch $journalist_pub chown root:www-data $journalist_pub chmod 640 $journalist_pub # Export the GPG public key # shellcheck disable=SC2024 sudo -u www-data gpg2 --homedir=/var/lib/securedrop/keys --export --armor "$fingerprint" > $journalist_pub # Verify integrity of what we just exported sudo -u www-data /var/www/securedrop/scripts/validate-pgp-key "$journalist_pub" "$fingerprint" fi fi } ``` The final step is to validate the exported key file passes `validate-pgp-key`, which is a wrapper for `redwood.is_valid_public_key()`. However, if validation fails for whatever reason (e.g. GPG export fails, it's a SHA-1 key, etc.), then we abort, which interrupts the postinst, so, e.g. database upgrades won't be applied. apache will be down, though it should be restarted when the nightly instance reboot happens. With that in mind, I think having the validation fail at package install time is bad, because it requires even more manual work to get an instance in a working state since you need to manually apply the updates after doing a key rotation. One of the proposals in standup from @zenmonkeykstop was to just have the JI exit if the submission key isn't valid, which will alert journalists and then their admin that something is wrong. I think this is reasonable and probably a better UX, and will let us remove the validate step in the postinst IMO. Works for me (:)) - if we can just use is_valid_public_key() in app initialization then that sounds simple enough. Yeah, from trying this on my staging instance I was momentarily confused by the postinst validation/failure, and as you mentioned it has a bunch of unintended side-effects. I think it's better to have it fail in the JI. In this case we don't have to worry about feature parity with SDW.
2023-10-26T20:58:26Z
[]
[]
freedomofpress/securedrop
7,045
freedomofpress__securedrop-7045
[ "7030" ]
058a9b2bb1c0be15d0ad1a790de4799a83fda5e2
diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -1,9 +1,13 @@ +import sys + from encryption import EncryptionManager, GpgKeyNotFoundError from execution import asynchronous from journalist_app import create_app from models import Source from sdconfig import SecureDropConfig +import redwood + config = SecureDropConfig.get_current() # app is imported by journalist.wsgi app = create_app(config) @@ -21,10 +25,28 @@ def prime_keycache() -> None: pass -prime_keycache() +def validate_journalist_key() -> None: + """Verify the journalist PGP key is valid""" + encryption_mgr = EncryptionManager.get_default() + # First check that we can read it + try: + journalist_key = encryption_mgr.get_journalist_public_key() + except Exception as e: + print(f"ERROR: Unable to read journalist public key: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Unable to read journalist public key: {e}") + sys.exit(1) + # And then what we read is valid + try: + redwood.is_valid_public_key(journalist_key) + except redwood.RedwoodError as e: + print(f"ERROR: Journalist public key is not valid: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Journalist public key is not valid: {e}") + sys.exit(1) if __name__ == "__main__": # pragma: no cover + validate_journalist_key() + prime_keycache() debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host app.run(debug=debug, host="0.0.0.0", port=8081)
diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -17,6 +17,7 @@ from flaky import flaky from flask import escape, g, url_for from flask_babel import gettext, ngettext +from journalist import validate_journalist_key from journalist_app.sessions import session from journalist_app.utils import mark_seen from models import ( @@ -51,6 +52,8 @@ from tests.utils.instrument import InstrumentedApp from two_factor import TOTP +from redwood import RedwoodError + from .utils import create_legacy_gpg_key, login_journalist # Smugly seed the RNG for deterministic testing @@ -3772,3 +3775,20 @@ def test_journalist_deletion(journalist_app, app_storage): assert len(SeenReply.query.filter_by(journalist_id=deleted.id).all()) == 2 # And there are no login attempts assert JournalistLoginAttempt.query.all() == [] + + +def test_validate_journalist_key(config, capsys): + # The test key passes validation + validate_journalist_key() + # Reading the key file fails + with patch( + "encryption.EncryptionManager.get_journalist_public_key", side_effect=RuntimeError("err") + ): + with pytest.raises(SystemExit): + validate_journalist_key() + assert capsys.readouterr().err == "ERROR: Unable to read journalist public key: err\n" + # Key fails validation + with patch("redwood.is_valid_public_key", side_effect=RedwoodError("err")): + with pytest.raises(SystemExit): + validate_journalist_key() + assert capsys.readouterr().err == "ERROR: Journalist public key is not valid: err\n"
determine post-upgrade failure-mode for a SHA-1-signed submission key ## Description After #6948 (for #6399), redwood will refuse to encrypt to a submission key with a SHA-1 signature. After #6928, `securedrop-admin sdconfig` will reject a submission key with a SHA-1 signature. This check guarantees that new and reconfigured instances will comply with #6948. What will happen to an instance with a SHA-1-signed signature after upgrading to v2.7.0? ## Possible approaches | Option | Documentation changes | Code changes | Implication | | --- | --- | --- | --- | | Fail open, but log | optional | ✓ | Admin must monitor logs and/or OSSEC alerts. | | Fail open, but document | ✓ | ✗ | Admin must monitor release notes or check documentation. | | Fail closed | optional | ✓[1] | Admin can contact us for help. | **Notes:** 1. @legoktm observes that, without a code change to handle this case, Apache will come back up after reboot even if the `postinst` script fails under `unattended-upgrades`.
For context, we expect this to be a pretty rare issue given that if people followed our documentation, they should not have generated a SHA-1 submission key. The submission key is currently stored in the GPG keyring, so we export it to disk for Sequoia to read (and for SecureDrop to serve) in the postinst: ```bash export_journalist_public_key() { # config.py is root-writable, so it's safe to run it as root to extract the fingerprint journalist_pub="/var/lib/securedrop/journalist.pub" # If the journalist.pub file doesn't exist if ! test -f $journalist_pub; then # And we have a config.py (during initial install it won't exist yet) if test -f /var/www/securedrop/config.py; then # n.b. based on sdconfig.py, this should work with very old config.py files. fingerprint=$(cd /var/www/securedrop; python3 -c "import config; print(config.JOURNALIST_KEY)") # Set up journalist.pub as root/www-data 640 before writing to it. touch $journalist_pub chown root:www-data $journalist_pub chmod 640 $journalist_pub # Export the GPG public key # shellcheck disable=SC2024 sudo -u www-data gpg2 --homedir=/var/lib/securedrop/keys --export --armor "$fingerprint" > $journalist_pub # Verify integrity of what we just exported sudo -u www-data /var/www/securedrop/scripts/validate-pgp-key "$journalist_pub" "$fingerprint" fi fi } ``` The final step is to validate the exported key file passes `validate-pgp-key`, which is a wrapper for `redwood.is_valid_public_key()`. However, if validation fails for whatever reason (e.g. GPG export fails, it's a SHA-1 key, etc.), then we abort, which interrupts the postinst, so, e.g. database upgrades won't be applied. apache will be down, though it should be restarted when the nightly instance reboot happens. With that in mind, I think having the validation fail at package install time is bad, because it requires even more manual work to get an instance in a working state since you need to manually apply the updates after doing a key rotation. One of the proposals in standup from @zenmonkeykstop was to just have the JI exit if the submission key isn't valid, which will alert journalists and then their admin that something is wrong. I think this is reasonable and probably a better UX, and will let us remove the validate step in the postinst IMO. Works for me (:)) - if we can just use is_valid_public_key() in app initialization then that sounds simple enough. Yeah, from trying this on my staging instance I was momentarily confused by the postinst validation/failure, and as you mentioned it has a bunch of unintended side-effects. I think it's better to have it fail in the JI. In this case we don't have to worry about feature parity with SDW.
2023-10-27T17:48:37Z
[]
[]
freedomofpress/securedrop
7,059
freedomofpress__securedrop-7059
[ "7058" ]
6267aec4e197e207aa8f1a9778ee04f22a3d0918
diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -5,8 +5,7 @@ from journalist_app import create_app from models import Source from sdconfig import SecureDropConfig - -import redwood +from startup import validate_journalist_key config = SecureDropConfig.get_current() # app is imported by journalist.wsgi @@ -25,28 +24,14 @@ def prime_keycache() -> None: pass -def validate_journalist_key() -> None: - """Verify the journalist PGP key is valid""" - encryption_mgr = EncryptionManager.get_default() - # First check that we can read it - try: - journalist_key = encryption_mgr.get_journalist_public_key() - except Exception as e: - print(f"ERROR: Unable to read journalist public key: {e}", file=sys.stderr) - app.logger.error(f"ERROR: Unable to read journalist public key: {e}") - sys.exit(1) - # And then what we read is valid - try: - redwood.is_valid_public_key(journalist_key) - except redwood.RedwoodError as e: - print(f"ERROR: Journalist public key is not valid: {e}", file=sys.stderr) - app.logger.error(f"ERROR: Journalist public key is not valid: {e}") - sys.exit(1) +# This code cannot be nested under if name == main because +# it needs to run when journalist.wsgi imports this file. +if not validate_journalist_key(app): + sys.exit(1) +prime_keycache() if __name__ == "__main__": # pragma: no cover - validate_journalist_key() - prime_keycache() debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host app.run(debug=debug, host="0.0.0.0", port=8081) diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -8,7 +8,7 @@ import version import werkzeug from db import db -from flask import Flask, g, redirect, render_template, request, session, url_for +from flask import Flask, g, make_response, redirect, render_template, request, session, url_for from flask_babel import gettext from flask_wtf.csrf import CSRFError, CSRFProtect from models import InstanceConfig @@ -17,6 +17,7 @@ from source_app import api, info, main from source_app.decorators import ignore_static from source_app.utils import clear_session_and_redirect_to_logged_out_page +from startup import validate_journalist_key def get_logo_url(app: Flask) -> str: @@ -61,6 +62,9 @@ def setup_i18n() -> None: app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI db.init_app(app) + # Check if the Submission Key is valid; if not, we'll disable the UI + app.config["SUBMISSION_KEY_VALID"] = validate_journalist_key() + @app.errorhandler(CSRFError) def handle_csrf_error(e: CSRFError) -> werkzeug.Response: return clear_session_and_redirect_to_logged_out_page(flask_session=session) @@ -106,6 +110,15 @@ def check_tor2web() -> Optional[werkzeug.Response]: return redirect(url_for("info.tor2web_warning")) return None + @app.before_request + @ignore_static + def check_submission_key() -> Optional[werkzeug.Response]: + if not app.config["SUBMISSION_KEY_VALID"]: + session.clear() + g.show_offline_message = True + return make_response(render_template("offline.html"), 503) + return None + @app.errorhandler(404) def page_not_found(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: return render_template("notfound.html"), 404 diff --git a/securedrop/startup.py b/securedrop/startup.py new file mode 100644 --- /dev/null +++ b/securedrop/startup.py @@ -0,0 +1,30 @@ +import sys +from typing import Optional + +from encryption import EncryptionManager +from flask import Flask + +import redwood + + +def validate_journalist_key(app: Optional[Flask] = None) -> bool: + """Verify the journalist PGP key is valid""" + encryption_mgr = EncryptionManager.get_default() + # First check that we can read it + try: + journalist_key = encryption_mgr.get_journalist_public_key() + except Exception as e: + if app: + print(f"ERROR: Unable to read journalist public key: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Unable to read journalist public key: {e}") + return False + # And then what we read is valid + try: + redwood.is_valid_public_key(journalist_key) + except redwood.RedwoodError as e: + if app: + print(f"ERROR: Journalist public key is not valid: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Journalist public key is not valid: {e}") + return False + + return True
diff --git a/molecule/testinfra/app/test_smoke.py b/molecule/testinfra/app/test_smoke.py --- a/molecule/testinfra/app/test_smoke.py +++ b/molecule/testinfra/app/test_smoke.py @@ -2,6 +2,7 @@ Basic smoke tests that verify the apps are functioning as expected """ import json +from pathlib import Path import pytest import testutils @@ -10,6 +11,12 @@ testinfra_hosts = [sdvars.app_hostname] +JOURNALIST_PUB = "/var/lib/securedrop/journalist.pub" +WEAK_KEY_CONTENTS = ( + Path(__file__).parent.parent.parent.parent / "redwood/res/weak_sample_key.asc" +).read_text() + + @pytest.mark.parametrize( ("name", "url", "curl_flags", "expected"), [ @@ -50,3 +57,39 @@ def test_redwood(host): assert "-----BEGIN PGP PUBLIC KEY BLOCK-----" in parsed[0] assert "-----BEGIN PGP PRIVATE KEY BLOCK-----" in parsed[1] assert len(parsed[2]) == 40 + + [email protected]_in_prod() +def test_weak_submission_key(host): + """ + If the Submission Key is weak (e.g. has a SHA-1 signature), + the JI should be down (500) and SI will return a 503. + """ + with host.sudo(): + old_public_key = host.file(JOURNALIST_PUB).content_string + try: + # Install a weak key + set_public_key(host, WEAK_KEY_CONTENTS) + assert host.run("systemctl restart apache2").rc == 0 + # Now try to hit the JI + response = host.run("curl -Li http://localhost:8080/").stdout + assert "HTTP/1.1 500 Internal Server Error" in response + # Now hit the SI + response = host.run("curl -i http://localhost:80/").stdout + assert "HTTP/1.1 503 SERVICE UNAVAILABLE" in response # Flask shouts + assert "We're sorry, our SecureDrop is currently offline." in response + + finally: + set_public_key(host, old_public_key) + assert host.run("systemctl restart apache2").rc == 0 + + +def set_public_key(host, pubkey: str) -> None: + """apparently testinfra doesn't provide a function to write a file?""" + res = host.run( + f"/usr/bin/python3 -c " + f'\'import pathlib; pathlib.Path("{JOURNALIST_PUB}")' + f'.write_text("""{pubkey}""".strip())\'' + ) + print(res.stderr) + assert res.rc == 0 diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -17,7 +17,6 @@ from flaky import flaky from flask import escape, g, url_for from flask_babel import gettext, ngettext -from journalist import validate_journalist_key from journalist_app.sessions import session from journalist_app.utils import mark_seen from models import ( @@ -52,8 +51,6 @@ from tests.utils.instrument import InstrumentedApp from two_factor import TOTP -from redwood import RedwoodError - from .utils import create_legacy_gpg_key, login_journalist # Smugly seed the RNG for deterministic testing @@ -3775,20 +3772,3 @@ def test_journalist_deletion(journalist_app, app_storage): assert len(SeenReply.query.filter_by(journalist_id=deleted.id).all()) == 2 # And there are no login attempts assert JournalistLoginAttempt.query.all() == [] - - -def test_validate_journalist_key(config, capsys): - # The test key passes validation - validate_journalist_key() - # Reading the key file fails - with patch( - "encryption.EncryptionManager.get_journalist_public_key", side_effect=RuntimeError("err") - ): - with pytest.raises(SystemExit): - validate_journalist_key() - assert capsys.readouterr().err == "ERROR: Unable to read journalist public key: err\n" - # Key fails validation - with patch("redwood.is_valid_public_key", side_effect=RedwoodError("err")): - with pytest.raises(SystemExit): - validate_journalist_key() - assert capsys.readouterr().err == "ERROR: Journalist public key is not valid: err\n" diff --git a/securedrop/tests/test_startup.py b/securedrop/tests/test_startup.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_startup.py @@ -0,0 +1,20 @@ +from unittest.mock import patch + +from startup import validate_journalist_key + +from redwood import RedwoodError + + +def test_validate_journalist_key(config, journalist_app, capsys): + # The test key passes validation + assert validate_journalist_key(journalist_app) is True + # Reading the key file fails + with patch( + "encryption.EncryptionManager.get_journalist_public_key", side_effect=RuntimeError("err") + ): + assert validate_journalist_key(journalist_app) is False + assert capsys.readouterr().err == "ERROR: Unable to read journalist public key: err\n" + # Key fails validation + with patch("redwood.is_valid_public_key", side_effect=RedwoodError("err")): + assert validate_journalist_key(journalist_app) is False + assert capsys.readouterr().err == "ERROR: Journalist public key is not valid: err\n" diff --git a/securedrop/tests/test_wsgi.py b/securedrop/tests/test_wsgi.py --- a/securedrop/tests/test_wsgi.py +++ b/securedrop/tests/test_wsgi.py @@ -1,4 +1,5 @@ import os +import shutil import subprocess import sys from pathlib import Path @@ -6,8 +7,27 @@ import pytest [email protected]() +def _journalist_pubkey(): + """provision a valid public key for the JI startup check""" + path = Path("/tmp/securedrop/journalist.pub") + if not path.exists(): + created_dir = False + try: + if not path.parent.exists(): + path.parent.mkdir() + created_dir = True + shutil.copy(Path(__file__).parent / "files/test_journalist_key.pub", path) + yield + finally: + if created_dir: + shutil.rmtree(path.parent) + else: + path.unlink() + + @pytest.mark.parametrize("filename", ["journalist.wsgi", "source.wsgi"]) -def test_wsgi(filename): +def test_wsgi(filename, _journalist_pubkey): """ Verify that all setup code and imports in the wsgi files work @@ -18,5 +38,6 @@ def test_wsgi(filename): wsgi = sd_dir / "debian/app-code/var/www" / filename python_path = os.getenv("PYTHONPATH", "") subprocess.check_call( - [sys.executable, str(wsgi)], env={"PYTHONPATH": f"{python_path}:{sd_dir}"} + [sys.executable, str(wsgi)], + env={"PYTHONPATH": f"{python_path}:{sd_dir}", "SECUREDROP_ENV": "test"}, )
[2.7.0] JI does not fail loudly when configured with a SHA-1 key ## Description Weak GPG keys are no longer supported (https://sequoia-pgp.org/blog/2023/02/01/202302-happy-sha1-day/). The JI should fail to start when configured with one (via a potential upgrade from a SecureDrop version that did support them and that was configured with a weak key), emitting an error in its logs as it does so. Instead, it's starting successfully and then failing on all encryption operations. ## Steps to Reproduce - install 2.6.0 with a weak (RSA 1024-bit) key - upgrade to 2.7.0 - visit the JI and attempt to submit a reply ## Expected Behavior - JI is unavailable, `journalist-error.log` records message about weak journalist key ## Actual Behavior - JI is available - replies fail with a 500 error - SI is available (this is actually expected) and submissions fail with a 500 error (this is suboptimal) Please provide screenshots where appropriate. ## Comments Suggestions to fix, any other relevant information.
2023-11-02T17:10:06Z
[]
[]
freedomofpress/securedrop
7,063
freedomofpress__securedrop-7063
[ "7058" ]
139c213d4a4bf912d33440a8fc43c6b73498524c
diff --git a/securedrop/journalist.py b/securedrop/journalist.py --- a/securedrop/journalist.py +++ b/securedrop/journalist.py @@ -5,8 +5,7 @@ from journalist_app import create_app from models import Source from sdconfig import SecureDropConfig - -import redwood +from startup import validate_journalist_key config = SecureDropConfig.get_current() # app is imported by journalist.wsgi @@ -25,28 +24,14 @@ def prime_keycache() -> None: pass -def validate_journalist_key() -> None: - """Verify the journalist PGP key is valid""" - encryption_mgr = EncryptionManager.get_default() - # First check that we can read it - try: - journalist_key = encryption_mgr.get_journalist_public_key() - except Exception as e: - print(f"ERROR: Unable to read journalist public key: {e}", file=sys.stderr) - app.logger.error(f"ERROR: Unable to read journalist public key: {e}") - sys.exit(1) - # And then what we read is valid - try: - redwood.is_valid_public_key(journalist_key) - except redwood.RedwoodError as e: - print(f"ERROR: Journalist public key is not valid: {e}", file=sys.stderr) - app.logger.error(f"ERROR: Journalist public key is not valid: {e}") - sys.exit(1) +# This code cannot be nested under if name == main because +# it needs to run when journalist.wsgi imports this file. +if not validate_journalist_key(app): + sys.exit(1) +prime_keycache() if __name__ == "__main__": # pragma: no cover - validate_journalist_key() - prime_keycache() debug = getattr(config, "env", "prod") != "prod" # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host app.run(debug=debug, host="0.0.0.0", port=8081) diff --git a/securedrop/source_app/__init__.py b/securedrop/source_app/__init__.py --- a/securedrop/source_app/__init__.py +++ b/securedrop/source_app/__init__.py @@ -8,7 +8,7 @@ import version import werkzeug from db import db -from flask import Flask, g, redirect, render_template, request, session, url_for +from flask import Flask, g, make_response, redirect, render_template, request, session, url_for from flask_babel import gettext from flask_wtf.csrf import CSRFError, CSRFProtect from models import InstanceConfig @@ -17,6 +17,7 @@ from source_app import api, info, main from source_app.decorators import ignore_static from source_app.utils import clear_session_and_redirect_to_logged_out_page +from startup import validate_journalist_key def get_logo_url(app: Flask) -> str: @@ -61,6 +62,9 @@ def setup_i18n() -> None: app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI db.init_app(app) + # Check if the Submission Key is valid; if not, we'll disable the UI + app.config["SUBMISSION_KEY_VALID"] = validate_journalist_key() + @app.errorhandler(CSRFError) def handle_csrf_error(e: CSRFError) -> werkzeug.Response: return clear_session_and_redirect_to_logged_out_page(flask_session=session) @@ -106,6 +110,15 @@ def check_tor2web() -> Optional[werkzeug.Response]: return redirect(url_for("info.tor2web_warning")) return None + @app.before_request + @ignore_static + def check_submission_key() -> Optional[werkzeug.Response]: + if not app.config["SUBMISSION_KEY_VALID"]: + session.clear() + g.show_offline_message = True + return make_response(render_template("offline.html"), 503) + return None + @app.errorhandler(404) def page_not_found(error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: return render_template("notfound.html"), 404 diff --git a/securedrop/startup.py b/securedrop/startup.py new file mode 100644 --- /dev/null +++ b/securedrop/startup.py @@ -0,0 +1,30 @@ +import sys +from typing import Optional + +from encryption import EncryptionManager +from flask import Flask + +import redwood + + +def validate_journalist_key(app: Optional[Flask] = None) -> bool: + """Verify the journalist PGP key is valid""" + encryption_mgr = EncryptionManager.get_default() + # First check that we can read it + try: + journalist_key = encryption_mgr.get_journalist_public_key() + except Exception as e: + if app: + print(f"ERROR: Unable to read journalist public key: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Unable to read journalist public key: {e}") + return False + # And then what we read is valid + try: + redwood.is_valid_public_key(journalist_key) + except redwood.RedwoodError as e: + if app: + print(f"ERROR: Journalist public key is not valid: {e}", file=sys.stderr) + app.logger.error(f"ERROR: Journalist public key is not valid: {e}") + return False + + return True
diff --git a/molecule/testinfra/app/test_smoke.py b/molecule/testinfra/app/test_smoke.py --- a/molecule/testinfra/app/test_smoke.py +++ b/molecule/testinfra/app/test_smoke.py @@ -2,6 +2,7 @@ Basic smoke tests that verify the apps are functioning as expected """ import json +from pathlib import Path import pytest import testutils @@ -10,6 +11,12 @@ testinfra_hosts = [sdvars.app_hostname] +JOURNALIST_PUB = "/var/lib/securedrop/journalist.pub" +WEAK_KEY_CONTENTS = ( + Path(__file__).parent.parent.parent.parent / "redwood/res/weak_sample_key.asc" +).read_text() + + @pytest.mark.parametrize( ("name", "url", "curl_flags", "expected"), [ @@ -50,3 +57,39 @@ def test_redwood(host): assert "-----BEGIN PGP PUBLIC KEY BLOCK-----" in parsed[0] assert "-----BEGIN PGP PRIVATE KEY BLOCK-----" in parsed[1] assert len(parsed[2]) == 40 + + [email protected]_in_prod() +def test_weak_submission_key(host): + """ + If the Submission Key is weak (e.g. has a SHA-1 signature), + the JI should be down (500) and SI will return a 503. + """ + with host.sudo(): + old_public_key = host.file(JOURNALIST_PUB).content_string + try: + # Install a weak key + set_public_key(host, WEAK_KEY_CONTENTS) + assert host.run("systemctl restart apache2").rc == 0 + # Now try to hit the JI + response = host.run("curl -Li http://localhost:8080/").stdout + assert "HTTP/1.1 500 Internal Server Error" in response + # Now hit the SI + response = host.run("curl -i http://localhost:80/").stdout + assert "HTTP/1.1 503 SERVICE UNAVAILABLE" in response # Flask shouts + assert "We're sorry, our SecureDrop is currently offline." in response + + finally: + set_public_key(host, old_public_key) + assert host.run("systemctl restart apache2").rc == 0 + + +def set_public_key(host, pubkey: str) -> None: + """apparently testinfra doesn't provide a function to write a file?""" + res = host.run( + f"/usr/bin/python3 -c " + f'\'import pathlib; pathlib.Path("{JOURNALIST_PUB}")' + f'.write_text("""{pubkey}""".strip())\'' + ) + print(res.stderr) + assert res.rc == 0 diff --git a/securedrop/tests/test_journalist.py b/securedrop/tests/test_journalist.py --- a/securedrop/tests/test_journalist.py +++ b/securedrop/tests/test_journalist.py @@ -17,7 +17,6 @@ from flaky import flaky from flask import escape, g, url_for from flask_babel import gettext, ngettext -from journalist import validate_journalist_key from journalist_app.sessions import session from journalist_app.utils import mark_seen from models import ( @@ -52,8 +51,6 @@ from tests.utils.instrument import InstrumentedApp from two_factor import TOTP -from redwood import RedwoodError - from .utils import create_legacy_gpg_key, login_journalist # Smugly seed the RNG for deterministic testing @@ -3775,20 +3772,3 @@ def test_journalist_deletion(journalist_app, app_storage): assert len(SeenReply.query.filter_by(journalist_id=deleted.id).all()) == 2 # And there are no login attempts assert JournalistLoginAttempt.query.all() == [] - - -def test_validate_journalist_key(config, capsys): - # The test key passes validation - validate_journalist_key() - # Reading the key file fails - with patch( - "encryption.EncryptionManager.get_journalist_public_key", side_effect=RuntimeError("err") - ): - with pytest.raises(SystemExit): - validate_journalist_key() - assert capsys.readouterr().err == "ERROR: Unable to read journalist public key: err\n" - # Key fails validation - with patch("redwood.is_valid_public_key", side_effect=RedwoodError("err")): - with pytest.raises(SystemExit): - validate_journalist_key() - assert capsys.readouterr().err == "ERROR: Journalist public key is not valid: err\n" diff --git a/securedrop/tests/test_startup.py b/securedrop/tests/test_startup.py new file mode 100644 --- /dev/null +++ b/securedrop/tests/test_startup.py @@ -0,0 +1,20 @@ +from unittest.mock import patch + +from startup import validate_journalist_key + +from redwood import RedwoodError + + +def test_validate_journalist_key(config, journalist_app, capsys): + # The test key passes validation + assert validate_journalist_key(journalist_app) is True + # Reading the key file fails + with patch( + "encryption.EncryptionManager.get_journalist_public_key", side_effect=RuntimeError("err") + ): + assert validate_journalist_key(journalist_app) is False + assert capsys.readouterr().err == "ERROR: Unable to read journalist public key: err\n" + # Key fails validation + with patch("redwood.is_valid_public_key", side_effect=RedwoodError("err")): + assert validate_journalist_key(journalist_app) is False + assert capsys.readouterr().err == "ERROR: Journalist public key is not valid: err\n" diff --git a/securedrop/tests/test_wsgi.py b/securedrop/tests/test_wsgi.py --- a/securedrop/tests/test_wsgi.py +++ b/securedrop/tests/test_wsgi.py @@ -1,4 +1,5 @@ import os +import shutil import subprocess import sys from pathlib import Path @@ -6,8 +7,27 @@ import pytest [email protected]() +def _journalist_pubkey(): + """provision a valid public key for the JI startup check""" + path = Path("/tmp/securedrop/journalist.pub") + if not path.exists(): + created_dir = False + try: + if not path.parent.exists(): + path.parent.mkdir() + created_dir = True + shutil.copy(Path(__file__).parent / "files/test_journalist_key.pub", path) + yield + finally: + if created_dir: + shutil.rmtree(path.parent) + else: + path.unlink() + + @pytest.mark.parametrize("filename", ["journalist.wsgi", "source.wsgi"]) -def test_wsgi(filename): +def test_wsgi(filename, _journalist_pubkey): """ Verify that all setup code and imports in the wsgi files work @@ -18,5 +38,6 @@ def test_wsgi(filename): wsgi = sd_dir / "debian/app-code/var/www" / filename python_path = os.getenv("PYTHONPATH", "") subprocess.check_call( - [sys.executable, str(wsgi)], env={"PYTHONPATH": f"{python_path}:{sd_dir}"} + [sys.executable, str(wsgi)], + env={"PYTHONPATH": f"{python_path}:{sd_dir}", "SECUREDROP_ENV": "test"}, )
[2.7.0] JI does not fail loudly when configured with a SHA-1 key ## Description Weak GPG keys are no longer supported (https://sequoia-pgp.org/blog/2023/02/01/202302-happy-sha1-day/). The JI should fail to start when configured with one (via a potential upgrade from a SecureDrop version that did support them and that was configured with a weak key), emitting an error in its logs as it does so. Instead, it's starting successfully and then failing on all encryption operations. ## Steps to Reproduce - install 2.6.0 with a weak (RSA 1024-bit) key - upgrade to 2.7.0 - visit the JI and attempt to submit a reply ## Expected Behavior - JI is unavailable, `journalist-error.log` records message about weak journalist key ## Actual Behavior - JI is available - replies fail with a 500 error - SI is available (this is actually expected) and submissions fail with a 500 error (this is suboptimal) Please provide screenshots where appropriate. ## Comments Suggestions to fix, any other relevant information.
2023-11-02T20:53:49Z
[]
[]