[FIX] docuseal_signing: harden template copies, API errors and emails
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m31s
tests / test (pull_request) Successful in 52s

- 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:
2026-11-09 17:35:19 +01:00
parent 87653552b1
commit fddc2e5c4b
7 changed files with 238 additions and 27 deletions

View File

@@ -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