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.

262 lines
8.8 KiB

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