You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
8.9 KiB

  1. # Copyright (C) 2015 Akretion (<http://www.akretion.com>)
  2. # Copyright (C) 2017 - Today: GRAP (http://www.grap.coop)
  3. # @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import re
  6. import uuid
  7. import logging
  8. from io import BytesIO
  9. import base64
  10. from psycopg2 import ProgrammingError
  11. from odoo import _, api, fields, models
  12. from odoo.exceptions import UserError
  13. logger = logging.getLogger(__name__)
  14. class SQLRequestMixin(models.AbstractModel):
  15. _name = 'sql.request.mixin'
  16. _description = 'SQL Request Mixin'
  17. _clean_query_enabled = True
  18. _check_prohibited_words_enabled = True
  19. _check_execution_enabled = True
  20. _sql_request_groups_relation = False
  21. _sql_request_users_relation = False
  22. STATE_SELECTION = [
  23. ('draft', 'Draft'),
  24. ('sql_valid', 'SQL Valid'),
  25. ]
  26. PROHIBITED_WORDS = [
  27. 'delete',
  28. 'drop',
  29. 'insert',
  30. 'alter',
  31. 'truncate',
  32. 'execute',
  33. 'create',
  34. 'update',
  35. 'ir_config_parameter',
  36. ]
  37. # Default Section
  38. @api.model
  39. def _default_group_ids(self):
  40. ir_model_obj = self.env['ir.model.data']
  41. return [ir_model_obj.xmlid_to_res_id(
  42. 'sql_request_abstract.group_sql_request_user')]
  43. @api.model
  44. def _default_user_ids(self):
  45. return []
  46. # Columns Section
  47. name = fields.Char('Name', required=True)
  48. query = fields.Text(
  49. string='Query', required=True, help="You can't use the following words"
  50. ": DELETE, DROP, CREATE, INSERT, ALTER, TRUNCATE, EXECUTE, UPDATE.")
  51. state = fields.Selection(
  52. string='State', selection=STATE_SELECTION, default='draft',
  53. help="State of the Request:\n"
  54. " * 'Draft': Not tested\n"
  55. " * 'SQL Valid': SQL Request has been checked and is valid")
  56. group_ids = fields.Many2many(
  57. comodel_name='res.groups', string='Allowed Groups',
  58. relation=_sql_request_groups_relation,
  59. column1='sql_id', column2='group_id',
  60. default=_default_group_ids)
  61. user_ids = fields.Many2many(
  62. comodel_name='res.users', string='Allowed Users',
  63. relation=_sql_request_users_relation,
  64. column1='sql_id', column2='user_id',
  65. default=_default_user_ids)
  66. # Action Section
  67. @api.multi
  68. def button_validate_sql_expression(self):
  69. for item in self:
  70. if item._clean_query_enabled:
  71. item._clean_query()
  72. if item._check_prohibited_words_enabled:
  73. item._check_prohibited_words()
  74. if item._check_execution_enabled:
  75. item._check_execution()
  76. item.state = 'sql_valid'
  77. return True
  78. @api.multi
  79. def button_set_draft(self):
  80. self.write({'state': 'draft'})
  81. # API Section
  82. @api.multi
  83. def _execute_sql_request(
  84. self, params=None, mode='fetchall', rollback=True,
  85. view_name=False, copy_options="CSV HEADER DELIMITER ';'"):
  86. """Execute a SQL request on the current database.
  87. ??? This function checks before if the user has the
  88. right to execute the request.
  89. :param params: (dict) of keys / values that will be replaced in
  90. the sql query, before executing it.
  91. :param mode: (str) result type expected. Available settings :
  92. * 'view': create a view with the select query. Extra param
  93. required 'view_name'.
  94. * 'materialized_view': create a MATERIALIZED VIEW with the
  95. select query. Extra parameter required 'view_name'.
  96. * 'fetchall': execute the select request, and return the
  97. result of 'cr.fetchall()'.
  98. * 'fetchone' : execute the select request, and return the
  99. result of 'cr.fetchone()'
  100. :param rollback: (boolean) mention if a rollback should be played after
  101. the execution of the query. Please keep this feature enabled
  102. for security reason, except if necessary.
  103. (Ignored if @mode in ('view', 'materialized_view'))
  104. :param view_name: (str) name of the view.
  105. (Ignored if @mode not in ('view', 'materialized_view'))
  106. :param copy_options: (str) mentions extra options for
  107. "COPY request STDOUT WITH xxx" request.
  108. (Ignored if @mode != 'stdout')
  109. ..note:: The following exceptions could be raised:
  110. psycopg2.ProgrammingError: Error in the SQL Request.
  111. odoo.exceptions.UserError:
  112. * 'mode' is not implemented.
  113. * materialized view is not supported by the Postgresql Server.
  114. """
  115. self.ensure_one()
  116. res = False
  117. # Check if the request is in a valid state
  118. if self.state == 'draft':
  119. raise UserError(_(
  120. "It is not allowed to execute a not checked request."))
  121. # Disable rollback if a creation of a view is asked
  122. if mode in ('view', 'materialized_view'):
  123. rollback = False
  124. # pylint: disable=sql-injection
  125. if params:
  126. query = self.query % params
  127. else:
  128. query = self.query
  129. query = query
  130. if mode in ('fetchone', 'fetchall'):
  131. pass
  132. elif mode == 'stdout':
  133. query = "COPY (%s) TO STDOUT WITH %s" % (query, copy_options)
  134. elif mode in 'view':
  135. query = "CREATE VIEW %s AS (%s);" % (query, view_name)
  136. elif mode in 'materialized_view':
  137. self._check_materialized_view_available()
  138. query = "CREATE MATERIALIZED VIEW %s AS (%s);" % (query, view_name)
  139. else:
  140. raise UserError(_("Unimplemented mode : '%s'" % mode))
  141. if rollback:
  142. rollback_name = self._create_savepoint()
  143. try:
  144. if mode == 'stdout':
  145. output = BytesIO()
  146. self.env.cr.copy_expert(query, output)
  147. res = base64.b64encode(output.getvalue())
  148. output.close()
  149. else:
  150. self.env.cr.execute(query)
  151. if mode == 'fetchall':
  152. res = self.env.cr.fetchall()
  153. elif mode == 'fetchone':
  154. res = self.env.cr.fetchone()
  155. finally:
  156. self._rollback_savepoint(rollback_name)
  157. return res
  158. # Private Section
  159. @api.model
  160. def _create_savepoint(self):
  161. rollback_name = '%s_%s' % (
  162. self._name.replace('.', '_'), uuid.uuid1().hex)
  163. # pylint: disable=sql-injection
  164. req = "SAVEPOINT %s" % (rollback_name)
  165. self.env.cr.execute(req)
  166. return rollback_name
  167. @api.model
  168. def _rollback_savepoint(self, rollback_name):
  169. # pylint: disable=sql-injection
  170. req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name)
  171. self.env.cr.execute(req)
  172. @api.model
  173. def _check_materialized_view_available(self):
  174. self.env.cr.execute("SHOW server_version;")
  175. res = self.env.cr.fetchone()[0].split('.')
  176. minor_version = float('.'.join(res[:2]))
  177. if minor_version < 9.3:
  178. raise UserError(_(
  179. "Materialized View requires PostgreSQL 9.3 or greater but"
  180. " PostgreSQL %s is currently installed.") % (minor_version))
  181. @api.multi
  182. def _clean_query(self):
  183. self.ensure_one()
  184. query = self.query.strip()
  185. while query[-1] == ';':
  186. query = query[:-1]
  187. self.query = query
  188. @api.multi
  189. def _check_prohibited_words(self):
  190. """Check if the query contains prohibited words, to avoid maliscious
  191. SQL requests"""
  192. self.ensure_one()
  193. query = self.query.lower()
  194. for word in self.PROHIBITED_WORDS:
  195. expr = r'\b%s\b' % word
  196. is_not_safe = re.search(expr, query)
  197. if is_not_safe:
  198. raise UserError(_(
  199. "The query is not allowed because it contains unsafe word"
  200. " '%s'") % (word))
  201. @api.multi
  202. def _check_execution(self):
  203. """Ensure that the query is valid, trying to execute it. A rollback
  204. is done after."""
  205. self.ensure_one()
  206. query = self._prepare_request_check_execution()
  207. rollback_name = self._create_savepoint()
  208. res = False
  209. try:
  210. self.env.cr.execute(query)
  211. res = self._hook_executed_request()
  212. except ProgrammingError as e:
  213. logger.exception("Failed query: %s", query)
  214. raise UserError(
  215. _("The SQL query is not valid:\n\n %s") % e)
  216. finally:
  217. self._rollback_savepoint(rollback_name)
  218. return res
  219. @api.multi
  220. def _prepare_request_check_execution(self):
  221. """Overload me to replace some part of the query, if it contains
  222. parameters"""
  223. self.ensure_one()
  224. return self.query
  225. def _hook_executed_request(self):
  226. """Overload me to insert custom code, when the SQL request has
  227. been executed, before the rollback.
  228. """
  229. self.ensure_one()
  230. return False