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.

260 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 openerp import _, api, fields, models
  12. from openerp.exceptions import Warning as 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. openerp.exceptions.Warning:
  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. req = "SAVEPOINT %s" % (rollback_name)
  160. self.env.cr.execute(req)
  161. return rollback_name
  162. @api.model
  163. def _rollback_savepoint(self, rollback_name):
  164. req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name)
  165. self.env.cr.execute(req)
  166. @api.model
  167. def _check_materialized_view_available(self):
  168. self.env.cr.execute("SHOW server_version;")
  169. res = self.env.cr.fetchone()[0].split('.')
  170. minor_version = float('.'.join(res[:2]))
  171. if minor_version < 9.3:
  172. raise UserError(_(
  173. "Materialized View requires PostgreSQL 9.3 or greater but"
  174. " PostgreSQL %s is currently installed.") % (minor_version))
  175. @api.multi
  176. def _clean_query(self):
  177. self.ensure_one()
  178. query = self.query.strip()
  179. while query[-1] == ';':
  180. query = query[:-1]
  181. self.query = query
  182. @api.multi
  183. def _check_prohibited_words(self):
  184. """Check if the query contains prohibited words, to avoid maliscious
  185. SQL requests"""
  186. self.ensure_one()
  187. query = self.query.lower()
  188. for word in self.PROHIBITED_WORDS:
  189. expr = r'\b%s\b' % word
  190. is_not_safe = re.search(expr, query)
  191. if is_not_safe:
  192. raise UserError(_(
  193. "The query is not allowed because it contains unsafe word"
  194. " '%s'") % (word))
  195. @api.multi
  196. def _check_execution(self):
  197. """Ensure that the query is valid, trying to execute it. A rollback
  198. is done after."""
  199. self.ensure_one()
  200. query = self._prepare_request_check_execution()
  201. rollback_name = self._create_savepoint()
  202. res = False
  203. try:
  204. self.env.cr.execute(query)
  205. res = self._hook_executed_request()
  206. except ProgrammingError as e:
  207. raise UserError(
  208. _("The SQL query is not valid:\n\n %s") % e.message)
  209. finally:
  210. self._rollback_savepoint(rollback_name)
  211. return res
  212. @api.multi
  213. def _prepare_request_check_execution(self):
  214. """Overload me to replace some part of the query, if it contains
  215. parameters"""
  216. self.ensure_one()
  217. return self.query
  218. def _hook_executed_request(self):
  219. """Overload me to insert custom code, when the SQL request has
  220. been executed, before the rollback.
  221. """
  222. self.ensure_one()
  223. return False