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.

263 lines
8.8 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. from io import BytesIO
  8. import base64
  9. from psycopg2 import ProgrammingError
  10. from odoo import _, api, fields, models
  11. from odoo.exceptions import UserError
  12. class SQLRequestMixin(models.AbstractModel):
  13. _name = 'sql.request.mixin'
  14. _description = '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. # pylint: disable=sql-injection
  122. if params:
  123. query = self.query % params
  124. else:
  125. query = self.query
  126. query = query
  127. if mode in ('fetchone', 'fetchall'):
  128. pass
  129. elif mode == 'stdout':
  130. query = "COPY (%s) TO STDOUT WITH %s" % (query, copy_options)
  131. elif mode in 'view':
  132. query = "CREATE VIEW %s AS (%s);" % (query, view_name)
  133. elif mode in 'materialized_view':
  134. self._check_materialized_view_available()
  135. query = "CREATE MATERIALIZED VIEW %s AS (%s);" % (query, view_name)
  136. else:
  137. raise UserError(_("Unimplemented mode : '%s'" % mode))
  138. if rollback:
  139. rollback_name = self._create_savepoint()
  140. try:
  141. if mode == 'stdout':
  142. output = BytesIO()
  143. self.env.cr.copy_expert(query, output)
  144. res = base64.b64encode(output.getvalue())
  145. output.close()
  146. else:
  147. self.env.cr.execute(query)
  148. if mode == 'fetchall':
  149. res = self.env.cr.fetchall()
  150. elif mode == 'fetchone':
  151. res = self.env.cr.fetchone()
  152. finally:
  153. self._rollback_savepoint(rollback_name)
  154. return res
  155. # Private Section
  156. @api.model
  157. def _create_savepoint(self):
  158. rollback_name = '%s_%s' % (
  159. self._name.replace('.', '_'), uuid.uuid1().hex)
  160. # pylint: disable=sql-injection
  161. req = "SAVEPOINT %s" % (rollback_name)
  162. self.env.cr.execute(req)
  163. return rollback_name
  164. @api.model
  165. def _rollback_savepoint(self, rollback_name):
  166. # pylint: disable=sql-injection
  167. req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name)
  168. self.env.cr.execute(req)
  169. @api.model
  170. def _check_materialized_view_available(self):
  171. self.env.cr.execute("SHOW server_version;")
  172. res = self.env.cr.fetchone()[0].split('.')
  173. minor_version = float('.'.join(res[:2]))
  174. if minor_version < 9.3:
  175. raise UserError(_(
  176. "Materialized View requires PostgreSQL 9.3 or greater but"
  177. " PostgreSQL %s is currently installed.") % (minor_version))
  178. @api.multi
  179. def _clean_query(self):
  180. self.ensure_one()
  181. query = self.query.strip()
  182. while query[-1] == ';':
  183. query = query[:-1]
  184. self.query = query
  185. @api.multi
  186. def _check_prohibited_words(self):
  187. """Check if the query contains prohibited words, to avoid maliscious
  188. SQL requests"""
  189. self.ensure_one()
  190. query = self.query.lower()
  191. for word in self.PROHIBITED_WORDS:
  192. expr = r'\b%s\b' % word
  193. is_not_safe = re.search(expr, query)
  194. if is_not_safe:
  195. raise UserError(_(
  196. "The query is not allowed because it contains unsafe word"
  197. " '%s'") % (word))
  198. @api.multi
  199. def _check_execution(self):
  200. """Ensure that the query is valid, trying to execute it. A rollback
  201. is done after."""
  202. self.ensure_one()
  203. query = self._prepare_request_check_execution()
  204. rollback_name = self._create_savepoint()
  205. res = False
  206. try:
  207. self.env.cr.execute(query)
  208. res = self._hook_executed_request()
  209. except ProgrammingError as e:
  210. raise UserError(
  211. _("The SQL query is not valid:\n\n %s") % e)
  212. finally:
  213. self._rollback_savepoint(rollback_name)
  214. return res
  215. @api.multi
  216. def _prepare_request_check_execution(self):
  217. """Overload me to replace some part of the query, if it contains
  218. parameters"""
  219. self.ensure_one()
  220. return self.query
  221. def _hook_executed_request(self):
  222. """Overload me to insert custom code, when the SQL request has
  223. been executed, before the rollback.
  224. """
  225. self.ensure_one()
  226. return False