diff --git a/as4/const.py b/as4/const.py index 566f964..5eb4a5f 100644 --- a/as4/const.py +++ b/as4/const.py @@ -24,3 +24,8 @@ ATTACHMENT_CIPHERTEXT_TRANSFORM = ( "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Ciphertext-Transform" ) +MEP_ONE_WAY = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay" +MEP_TWO_WAY = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/twoWay" +MEP_BINDING_PUSH = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/push" +MEP_BINDING_PULL = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/pull" +DEFAULT_MPC = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/defaultMPC" diff --git a/as4/core/pmode.py b/as4/core/pmode.py new file mode 100644 index 0000000..1593f0b --- /dev/null +++ b/as4/core/pmode.py @@ -0,0 +1,135 @@ +"""The P-Mode: one agreement between two parties about how they exchange messages. + +A P-Mode is data only. A profile makes and checks P-Modes; building and parsing read them. +Trust anchors are not here: which certificates a deployment trusts comes from the deployment, +and a leg only pins the certificates particular to one partner. +""" + +from datetime import timedelta +from enum import StrEnum +from typing import Self + +from as4 import const +from as4.core.common import AS4PartyIdentity +from as4.core.serialisation import SerialisableCertificate +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class MEP(StrEnum): + ONE_WAY = const.MEP_ONE_WAY + TWO_WAY = const.MEP_TWO_WAY + + +class MEPBinding(StrEnum): + PUSH = const.MEP_BINDING_PUSH + PULL = const.MEP_BINDING_PULL + + +class ReceiptReplyPattern(StrEnum): + RESPONSE = "response" + CALLBACK = "callback" + + +class PModeParty(BaseModel): + model_config = ConfigDict(frozen=True) + + party_id: str + party_type: str | None = None + role: str + + @property + def identity(self) -> AS4PartyIdentity: + return AS4PartyIdentity(party_id=self.party_id, party_type=self.party_type) + + +class PModeLegProtocol(BaseModel): + model_config = ConfigDict(frozen=True) + + # The receiving MSH's endpoint. Unset when this side is the receiver. + address: str | None = None + soap_version: str = "1.2" + + +class PModeLegBusinessInfo(BaseModel): + model_config = ConfigDict(frozen=True) + + # An unset service or action matches any value, for profiles where these vary per message. + service: str | None = None + service_type: str | None = None + action: str | None = None + mpc: str = const.DEFAULT_MPC + + +class PModeLegErrorHandling(BaseModel): + model_config = ConfigDict(frozen=True) + + report_as_response: bool = True + report_sender_errors_to: str | None = None + report_receiver_errors_to: str | None = None + process_error_notify_consumer: bool = False + process_error_notify_producer: bool = False + delivery_failures_notify_producer: bool = False + + +class PModeLegSecurity(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True) + + sign_required: bool = True + signature_algorithm: str + signature_digest_algorithm: str + # A certificate pinned for this partner. Unset means the deployment's trust decides. + signature_certificate: SerialisableCertificate | None = None + + encrypt_required: bool = True + encryption_algorithm: str + encryption_minimum_strength: int | None = None + encryption_certificate: SerialisableCertificate | None = None + + required_coverage: frozenset[str] = frozenset({"messaging", "body", "payloads"}) + + send_receipt: bool = True + receipt_non_repudiation: bool = True + receipt_reply_pattern: ReceiptReplyPattern = ReceiptReplyPattern.RESPONSE + + +class PModeLeg(BaseModel): + model_config = ConfigDict(frozen=True) + + protocol: PModeLegProtocol = Field(default_factory=PModeLegProtocol) + business_info: PModeLegBusinessInfo = Field(default_factory=PModeLegBusinessInfo) + error_handling: PModeLegErrorHandling = Field(default_factory=PModeLegErrorHandling) + security: PModeLegSecurity + + +class PModeReceptionAwareness(BaseModel): + """as4 carries these but does not act on them: retrying is the caller's job.""" + + model_config = ConfigDict(frozen=True) + + enabled: bool = True + retry: bool = True + max_retries: int = Field(default=1, ge=0) + retry_interval: timedelta = timedelta(seconds=10) + duplicate_detection: bool = True + + +class PMode(BaseModel): + model_config = ConfigDict(frozen=True) + + id: str + agreement: str | None = None + mep: MEP = MEP.ONE_WAY + binding: MEPBinding = MEPBinding.PUSH + initiator: PModeParty + responder: PModeParty + leg1: PModeLeg + leg2: PModeLeg | None = None + reception_awareness: PModeReceptionAwareness = Field(default_factory=PModeReceptionAwareness) + + @model_validator(mode="after") + def legs_match_the_mep(self) -> Self: + if self.mep is MEP.ONE_WAY and self.leg2 is not None: + raise ValueError("A one-way P-Mode has a single leg") + if self.mep is MEP.TWO_WAY and self.leg2 is None: + raise ValueError("A two-way P-Mode needs a second leg") + return self diff --git a/as4/profiles/peppol/pmode.py b/as4/profiles/peppol/pmode.py new file mode 100644 index 0000000..a581e27 --- /dev/null +++ b/as4/profiles/peppol/pmode.py @@ -0,0 +1,43 @@ +from as4 import const +from as4.core.pmode import ( + MEP, + MEPBinding, + PMode, + PModeLeg, + PModeLegBusinessInfo, + PModeLegProtocol, + PModeLegSecurity, + PModeParty, +) + + +def peppol_pmode_id(initiator_id: str, responder_id: str) -> str: + """Derived P-Modes need stable ids, so an exchange can name the one it used and it can be rebuilt.""" + return f"{initiator_id}-{responder_id}" + + +def peppol_pmode(initiator_id: str, responder_id: str, address: str | None = None) -> PMode: + """Everything is fixed by the Peppol AS4 profile except who the two access points are and where to send.""" + return PMode( + id=peppol_pmode_id(initiator_id, responder_id), + agreement=const.PEPPOL_AP_PROVIDER, + mep=MEP.ONE_WAY, + binding=MEPBinding.PUSH, + initiator=PModeParty( + party_id=initiator_id, party_type=const.PEPPOL_PARTY_IDENTIFIER_TYPE, role=const.INITIATOR + ), + responder=PModeParty( + party_id=responder_id, party_type=const.PEPPOL_PARTY_IDENTIFIER_TYPE, role=const.RESPONDER + ), + leg1=PModeLeg( + protocol=PModeLegProtocol(address=address), + # The process and document type vary per message, so only the service type is fixed. + business_info=PModeLegBusinessInfo(service_type=const.CENBII_PROCID_UBL), + security=PModeLegSecurity( + signature_algorithm=const.DSIG_RSA_SHA256, + signature_digest_algorithm=const.XMLENC_SHA256, + encryption_algorithm=const.AES_128_GCM, + encryption_minimum_strength=128, + ), + ), + ) diff --git a/tests/test_pmode/test_pmode.py b/tests/test_pmode/test_pmode.py new file mode 100644 index 0000000..a889f2e --- /dev/null +++ b/tests/test_pmode/test_pmode.py @@ -0,0 +1,62 @@ +import pytest +from as4 import const +from as4.core.pmode import MEP, PMode, PModeLeg, PModeLegSecurity, PModeParty +from as4.profiles.peppol.pmode import peppol_pmode +from pydantic import ValidationError + +SECURITY = PModeLegSecurity( + signature_algorithm=const.DSIG_RSA_SHA256, + signature_digest_algorithm=const.XMLENC_SHA256, + encryption_algorithm=const.AES_128_GCM, +) +INITIATOR = PModeParty(party_id="A", role=const.INITIATOR) +RESPONDER = PModeParty(party_id="B", role=const.RESPONDER) + + +def test_one_way_by_default(): + pmode = PMode(id="p", initiator=INITIATOR, responder=RESPONDER, leg1=PModeLeg(security=SECURITY)) + assert pmode.mep is MEP.ONE_WAY + assert pmode.leg2 is None + + +def test_a_one_way_pmode_refuses_a_second_leg(): + leg = PModeLeg(security=SECURITY) + with pytest.raises(ValidationError, match="single leg"): + PMode(id="p", initiator=INITIATOR, responder=RESPONDER, leg1=leg, leg2=leg) + + +def test_a_two_way_pmode_needs_a_second_leg(): + with pytest.raises(ValidationError, match="second leg"): + PMode(id="p", mep=MEP.TWO_WAY, initiator=INITIATOR, responder=RESPONDER, leg1=PModeLeg(security=SECURITY)) + + +def test_pmode_is_frozen(): + pmode = PMode(id="p", initiator=INITIATOR, responder=RESPONDER, leg1=PModeLeg(security=SECURITY)) + with pytest.raises(ValidationError): + pmode.id = "q" + + +def test_security_has_no_algorithm_defaults(): + with pytest.raises(ValidationError): + PModeLegSecurity() # type: ignore[call-arg] + + +def test_party_identity_round_trips(): + party = PModeParty(party_id="POP000123", party_type=const.PEPPOL_PARTY_IDENTIFIER_TYPE, role=const.INITIATOR) + assert party.identity.party_id == "POP000123" + assert party.identity.party_type == const.PEPPOL_PARTY_IDENTIFIER_TYPE + + +def test_peppol_pmode_fixes_everything_but_the_parties_and_address(): + pmode = peppol_pmode("POP000123", "POP000456", "https://ap.example/as4") + assert pmode.id == "POP000123-POP000456" + assert pmode.agreement == const.PEPPOL_AP_PROVIDER + assert pmode.initiator.party_type == const.PEPPOL_PARTY_IDENTIFIER_TYPE + assert pmode.leg1.protocol.address == "https://ap.example/as4" + assert pmode.leg1.business_info.service is None + assert pmode.leg1.business_info.service_type == const.CENBII_PROCID_UBL + assert pmode.leg1.security.encryption_algorithm == const.AES_128_GCM + + +def test_peppol_pmode_is_deterministic(): + assert peppol_pmode("A", "B", "u") == peppol_pmode("A", "B", "u")