diff --git a/legal-api/flags.json b/legal-api/flags.json index c3ccc9a4ac..f07db3a6c2 100644 --- a/legal-api/flags.json +++ b/legal-api/flags.json @@ -18,7 +18,15 @@ "authV2Tasks", "authV2ArReminder", "authV2Comments", - "authV2FilingComments" + "authV2FilingComments", + "authV2AccountId", + "authV2FilingDocuments", + "authV2ClientDocuments", + "authV2NameRequests", + "authV2BusinessCreate", + "authV2Settings", + "authV2DigitalCredentials", + "authV2UserRoles" ], "enable-staff-draft-filing-bypass": [ "agmLocationChange", diff --git a/legal-api/src/legal_api/resources/v2/business/business.py b/legal-api/src/legal_api/resources/v2/business/business.py index aeece05236..111b0d2a2c 100644 --- a/legal-api/src/legal_api/resources/v2/business/business.py +++ b/legal-api/src/legal_api/resources/v2/business/business.py @@ -47,6 +47,9 @@ get_allowed, get_could_files, has_any_roles, + is_account_member, + is_new_feature_enabled, + log_unauthorized_request, ) from legal_api.services.permissions import ListActionsPermissionsAllowed, PermissionService from legal_api.services.search_service import AffiliationSearchDetails, BusinessSearchService @@ -109,7 +112,7 @@ def get_businesses(identifier: str): q_account = request.args.get("account") current_app.logger.info("account info request, for account: %s", q_account) - if q_account and jwt.has_one_of_roles([SYSTEM_ROLE, ACCOUNT_IDENTITY]): + if q_account and has_any_roles(jwt, [SYSTEM_ROLE, ACCOUNT_IDENTITY]): account_response = AccountService.get_account_by_affiliated_identifier(identifier, flags) current_app.logger.info("VALID account request, for accountId: %s, by: %s, jwt: %s, for org account: %s", q_account, @@ -199,6 +202,12 @@ def post_businesses(): else: filing_title = Filing.FILINGS[filing_type]["title"] + is_create_gate_on = is_new_feature_enabled("authV2BusinessCreate") + if is_create_gate_on and not is_account_member(jwt, filing_account_id): + log_unauthorized_request("business create", filing_account_id) + return {"message": babel("You are not authorized to create a business for this account.")}, \ + HTTPStatus.FORBIDDEN + bootstrap = RegistrationBootstrapService.create_bootstrap(filing_account_id) if not isinstance(bootstrap, RegistrationBootstrap): return {"error": babel(f"Unable to create {filing_title} Filing.")}, \ diff --git a/legal-api/src/legal_api/resources/v2/business/business_account_settings.py b/legal-api/src/legal_api/resources/v2/business/business_account_settings.py index 66cae68b39..97057e22b7 100644 --- a/legal-api/src/legal_api/resources/v2/business/business_account_settings.py +++ b/legal-api/src/legal_api/resources/v2/business/business_account_settings.py @@ -33,21 +33,30 @@ from flask_cors import cross_origin from business_model.models import Business, BusinessAccountSettings -from legal_api.services.authz import authorized, get_account_products +from legal_api.services.authz import account_membership_denied, authorized, get_account_products from legal_api.utils.auth import jwt from .bp import bp +SETTINGS_FEATURE = "authV2Settings" # a value inside the enable-new-feature flag + + +def _account_forbidden_response(): + """Return the 403 for a caller who does not belong to the account in the path.""" + return jsonify({"message": "Not authorized to access business settings for this account."}), HTTPStatus.FORBIDDEN + @bp.route("/settings/", methods=["GET"]) @bp.route("/settings//", methods=["GET"]) @cross_origin() @jwt.requires_auth -def get_business_account_settings(account_id: str, identifier: str | None = None): +def get_business_account_settings(account_id: str, identifier: str | None = None): # noqa: PLR0911 """Return a JSON object containing the settings information for the business and account combination.""" if identifier: if not authorized(identifier, jwt, action=["view"]): return jsonify({"message": f"You are not authorized to view business {identifier} settings."}), HTTPStatus.UNAUTHORIZED + if account_membership_denied(SETTINGS_FEATURE, "settings", account_id, jwt): + return _account_forbidden_response() business = Business.find_by_identifier(identifier) if not business: @@ -77,9 +86,10 @@ def get_business_account_settings(account_id: str, identifier: str | None = None @jwt.requires_auth def update_business_account_settings(account_id: str, identifier: str): """Update the settings information for the business and account combination.""" - # FUTURE: Verify they are allowed to update the account - #30992 if not authorized(identifier, jwt, action=["edit"]): return jsonify({"message": f"You are not authorized to edit business {identifier} settings."}), HTTPStatus.UNAUTHORIZED + if account_membership_denied(SETTINGS_FEATURE, "settings", account_id, jwt): + return _account_forbidden_response() business = Business.find_by_identifier(identifier) if not business: @@ -95,9 +105,10 @@ def update_business_account_settings(account_id: str, identifier: str): @jwt.requires_auth def delete_business_account_settings(account_id: str, identifier: str): """Update the settings information for the business and account combination.""" - # FUTURE: Verify they are allowed to update the account - #30992 if not authorized(identifier, jwt, action=["edit"]): return jsonify({"message": f"You are not authorized to remove business {identifier} settings."}), HTTPStatus.UNAUTHORIZED + if account_membership_denied(SETTINGS_FEATURE, "settings", account_id, jwt): + return _account_forbidden_response() business = Business.find_by_identifier(identifier) if not business: diff --git a/legal-api/src/legal_api/resources/v2/business/business_digital_credentials.py b/legal-api/src/legal_api/resources/v2/business/business_digital_credentials.py index 6dce4e9801..0a8167cf68 100644 --- a/legal-api/src/legal_api/resources/v2/business/business_digital_credentials.py +++ b/legal-api/src/legal_api/resources/v2/business/business_digital_credentials.py @@ -37,6 +37,7 @@ ) from legal_api.decorators import can_access_digital_credentials from legal_api.services import digital_credentials +from legal_api.services.authz import is_new_feature_enabled, log_unauthorized_request from legal_api.utils.auth import jwt from .bp import bp @@ -61,6 +62,25 @@ def get_business_user(identifier) -> tuple[DCBusinessUser | None, dict | None, H return business_user, None, None +def _is_owner_denied(identifier: str, record: DCConnection | DCCredential) -> bool: + """Return True (and log) when the authV2DigitalCredentials gate is on and the record is not the caller's.""" + if not is_new_feature_enabled("authV2DigitalCredentials"): + return False + business_user, _, _ = get_business_user(identifier) + # older credentials have no business user of their own, so fall back to their connection's + owner_id = record.business_user_id or getattr(getattr(record, "connection", None), "business_user_id", None) + if business_user and owner_id == business_user.id: + return False + log_unauthorized_request("digital credentials", identifier) + return True + + +def _not_owner_response(identifier: str): + """Return the 403 for a connection or credential that belongs to another user or business.""" + return jsonify({"message": f"You are not authorized to change this record for {identifier}."}), \ + HTTPStatus.FORBIDDEN + + @bp.route("//digitalCredentials/invitation", methods=["POST"], strict_slashes=False) @cross_origin() @jwt.requires_auth @@ -141,6 +161,9 @@ def attest_connection(identifier, connection_id): if not (connection := DCConnection.find_by_connection_id(connection_id=connection_id)): return jsonify({"message": f"{identifier} connection not found."}), HTTPStatus.NOT_FOUND + if _is_owner_denied(identifier, connection): + return _not_owner_response(identifier) + if digital_credentials.attest_connection(connection_id=connection.connection_id) is None: return jsonify({"message": "Unable to request connection attestation."}), HTTPStatus.INTERNAL_SERVER_ERROR @@ -160,6 +183,9 @@ def delete_connection(identifier, connection_id): if not (connection := DCConnection.find_by_connection_id(connection_id=connection_id)): return jsonify({"message": f"{identifier} connection not found."}), HTTPStatus.NOT_FOUND + if _is_owner_denied(identifier, connection): + return _not_owner_response(identifier) + if (connection.connection_state != DCConnection.State.INVITATION_SENT.value and digital_credentials.remove_connection_record(connection_id=connection.connection_id) is None): return jsonify({"message": "Failed to remove connection record."}), HTTPStatus.INTERNAL_SERVER_ERROR @@ -299,6 +325,9 @@ def revoke_credential(identifier, credential_id): if not credential or credential.is_revoked: return jsonify({"message": f"{identifier} issued credential not found."}), HTTPStatus.NOT_FOUND + if _is_owner_denied(identifier, credential): + return _not_owner_response(identifier) + reissue = request.get_json().get("reissue", False) reason = DCRevocationReason.SELF_REISSUANCE if reissue else DCRevocationReason.SELF_REVOCATION @@ -326,6 +355,9 @@ def delete_credential(identifier, credential_id): if not (credential := DCCredential.find_by_credential_id(credential_id=credential_id)): return jsonify({"message": f"{identifier} issued credential not found."}), HTTPStatus.NOT_FOUND + if _is_owner_denied(identifier, credential): + return _not_owner_response(identifier) + if (digital_credentials.fetch_credential_exchange_record(credential.credential_exchange_id) is not None and digital_credentials.remove_credential_exchange_record(credential.credential_exchange_id) is None): return jsonify({"message": "Failed to remove credential exchange record."}), HTTPStatus.INTERNAL_SERVER_ERROR diff --git a/legal-api/src/legal_api/resources/v2/business/business_filings/business_documents.py b/legal-api/src/legal_api/resources/v2/business/business_filings/business_documents.py index cc4d205c25..950d9221b8 100644 --- a/legal-api/src/legal_api/resources/v2/business/business_filings/business_documents.py +++ b/legal-api/src/legal_api/resources/v2/business/business_filings/business_documents.py @@ -37,6 +37,7 @@ from legal_api.resources.v2.business.bp import bp from legal_api.services import authorized from legal_api.services import doc_service as client_doc_service +from legal_api.services.authz import is_new_feature_enabled, log_unauthorized_request from legal_api.services.request_context import add_account_linking_key_header from legal_api.utils.auth import jwt from legal_api.utils.util import cors_preflight, is_temp_reg_identifier @@ -57,7 +58,7 @@ @bp.route(DOCUMENTS_BASE_ROUTE + "/static/", methods=["GET", "OPTIONS"]) @cross_origin() @jwt.requires_auth -def get_documents(identifier: str, # noqa: PLR0911, PLR0912 +def get_documents(identifier: str, filing_id: int, legal_filing_name: str | None = None, file_key: str | None = None): @@ -67,6 +68,32 @@ def get_documents(identifier: str, # noqa: PLR0911, PLR0912 return jsonify( message=get_error_message(ErrorCode.NOT_AUTHORIZED, identifier=identifier) ), HTTPStatus.UNAUTHORIZED + + business, filing, not_found = _find_business_and_filing(identifier, filing_id) + if not_found: + return not_found + + if not legal_filing_name and not file_key: + return _get_filing_document_list(identifier, business, filing) + + if APP_PDF in request.accept_mimetypes: + file_name = (legal_filing_name or file_key) + if not _is_document_available(business, filing, file_name): + return jsonify( + message=get_error_message(ErrorCode.DOCUMENT_NOT_FOUND, + file_name=file_name, filing_id=filing_id, identifier=identifier) + ), HTTPStatus.NOT_FOUND + return _get_document_pdf(identifier, business, filing, legal_filing_name, file_key) + + return {}, HTTPStatus.NOT_FOUND + + +def _find_business_and_filing(identifier: str, filing_id: int) -> tuple: + """Return the business, the filing, and the 404 response when either is missing. + + - temp registration: the business is the one its filing created, if any + - temp registration whose filing was withdrawn: the notice of withdrawal filing, when that is the one asked for + """ is_temp_reg = is_temp_reg_identifier(identifier) if is_temp_reg: filing_model = FilingModel.get_temp_reg_filing(identifier) @@ -75,65 +102,75 @@ def get_documents(identifier: str, # noqa: PLR0911, PLR0912 business = Business.find_by_identifier(identifier) if not business and not is_temp_reg: - return jsonify( + return None, None, (jsonify( message=get_error_message(ErrorCode.MISSING_BUSINESS, identifier=identifier) - ), HTTPStatus.NOT_FOUND + ), HTTPStatus.NOT_FOUND) filing = Filing.get(identifier, filing_id) if filing and is_temp_reg and filing.id != filing_id: - withdrawn_filing = Filing.get_by_withdrawn_filing_id(filing_id=filing_id, - withdrawn_filing_id=filing.id, - filing_type=Filing.FilingTypes.NOTICEOFWITHDRAWAL) - if withdrawn_filing: - filing = withdrawn_filing + filing = Filing.get_by_withdrawn_filing_id(filing_id=filing_id, + withdrawn_filing_id=filing.id, + filing_type=Filing.FilingTypes.NOTICEOFWITHDRAWAL) or filing if not filing: - return jsonify( + return None, None, (jsonify( message=get_error_message(ErrorCode.FILING_NOT_FOUND, filing_id=filing_id, identifier=identifier) - ), HTTPStatus.NOT_FOUND + ), HTTPStatus.NOT_FOUND) - if not legal_filing_name and not file_key: - if is_temp_reg and filing.status == Filing.Status.COMPLETED and \ - filing.filing_type != Filing.FilingTypes.NOTICEOFWITHDRAWAL: - return {"documents": {}}, HTTPStatus.OK - return _get_document_list(business, filing) + return business, filing, None - if APP_PDF in request.accept_mimetypes: - file_name = (legal_filing_name or file_key) - if not _is_document_available(business, filing, file_name): + +def _get_filing_document_list(identifier: str, business: Business, filing: Filing): + """Return the document list, empty for a completed temp registration filing that is not a notice of withdrawal.""" + if is_temp_reg_identifier(identifier) and filing.status == Filing.Status.COMPLETED and \ + filing.filing_type != Filing.FilingTypes.NOTICEOFWITHDRAWAL: + return {"documents": {}}, HTTPStatus.OK + return _get_document_list(business, filing) + + +def _get_document_pdf(identifier: str, # noqa: PLR0911 + business: Business, + filing: Filing, + legal_filing_name: str | None, + file_key: str | None): + """Return one available document of the filing as a PDF.""" + if _should_regenerate(legal_filing_name): + return _get_regenerated_pdf(filing, legal_filing_name) + + if drs_params := _get_drs_params(): + if _is_drs_id_denied(business, filing, drs_params.get(PARAM_DRS_ID), identifier): return jsonify( - message=get_error_message(ErrorCode.DOCUMENT_NOT_FOUND, - file_name=file_name, filing_id=filing_id, identifier=identifier) - ), HTTPStatus.NOT_FOUND + message=get_error_message(ErrorCode.NOT_AUTHORIZED, identifier=identifier) + ), HTTPStatus.FORBIDDEN + return _get_drs_documents(drs_params) - if _should_regenerate(legal_filing_name): - if jwt.contains_role(request_ctx.current_user, [UserRoles.staff, UserRoles.system]): - return get_pdf(filing.storage, legal_filing_name, True) - else: - return jsonify( - message="Unauthorized to regenerate" - ), HTTPStatus.UNAUTHORIZED - - if drs_params := _get_drs_params(): - return _get_drs_documents(drs_params) - - if legal_filing_name: - if legal_filing_name.lower().startswith("receipt"): - return _get_receipt(business, filing) - - return get_pdf(filing.storage, legal_filing_name) - elif file_key and (match := re.match(r"^([A-Z]+)-(DS\d+)$", file_key)): - drs_response = client_doc_service.get_document(match.group(2), match.group(1), doc_binary=True) - return current_app.response_class( - response=drs_response.content, - status=drs_response.status_code, - mimetype=APP_PDF - ) + if legal_filing_name: + if legal_filing_name.lower().startswith("receipt"): + return _get_receipt(business, filing) + + return get_pdf(filing.storage, legal_filing_name) + + if file_key and (match := re.match(r"^([A-Z]+)-(DS\d+)$", file_key)): + drs_response = client_doc_service.get_document(match.group(2), match.group(1), doc_binary=True) + return current_app.response_class( + response=drs_response.content, + status=drs_response.status_code, + mimetype=APP_PDF + ) return {}, HTTPStatus.NOT_FOUND +def _get_regenerated_pdf(filing: Filing, legal_filing_name: str): + """Return the regenerated report, staff / system only.""" + if jwt.contains_role(request_ctx.current_user, [UserRoles.staff, UserRoles.system]): + return get_pdf(filing.storage, legal_filing_name, True) + return jsonify( + message="Unauthorized to regenerate" + ), HTTPStatus.UNAUTHORIZED + + def _get_drs_params() -> dict: """Extract DRS parameters from the request.""" params: dict = {} @@ -186,23 +223,38 @@ def _is_document_available(business, filing, file_name): return file_name in documents +def _get_drs_filing_documents(business: Business, filing: Filing) -> list: + """Return the DRS reports/documents stored for the filing.""" + storage: FilingModel = filing.storage + if not storage or storage.paper_only: + return [] + drs_filing_id: int = storage.id + if storage.source and storage.source == storage.Source.COLIN.value and storage.meta_data: + meta_data = storage.meta_data + if meta_data and meta_data.get("colinFilingInfo") and meta_data["colinFilingInfo"].get("eventId"): + drs_filing_id = meta_data["colinFilingInfo"].get("eventId") + identifier = business.identifier if business else storage.temp_reg + return DocumentService().get_documents_by_filing_id(identifier, drs_filing_id) + + +def _is_drs_id_denied(business: Business, filing: Filing, drs_id: str, identifier: str) -> bool: + """Return True (and log) when the authV2FilingDocuments gate is on and the drsId is not one of the filing's.""" + if not drs_id or not is_new_feature_enabled("authV2FilingDocuments"): + return False + if any(str(doc.get("identifier")) == drs_id for doc in _get_drs_filing_documents(business, filing)): + return False + log_unauthorized_request("filing documents", identifier) + return True + + def _get_document_list(business: Business, filing: Filing): """Get list of document outputs.""" document_list = Filing.get_document_list(business, filing, jwt) if not (document_list): return {}, HTTPStatus.NOT_FOUND - storage: FilingModel = filing.storage # If DRS reports/documents exist add the DRS download info to the document URLs. - if storage and not storage.paper_only: - drs_filing_id: int = storage.id - if storage.source and storage.source == storage.Source.COLIN.value and storage.meta_data: - meta_data = storage.meta_data - if meta_data and meta_data.get("colinFilingInfo") and meta_data["colinFilingInfo"].get("eventId"): - drs_filing_id = meta_data["colinFilingInfo"].get("eventId") - identifier = business.identifier if business else storage.temp_reg - doc_service: DocumentService = DocumentService() - drs_docs: list = doc_service.get_documents_by_filing_id(identifier, drs_filing_id) - document_list = doc_service.update_document_list(drs_docs, document_list, filing) + drs_docs: list = _get_drs_filing_documents(business, filing) + document_list = DocumentService().update_document_list(drs_docs, document_list, filing) return jsonify(document_list), HTTPStatus.OK diff --git a/legal-api/src/legal_api/resources/v2/business/business_filings/business_filings.py b/legal-api/src/legal_api/resources/v2/business/business_filings/business_filings.py index 0d1aa7daa4..e26e6001c3 100644 --- a/legal-api/src/legal_api/resources/v2/business/business_filings/business_filings.py +++ b/legal-api/src/legal_api/resources/v2/business/business_filings/business_filings.py @@ -69,8 +69,11 @@ namex, ) from legal_api.services.authz import ( + ROLES_AUTHORIZED_BY_ROLE, auth_v2_denied, business_blocker_check, + get_scoped_account_id, + has_any_roles, is_allowed, is_draft_rebase_checks_enabled, is_draft_rebase_scoped_filing, @@ -111,7 +114,7 @@ def get_filings(identifier: str, filing_id: int | None = None): """Return a JSON object with meta information about the Filing Submission.""" if filing_id or is_temp_reg_identifier(identifier): if str(request.args.get("public", None)).lower() == "true": - return ListFilingResource.get_single_filing_public_json(filing_id) + return ListFilingResource.get_single_filing_public_json(identifier, filing_id) if auth_v2_denied("authV2Filing", "filing", identifier, jwt, ["view"]): return jsonify({"message": @@ -361,14 +364,40 @@ def get_single_filing_by_filing_id(filing_id): return {"error": "Unable to retrieve filing data."}, HTTPStatus.INTERNAL_SERVER_ERROR +def _pay_account_header() -> dict: + """Return the Account-Id header for pay-api, so the invoice is billed to the account authorized() verified. + + - caller authorized() passes by role (staff types, system, colin): none, pay-api resolves the account + - request not scoped to an account (get_scoped_account_id): none + """ + if has_any_roles(jwt, ROLES_AUTHORIZED_BY_ROLE): + return {} + account_id = get_scoped_account_id() + return {"Account-Id": account_id} if account_id else {} + + class ListFilingResource: # pylint: disable=too-many-public-methods """Business Filings service.""" @staticmethod - def get_single_filing_public_json(filing_id: int): + def is_filing_of_identifier(identifier: str, filing: Filing) -> bool: + """Return True when the filing is reachable under the identifier. + + - temp identifier: the filing's own temp registration + - business: one of its filings, or its state filing (an amalgamating business's is the new business's) + """ + if is_temp_reg_identifier(identifier): + return filing.temp_reg == identifier + if not (business := Business.find_by_identifier(identifier)): + return False + return filing.id == business.state_filing_id or filing.business_id == business.id + + @staticmethod + def get_single_filing_public_json(identifier: str, filing_id: int): """Return public details of a filing.""" filing: Filing = Filing.find_by_id(filing_id) - if not filing or not (filing_name := filing.filing_type): + if (not filing or not (filing_name := filing.filing_type) + or not ListFilingResource.is_filing_of_identifier(identifier, filing)): return jsonify({"message": f"Filing {filing_id} not found"}), HTTPStatus.NOT_FOUND filing_json = {"header": {"name": filing_name}, filing_name: {}} @@ -1167,6 +1196,7 @@ def create_invoice(business: Business, # noqa: PLR0912, PLR0915 headers = {"Authorization": "Bearer " + token, "Content-Type": "application/json"} add_account_linking_key_header(headers) + headers.update(_pay_account_header()) current_app.logger.debug(f"Pay api call - url: {payment_svc_url}, payload: {payload}") rv = requests.post(url=payment_svc_url, json=payload, diff --git a/legal-api/src/legal_api/resources/v2/business/colin_sync.py b/legal-api/src/legal_api/resources/v2/business/colin_sync.py index 3f3b8cf4c3..de75a244af 100644 --- a/legal-api/src/legal_api/resources/v2/business/colin_sync.py +++ b/legal-api/src/legal_api/resources/v2/business/colin_sync.py @@ -471,14 +471,14 @@ def get_colin_event_id(colin_id=None): def get_last_event_id(identifier): """Get the last colin event id for the identifier.""" query = db.session.execute(text( - f""" + """ select max(colin_event_id) from colin_event_ids join filings on filings.id = colin_event_ids.filing_id join businesses on businesses.id = filings.business_id - where businesses.identifier = '{identifier}' + where businesses.identifier = :identifier limit 1 """ - )) + ), {"identifier": identifier}) last_event_id = query.scalar() if not last_event_id: return {"message": "No colin ids found"}, HTTPStatus.NOT_FOUND @@ -493,17 +493,17 @@ def update_colin_event_id(colin_id): """Add a row to the colin_last_update table.""" try: db.session.execute(text( - f""" + """ insert into colin_last_update (last_update, last_event_id) - values (current_timestamp, {colin_id}) + values (current_timestamp, :colin_id) """ - )) + ), {"colin_id": colin_id}) db.session.commit() return get_colin_event_id() except Exception as err: # pylint: disable=broad-except current_app.logger.error(f"Error updating colin_last_update table in legal db: {err}") - return {"message: failed to update colin_last_update.", 500} + return {"message": "failed to update colin_last_update."}, HTTPStatus.INTERNAL_SERVER_ERROR @bp.route("/internal/tax_ids", methods=["GET"]) diff --git a/legal-api/src/legal_api/resources/v2/business/filing_comments.py b/legal-api/src/legal_api/resources/v2/business/filing_comments.py index 5c8e8d8894..e39bfabcbe 100644 --- a/legal-api/src/legal_api/resources/v2/business/filing_comments.py +++ b/legal-api/src/legal_api/resources/v2/business/filing_comments.py @@ -32,7 +32,8 @@ from .bp import bp -@bp.route("//filings//comments/", methods=["PUT", "PATCH", "DELETE"]) +@bp.route("//filings//comments/", + methods=["POST", "PUT", "PATCH", "DELETE"]) @cross_origin() @jwt.requires_auth def not_allowed_filing_comments(identifier, filing_id, comment_id=None): # pylint: disable=W0613; matching signature @@ -73,7 +74,6 @@ def get_filing_comments(identifier, filing_id, comment_id=None): @bp.route("//filings//comments", methods=["POST"]) -@bp.route("//filings//comments/", methods=["POST"]) @cross_origin() @jwt.requires_auth def post_filing_comments(identifier, filing_id): diff --git a/legal-api/src/legal_api/resources/v2/document.py b/legal-api/src/legal_api/resources/v2/document.py index dbdd87526f..4bc484dd45 100644 --- a/legal-api/src/legal_api/resources/v2/document.py +++ b/legal-api/src/legal_api/resources/v2/document.py @@ -13,18 +13,32 @@ # limitations under the License. """Module for maintaining client documents.""" +import re from http import HTTPStatus from flask import Blueprint, current_app, jsonify, request from flask_cors import cross_origin - -from business_model.models import Document, Filing -from legal_api.services import doc_service +from sqlalchemy import or_ + +from business_model.models import Business, Document, Filing +from legal_api.services import authorized, doc_service +from legal_api.services.authz import ( + STAFF_ROLE, + SYSTEM_ROLE, + AuthServiceUnavailableError, + has_any_roles, + is_new_feature_enabled, + log_unauthorized_request, +) from legal_api.utils.auth import jwt bp = Blueprint("DOCUMENTS2", __name__, url_prefix="/api/v2/documents") +CLIENT_DOCUMENTS_FEATURE = "authV2ClientDocuments" # a value inside the enable-new-feature flag + DOCUMENT_CLASS_DEFAULT = "CORP" +# DRS class-DRS id, or a bare DRS id: anything else can reach DRS as a different id than the one checked here +DOCUMENT_KEY_PATTERN = re.compile(r"(?:[A-Z_]+-)?DS[0-9A-Z]+") DOCUMENT_TYPE_DEFAULT = "COSD" HEADER_ACCEPT = "Accept" PARAM_FILENAME = "filename" @@ -89,13 +103,76 @@ +def _find_linked_documents(document_key: str) -> list[Document]: + """Return the documents rows for the DRS document the key resolves to. + + - the DRS calls use only the id part of the key, so every spelling of a key must find the same rows + """ + drs_ids = {get_drs_id_from_key(document_key), doc_service.get_drs_id(Document(file_key=document_key))} + filters = [Document.file_key == document_key] + for drs_id in drs_ids: + filters.extend([Document.file_key == drs_id, Document.file_key.endswith(f"-{drs_id}", autoescape=True)]) + candidates = Document.query.filter(or_(*filters)).all() + return [doc for doc in candidates if doc.file_key == document_key or doc_service.get_drs_id(doc) in drs_ids] + + def is_draft_filing(file_key: str) -> bool: """Check if the filing is a draft filing.""" - document = Document.find_by_file_key(file_key) - if not document: - return True - filing = Filing.find_by_id(document.filing_id) - return filing and filing.status == Filing.Status.DRAFT.value + for document in _find_linked_documents(file_key): + filing = Filing.find_by_id(document.filing_id) + if not filing or filing.status != Filing.Status.DRAFT.value: + return False + return True + + +def _get_linked_identifier(document: Document) -> str | None: + """Return the business (or temp registration) identifier the document row belongs to.""" + if document.business_id and (business := Business.find_by_internal_id(document.business_id)): + return business.identifier + if document.filing_id and (filing := Filing.find_by_id(document.filing_id)): + if filing.business_id and (business := Business.find_by_internal_id(filing.business_id)): + return business.identifier + return filing.temp_reg + return None + + +def _is_client_document_denied(document_key: str, action: str) -> bool: + """Return True (and log) when the authV2ClientDocuments gate is on and the caller cannot access the document. + + - no documents row for the key (upload not yet linked to a filing): allowed + - row with no resolvable business: staff / system only + """ + if not is_new_feature_enabled(CLIENT_DOCUMENTS_FEATURE): + return False + for document in _find_linked_documents(document_key): + if identifier := _get_linked_identifier(document): + is_allowed = authorized(identifier, jwt, [action]) + else: + is_allowed = has_any_roles(jwt, [STAFF_ROLE, SYSTEM_ROLE]) + if not is_allowed: + log_unauthorized_request("client document", document_key) + return True + return False + + +def _is_client_document_update_denied(document_key: str) -> bool: + """Return True (and log) when the authV2ClientDocuments gate is on and the caller is not staff / system.""" + if not is_new_feature_enabled(CLIENT_DOCUMENTS_FEATURE) or has_any_roles(jwt, [STAFF_ROLE, SYSTEM_ROLE]): + return False + log_unauthorized_request("client document", document_key) + return True + + +def _invalid_key_response(document_key: str): + """Return the 400 for a document key that is not a DRS class-DRS id, or None when the key is well formed.""" + if DOCUMENT_KEY_PATTERN.fullmatch(document_key): + return None + return jsonify(message="Invalid document key."), HTTPStatus.BAD_REQUEST + + +def _forbidden_response(): + """Return the 403 for a denied client document request.""" + return jsonify(message="You are not authorized to access this document."), HTTPStatus.FORBIDDEN @@ -166,7 +243,11 @@ def delete_client_document(document_key): INTERNAL_SERVER_ERROR: default when any exception. Any response code returned from the DRS API, typically NOT_FOUND. """ + if invalid_key := _invalid_key_response(document_key): + return invalid_key try: + if _is_client_document_denied(document_key, "edit"): + return _forbidden_response() if is_draft_filing(document_key): bus_doc: Document = Document(file_key=document_key) response = doc_service.delete_document(bus_doc) @@ -178,6 +259,8 @@ def delete_client_document(document_key): message=f"Error deleting file {document_key}." ), response.status_code return jsonify({"message": "Filing is not a draft."}), HTTPStatus.FORBIDDEN + except AuthServiceUnavailableError: + raise except Exception as e: current_app.logger.error(f"Error deleting file {document_key}: {e}") return jsonify( @@ -201,7 +284,11 @@ def get_client_document(document_key): Any response code returned from the DRS API, typically NOT_FOUND. INTERNAL_SERVER_ERROR: default when any exception. """ + if invalid_key := _invalid_key_response(document_key): + return invalid_key try: + if _is_client_document_denied(document_key, "view"): + return _forbidden_response() doc_class = get_drs_class_from_key(document_key) drs_id = get_drs_id_from_key(document_key) accept = request.headers.get(HEADER_ACCEPT) @@ -220,6 +307,8 @@ def get_client_document(document_key): return jsonify( message=f"Error getting file {document_key}." ), response.status_code + except AuthServiceUnavailableError: + raise except Exception as e: current_app.logger.error(f"Error getting file {document_key}: {e}") return jsonify( @@ -242,7 +331,11 @@ def replace_client_document(document_key): INTERNAL_SERVER_ERROR: default when any exception. Any response code returned from the DRS API. """ + if invalid_key := _invalid_key_response(document_key): + return invalid_key try: + if _is_client_document_denied(document_key, "edit"): + return _forbidden_response() if is_draft_filing(document_key): bus_doc: Document = Document(file_key=document_key) response = doc_service.add_replace_document(bus_doc, request.get_data(), content_type=request.content_type) @@ -254,6 +347,8 @@ def replace_client_document(document_key): message=f"Error replacing file {document_key}." ), response.status_code return jsonify({"message": "Cannot replace when filing is not a draft."}), HTTPStatus.FORBIDDEN + except AuthServiceUnavailableError: + raise except Exception as e: current_app.logger.error(f"Error replacing file {document_key}: {e}") return jsonify( @@ -279,7 +374,11 @@ def update_client_document_info(document_key): INTERNAL_SERVER_ERROR: default when any exception. Any response code returned from the DRS API. """ + if invalid_key := _invalid_key_response(document_key): + return invalid_key try: + if _is_client_document_update_denied(document_key): + return _forbidden_response() bus_doc: Document = Document(file_key=document_key) request_json: dict = request.get_json() update_payload: dict = {} diff --git a/legal-api/src/legal_api/resources/v2/namerequest.py b/legal-api/src/legal_api/resources/v2/namerequest.py index fb3ef11240..2aa4d666f0 100644 --- a/legal-api/src/legal_api/resources/v2/namerequest.py +++ b/legal-api/src/legal_api/resources/v2/namerequest.py @@ -21,7 +21,8 @@ from flask_cors import cross_origin from business_account import AccountService -from legal_api.services import flags, namex +from legal_api.services import authorized, flags, namex +from legal_api.services.authz import AuthServiceUnavailableError, is_new_feature_enabled from legal_api.services.permissions import ListActionsPermissionsAllowed, PermissionService from legal_api.utils.auth import jwt from legal_api.utils.formatting import normalize_phone @@ -29,6 +30,18 @@ bp = Blueprint("NAMEREQUEST2", __name__, url_prefix="/api/v2/nameRequests") +def _is_affiliated(identifier: str) -> bool: + """Return True when the caller can reach the NR through an affiliation. + + - authV2NameRequests on: the caller is authorized to view the NR + - off: the NR is affiliated to any account + """ + if is_new_feature_enabled("authV2NameRequests"): + return authorized(identifier, jwt, ["view"]) + orgs_response = AccountService.get_account_by_affiliated_identifier(identifier, flags) + return bool(orgs_response and orgs_response.get("orgs")) + + @bp.route("//validate", methods=["GET"]) @cross_origin() @jwt.requires_auth @@ -51,11 +64,7 @@ def validate_with_contact_info(identifier): # noqa: PLR0911 if allowed_permission in authorized_permissions: return jsonify(nr_json) - # Check the NR is affiliated with this account - orgs_response = AccountService.get_account_by_affiliated_identifier(identifier, flags) - - # If affiliated with the account, return the NR - if len(orgs_response["orgs"]): + if _is_affiliated(identifier): return jsonify(nr_json) # The request must include email or phone number @@ -71,6 +80,8 @@ def validate_with_contact_info(identifier): # noqa: PLR0911 return make_response(jsonify(message="Invalid email or phone number."), 400) return jsonify(nr_json) + except AuthServiceUnavailableError: + raise except Exception as err: current_app.logger.error(err) return jsonify( diff --git a/legal-api/src/legal_api/services/authz.py b/legal-api/src/legal_api/services/authz.py index fc39e65813..e017d2d64e 100644 --- a/legal-api/src/legal_api/services/authz.py +++ b/legal-api/src/legal_api/services/authz.py @@ -23,6 +23,7 @@ from requests import Session, exceptions from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry +from werkzeug.exceptions import ServiceUnavailable from business_common.utils.legislation_datetime import LegislationDatetime from business_model.models import Business, Filing, UserRoles @@ -56,6 +57,14 @@ STAFF_DRAFT_FILING_BYPASS_FLAG = "enable-staff-draft-filing-bypass" DRAFT_REBASE_CHECKS_FEATURE = "draftRebaseChecks" # a value inside the enable-new-feature flag MIGRATED_COURT_ORDER_FEATURE = "migratedCourtOrder" # a value inside the enable-new-feature flag +ACCOUNT_SCOPED_AUTH_FEATURE = "authV2AccountId" # a value inside the enable-new-feature flag +USER_ROLES_FEATURE = "authV2UserRoles" # a value inside the enable-new-feature flag + +# roles authorized() passes before any auth api call +ROLES_AUTHORIZED_BY_ROLE = [STAFF_ROLE, SYSTEM_ROLE, COLIN_SVC_ROLE, MAXIMUS_STAFF_ROLE, SBC_STAFF_ROLE, + CONTACT_CENTRE_STAFF_ROLE, SBC_FINANCE_STAFF_ROLE] +# Account-Id values UIs send when no account is selected +PLACEHOLDER_ACCOUNT_IDS = ["0", "undefined", "null"] class BusinessBlocker(str, Enum): @@ -85,8 +94,18 @@ class BusinessRequirement(str, Enum): NO_RESTRICTION = "NO_RESTRICTION" -def _call_auth_api(path: str, token: str) -> Response: - """Return the auth api response for the given endpoint path.""" +class AuthServiceUnavailableError(ServiceUnavailable): + """Auth api gave no usable answer, so access can be neither granted nor denied (503).""" + + description = "Authorization service is unavailable, please try again later." + + +def _call_auth_api(path: str, token: str, account_id: str | None = None) -> Response: + """Return the auth api response for the given endpoint path. + + - account_id given: sent as Account-Id, so auth scopes the lookup to that account + - no answer or a 5xx: raises AuthServiceUnavailableError + """ if not token: return None @@ -97,6 +116,8 @@ def _call_auth_api(path: str, token: str) -> Response: headers = {"Authorization": "Bearer " + token} add_account_linking_key_header(headers) + if account_id: + headers["Account-Id"] = account_id try: http = Session() retries = Retry(total=5, @@ -106,7 +127,6 @@ def _call_auth_api(path: str, token: str) -> Response: http.mount("https://", HTTPAdapter(max_retries=retries)) resp = http.get(url=auth_url, headers=headers) current_app.logger.debug(f"Auth get {path} response status: {resp.status_code!s}") - return resp except (exceptions.ConnectionError, # pylint: disable=broad-except exceptions.Timeout, @@ -114,7 +134,12 @@ def _call_auth_api(path: str, token: str) -> Response: Exception) as err: current_app.logger.debug(err.with_traceback(None)) current_app.logger.error(f"Auth connection failure, url: {auth_url}") - return None + raise AuthServiceUnavailableError from err + + if resp.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR: + current_app.logger.error(f"Auth server error {resp.status_code!s}, url: {auth_url}") + raise AuthServiceUnavailableError + return resp def authorized( # noqa: PLR0911 @@ -146,21 +171,51 @@ def authorized( # noqa: PLR0911 ): return True - if jwt.has_one_of_roles([BASIC_USER, PUBLIC_USER]): + if not has_any_roles(jwt, [BASIC_USER, PUBLIC_USER]) and is_new_feature_enabled(USER_ROLES_FEATURE): + log_unauthorized_request("entity access without a basic or public user role", identifier) + return False - # disallow - only staff are allowed - staff_only_actions = ["add_comment"] - if any(elem in action for elem in staff_only_actions): - return False + # disallow - only staff are allowed + staff_only_actions = ["add_comment"] + if any(elem in action for elem in staff_only_actions): + return False + + return _has_entity_roles(identifier, jwt, action) + + +def _has_entity_roles(identifier: str, jwt: JwtManager, action: list[str]) -> bool: + """Return True when auth grants the caller every action on the entity. - auth_identifier = get_auth_identifier(identifier) - rv = _call_auth_api(f"entities/{auth_identifier}/authorizations", jwt.get_token_auth_header()) - if rv and rv.status_code == HTTPStatus.OK and (roles := rv.json().get("roles")): - return all(elem.lower() in roles for elem in action) + - request scoped to an account (get_scoped_account_id): the caller must hold the roles through that account + - otherwise: any account the caller belongs to counts + """ + account_id = get_scoped_account_id() + auth_identifier = get_auth_identifier(identifier) + rv = _call_auth_api(f"entities/{auth_identifier}/authorizations", jwt.get_token_auth_header(), account_id) + roles = rv.json().get("roles") if rv and rv.status_code == HTTPStatus.OK else None + if roles and all(elem.lower() in roles for elem in action): + return True + if account_id: + log_unauthorized_request("account-scoped entity access", identifier) return False +def get_scoped_account_id() -> str | None: + """Return the Account-Id header when auth and pay lookups must be scoped to that account. + + - header missing or a UI placeholder: None + - Account-Linking-Key sent: None, the linking key path is left as it was + - authV2AccountId off: None + """ + account_id = (request.headers.get("Account-Id") or "").strip() + if not account_id or account_id.lower() in PLACEHOLDER_ACCOUNT_IDS: + return None + if request.headers.get("Account-Linking-Key"): + return None + return account_id if is_new_feature_enabled(ACCOUNT_SCOPED_AUTH_FEATURE) else None + + def get_auth_identifier(identifier: str) -> str: """Return the identifier auth holds the affiliation under. @@ -1023,6 +1078,21 @@ def auth_v2_denied(feature: str, subject: str, identifier: str, jwt: JwtManager, return False +def is_account_member(jwt: JwtManager, account_id: str) -> bool: + """Return True when the caller is staff / system or belongs to the account.""" + if has_any_roles(jwt, [STAFF_ROLE, SYSTEM_ROLE]): + return True + return get_account_products(jwt.get_token_auth_header(), str(account_id)) is not None + + +def account_membership_denied(feature: str, subject: str, account_id: str, jwt: JwtManager) -> bool: + """Return True (and log) when the auth-v2 gate is on and the caller does not belong to the account.""" + if is_new_feature_enabled(feature) and not is_account_member(jwt, account_id): + log_unauthorized_request(subject, account_id) + return True + return False + + def is_draft_rebase_checks_enabled() -> bool: """Return True when draftRebaseChecks is in the enable-new-feature flag.""" return is_new_feature_enabled(DRAFT_REBASE_CHECKS_FEATURE) @@ -1389,12 +1459,14 @@ def add_allowable_filing_type(is_allowable: bool = False, return allowable_filing_types -def get_account_id(_, account_id: str | None = None) -> str: - """Return the account id.""" - return account_id or request.headers.get("Account-Id", None) +def _account_products_cache_key(_, account_id: str | None = None) -> str: + """Return the cache key: account plus caller, so one member's result is never served to another caller.""" + account_id = account_id or request.headers.get("Account-Id", None) + caller = (getattr(g, "jwt_oidc_token_info", None) or {}).get("sub") + return f"account_products_{account_id}_{caller}" -@cache.cached(timeout=600, make_cache_key=get_account_id, cache_none=True) +@cache.cached(timeout=600, make_cache_key=_account_products_cache_key, cache_none=True) def get_account_products(token: str, account_id: str | None = None) -> list: """Return the account products of the org identified by the account id.""" account_id = account_id or request.headers.get("Account-Id", None) @@ -1405,8 +1477,14 @@ def get_account_products(token: str, account_id: str | None = None) -> list: def has_product(code: str, token: str) -> bool: - """Return if the user has the active product subscription for the given code.""" - user_products = get_account_products(token) + """Return if the user has the active product subscription for the given code. + + - auth unavailable: False, a product pass is only ever an extra grant + """ + try: + user_products = get_account_products(token) + except AuthServiceUnavailableError: + return False if not user_products or not isinstance(user_products, list): return False diff --git a/legal-api/tests/unit/resources/v2/test_business.py b/legal-api/tests/unit/resources/v2/test_business.py index ea46fa1511..eebad0f8a1 100644 --- a/legal-api/tests/unit/resources/v2/test_business.py +++ b/legal-api/tests/unit/resources/v2/test_business.py @@ -190,6 +190,35 @@ def test_create_one_shot_rejected_rolls_back_bootstrap(session, client, jwt): assert not RegistrationBootstrap.find_by_identifier(temp_identifier) +@pytest.mark.parametrize('test_name, gate_on, role, is_member, expected_denied', [ + ('not_a_member', True, PUBLIC_USER, False, True), + ('member', True, PUBLIC_USER, True, False), + ('staff_not_a_member', True, STAFF_ROLE, False, False), + ('system_not_a_member', True, SYSTEM_ROLE, False, False), + ('not_a_member_gate_off', False, PUBLIC_USER, False, False), +]) +def test_create_business_for_another_account(app, session, client, jwt, requests_mock, monkeypatch, + test_name, gate_on, role, is_member, expected_denied): + """Assert POST /businesses refuses an accountId the caller does not belong to, before any temp identifier.""" + filing = _one_shot_incorporation({'identifier': '{{temp_identifier}}'}) + account_id = filing['filing']['header']['accountId'] + mock_new_feature(monkeypatch, 'authV2BusinessCreate', gate_on) + products_url = f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true" + if is_member: + requests_mock.get(products_url, json=[]) + else: + requests_mock.get(products_url, status_code=HTTPStatus.FORBIDDEN) + + with patch.object(RegistrationBootstrapService, 'create_bootstrap', + return_value={'error': 'stop here'}) as mock_create: + rv = client.post('/api/v2/businesses?draft=true', + json=filing, + headers=create_header(jwt, [role], test_name)) + + assert (rv.status_code == HTTPStatus.FORBIDDEN) is expected_denied + assert mock_create.called is not expected_denied + + def test_create_one_shot_payment_failure_keeps_bootstrap(app, session, client, jwt, requests_mock): """Assert a one-shot filing saved before a payment failure keeps its temp identifier and affiliation.""" filing = _one_shot_incorporation({'identifier': '{{temp_identifier}}'}) @@ -1515,3 +1544,50 @@ def test_ar_reminder_authorization(app, session, client, jwt, monkeypatch, reque assert rv.status_code == expected assert Business.find_by_identifier(identifier).send_ar_ind is not (method == 'put' and expected == HTTPStatus.OK) + + +@pytest.mark.parametrize('test_name, role, expected_account_id', [ + ('system', SYSTEM_ROLE, '2468'), + ('account_identity', ACCOUNT_IDENTITY, '2468'), + ('staff', STAFF_ROLE, None), + ('public_user', PUBLIC_USER, None), +]) +def test_get_business_account_lookup_roles(app, session, client, jwt, requests_mock, + test_name, role, expected_account_id): + """Assert that ?account= only returns accountId to a system or account identity caller.""" + identifier = 'CP7654321' + factory_business_model(legal_name='legal_name', + identifier=identifier, + founding_date=datetime.fromtimestamp(0, UTC), + last_ledger_timestamp=datetime.fromtimestamp(0, UTC), + last_modified=datetime.fromtimestamp(0, UTC)) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", + json={'roles': ['view']}) + + with patch('legal_api.resources.v2.business.business.AccountService.get_account_by_affiliated_identifier', + return_value={'orgs': [{'id': 2468}]}) as account_lookup: + rv = client.get(f'/api/v2/businesses/{identifier}?account=2468', + headers=create_header(jwt, [role], identifier)) + + assert rv.status_code == HTTPStatus.OK + assert rv.json['business'].get('accountId') == expected_account_id + assert account_lookup.called is bool(expected_account_id) + + +def test_get_business_auth_unavailable_unversioned_path(app, session, client, jwt, requests_mock): + """Assert that an auth outage is a 503, not an unauthorized response, through the unversioned /api path.""" + identifier = 'CP7654321' + factory_business_model(legal_name='legal_name', + identifier=identifier, + founding_date=datetime.fromtimestamp(0, UTC), + last_ledger_timestamp=datetime.fromtimestamp(0, UTC), + last_modified=datetime.fromtimestamp(0, UTC)) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", + exc=exceptions.ConnectionError) + + rv = client.get(f'/api/businesses/{identifier}', + headers=create_header(jwt, [PUBLIC_USER], identifier), + follow_redirects=True) + + assert rv.status_code == HTTPStatus.SERVICE_UNAVAILABLE + assert rv.json == {'message': 'Authorization service is unavailable, please try again later.'} diff --git a/legal-api/tests/unit/resources/v2/test_business_account_settings.py b/legal-api/tests/unit/resources/v2/test_business_account_settings.py index 2ce0aba6f1..5aa47fc38f 100644 --- a/legal-api/tests/unit/resources/v2/test_business_account_settings.py +++ b/legal-api/tests/unit/resources/v2/test_business_account_settings.py @@ -27,11 +27,13 @@ """Tests to assure the BusinessAccountSettings endpoints.""" from http import HTTPStatus +import pytest + from business_model.models import BusinessAccountSettings from legal_api.services.authz import PUBLIC_USER from tests.unit.models import factory_business -from tests.unit.services.utils import create_header +from tests.unit.services.utils import create_header, mock_new_feature def test_get_business_account_settings(app, session, client, jwt, requests_mock): @@ -44,6 +46,7 @@ def test_get_business_account_settings(app, session, client, jwt, requests_mock) # mock response from auth to give view access requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': ['view']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", json=[{'code': 'product'}]) # test rv = client.get(f'/api/v2/businesses/settings/{account_id}/{identifier}', @@ -63,6 +66,7 @@ def test_get_business_account_settings_default(app, session, client, jwt, reques # mock response from auth to give view access requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': ['view']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", json=[{'code': 'product'}]) # verify setup assert not BusinessAccountSettings.find_by_business_account(business.id, account_id) @@ -85,6 +89,7 @@ def test_get_business_account_settings_default_exists(app, session, client, jwt, # mock response from auth to give view access requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': ['view']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", json=[{'code': 'product'}]) # verify setup assert BusinessAccountSettings.find_by_business_account(business.id, account_id) @@ -134,6 +139,7 @@ def test_create_business_account_settings(app, session, client, jwt, requests_mo # mock response from auth to give edit access requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': ['edit']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", json=[{'code': 'product'}]) # verify setup assert not BusinessAccountSettings.find_by_business_account(business.id, account_id) @@ -168,6 +174,7 @@ def test_update_business_account_settings(app, session, client, jwt, requests_mo # mock response from auth to give edit access requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': ['edit']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", json=[{'code': 'product'}]) # verify setup assert initial_email == (BusinessAccountSettings.find_by_business_account(business.id, account_id)).json['email'] @@ -191,6 +198,7 @@ def test_delete_business_account_settings(app, session, client, jwt, requests_mo # mock response from auth to give edit access requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': ['edit']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", json=[{'code': 'product'}]) # verify setup assert BusinessAccountSettings.find_by_business_account(business.id, account_id) @@ -200,3 +208,29 @@ def test_delete_business_account_settings(app, session, client, jwt, requests_mo # check assert rv.status_code == HTTPStatus.OK assert not BusinessAccountSettings.find_by_business_account(business.id, account_id) + + +@pytest.mark.parametrize('test_name, gate_on, expected', [ + ('gate_on', True, HTTPStatus.FORBIDDEN), + ('gate_off', False, HTTPStatus.OK), +]) +@pytest.mark.parametrize('method', ['get', 'delete']) +def test_business_account_settings_other_account(app, session, client, jwt, requests_mock, monkeypatch, + method, test_name, gate_on, expected): + """Assert that settings of an account the caller does not belong to are refused when the gate is on.""" + identifier = 'BC1234567' + account_id = 1 + business = factory_business(identifier) + BusinessAccountSettings.create_or_update(business.id, account_id, {}) + mock_new_feature(monkeypatch, 'authV2Settings', gate_on) + + # the caller can edit the business, but auth refuses the account in the path + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", + json={'roles': ['view', 'edit']}) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/orgs/{account_id}/products?include_hidden=true", + status_code=HTTPStatus.FORBIDDEN) + + rv = getattr(client, method)(f'/api/v2/businesses/settings/{account_id}/{identifier}', + headers=create_header(jwt, [PUBLIC_USER], identifier)) + + assert rv.status_code == expected diff --git a/legal-api/tests/unit/resources/v2/test_business_digital_credentials.py b/legal-api/tests/unit/resources/v2/test_business_digital_credentials.py index 1834cc41da..085d6cb41c 100644 --- a/legal-api/tests/unit/resources/v2/test_business_digital_credentials.py +++ b/legal-api/tests/unit/resources/v2/test_business_digital_credentials.py @@ -21,12 +21,14 @@ from http import HTTPStatus from unittest.mock import patch +import pytest + from business_model.models import DCConnection, DCDefinition, User from business_registry_digital_credentials import DigitalCredentialsService from legal_api.services.authz import BASIC_USER -from tests.unit.models import create_dc_business_user, create_dc_connection, create_dc_credential, create_dc_definition, factory_business -from tests.unit.services.utils import create_header, helper_create_jwt_json_token_claims +from tests.unit.models import create_dc_business_user, create_dc_connection, create_dc_credential, create_dc_definition, factory_business, factory_user +from tests.unit.services.utils import create_header, helper_create_jwt_json_token_claims, mock_new_feature content_type = 'application/json' @@ -303,3 +305,92 @@ def test_webhook_connection_attest_notification(app, session, client, jwt): assert rv.json.get('connections')[0].get('isAttested') == True assert rv.json.get('connections')[0].get('lastAttested') != '' assert rv.json.get('connections')[0].get('connectionState') == connection.connection_state + + +@pytest.mark.parametrize('test_name, gate_on, expected', [ + ('gate_on', True, HTTPStatus.FORBIDDEN), + ('gate_off', False, HTTPStatus.OK), +]) +@patch('legal_api.decorators.are_digital_credentials_allowed', return_value=True) +def test_attest_connection_of_another_user(mock_allowed, app, session, client, jwt, monkeypatch, + test_name, gate_on, expected): + """Assert a connection that belongs to another user is refused when the gate is on.""" + identifier = 'FM1234567' + other_business_user = create_dc_business_user(factory_business(identifier), factory_user('other-user')) + connection = create_dc_connection(other_business_user) + mock_new_feature(monkeypatch, 'authV2DigitalCredentials', gate_on) + + with patch.object(DigitalCredentialsService, 'attest_connection', return_value={}): + rv = client.post( + f'/api/v2/businesses/{identifier}/digitalCredentials/connections/{connection.connection_id}/attest', + headers=create_header(jwt, test_roles, test_user), content_type=content_type) + + assert rv.status_code == expected + + +@pytest.mark.parametrize('test_name, gate_on, expected', [ + ('gate_on', True, HTTPStatus.FORBIDDEN), + ('gate_off', False, HTTPStatus.OK), +]) +@patch('legal_api.decorators.are_digital_credentials_allowed', return_value=True) +def test_delete_credential_of_another_user(mock_allowed, app, session, client, jwt, monkeypatch, + test_name, gate_on, expected): + """Assert a credential that belongs to another user is refused when the gate is on.""" + identifier = 'FM1234567' + credential = create_dc_credential(factory_business(identifier), factory_user('other-user')) + credential.credential_id = '123456' + credential.save() + mock_new_feature(monkeypatch, 'authV2DigitalCredentials', gate_on) + + with patch.object(DigitalCredentialsService, 'fetch_credential_exchange_record', return_value=None): + rv = client.delete(f'/api/v2/businesses/{identifier}/digitalCredentials/{credential.credential_id}', + headers=create_header(jwt, test_roles, test_user), content_type=content_type) + + assert rv.status_code == expected + + +@pytest.mark.parametrize('test_name, gate_on, expected', [ + ('gate_on', True, HTTPStatus.FORBIDDEN), + ('gate_off', False, HTTPStatus.OK), +]) +@patch('legal_api.decorators.are_digital_credentials_allowed', return_value=True) +def test_delete_connection_of_another_user(mock_allowed, app, session, client, jwt, monkeypatch, + test_name, gate_on, expected): + """Assert deleting a connection that belongs to another user is refused when the gate is on.""" + identifier = 'FM1234567' + other_business_user = create_dc_business_user(factory_business(identifier), factory_user('other-user')) + connection = create_dc_connection(other_business_user) + mock_new_feature(monkeypatch, 'authV2DigitalCredentials', gate_on) + + rv = client.delete(f'/api/v2/businesses/{identifier}/digitalCredentials/connections/{connection.connection_id}', + headers=create_header(jwt, test_roles, test_user), content_type=content_type) + + assert rv.status_code == expected + assert bool(DCConnection.find_by_id(connection.id)) is gate_on + + +@pytest.mark.parametrize('test_name, gate_on, expected', [ + ('gate_on', True, HTTPStatus.FORBIDDEN), + ('gate_off', False, HTTPStatus.OK), +]) +@patch('legal_api.decorators.are_digital_credentials_allowed', return_value=True) +def test_revoke_credential_of_another_user(mock_allowed, app, session, client, jwt, monkeypatch, + test_name, gate_on, expected): + """Assert revoking a credential that belongs to another user is refused when the gate is on.""" + identifier = 'FM1234567' + business = factory_business(identifier) + caller = User.get_or_create_user_by_jwt(helper_create_jwt_json_token_claims(test_roles, test_user)) + caller_connection = create_dc_connection(create_dc_business_user(business, caller), is_active=True) + caller_connection.connection_id = 'the-callers-own-connection' + caller_connection.save() + credential = create_dc_credential(business, factory_user('other-user')) + credential.credential_id = '123456' + credential.save() + mock_new_feature(monkeypatch, 'authV2DigitalCredentials', gate_on) + + with patch.object(DigitalCredentialsService, 'revoke_credential', return_value={}) as mock_revoke: + rv = client.post(f'/api/v2/businesses/{identifier}/digitalCredentials/{credential.credential_id}/revoke', + headers=create_header(jwt, test_roles, test_user), json={}) + + assert rv.status_code == expected + assert mock_revoke.called is not gate_on diff --git a/legal-api/tests/unit/resources/v2/test_business_filings/test_business_filings_validate_section.py b/legal-api/tests/unit/resources/v2/test_business_filings/test_business_filings_validate_section.py index 52b392b7a6..31d4f0c063 100644 --- a/legal-api/tests/unit/resources/v2/test_business_filings/test_business_filings_validate_section.py +++ b/legal-api/tests/unit/resources/v2/test_business_filings/test_business_filings_validate_section.py @@ -24,24 +24,24 @@ ENDPOINT_PATH = "/api/v2/businesses/{identifier}/filings/validate-section" -def test_validate_sections_unauthorized(app, session, client, jwt): +def test_validate_sections_unauthorized(app, session, client, jwt, requests_mock): """Test 403 Forbidden when an unauthorized user attempts to validate.""" identifier = "BC1234567" factory_business(identifier, entity_type="BC") - - with patch("legal_api.services.authorized", return_value=False): - rv = client.post( - ENDPOINT_PATH.format(identifier=identifier), - headers=create_header(jwt, [PUBLIC_USER], identifier), - json={ - "filingType": "correction", - "section": "nameRequest", - "data": {"legalName": "SAMPLE LTD."}, - }, - ) - - assert rv.status_code == HTTPStatus.FORBIDDEN - assert "Not Authorized" in rv.json.get("message", "") + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={"roles": []}) + + rv = client.post( + ENDPOINT_PATH.format(identifier=identifier), + headers=create_header(jwt, [PUBLIC_USER], identifier), + json={ + "filingType": "correction", + "section": "nameRequest", + "data": {"legalName": "SAMPLE LTD."}, + }, + ) + + assert rv.status_code == HTTPStatus.FORBIDDEN + assert "Not Authorized" in rv.json.get("message", "") def test_validate_sections_missing_required_params(app, session, client, jwt): diff --git a/legal-api/tests/unit/resources/v2/test_business_filings/test_filing_documents.py b/legal-api/tests/unit/resources/v2/test_business_filings/test_filing_documents.py index 82f9644973..e97cfc7dfc 100644 --- a/legal-api/tests/unit/resources/v2/test_business_filings/test_filing_documents.py +++ b/legal-api/tests/unit/resources/v2/test_business_filings/test_filing_documents.py @@ -60,7 +60,7 @@ factory_completed_filing, factory_filing, ) -from tests.unit.services.utils import create_header, helper_create_jwt +from tests.unit.services.utils import create_header, mock_new_feature ADMIN_DISSOLUTION = copy.deepcopy(DISSOLUTION) ADMIN_DISSOLUTION['dissolutionType'] = 'administrative' @@ -1032,3 +1032,30 @@ def test_admin_dissolution_firm_documents_no_certificate(app, session, client, j assert 'certificateOfDissolution' not in documents assert {'dissolution': f'{base_url}/api/v2/businesses/{identifier}/filings/{filing.id}/documents/dissolution'} \ in documents['legalFilings'] + + +@pytest.mark.parametrize('test_name, gate_on, drs_id, expected', [ + ('own_drs_id', True, 'DS0000100001', HTTPStatus.OK), + ('other_filing_drs_id', True, 'DS0000999999', HTTPStatus.FORBIDDEN), + ('other_filing_drs_id_gate_off', False, 'DS0000999999', HTTPStatus.OK), +]) +def test_get_drs_document_of_another_filing(session, client, jwt, mocker, monkeypatch, + test_name, gate_on, drs_id, expected): + """Assert a drsId that is not one of the filing's DRS documents is refused when the gate is on.""" + from legal_api.resources.v2.business.business_filings import business_documents + + identifier = 'CP7654321' + business = factory_business(identifier) + filing = factory_filing(business, copy.deepcopy(FILING_HEADER)) + mock_new_feature(monkeypatch, 'authV2FilingDocuments', gate_on) + mocker.patch.object(business_documents, '_is_document_available', return_value=True) + mocker.patch.object(business_documents.DocumentService, 'get_documents_by_filing_id', + return_value=[{'identifier': 'DS0000100001', 'reportType': 'RECEIPT'}]) + mocker.patch.object(business_documents, '_get_drs_documents', + return_value=(b'drs-pdf', HTTPStatus.OK, business_documents.CONTENT_PDF)) + + rv = client.get(f'/api/v2/businesses/{identifier}/filings/{filing.id}/documents/receipt' + f'?reportType=RECEIPT&drsId={drs_id}', + headers=create_header(jwt, [STAFF_ROLE], identifier, **{'accept': 'application/pdf'})) + + assert rv.status_code == expected diff --git a/legal-api/tests/unit/resources/v2/test_business_filings/test_filings.py b/legal-api/tests/unit/resources/v2/test_business_filings/test_filings.py index bc8be87e10..003dcc4e90 100644 --- a/legal-api/tests/unit/resources/v2/test_business_filings/test_filings.py +++ b/legal-api/tests/unit/resources/v2/test_business_filings/test_filings.py @@ -46,7 +46,17 @@ ) from legal_api.resources.v2.business.business_filings.business_filings import ListFilingResource from legal_api.services import flags -from legal_api.services.authz import BASIC_USER, PUBLIC_USER, STAFF_ROLE +from legal_api.services.authz import ( + BASIC_USER, + COLIN_SVC_ROLE, + CONTACT_CENTRE_STAFF_ROLE, + MAXIMUS_STAFF_ROLE, + PUBLIC_USER, + SBC_FINANCE_STAFF_ROLE, + SBC_STAFF_ROLE, + STAFF_ROLE, + SYSTEM_ROLE, +) from legal_api.services.bootstrap import RegistrationBootstrapService from registry_schemas.example_data import ( ALTERATION_FILING_TEMPLATE, @@ -446,6 +456,27 @@ def test_get_one_business_filing_by_id_raw_json(session, client, jwt): assert rv.json['filing']['business'] == ANNUAL_REPORT['filing']['business'] +@pytest.mark.parametrize('test_name, url_identifier, is_state_filing, expected', [ + ('own_filing', 'CP7654321', False, HTTPStatus.OK), + ('other_business', 'CP1111111', False, HTTPStatus.NOT_FOUND), + ('other_business_state_filing', 'CP1111111', True, HTTPStatus.OK), + ('unknown_business', 'CP9999999', False, HTTPStatus.NOT_FOUND), +]) +def test_get_public_filing_scoped_to_business(session, client, jwt, test_name, url_identifier, is_state_filing, + expected): + """Assert that ?public=true only returns a filing of the business in the URL, or its state filing.""" + filing = factory_filing(factory_business('CP7654321'), ANNUAL_REPORT) + other_business = factory_business('CP1111111') + if is_state_filing: + other_business.state_filing_id = filing.id + other_business.save() + + rv = client.get(f'/api/v2/businesses/{url_identifier}/filings/{filing.id}?public=true', + headers=create_header(jwt, [PUBLIC_USER], url_identifier)) + + assert rv.status_code == expected + + @pytest.mark.parametrize( 'test_name, filing_name, filing', [ @@ -604,10 +635,11 @@ def test_post_authorized_draft_ar(session, client, jwt): assert rv.status_code == HTTPStatus.CREATED -def test_post_not_authorized_draft_ar(session, client, jwt): +def test_post_not_authorized_draft_ar(app, session, client, jwt, requests_mock): """Assert that a unpaid filing can be posted.""" identifier = 'CP7654321' factory_business(identifier) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': []}) data = get_filing_template('annualReport', identifier) rv = client.post(f'/api/v2/businesses/{identifier}/filings?draft=true', json=data, @@ -617,10 +649,11 @@ def test_post_not_authorized_draft_ar(session, client, jwt): assert rv.status_code == HTTPStatus.UNAUTHORIZED -def test_post_not_allowed_historical(session, client, jwt): +def test_post_not_allowed_historical(app, session, client, jwt, requests_mock): """Assert that a filing is not allowed for historical business.""" identifier = 'CP7654321' factory_business(identifier, state=Business.State.HISTORICAL) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': []}) data = get_filing_template('annualReport', identifier) rv = client.post(f'/api/v2/businesses/{identifier}/filings', json=data, @@ -1938,6 +1971,54 @@ def test_create_invoice_forwards_account_linking_key(session, requests_mock, cli assert pay_mock.last_request.headers.get('Account-Linking-Key') == 'test-linking-key' +@pytest.mark.parametrize('test_name, role, feature_on, account_id, linking_key, expected_account', [ + ('public_user', PUBLIC_USER, True, '12345', None, '12345'), + ('public_user_feature_off', PUBLIC_USER, False, '12345', None, None), + ('public_user_linking_key', PUBLIC_USER, True, '12345', 'test-linking-key', None), + ('public_user_placeholder_account', PUBLIC_USER, True, '0', None, None), + ('staff', STAFF_ROLE, True, '12345', None, None), + ('system', SYSTEM_ROLE, True, '12345', None, None), + ('colin', COLIN_SVC_ROLE, True, '12345', None, None), + ('sbc_staff', SBC_STAFF_ROLE, True, '12345', None, None), + ('maximus_staff', MAXIMUS_STAFF_ROLE, True, '12345', None, None), + ('contact_centre_staff', CONTACT_CENTRE_STAFF_ROLE, True, '12345', None, None), + ('sbc_finance_staff', SBC_FINANCE_STAFF_ROLE, True, '12345', None, None), +]) +def test_create_invoice_forwards_account_id(session, requests_mock, client, jwt, monkeypatch, + test_name, role, feature_on, account_id, linking_key, expected_account): + """Assert that create_invoice forwards a real Account-Id to pay-api only for callers authorized through auth.""" + mock_new_feature(monkeypatch, 'authV2AccountId', feature_on) + identifier = 'CP1234567' + coa = copy.deepcopy(FILING_HEADER) + coa['filing']['header']['name'] = 'changeOfAddress' + coa['filing']['changeOfAddress'] = copy.deepcopy(CHANGE_OF_ADDRESS) + coa['filing']['changeOfAddress']['offices']['registeredOffice']['deliveryAddress']['addressCountry'] = 'CA' + coa['filing']['changeOfAddress']['offices']['registeredOffice']['mailingAddress']['addressCountry'] = 'CA' + coa['filing']['business']['identifier'] = identifier + + b = factory_business(identifier, (datetime.now(UTC) - datedelta.YEAR), None, Business.LegalTypes.COOP.value) + factory_business_mailing_address(b) + + requests_mock.get(f"{current_app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", + json={'roles': ['edit', 'view']}) + pay_mock = requests_mock.post(current_app.config.get('PAYMENT_SVC_URL'), + json={'id': 21322, 'statusCode': 'COMPLETED', 'isPaymentActionRequired': False}, + status_code=HTTPStatus.CREATED) + extra_headers = {'Account-Id': account_id} + if linking_key: + extra_headers['Account-Linking-Key'] = linking_key + + business_filings_module = 'legal_api.resources.v2.business.business_filings.business_filings' + with patch(f'{business_filings_module}.is_allowed', return_value=True), \ + patch(f'{business_filings_module}.validate', return_value=None): + rv = client.post(f'/api/v2/businesses/{identifier}/filings', + json=coa, + headers=create_header(jwt, [role], identifier, **extra_headers)) + + assert rv.status_code == HTTPStatus.CREATED + assert pay_mock.last_request.headers.get('Account-Id') == expected_account + + @pytest.mark.parametrize( 'test_name, pay_response_account, expected_payment_account', [ diff --git a/legal-api/tests/unit/resources/v2/test_colin_sync.py b/legal-api/tests/unit/resources/v2/test_colin_sync.py index aa8f9f2194..5dcbc22ef0 100644 --- a/legal-api/tests/unit/resources/v2/test_colin_sync.py +++ b/legal-api/tests/unit/resources/v2/test_colin_sync.py @@ -188,6 +188,26 @@ def test_get_colin_last_update(session, client, jwt): assert rv.json == {'maxId': colin_id} +def test_get_last_event_id(session, client, jwt): + """Assert the internal/last-event-id endpoint only matches the exact identifier.""" + identifier = 'CP7654321' + b = factory_business(identifier) + filing = factory_completed_filing(b, ANNUAL_REPORT) + colin_event_id = ColinEventId() + colin_event_id.colin_event_id = 1234 + filing.colin_event_ids.append(colin_event_id) + filing.save() + + rv = client.get(f'/api/v2/businesses/internal/last-event-id/{identifier}', + headers=create_header(jwt, [COLIN_SVC_ROLE])) + assert rv.status_code == HTTPStatus.OK + assert rv.json == {'maxId': 1234} + + rv = client.get("/api/v2/businesses/internal/last-event-id/x' or '1'='1", + headers=create_header(jwt, [COLIN_SVC_ROLE])) + assert rv.status_code == HTTPStatus.NOT_FOUND + + def test_post_colin_last_update(session, client, jwt): """Assert the internal/filings/colin_id post endpoint updates the colin_last_update table.""" colin_id = 1234 diff --git a/legal-api/tests/unit/resources/v2/test_document.py b/legal-api/tests/unit/resources/v2/test_document.py index 316ee12cce..14926d7068 100644 --- a/legal-api/tests/unit/resources/v2/test_document.py +++ b/legal-api/tests/unit/resources/v2/test_document.py @@ -21,11 +21,14 @@ import pytest from flask import current_app +from requests import exceptions +from business_model.models import Document from legal_api.resources.v2 import document -from legal_api.services.authz import STAFF_ROLE +from legal_api.services.authz import PUBLIC_USER, STAFF_ROLE -from tests.unit.services.utils import create_header +from tests.unit.models import factory_business, factory_completed_filing, factory_filing +from tests.unit.services.utils import create_header, mock_new_feature MOCK_DRS_URL = "https://test.api.connect.gov.bc.ca/mockTarget/doc/api/v1" @@ -250,3 +253,143 @@ def test_get_drs_class(session, jwt, filekey, doc_class): """Assert that extracting the DRS doc class from a business documents record filekey produces the expected result.""" result = document.get_drs_class_from_key(filekey) assert result == doc_class + + +LINKED_FILE_KEY = 'CORP-DS0100001000' + + +def _link_client_document(identifier: str, completed: bool = False): + """Link LINKED_FILE_KEY to a court order filing of a new business.""" + business = factory_business(identifier) + filing_json = {'filing': {'header': {'name': 'courtOrder'}}} + filing = factory_completed_filing(business, filing_json) if completed else factory_filing(business, filing_json) + Document(type='court_order', file_key=LINKED_FILE_KEY, filing_id=filing.id, business_id=business.id).save() + + +def _mock_drs(mocker): + """Mock every DRS call the client document routes make, returning the mocks by name.""" + drs_response = mocker.MagicMock(ok=True, status_code=HTTPStatus.OK, content=b'pdf') + return {drs_call: mocker.patch.object(document.doc_service, drs_call, return_value=drs_response) + for drs_call in ('get_document', 'add_replace_document', 'delete_document', 'update_document_record')} + + +@pytest.mark.parametrize('test_name, gate_on, linked, method, url_key, role, auth_roles, expected', [ + ('get_linked', True, True, 'get', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('put_linked', True, True, 'put', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('delete_linked', True, True, 'delete', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('get_linked_other_class', True, True, 'get', 'FIRM-DS0100001000', PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('get_linked_bare_id', True, True, 'get', 'DS0100001000', PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('get_linked_encoded_hyphen', True, True, 'get', 'CORP%2DDS0100001000', PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('get_linked_ds_class', True, True, 'get', 'DSX-DS0100001000', PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('delete_linked_ds_class', True, True, 'delete', 'DSX-DS0100001000', PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('get_linked_view_only', True, True, 'get', LINKED_FILE_KEY, PUBLIC_USER, ['view'], HTTPStatus.OK), + ('put_linked_view_only', True, True, 'put', LINKED_FILE_KEY, PUBLIC_USER, ['view'], HTTPStatus.FORBIDDEN), + ('put_linked_affiliated', True, True, 'put', LINKED_FILE_KEY, PUBLIC_USER, ['view', 'edit'], HTTPStatus.OK), + ('delete_linked_affiliated', True, True, 'delete', LINKED_FILE_KEY, PUBLIC_USER, ['view', 'edit'], HTTPStatus.OK), + ('get_linked_staff', True, True, 'get', LINKED_FILE_KEY, STAFF_ROLE, [], HTTPStatus.OK), + ('get_unlinked', True, False, 'get', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.OK), + ('patch_public', True, False, 'patch', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.FORBIDDEN), + ('patch_staff', True, False, 'patch', LINKED_FILE_KEY, STAFF_ROLE, [], HTTPStatus.OK), + ('get_linked_gate_off', False, True, 'get', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.OK), + ('patch_public_gate_off', False, False, 'patch', LINKED_FILE_KEY, PUBLIC_USER, [], HTTPStatus.OK), +]) +def test_client_document_authorization(app, session, client, jwt, requests_mock, monkeypatch, mocker, + test_name, gate_on, linked, method, url_key, role, auth_roles, expected): + """Assert a linked document needs access to its business under any spelling of its key when the gate is on.""" + identifier = 'BC7654321' + if linked: + _link_client_document(identifier) + mock_new_feature(monkeypatch, 'authV2ClientDocuments', gate_on) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", + json={'roles': auth_roles}) + drs_calls = _mock_drs(mocker) + + rv = getattr(client, method)(f'/api/v2/documents/client/{url_key}', + headers=create_header(jwt, [role], identifier), + json={} if method == 'patch' else None) + + assert rv.status_code == expected + assert any(drs_call.called for drs_call in drs_calls.values()) is (expected == HTTPStatus.OK) + + +@pytest.mark.parametrize('test_name, method, url_key', [ + ('delete_exact_key', 'delete', LINKED_FILE_KEY), + ('put_bare_id', 'put', 'DS0100001000'), +]) +def test_client_document_completed_filing_not_draft(app, session, client, jwt, monkeypatch, mocker, + test_name, method, url_key): + """Assert a document of a completed filing cannot be replaced or deleted under any spelling of its key.""" + identifier = 'BC7654321' + _link_client_document(identifier, completed=True) + mock_new_feature(monkeypatch, 'authV2ClientDocuments', False) + drs_calls = _mock_drs(mocker) + + rv = getattr(client, method)(f'/api/v2/documents/client/{url_key}', + headers=create_header(jwt, [STAFF_ROLE], identifier)) + + assert rv.status_code == HTTPStatus.FORBIDDEN + assert not any(drs_call.called for drs_call in drs_calls.values()) + + +@pytest.mark.parametrize('test_name, method, url_key', [ + ('get_fragment', 'get', f'{LINKED_FILE_KEY}%23x'), + ('get_query_separator', 'get', f'{LINKED_FILE_KEY}&x'), + ('get_lowercase', 'get', LINKED_FILE_KEY.lower()), + ('get_wildcard', 'get', 'CORP-DS010000100%25'), + ('get_suffix', 'get', f'{LINKED_FILE_KEY}-x'), + ('delete_suffix', 'delete', f'{LINKED_FILE_KEY}-x'), + ('delete_fragment', 'delete', f'{LINKED_FILE_KEY}%23x'), + ('delete_query', 'delete', 'DS0100001000%3Fx'), + ('put_fragment', 'put', 'DS0100001000%23x'), + ('patch_fragment', 'patch', f'{LINKED_FILE_KEY}%23x'), + ('get_trailing_newline', 'get', f'{LINKED_FILE_KEY}%0A'), + ('get_trailing_space', 'get', f'{LINKED_FILE_KEY}%20'), + ('get_double_encoded', 'get', f'{LINKED_FILE_KEY}%2523x'), + ('get_fullwidth_digit', 'get', 'CORP-DS%EF%BC%91'), +]) +def test_client_document_malformed_key(app, session, client, jwt, monkeypatch, mocker, test_name, method, url_key): + """Assert a key DRS could read as another document's id is rejected before any check or DRS call.""" + identifier = 'BC7654321' + _link_client_document(identifier) + mock_new_feature(monkeypatch, 'authV2ClientDocuments', False) + drs_calls = _mock_drs(mocker) + + rv = getattr(client, method)(f'/api/v2/documents/client/{url_key}', + headers=create_header(jwt, [STAFF_ROLE], identifier), + json={} if method == 'patch' else None) + + assert rv.status_code == HTTPStatus.BAD_REQUEST + assert not any(drs_call.called for drs_call in drs_calls.values()) + + +@pytest.mark.parametrize('test_name, url_key', [ + ('longer_id', 'CORP-DS01000010001'), + ('shorter_id', 'CORP-DS010000100'), +]) +def test_client_document_similar_key_is_unlinked(app, session, client, jwt, requests_mock, monkeypatch, mocker, + test_name, url_key): + """Assert a key whose id only resembles a linked document's is treated as its own, unlinked document.""" + identifier = 'BC7654321' + _link_client_document(identifier) + mock_new_feature(monkeypatch, 'authV2ClientDocuments', True) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", json={'roles': []}) + drs_calls = _mock_drs(mocker) + + rv = client.get(f'/api/v2/documents/client/{url_key}', headers=create_header(jwt, [PUBLIC_USER], identifier)) + + assert rv.status_code == HTTPStatus.OK + assert drs_calls['get_document'].called + + +def test_client_document_auth_unavailable(app, session, client, jwt, requests_mock, mocker): + """Assert an auth outage on a linked document is a 503, not the route's generic 500.""" + identifier = 'BC7654321' + _link_client_document(identifier) + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/{identifier}/authorizations", + exc=exceptions.ConnectionError) + _mock_drs(mocker) + + rv = client.get(f'/api/v2/documents/client/{LINKED_FILE_KEY}', + headers=create_header(jwt, [PUBLIC_USER], identifier)) + + assert rv.status_code == HTTPStatus.SERVICE_UNAVAILABLE diff --git a/legal-api/tests/unit/resources/v2/test_filing_comments.py b/legal-api/tests/unit/resources/v2/test_filing_comments.py index b509e282d7..9cab20dd84 100644 --- a/legal-api/tests/unit/resources/v2/test_filing_comments.py +++ b/legal-api/tests/unit/resources/v2/test_filing_comments.py @@ -333,6 +333,22 @@ def test_put_comment_error(session, client, jwt): assert HTTPStatus.METHOD_NOT_ALLOWED == rv.status_code +def test_post_comment_by_id_error(session, client, jwt): + """Assert that the POST endpoint isn't allowed on a comment id.""" + b = factory_business('CP1111111') + f = factory_filing(b, ANNUAL_REPORT) + c = factory_comment(b, f) + + json_data = copy.deepcopy(SAMPLE_JSON_DATA) + json_data['comment']['filingId'] = f.id + + rv = client.post(f'/api/v2/businesses/{b.identifier}/filings/{f.id}/comments/{c.id}', + json=json_data, + headers=create_header(jwt, [STAFF_ROLE])) + + assert HTTPStatus.METHOD_NOT_ALLOWED == rv.status_code + + def test_delete_comment_error(session, client, jwt): """Assert that the DELETE endpoint isn't allowed.""" b = factory_business('CP1111111') diff --git a/legal-api/tests/unit/resources/v2/test_name_requests.py b/legal-api/tests/unit/resources/v2/test_name_requests.py index 7625c508bd..ccd10ae94e 100644 --- a/legal-api/tests/unit/resources/v2/test_name_requests.py +++ b/legal-api/tests/unit/resources/v2/test_name_requests.py @@ -370,15 +370,47 @@ def test_nr_success_public_user(session, mocker, client, jwt): 'query_nr_number', return_value=MagicMock(status_code=200, json=MagicMock(return_value=nr_approved))): - mocker.patch('legal_api.resources.v2.namerequest.AccountService.get_account_by_affiliated_identifier', - return_value={'orgs': [{'id': 123456}]}) + mocker.patch('legal_api.resources.v2.namerequest.authorized', return_value=True) rv = client.get('/api/v2/nameRequests/NR 1234567/validate', headers=create_header(jwt, [UserRoles.public_user])) assert rv.status_code == 200 -def test_nr_not_affiliated_public_user(session, mocker, client, jwt): +def test_nr_affiliated_to_another_account_public_user(session, mocker, client, jwt): + """Test NR for public user role: an affiliation the caller cannot view does not return the NR.""" + with patch.object(namex, + 'query_nr_number', + return_value=MagicMock(status_code=200, + json=MagicMock(return_value=nr_approved))): + affiliated = mocker.patch( + 'legal_api.resources.v2.namerequest.AccountService.get_account_by_affiliated_identifier', + return_value={'orgs': [{'id': 123456}]}) + mocker.patch('legal_api.resources.v2.namerequest.authorized', return_value=False) + rv = client.get('/api/v2/nameRequests/NR 1234567/validate', + headers=create_header(jwt, [UserRoles.public_user])) + assert rv.status_code == 403 + assert rv.json == {'message': 'The request must include email or phone number.'} + affiliated.assert_not_called() + + +def test_nr_affiliation_lookup_fails_gate_off(session, mocker, client, jwt): + """Test NR for public user role, gate off: a failed affiliation lookup falls through to the contact check.""" + with patch.object(namex, + 'query_nr_number', + return_value=MagicMock(status_code=200, + json=MagicMock(return_value=nr_approved))): + mocker.patch('legal_api.resources.v2.namerequest.is_new_feature_enabled', return_value=False) + mocker.patch('legal_api.resources.v2.namerequest.AccountService.get_account_by_affiliated_identifier', + return_value=None) + rv = client.get('/api/v2/nameRequests/NR 1234567/validate', + headers=create_header(jwt, [UserRoles.public_user])) + assert rv.status_code == 403 + assert rv.json == {'message': 'The request must include email or phone number.'} + + +def test_nr_not_affiliated_public_user(app, session, mocker, client, jwt, requests_mock): """Test NR for public user role, NR not affiliated, email or phone is required.""" + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/NR 1234567/authorizations", json={'roles': []}) with patch.object(namex, 'query_nr_number', return_value=MagicMock(status_code=200, @@ -390,8 +422,9 @@ def test_nr_not_affiliated_public_user(session, mocker, client, jwt): assert rv.status_code == 403 assert rv.json == {'message': 'The request must include email or phone number.'} -def test_nr_valid_contact_public_user(session, mocker, client, jwt): +def test_nr_valid_contact_public_user(app, session, mocker, client, jwt, requests_mock): """Test NR for public user role, NR not affiliated, valid email or phone.""" + requests_mock.get(f"{app.config.get('AUTH_SVC_URL')}/entities/NR 1234567/authorizations", json={'roles': []}) with patch.object(namex, 'query_nr_number', return_value=MagicMock(status_code=200, diff --git a/legal-api/tests/unit/services/test_authorization.py b/legal-api/tests/unit/services/test_authorization.py index 0924840490..86d461e2e5 100644 --- a/legal-api/tests/unit/services/test_authorization.py +++ b/legal-api/tests/unit/services/test_authorization.py @@ -23,6 +23,7 @@ from http import HTTPStatus import pytest +import requests from datedelta import datedelta from unittest.mock import patch, PropertyMock from flask import g, jsonify @@ -32,7 +33,7 @@ from business_model.models import Business, Filing, RegistrationBootstrap from legal_api import create_app from legal_api.services.authz import BASIC_USER, COLIN_SVC_ROLE, CONTACT_CENTRE_STAFF_ROLE , MAXIMUS_STAFF_ROLE, \ - PUBLIC_USER, STAFF_ROLE, SBC_STAFF_ROLE, SBC_FINANCE_STAFF_ROLE, \ + PUBLIC_USER, STAFF_ROLE, SBC_STAFF_ROLE, SBC_FINANCE_STAFF_ROLE, AuthServiceUnavailableError, \ authorized, get_auth_identifier, is_allowed, get_allowed, get_allowed_filings, get_allowable_actions, get_allowable_filings_dict, \ get_staff_draft_bypass_filing_types, has_blocker_filing, is_draft_rebase_scoped_filing from legal_api.services.permissions import PermissionService @@ -58,7 +59,8 @@ ) from tests import integration_authorization, not_github_ci from tests.unit.models import factory_batch, factory_batch_processing, factory_business, factory_filing, factory_incomplete_statuses, factory_completed_filing -from tests.unit.services.utils import create_business, create_header, helper_create_jwt, jwt_request_context +from tests.unit.services.utils import create_business, create_header, helper_create_jwt, jwt_request_context, \ + mock_new_feature DELAY_DISSOLUTION = { @@ -560,7 +562,7 @@ def test_authorized_temp_reg_identifier(monkeypatch, app, session, jwt, test_nam called_paths = [] - def mock_call_auth_api(path, token): # pylint: disable=unused-argument + def mock_call_auth_api(path, token, account_id=None): # pylint: disable=unused-argument called_paths.append(path) resp = Response() resp.status_code = HTTPStatus.OK @@ -607,19 +609,14 @@ def test_call_auth_api_forwards_account_linking_key(app, jwt, requests_mock): def test_authorized_bad_url(monkeypatch, app, jwt): - """Assert that an invalid auth service URL returns False.""" + """Assert that an unreachable auth service URL raises a 503 instead of reading as not authorized.""" identifier = 'CP1234567' username = 'username' roles = [BASIC_USER] - with jwt_request_context(app, jwt, roles=roles, username=username): - auth_svc_url = app.config['AUTH_SVC_URL'] - app.config['AUTH_SVC_URL'] = 'http://no.way.this.works/dribble' - - rv = authorized(identifier, jwt, ['view']) - - app.config['AUTH_SVC_URL'] = auth_svc_url - - assert not rv + monkeypatch.setitem(app.config, 'AUTH_SVC_URL', 'http://no.way.this.works/dribble') + with jwt_request_context(app, jwt, roles=roles, username=username), \ + pytest.raises(AuthServiceUnavailableError): + authorized(identifier, jwt, ['view']) @pytest.mark.parametrize( "test_name, roles_in_token, expected_role", @@ -4330,3 +4327,123 @@ def test_auth_v2_denied(monkeypatch, app, jwt, caplog, test_name, flag_on, is_au assert authz.auth_v2_denied('authV2Tasks', 'tasks', 'CP7654321', jwt, ['view']) is expected assert ('Unauthorized request for tasks: CP7654321' in caplog.text) is expected + + +@pytest.mark.parametrize('test_name, flag_on, account_id, linking_key, expected_header', [ + ('gate_on_account_sent', True, '2468', None, '2468'), + ('gate_off_account_sent', False, '2468', None, None), + ('gate_on_no_account', True, '', None, None), + ('gate_on_placeholder_zero', True, '0', None, None), + ('gate_on_placeholder_undefined', True, 'undefined', None, None), + ('gate_on_placeholder_null', True, 'null', None, None), + ('gate_on_linking_key', True, '2468', 'test-linking-key', None), +]) +def test_authorized_scopes_to_account(monkeypatch, app, jwt, requests_mock, + test_name, flag_on, account_id, linking_key, expected_header): + """Assert that only a real Account-Id reaches auth, with the gate on and no linking key.""" + from legal_api.services import authz + monkeypatch.setattr(authz, 'is_new_feature_enabled', lambda feature: flag_on) + auth_mock = requests_mock.get(f"{app.config['AUTH_SVC_URL']}/entities/CP7654321/authorizations", + json={'roles': ['view', 'edit']}) + extra_headers = {'Account-Linking-Key': linking_key} if linking_key else {} + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], account_id=account_id, **extra_headers): + assert authz.authorized('CP7654321', jwt, ['edit']) + + assert auth_mock.last_request.headers.get('Account-Id') == expected_header + + +@pytest.mark.parametrize('test_name, flag_on, expected_log', [ + ('gate_on', True, True), + ('gate_off', False, False), +]) +def test_authorized_account_denied(monkeypatch, app, jwt, requests_mock, caplog, test_name, flag_on, expected_log): + """Assert that an account without the roles is denied, and logged when the account-scoped gate is on.""" + from legal_api.services import authz + monkeypatch.setattr(authz, 'is_new_feature_enabled', lambda feature: flag_on) + requests_mock.get(f"{app.config['AUTH_SVC_URL']}/entities/CP7654321/authorizations", json={}) + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], account_id='2468'), caplog.at_level('WARNING'): + assert not authz.authorized('CP7654321', jwt, ['edit']) + + assert ('Unauthorized request for account-scoped entity access: CP7654321' in caplog.text) is expected_log + + +def test_account_products_cached_per_caller(app, jwt, requests_mock): + """Assert one member's cached products are not served to another caller sending the same Account-Id.""" + from legal_api.services.authz import get_account_products + products_url = f"{app.config['AUTH_SVC_URL']}/orgs/2468/products?include_hidden=true" + + requests_mock.get(products_url, json=[{'code': 'CA_SEARCH', 'subscriptionStatus': 'ACTIVE'}]) + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], username='member', account_id='2468'): + assert get_account_products(jwt.get_token_auth_header()) + + requests_mock.get(products_url, status_code=HTTPStatus.FORBIDDEN) + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], username='not-a-member', account_id='2468', + extra_claims={'sub': 'a-different-caller'}): + assert get_account_products(jwt.get_token_auth_header()) is None + + +@pytest.mark.parametrize('test_name, auth_response', [ + ('connection_error', {'exc': requests.exceptions.ConnectionError}), + ('timeout', {'exc': requests.exceptions.Timeout}), + ('server_error', {'status_code': HTTPStatus.BAD_GATEWAY}), +]) +def test_authorized_auth_unavailable(app, jwt, requests_mock, test_name, auth_response): + """Assert that an auth outage raises a 503 instead of reading as not authorized.""" + requests_mock.get(f"{app.config['AUTH_SVC_URL']}/entities/CP7654321/authorizations", **auth_response) + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], account_id=''), \ + pytest.raises(AuthServiceUnavailableError) as excinfo: + authorized('CP7654321', jwt, ['edit']) + + assert excinfo.value.code == HTTPStatus.SERVICE_UNAVAILABLE + + +def test_authorized_auth_denial_is_not_an_outage(app, jwt, requests_mock): + """Assert that a 4xx from auth still reads as not authorized.""" + requests_mock.get(f"{app.config['AUTH_SVC_URL']}/entities/CP7654321/authorizations", + status_code=HTTPStatus.FORBIDDEN) + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], account_id=''): + assert not authorized('CP7654321', jwt, ['edit']) + + +def test_has_product_auth_unavailable(app, jwt, requests_mock): + """Assert that an auth outage reads as no product, so the CA_SEARCH pass never fails a request.""" + from legal_api.services.authz import has_product + requests_mock.get(f"{app.config['AUTH_SVC_URL']}/orgs/1357/products?include_hidden=true", + exc=requests.exceptions.ConnectionError) + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], account_id='1357'): + assert not has_product('CA_SEARCH', jwt.get_token_auth_header()) + + +def test_is_account_member_auth_unavailable_not_cached(app, jwt, requests_mock): + """Assert that an auth outage raises a 503 for a membership check and is not cached as a denial.""" + from legal_api.services.authz import is_account_member + products_url = f"{app.config['AUTH_SVC_URL']}/orgs/1359/products?include_hidden=true" + + with jwt_request_context(app, jwt, roles=[PUBLIC_USER], account_id='1359'): + requests_mock.get(products_url, exc=requests.exceptions.ConnectionError) + with pytest.raises(AuthServiceUnavailableError): + is_account_member(jwt, '1359') + + requests_mock.get(products_url, json=[]) + assert is_account_member(jwt, '1359') + + +@pytest.mark.parametrize('test_name, roles, flag_on, expected, calls_auth', [ + ('public_user_gate_on', [PUBLIC_USER], True, True, True), + ('basic_gate_on', [BASIC_USER], True, True, True), + ('other_role_gate_on', ['NONE'], True, False, False), + ('no_roles_gate_on', [], True, False, False), + ('other_role_gate_off', ['NONE'], False, True, True), +]) +def test_authorized_user_roles(monkeypatch, app, jwt, requests_mock, caplog, + test_name, roles, flag_on, expected, calls_auth): + """Assert that a caller without a basic / public user role never reaches auth when authV2UserRoles is on.""" + mock_new_feature(monkeypatch, 'authV2UserRoles', flag_on) + auth_mock = requests_mock.get(f"{app.config['AUTH_SVC_URL']}/entities/CP7654321/authorizations", + json={'roles': ['view', 'edit']}) + with jwt_request_context(app, jwt, roles=roles, account_id=''), caplog.at_level('WARNING'): + assert authorized('CP7654321', jwt, ['edit']) is expected + + assert auth_mock.called is calls_auth + assert ('Unauthorized request for entity access without a basic or public user role: CP7654321' + in caplog.text) is not expected