[FIX] docuseal_signing: harden template copies, API errors and emails
- Do not copy the contextual action nor the submitter role with a template: a copy sharing the action would rewrite or delete the original's. - Make the template ID read-only once fetched from Docuseal: another Docuseal template needs a new entry. - Report an invalid API URL or token, an unexpected (non-JSON) response and a connection dropped mid-response as a readable UserError. - Refuse to email a signature request to contacts without a valid email address (email_normalize), before any call to Docuseal. - Stop logging the field values and the Docuseal response, which hold personal data and the signing links. - Prevent adding mapping lines by hand: they come from Docuseal only. Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,7 +15,9 @@ signatures from partners in a few clicks.
|
||||
- **Field mapping** (`docuseal.template.field`): map each Docuseal
|
||||
field of the selected role to a `res.partner` field. Fetching again
|
||||
keeps the existing mappings; changing the role loads the fields of
|
||||
the new role from Docuseal with an empty mapping. Fields are kept in
|
||||
the new role from Docuseal with an empty mapping (with a warning in
|
||||
the form). Once fetched, the template ID is read-only: another
|
||||
Docuseal template needs a new entry. Fields are kept in
|
||||
the order returned by the Docuseal API (reorderable with drag &
|
||||
drop). Values are
|
||||
pre-filled at submission time and locked so the signer cannot change
|
||||
@@ -65,7 +67,8 @@ Behavior of both calls:
|
||||
|
||||
- One Docuseal submission is created per partner, using the template's
|
||||
Docuseal `template_id` and `submitter_role_id`; the partner's `name`
|
||||
and `email` identify the submitter.
|
||||
and `email` identify the submitter. When the request is emailed, every
|
||||
partner must have an email address: otherwise nothing is sent.
|
||||
- Each mapped Docuseal field is pre-filled from the partner field set
|
||||
in `docuseal.template.field`. Non-empty values are locked
|
||||
(`readonly=True`) so the signer cannot change them; empty values
|
||||
@@ -75,7 +78,8 @@ Behavior of both calls:
|
||||
their human-readable label.
|
||||
- Both methods return the list of Docuseal API responses (one dict per
|
||||
submission). A missing API token or a Docuseal error (with the
|
||||
explanation sent by Docuseal) raises a `UserError`; with several
|
||||
explanation sent by Docuseal), an invalid API URL or an unreachable
|
||||
instance raises a `UserError`; with several
|
||||
partners, the submissions created before the error are not rolled
|
||||
back in Docuseal.
|
||||
|
||||
|
||||
@@ -235,11 +235,14 @@ msgstr "ID du template"
|
||||
#. module: docuseal_signing
|
||||
#: model:ir.model.fields,help:docuseal_signing.field_docuseal_template__template_id
|
||||
msgid ""
|
||||
"You can find the template id in the URL when you have selected the template "
|
||||
"in Docuseal."
|
||||
"You can find the template id in the URL when you have selected the "
|
||||
"template in Docuseal. It cannot be changed once fetched from Docuseal: to "
|
||||
"use another template, create a new entry."
|
||||
msgstr ""
|
||||
"Vous trouverez l'identifiant du template dans l'URL après avoir sélectionné "
|
||||
"le template dans Docuseal."
|
||||
"le template dans Docuseal. Il ne peut plus être modifié une fois rapatrié "
|
||||
"depuis Docuseal : pour utiliser un autre template, veuillez créer une "
|
||||
"nouvelle entrée."
|
||||
|
||||
#. module: docuseal_signing
|
||||
#: model:ir.model.fields,field_description:docuseal_signing.field_docuseal_template_field__partner_field_id
|
||||
@@ -341,3 +344,39 @@ msgstr "Signature demandée"
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid "The signature request has been sent to %(partner)s."
|
||||
msgstr "La demande de signature a été envoyée à %(partner)s."
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid "The Docuseal API URL %(url)s is invalid: %(error)s"
|
||||
msgstr "L'URL de l'API Docuseal %(url)s est invalide : %(error)s"
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid ""
|
||||
"Docuseal returned an unexpected response from %(url)s. "
|
||||
"Check the Docuseal API URL in the General Settings."
|
||||
msgstr ""
|
||||
"Docuseal a renvoyé une réponse inattendue depuis %(url)s. Vérifiez "
|
||||
"l'URL de l'API Docuseal dans les Paramètres généraux."
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid ""
|
||||
"The signature request cannot be emailed to contacts "
|
||||
"without a valid email address: %(partners)s"
|
||||
msgstr ""
|
||||
"La demande de signature ne peut pas être envoyée par e-mail aux contacts "
|
||||
"sans adresse e-mail valide : %(partners)s"
|
||||
|
||||
#. module: docuseal_signing
|
||||
#. odoo-python
|
||||
#: code:addons/docuseal_signing/models/docuseal_template.py:0
|
||||
msgid ""
|
||||
"The request to Docuseal could not be sent: %(error)s. "
|
||||
"Check the Docuseal API token in the General Settings."
|
||||
msgstr ""
|
||||
"La requête vers Docuseal n'a pas pu être envoyée : %(error)s. "
|
||||
"Vérifiez le token API Docuseal dans les Paramètres généraux."
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import http.client
|
||||
import json
|
||||
import logging
|
||||
import urllib.error
|
||||
@@ -5,6 +6,7 @@ import urllib.request
|
||||
|
||||
from odoo import Command, _, api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
from odoo.tools.mail import email_normalize
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -18,8 +20,10 @@ class DocusealTemplate(models.Model):
|
||||
name = fields.Char(string="Name")
|
||||
template_id = fields.Integer(
|
||||
string="Template ID",
|
||||
help="You can find the template id in the URL when you have selected the template in Docuseal.",
|
||||
required=True
|
||||
help="You can find the template id in the URL when you have selected "
|
||||
"the template in Docuseal. It cannot be changed once fetched from "
|
||||
"Docuseal: to use another template, create a new entry.",
|
||||
required=True,
|
||||
)
|
||||
role_ids = fields.One2many(
|
||||
comodel_name="docuseal.template.role",
|
||||
@@ -30,6 +34,8 @@ class DocusealTemplate(models.Model):
|
||||
comodel_name="docuseal.template.role",
|
||||
string="Submitter role",
|
||||
domain="[('template_id', '=', id)]",
|
||||
# Roles belong to their template and are not copied with it.
|
||||
copy=False,
|
||||
help="Submitter role of the Docuseal template that the contact "
|
||||
"signs as. The available roles are fetched from Docuseal.",
|
||||
)
|
||||
@@ -43,6 +49,8 @@ class DocusealTemplate(models.Model):
|
||||
string="Server action",
|
||||
readonly=True,
|
||||
ondelete="set null",
|
||||
# A copy sharing the action would rewrite or delete the original's.
|
||||
copy=False,
|
||||
)
|
||||
|
||||
def _docuseal_request(self, path, payload=None):
|
||||
@@ -66,12 +74,22 @@ class DocusealTemplate(models.Model):
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(
|
||||
f"{api_url}{path}", data=data, headers=headers
|
||||
)
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
f"{api_url}{path}", data=data, headers=headers
|
||||
)
|
||||
except ValueError as err:
|
||||
# Raised by urllib for a URL without scheme or host.
|
||||
raise UserError(
|
||||
_(
|
||||
"The Docuseal API URL %(url)s is invalid: %(error)s",
|
||||
url=api_url,
|
||||
error=err,
|
||||
)
|
||||
) from err
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
body = resp.read()
|
||||
except urllib.error.HTTPError as err:
|
||||
raise UserError(
|
||||
_(
|
||||
@@ -80,12 +98,33 @@ class DocusealTemplate(models.Model):
|
||||
detail=self._docuseal_error_detail(err),
|
||||
)
|
||||
) from err
|
||||
except (urllib.error.URLError, TimeoutError) as err:
|
||||
except ValueError as err:
|
||||
# Raised by http.client for an invalid header value, such as an
|
||||
# API token pasted with a line break or a non-latin-1 character.
|
||||
raise UserError(
|
||||
_(
|
||||
"The request to Docuseal could not be sent: %(error)s. "
|
||||
"Check the Docuseal API token in the General Settings.",
|
||||
error=err,
|
||||
)
|
||||
) from err
|
||||
except (OSError, http.client.HTTPException) as err:
|
||||
# URLError, timeouts and connections dropped mid-response.
|
||||
raise UserError(
|
||||
_(
|
||||
"Docuseal could not be reached at %(url)s: %(error)s",
|
||||
url=api_url,
|
||||
error=getattr(err, "reason", err),
|
||||
error=str(getattr(err, "reason", err)) or type(err).__name__,
|
||||
)
|
||||
) from err
|
||||
try:
|
||||
return json.loads(body.decode())
|
||||
except ValueError as err:
|
||||
raise UserError(
|
||||
_(
|
||||
"Docuseal returned an unexpected response from %(url)s. "
|
||||
"Check the Docuseal API URL in the General Settings.",
|
||||
url=api_url,
|
||||
)
|
||||
) from err
|
||||
|
||||
@@ -287,6 +326,21 @@ class DocusealTemplate(models.Model):
|
||||
|
||||
def _create_submissions(self, partners, send_email=True):
|
||||
self.ensure_one()
|
||||
if send_email:
|
||||
# Check every partner before the first call, so that no request
|
||||
# is sent when one of them cannot receive it.
|
||||
# email_normalize refuses empty, malformed and multiple addresses.
|
||||
without_email = partners.filtered(
|
||||
lambda partner: not email_normalize(partner.email)
|
||||
)
|
||||
if without_email:
|
||||
raise UserError(
|
||||
_(
|
||||
"The signature request cannot be emailed to contacts "
|
||||
"without a valid email address: %(partners)s",
|
||||
partners=", ".join(without_email.mapped("display_name")),
|
||||
)
|
||||
)
|
||||
|
||||
results = []
|
||||
for partner in partners:
|
||||
@@ -323,21 +377,18 @@ class DocusealTemplate(models.Model):
|
||||
"submitters": [{
|
||||
"name": partner.name,
|
||||
"role": self.submitter_role_id.name or "",
|
||||
"email": partner.email or "",
|
||||
"email": email_normalize(partner.email) or partner.email or "",
|
||||
"fields": submitter_fields,
|
||||
}],
|
||||
}
|
||||
# Do not log the field values (personal data) nor the response:
|
||||
# it contains the signing links of the submitters.
|
||||
_logger.info(
|
||||
"Docuseal: creating submission for %s with template %s "
|
||||
"(send_email=%s), fields: %s",
|
||||
partner.name,
|
||||
"Docuseal: creating submission for res.partner %s with "
|
||||
"template %s (send_email=%s)",
|
||||
partner.id,
|
||||
self.template_id,
|
||||
send_email,
|
||||
submitter_fields,
|
||||
)
|
||||
result = self._docuseal_request("/api/submissions", payload)
|
||||
_logger.info(
|
||||
"Docuseal submission created for %s: %s", partner.name, result
|
||||
)
|
||||
results.append(result)
|
||||
results.append(self._docuseal_request("/api/submissions", payload))
|
||||
return results
|
||||
|
||||
@@ -223,3 +223,15 @@ class TestFetchFields(DocusealApiMockMixin, TransactionCase):
|
||||
self.env["ir.config_parameter"].sudo().set_param("docuseal.api_token", "")
|
||||
with self.assertRaises(UserError):
|
||||
self.template.action_fetch_fields()
|
||||
|
||||
def test_template_id_is_readonly_once_fetched(self):
|
||||
"""The template ID can be set on a new entry, and becomes read-only
|
||||
once roles have been fetched from Docuseal."""
|
||||
form = Form(self.env["docuseal.template"])
|
||||
form.template_id = 1000
|
||||
new_template = form.save()
|
||||
|
||||
with Form(new_template) as form:
|
||||
self.assertFalse(form._get_modifier("template_id", "readonly"))
|
||||
with Form(self.template) as form:
|
||||
self.assertTrue(form._get_modifier("template_id", "readonly"))
|
||||
|
||||
@@ -98,3 +98,25 @@ class TestServerAction(DocusealApiMockMixin, TransactionCase):
|
||||
):
|
||||
self._run_action(template, partners, self.env.user)
|
||||
self.assertFalse(self.requests)
|
||||
|
||||
def test_copy_does_not_share_action_or_role(self):
|
||||
"""A duplicated template gets neither the contextual action nor
|
||||
the role of the original, so it cannot rewrite or delete them."""
|
||||
template = self.env["docuseal.template"].create({
|
||||
"name": "Contract",
|
||||
"template_id": 791,
|
||||
})
|
||||
template.submitter_role_id = self.env["docuseal.template.role"].create({
|
||||
"template_id": template.id,
|
||||
"name": "Signer",
|
||||
})
|
||||
template.action_create_server_action()
|
||||
action = template.server_action_id
|
||||
|
||||
duplicate = template.copy()
|
||||
self.assertFalse(duplicate.server_action_id)
|
||||
self.assertFalse(duplicate.submitter_role_id)
|
||||
|
||||
duplicate.unlink()
|
||||
self.assertTrue(action.exists())
|
||||
self.assertEqual(template.server_action_id, action)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import urllib.error
|
||||
@@ -119,7 +120,10 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
|
||||
def test_one_submission_per_partner(self):
|
||||
"""Each partner gets its own submission with a single submitter."""
|
||||
self._set_api_config()
|
||||
partner2 = self.env["res.partner"].create({"name": "Alex Martin"})
|
||||
partner2 = self.env["res.partner"].create({
|
||||
"name": "Alex Martin",
|
||||
"email": "alex@example.com",
|
||||
})
|
||||
with self._mock_api({"id": 57}):
|
||||
self.template._create_submissions(self.partner | partner2)
|
||||
|
||||
@@ -169,3 +173,78 @@ class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
|
||||
side_effect=error,
|
||||
), self.assertRaisesRegex(UserError, "422: Role not found"):
|
||||
self.template._create_submissions(self.partner)
|
||||
|
||||
def test_partner_without_email_is_refused(self):
|
||||
"""No request is sent when a contact cannot receive the email,
|
||||
even if the other contacts can."""
|
||||
self._set_api_config()
|
||||
no_email = self.env["res.partner"].create({"name": "Sam Leroy"})
|
||||
with self._mock_api({"id": 62}), self.assertRaisesRegex(
|
||||
UserError, "Sam Leroy"
|
||||
):
|
||||
self.template._create_submissions(self.partner | no_email)
|
||||
self.assertFalse(self.requests)
|
||||
|
||||
# A draft is not emailed: no email address is required.
|
||||
with self._mock_api({"id": 63}):
|
||||
self.template._create_draft_submissions(no_email)
|
||||
self.assertEqual(len(self.requests), 1)
|
||||
|
||||
def _assert_user_error(self, regex, **urlopen_patch):
|
||||
with mock.patch.object(
|
||||
docuseal_template_module.urllib.request, "urlopen", **urlopen_patch
|
||||
), self.assertRaisesRegex(UserError, regex):
|
||||
self.template._create_submissions(self.partner)
|
||||
|
||||
def test_invalid_api_url_raises_user_error(self):
|
||||
"""An API URL without scheme is reported, not a traceback."""
|
||||
self._set_api_config(api_url="sign.example.com")
|
||||
with self.assertRaisesRegex(UserError, "is invalid"):
|
||||
self.template._create_submissions(self.partner)
|
||||
|
||||
def test_unexpected_response_raises_user_error(self):
|
||||
"""A non-JSON response (proxy, login page) is reported."""
|
||||
self._set_api_config()
|
||||
resp = mock.MagicMock()
|
||||
resp.read.return_value = b"<html>Login</html>"
|
||||
context = mock.MagicMock()
|
||||
context.__enter__.return_value = resp
|
||||
self._assert_user_error("unexpected response", return_value=context)
|
||||
|
||||
def test_dropped_connection_raises_user_error(self):
|
||||
"""A connection dropped mid-response is reported."""
|
||||
self._set_api_config()
|
||||
self._assert_user_error(
|
||||
"could not be reached",
|
||||
side_effect=http.client.RemoteDisconnected("closed"),
|
||||
)
|
||||
self._assert_user_error(
|
||||
"could not be reached",
|
||||
side_effect=http.client.IncompleteRead(b""),
|
||||
)
|
||||
|
||||
def test_malformed_email_is_refused(self):
|
||||
"""Malformed and multiple email addresses are refused too."""
|
||||
self._set_api_config()
|
||||
for email in (" ", "not-an-email", "a@example.com; b@example.com"):
|
||||
self.partner.email = email
|
||||
with self._mock_api({"id": 64}), self.assertRaisesRegex(
|
||||
UserError, "valid email"
|
||||
):
|
||||
self.template._create_submissions(self.partner)
|
||||
self.assertFalse(self.requests)
|
||||
|
||||
def test_invalid_token_raises_user_error(self):
|
||||
"""A token pasted with a line break is reported as a token problem,
|
||||
not as an invalid URL."""
|
||||
self._set_api_config()
|
||||
self.env["ir.config_parameter"].sudo().set_param(
|
||||
"docuseal.api_token", "abc\ndef"
|
||||
)
|
||||
with self.assertRaisesRegex(UserError, "API token"):
|
||||
self.template._create_submissions(self.partner)
|
||||
|
||||
def test_error_without_message_names_the_exception(self):
|
||||
"""An exception without message still explains what happened."""
|
||||
self._set_api_config()
|
||||
self._assert_user_error("TimeoutError", side_effect=TimeoutError())
|
||||
|
||||
@@ -39,7 +39,10 @@
|
||||
<sheet>
|
||||
<group>
|
||||
<field name="name"/>
|
||||
<field name="template_id"/>
|
||||
<!-- Roles only exist once fetched from Docuseal: from
|
||||
then on, another template needs a new entry. -->
|
||||
<field name="role_ids" invisible="1"/>
|
||||
<field name="template_id" readonly="role_ids"/>
|
||||
<button
|
||||
colspan="2"
|
||||
name="action_fetch_fields"
|
||||
@@ -55,7 +58,8 @@
|
||||
/>
|
||||
</group>
|
||||
<field name="field_ids" string="Field mapping">
|
||||
<list editable="bottom">
|
||||
<!-- Lines come from Docuseal only: no manual creation. -->
|
||||
<list editable="bottom" create="0">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field
|
||||
name="docuseal_field_name"
|
||||
|
||||
Reference in New Issue
Block a user