Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion legal-api/flags.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@
"authV2Tasks",
"authV2ArReminder",
"authV2Comments",
"authV2FilingComments"
"authV2FilingComments",
"authV2AccountId",
"authV2FilingDocuments",
"authV2ClientDocuments",
"authV2NameRequests",
"authV2BusinessCreate",
"authV2Settings",
"authV2DigitalCredentials",
"authV2UserRoles"
],
"enable-staff-draft-filing-bypass": [
"agmLocationChange",
Expand Down
11 changes: 10 additions & 1 deletion legal-api/src/legal_api/resources/v2/business/business.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.")}, \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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/<string:account_id>", methods=["GET"])
@bp.route("/settings/<string:account_id>/<string:identifier>", 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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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("/<string:identifier>/digitalCredentials/invitation", methods=["POST"], strict_slashes=False)
@cross_origin()
@jwt.requires_auth
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -57,7 +58,7 @@
@bp.route(DOCUMENTS_BASE_ROUTE + "/static/<string:file_key>", 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):
Expand All @@ -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)
Expand All @@ -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 = {}
Expand Down Expand Up @@ -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


Expand Down
Loading