Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ jobs:

- name: Install uv
uses: astral-sh/setup-uv@v6
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: uv sync
Expand Down
4 changes: 2 additions & 2 deletions src/ksef/auth/xades.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging
import time
import uuid
from typing import Mapping, Optional, Tuple
from typing import Mapping, Optional, Tuple, Union
from urllib.parse import urljoin

import requests
Expand Down Expand Up @@ -185,7 +185,7 @@ def _get_challenge(self) -> AuthChallenge:
raise error
return AuthChallenge.from_dict(response.json())

def _load_private_key(self) -> "rsa.RSAPrivateKey | ec.EllipticCurvePrivateKey":
def _load_private_key(self) -> Union[rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey]:
"""Load the private key (RSA or EC) from PEM or DER bytes."""
try:
key = serialization.load_pem_private_key(
Expand Down
23 changes: 20 additions & 3 deletions src/ksef/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,14 @@ def send_invoice(self, nip: str, invoice: Invoice) -> SendInvoiceResponse:
This convenience method opens a session, sends the invoice, and closes
the session automatically.

A failure while closing the session (network error or HTTP error
response) is logged and does not propagate. Once the invoice has been
accepted by ``send_invoice_in_session()`` it exists in KSeF, so raising
would make callers treat a delivered invoice as failed and retry it,
producing a duplicate. KSeF closes abandoned sessions on its own.
Likewise, if sending fails, the original send error is raised rather
than being masked by a close failure.

Parameters
----------
nip : str
Expand All @@ -324,10 +332,19 @@ def send_invoice(self, nip: str, invoice: Invoice) -> SendInvoiceResponse:
session_context=session_context,
invoice=invoice,
)
return send_response
finally:
# Always close session
self.close_session(session_context)
# Always close session, but never let a close failure mask the
# outcome of the send (successful response or original exception).
try:
self.close_session(session_context)
except requests.RequestException:
logger.warning(
"Failed to close KSeF session %s; the send outcome is unaffected",
session_context.reference_number,
exc_info=True,
)

return send_response

def get_session_status(self, session_reference_number: str) -> SessionStatusResponse:
"""Get the status of a session.
Expand Down
92 changes: 92 additions & 0 deletions tests/test_client_invoices.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from decimal import Decimal
from unittest.mock import MagicMock

import pytest
import requests
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
Expand Down Expand Up @@ -321,6 +323,96 @@ def test_send_invoice_full_flow(mocked_responses: RequestsMock) -> None:
assert len(mocked_responses.calls) == 4 # noqa: PLR2004


def _mock_open_session(mocked_responses: RequestsMock) -> None:
cert_der, _ = _generate_test_certificate()
_mock_public_key_certs(mocked_responses, cert_der)
mocked_responses.add(
url=f"{BASE}{URL_SESSIONS_ONLINE}",
method="POST",
content_type="application/json",
json={"referenceNumber": "session-ref-123"},
)


def _mock_send_invoice_ok(mocked_responses: RequestsMock) -> None:
mocked_responses.add(
url=f"{BASE}sessions/online/session-ref-123/invoices",
method="POST",
status=202,
content_type="application/json",
json={"referenceNumber": "invoice-ref-456"},
)


def test_send_invoice_returns_response_when_close_connection_fails(
mocked_responses: RequestsMock,
) -> None:
"""A network error on close must not discard an already-accepted invoice."""
_mock_open_session(mocked_responses)
_mock_send_invoice_ok(mocked_responses)
mocked_responses.add(
url=f"{BASE}sessions/online/session-ref-123/close",
method="POST",
body=requests.exceptions.ConnectionError("Connection reset by peer"),
)

client = Client(authorization=_create_mock_authorization(), environment=Environment.TEST)
response = client.send_invoice(nip="1234567890", invoice=_create_test_invoice())

assert isinstance(response, SendInvoiceResponse)
assert response.reference_number == "invoice-ref-456"
assert response.session_reference_number == "session-ref-123"
assert mocked_responses.calls[-1].request.url == f"{BASE}sessions/online/session-ref-123/close"


def test_send_invoice_returns_response_when_close_returns_http_error(
mocked_responses: RequestsMock,
) -> None:
"""An HTTP error response on close must not discard an already-accepted invoice."""
_mock_open_session(mocked_responses)
_mock_send_invoice_ok(mocked_responses)
mocked_responses.add(
url=f"{BASE}sessions/online/session-ref-123/close",
method="POST",
status=500,
content_type="application/json",
json={"exception": "internal error"},
)

client = Client(authorization=_create_mock_authorization(), environment=Environment.TEST)
response = client.send_invoice(nip="1234567890", invoice=_create_test_invoice())

assert response.reference_number == "invoice-ref-456"


def test_send_invoice_raises_send_error_not_close_error(
mocked_responses: RequestsMock,
) -> None:
"""When sending fails, the send error is raised, not a subsequent close error."""
_mock_open_session(mocked_responses)
mocked_responses.add(
url=f"{BASE}sessions/online/session-ref-123/invoices",
method="POST",
status=400,
content_type="application/json",
json={"exception": "invalid invoice"},
)
mocked_responses.add(
url=f"{BASE}sessions/online/session-ref-123/close",
method="POST",
body=requests.exceptions.ConnectionError("Connection reset by peer"),
)

client = Client(authorization=_create_mock_authorization(), environment=Environment.TEST)

with pytest.raises(requests.exceptions.HTTPError) as exc_info:
client.send_invoice(nip="1234567890", invoice=_create_test_invoice())

assert exc_info.value.response.status_code == 400 # noqa: PLR2004
# Close was still attempted.
assert mocked_responses.calls[-1].request.url == f"{BASE}sessions/online/session-ref-123/close"


def test_send_invoice_sets_session_reference_number(mocked_responses: RequestsMock) -> None:
"""Test that send_invoice_in_session sets session_reference_number."""
session_context = SessionContext(
Expand Down
Loading
Loading