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.

267 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. @api.multi
  78. def button_set_draft(self):
  79. self.write({'state': 'draft'})
  80. # API Section
  81. @api.multi
  82. def _execute_sql_request(
  83. self, params=None, mode='fetchall', rollback=True,
  84. view_name=False, copy_options="CSV HEADER DELIMITER ';'"):
  85. """Execute a SQL request on the current database.
  86. ??? This function checks before if the user has the
  87. right to execute the request.
  88. :param params: (dict) of keys / values that will be replaced in
  89. the sql query, before executing it.
  90. :param mode: (str) result type expected. Available settings :
  91. * 'view': create a view with the select query. Extra param
  92. required 'view_name'.
  93. * 'materialized_view': create a MATERIALIZED VIEW with the
  94. select query. Extra parameter required 'view_name'.
  95. * 'fetchall': execute the select request, and return the
  96. result of 'cr.fetchall()'.
  97. * 'fetchone' : execute the select request, and return the
  98. result of 'cr.fetchone()'
  99. :param rollback: (boolean) mention if a rollback should be played after
  100. the execution of the query. Please keep this feature enabled
  101. for security reason, except if necessary.
  102. (Ignored if @mode in ('view', 'materialized_view'))
  103. :param view_name: (str) name of the view.
  104. (Ignored if @mode not in ('view', 'materialized_view'))
  105. :param copy_options: (str) mentions extra options for
  106. "COPY request STDOUT WITH xxx" request.
  107. (Ignored if @mode != 'stdout')
  108. ..note:: The following exceptions could be raised:
  109. psycopg2.ProgrammingError: Error in the SQL Request.
  110. odoo.exceptions.UserError:
  111. * 'mode' is not implemented.
  112. * materialized view is not supported by the Postgresql Server.
  113. """
  114. self.ensure_one()
  115. res = False
  116. # Check if the request is in a valid state
  117. if self.state == 'draft':
  118. raise UserError(_(
  119. "It is not allowed to execute a not checked request."))
  120. # Disable rollback if a creation of a view is asked
  121. if mode in ('view', 'materialized_view'):
  122. rollback = False
  123. # pylint: disable=sql-injection
  124. if params:
  125. query = self.query % params
  126. else:
  127. query = self.query
  128. query = query
  129. if mode in ('fetchone', 'fetchall'):
  130. pass
  131. elif mode == 'stdout':
  132. query = "COPY (%s) TO STDOUT WITH %s" % (query, copy_options)
  133. elif mode in 'view':
  134. query = "CREATE VIEW %s AS (%s);" % (query, view_name)
  135. elif mode in 'materialized_view':
  136. self._check_materialized_view_available()
  137. query = "CREATE MATERIALIZED VIEW %s AS (%s);" % (query, view_name)
  138. else:
  139. raise UserError(_("Unimplemented mode : '%s'" % mode))
  140. if rollback:
  141. rollback_name = self._create_savepoint()
  142. try:
  143. if mode == 'stdout':
  144. output = BytesIO()
  145. self.env.cr.copy_expert(query, output)
  146. res = base64.b64encode(output.getvalue())
  147. output.close()
  148. else:
  149. self.env.cr.execute(query)
  150. if mode == 'fetchall':
  151. res = self.env.cr.fetchall()
  152. elif mode == 'fetchone':
  153. res = self.env.cr.fetchone()
  154. finally:
  155. self._rollback_savepoint(rollback_name)
  156. return res
  157. # Private Section
  158. @api.model
  159. def _create_savepoint(self):
  160. rollback_name = '%s_%s' % (
  161. self._name.replace('.', '_'), uuid.uuid1().hex)
  162. # pylint: disable=sql-injection
  163. req = "SAVEPOINT %s" % (rollback_name)
  164. self.env.cr.execute(req)
  165. return rollback_name
  166. @api.model
  167. def _rollback_savepoint(self, rollback_name):
  168. # pylint: disable=sql-injection
  169. req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name)
  170. self.env.cr.execute(req)
  171. @api.model
  172. def _check_materialized_view_available(self):
  173. self.env.cr.execute("SHOW server_version;")
  174. res = self.env.cr.fetchone()[0].split('.')
  175. minor_version = float('.'.join(res[:2]))
  176. if minor_version < 9.3:
  177. raise UserError(_(
  178. "Materialized View requires PostgreSQL 9.3 or greater but"
  179. " PostgreSQL %s is currently installed.") % (minor_version))
  180. @api.multi
  181. def _clean_query(self):
  182. self.ensure_one()
  183. query = self.query.strip()
  184. while query[-1] == ';':
  185. query = query[:-1]
  186. self.query = query
  187. @api.multi
  188. def _check_prohibited_words(self):
  189. """Check if the query contains prohibited words, to avoid maliscious
  190. SQL requests"""
  191. self.ensure_one()
  192. query = self.query.lower()
  193. for word in self.PROHIBITED_WORDS:
  194. expr = r'\b%s\b' % word
  195. is_not_safe = re.search(expr, query)
  196. if is_not_safe:
  197. raise UserError(_(
  198. "The query is not allowed because it contains unsafe word"
  199. " '%s'") % (word))
  200. @api.multi
  201. def _check_execution(self):
  202. """Ensure that the query is valid, trying to execute it. A rollback
  203. is done after."""
  204. self.ensure_one()
  205. query = self._prepare_request_check_execution()
  206. rollback_name = self._create_savepoint()
  207. res = False
  208. try:
  209. self.env.cr.execute(query)
  210. res = self._hook_executed_request()
  211. except ProgrammingError as e:
  212. logger.exception("Failed query: %s", query)
  213. raise UserError(
  214. _("The SQL query is not valid:\n\n %s") % e)
  215. finally:
  216. self._rollback_savepoint(rollback_name)
  217. return res
  218. @api.multi
  219. def _prepare_request_check_execution(self):
  220. """Overload me to replace some part of the query, if it contains
  221. parameters"""
  222. self.ensure_one()
  223. return self.query
  224. def _hook_executed_request(self):
  225. """Overload me to insert custom code, when the SQL request has
  226. been executed, before the rollback.
  227. """
  228. self.ensure_one()
  229. return False