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.

422 lines
16 KiB

  1. # -*- coding: utf-8 -*-
  2. import json
  3. import time
  4. import os
  5. import base64
  6. from odoo import http
  7. import werkzeug
  8. from .. api import resource
  9. try:
  10. from jwcrypto import jwk, jwt
  11. from cryptography.hazmat.backends import default_backend
  12. from cryptography.hazmat.primitives import hashes
  13. except ImportError:
  14. pass
  15. def jwk_from_json(json_key):
  16. key = jwk.JWK()
  17. key.import_key(**json.loads(json_key))
  18. return key
  19. def jwt_encode(claims, key):
  20. token = jwt.JWT(
  21. header={'alg': key._params['alg'], 'kid': key._params['kid']},
  22. claims=claims
  23. )
  24. token.make_signed_token(key)
  25. return token.serialize()
  26. def jwt_decode(serialized, key):
  27. token = jwt.JWT(jwt=serialized, key=key)
  28. return json.loads(token.claims)
  29. RESPONSE_TYPES_SUPPORTED = [
  30. 'code',
  31. 'token',
  32. 'id_token token',
  33. 'id_token'
  34. ]
  35. class OAuthException(Exception):
  36. INVALID_REQUEST = 'invalid_request'
  37. INVALID_CLIENT = 'invalid_client'
  38. UNSUPPORTED_RESPONSE_TYPE = 'unsupported_response_type'
  39. INVALID_GRANT = 'invalid_grant'
  40. UNSUPPORTED_GRANT_TYPE = 'unsupported_grant_type'
  41. RESTRICTED_APP = 'restricted_app'
  42. def __init__(self, message, type):
  43. super(Exception, self).__init__(message)
  44. self.type = type
  45. class Main(http.Controller):
  46. def __get_authorization_code_jwk(self, req):
  47. return jwk_from_json(req.env['ir.config_parameter'].sudo().get_param(
  48. 'galicea_openid_connect.authorization_code_jwk'
  49. ))
  50. def __get_id_token_jwk(self, req):
  51. return jwk_from_json(req.env['ir.config_parameter'].sudo().get_param(
  52. 'galicea_openid_connect.id_token_jwk'
  53. ))
  54. def __validate_client(self, req, **query):
  55. if 'client_id' not in query:
  56. raise OAuthException(
  57. 'client_id param is missing',
  58. OAuthException.INVALID_CLIENT,
  59. )
  60. client_id = query['client_id']
  61. client = req.env['galicea_openid_connect.client'].sudo().search(
  62. [('client_id', '=', client_id)]
  63. )
  64. if not client:
  65. raise OAuthException(
  66. 'client_id param is invalid',
  67. OAuthException.INVALID_CLIENT,
  68. )
  69. return client
  70. def __validate_redirect_uri(self, client, req, **query):
  71. if 'redirect_uri' not in query:
  72. raise OAuthException(
  73. 'redirect_uri param is missing',
  74. OAuthException.INVALID_GRANT,
  75. )
  76. redirect_uri = query['redirect_uri']
  77. if client.auth_redirect_uri != redirect_uri:
  78. raise OAuthException(
  79. 'redirect_uri param doesn\'t match the pre-configured redirect URI',
  80. OAuthException.INVALID_GRANT,
  81. )
  82. return redirect_uri
  83. def __validate_client_secret(self, client, req, **query):
  84. if 'client_secret' not in query or query['client_secret'] != client.secret:
  85. raise OAuthException(
  86. 'client_secret param is not valid',
  87. OAuthException.INVALID_CLIENT,
  88. )
  89. def __validate_user(self, client, user):
  90. if not client.user_group_id:
  91. return
  92. if client.user_group_id not in user.groups_id:
  93. raise OAuthException(
  94. 'User is not allowed to use this client',
  95. OAuthException.RESTRICTED_APP
  96. )
  97. @http.route('/.well-known/openid-configuration', auth='public', type='http')
  98. def metadata(self, req, **query):
  99. base_url = http.request.httprequest.host_url
  100. data = {
  101. 'issuer': base_url,
  102. 'authorization_endpoint': base_url + 'oauth/authorize',
  103. 'token_endpoint': base_url + 'oauth/token',
  104. 'userinfo_endpoint': base_url + 'oauth/userinfo',
  105. 'jwks_uri': base_url + 'oauth/jwks',
  106. 'scopes_supported': ['openid'],
  107. 'response_types_supported': RESPONSE_TYPES_SUPPORTED,
  108. 'grant_types_supported': ['authorization_code', 'implicit', 'password', 'client_credentials'],
  109. 'subject_types_supported': ['public'],
  110. 'id_token_signing_alg_values_supported': ['RS256'],
  111. 'token_endpoint_auth_methods_supported': ['client_secret_post']
  112. }
  113. return json.dumps(data)
  114. @http.route('/oauth/jwks', auth='public', type='http')
  115. def jwks(self, req, **query):
  116. keyset = jwk.JWKSet()
  117. keyset.add(self.__get_id_token_jwk(req))
  118. return keyset.export(private_keys=False)
  119. @resource('/oauth/userinfo', method='GET')
  120. def userinfo(self, req, **query):
  121. user = req.env.user
  122. values = {
  123. 'sub': str(user.id),
  124. # Needed in case the client is another Odoo instance
  125. 'user_id': str(user.id),
  126. 'name': user.name,
  127. }
  128. if user.email:
  129. values['email'] = user.email
  130. return values
  131. @resource('/oauth/clientinfo', method='GET', auth='client')
  132. def clientinfo(self, req, **query):
  133. client = req.env['galicea_openid_connect.client'].browse(req.context['client_id'])
  134. return {
  135. 'name': client.name
  136. }
  137. @http.route('/oauth/authorize', auth='public', type='http', csrf=False)
  138. def authorize(self, req, **query):
  139. # First, validate client_id and redirect_uri params.
  140. try:
  141. client = self.__validate_client(req, **query)
  142. redirect_uri = self.__validate_redirect_uri(client, req, **query)
  143. except OAuthException as e:
  144. # If those are not valid, we must not redirect back to the client
  145. # - instead, we display a message to the user
  146. return req.render('galicea_openid_connect.error', {'exception': e})
  147. scopes = query['scope'].split(' ') if query.get('scope') else []
  148. is_openid_request = 'openid' in scopes
  149. # state, if present, is just mirrored back to the client
  150. response_params = {}
  151. if 'state' in query:
  152. response_params['state'] = query['state']
  153. response_mode = query.get('response_mode')
  154. try:
  155. if response_mode and response_mode not in ['query', 'fragment']:
  156. response_mode = None
  157. raise OAuthException(
  158. 'The only supported response_modes are \'query\' and \'fragment\'',
  159. OAuthException.INVALID_REQUEST
  160. )
  161. if 'response_type' not in query:
  162. raise OAuthException(
  163. 'response_type param is missing',
  164. OAuthException.INVALID_REQUEST,
  165. )
  166. response_type = query['response_type']
  167. if response_type not in RESPONSE_TYPES_SUPPORTED:
  168. raise OAuthException(
  169. 'The only supported response_types are: {}'.format(', '.join(RESPONSE_TYPES_SUPPORTED)),
  170. OAuthException.UNSUPPORTED_RESPONSE_TYPE,
  171. )
  172. except OAuthException as e:
  173. response_params['error'] = e.type
  174. response_params['error_description'] = e.message
  175. return self.__redirect(redirect_uri, response_params, response_mode or 'query')
  176. if not response_mode:
  177. response_mode = 'query' if response_type == 'code' else 'fragment'
  178. user = req.env.user
  179. # In case user is not logged in, we redirect to the login page and come back
  180. needs_login = user.login == 'public'
  181. # Also if they didn't authenticate recently enough
  182. if 'max_age' in query and http.request.session.get('auth_time', 0) + int(query['max_age']) < time.time():
  183. needs_login = True
  184. if needs_login:
  185. params = {
  186. 'force_auth_and_redirect': '/oauth/authorize?{}'.format(werkzeug.url_encode(query))
  187. }
  188. return self.__redirect('/web/login', params, 'query')
  189. self.__validate_user(client, user)
  190. response_types = response_type.split()
  191. extra_claims = {
  192. 'sid': http.request.httprequest.session.sid,
  193. }
  194. if 'nonce' in query:
  195. extra_claims['nonce'] = query['nonce']
  196. if 'code' in response_types:
  197. # Generate code that can be used by the client server to retrieve
  198. # the token. It's set to be valid for 60 seconds only.
  199. # TODO: The spec says the code should be single-use. We're not enforcing
  200. # that here.
  201. payload = {
  202. 'redirect_uri': redirect_uri,
  203. 'client_id': client.client_id,
  204. 'user_id': user.id,
  205. 'scopes': scopes,
  206. 'exp': int(time.time()) + 60
  207. }
  208. payload.update(extra_claims)
  209. key = self.__get_authorization_code_jwk(req)
  210. response_params['code'] = jwt_encode(payload, key)
  211. if 'token' in response_types:
  212. access_token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  213. user.id,
  214. client.id
  215. ).token
  216. response_params['access_token'] = access_token
  217. response_params['token_type'] = 'bearer'
  218. digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
  219. digest.update(access_token.encode('ascii'))
  220. at_hash = digest.finalize()
  221. extra_claims['at_hash'] = base64.urlsafe_b64encode(at_hash[:16]).strip('=')
  222. if 'id_token' in response_types:
  223. response_params['id_token'] = self.__create_id_token(req, user.id, client, extra_claims)
  224. return self.__redirect(redirect_uri, response_params, response_mode)
  225. @http.route('/oauth/token', auth='public', type='http', methods=['POST', 'OPTIONS'], csrf=False)
  226. def token(self, req, **query):
  227. cors_headers = {
  228. 'Access-Control-Allow-Origin': '*',
  229. 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-Debug-Mode, Authorization',
  230. 'Access-Control-Max-Age': 60 * 60 * 24,
  231. }
  232. if req.httprequest.method == 'OPTIONS':
  233. return http.Response(
  234. status=200,
  235. headers=cors_headers
  236. )
  237. try:
  238. if 'grant_type' not in query:
  239. raise OAuthException(
  240. 'grant_type param is missing',
  241. OAuthException.INVALID_REQUEST,
  242. )
  243. if query['grant_type'] == 'authorization_code':
  244. return json.dumps(self.__handle_grant_type_authorization_code(req, **query))
  245. elif query['grant_type'] == 'client_credentials':
  246. return json.dumps(self.__handle_grant_type_client_credentials(req, **query))
  247. elif query['grant_type'] == 'password':
  248. return werkzeug.Response(
  249. response=json.dumps(self.__handle_grant_type_password(req, **query)),
  250. headers=cors_headers
  251. )
  252. else:
  253. raise OAuthException(
  254. 'Unsupported grant_type param: \'{}\''.format(query['grant_type']),
  255. OAuthException.UNSUPPORTED_GRANT_TYPE,
  256. )
  257. except OAuthException as e:
  258. body = json.dumps({'error': e.type, 'error_description': e.message})
  259. return werkzeug.Response(response=body, status=400, headers=cors_headers)
  260. def __handle_grant_type_authorization_code(self, req, **query):
  261. client = self.__validate_client(req, **query)
  262. redirect_uri = self.__validate_redirect_uri(client, req, **query)
  263. self.__validate_client_secret(client, req, **query)
  264. if 'code' not in query:
  265. raise OAuthException(
  266. 'code param is missing',
  267. OAuthException.INVALID_GRANT,
  268. )
  269. try:
  270. payload = jwt_decode(query['code'], self.__get_authorization_code_jwk(req))
  271. except jwt.JWTExpired:
  272. raise OAuthException(
  273. 'Code expired',
  274. OAuthException.INVALID_GRANT,
  275. )
  276. except ValueError:
  277. raise OAuthException(
  278. 'code malformed',
  279. OAuthException.INVALID_GRANT,
  280. )
  281. if payload['client_id'] != client.client_id:
  282. raise OAuthException(
  283. 'client_id doesn\'t match the authorization request',
  284. OAuthException.INVALID_GRANT,
  285. )
  286. if payload['redirect_uri'] != redirect_uri:
  287. raise OAuthException(
  288. 'redirect_uri doesn\'t match the authorization request',
  289. OAuthException.INVALID_GRANT,
  290. )
  291. # Retrieve/generate access token. We currently only store one per user/client
  292. token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  293. payload['user_id'],
  294. client.id
  295. )
  296. response = {
  297. 'access_token': token.token,
  298. 'token_type': 'bearer'
  299. }
  300. if 'openid' in payload['scopes']:
  301. extra_claims = { name: payload[name] for name in payload if name in ['sid', 'nonce'] }
  302. response['id_token'] = self.__create_id_token(req, payload['user_id'], client, extra_claims)
  303. return response
  304. def __handle_grant_type_password(self, req, **query):
  305. client = self.__validate_client(req, **query)
  306. if not client.allow_password_grant:
  307. raise OAuthException(
  308. 'This client is not allowed to perform password flow',
  309. OAuthException.UNSUPPORTED_GRANT_TYPE
  310. )
  311. for param in ['username', 'password']:
  312. if param not in query:
  313. raise OAuthException(
  314. '{} is required'.format(param),
  315. OAuthException.INVALID_REQUEST
  316. )
  317. user_id = req.env['res.users'].authenticate(
  318. req.env.cr.dbname,
  319. query['username'],
  320. query['password'],
  321. None
  322. )
  323. if not user_id:
  324. raise OAuthException(
  325. 'Invalid username or password',
  326. OAuthException.INVALID_REQUEST
  327. )
  328. self.__validate_user(client, req.env['res.users'].sudo().browse(user_id))
  329. scopes = query['scope'].split(' ') if query.get('scope') else []
  330. # Retrieve/generate access token. We currently only store one per user/client
  331. token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  332. user_id,
  333. client.id
  334. )
  335. response = {
  336. 'access_token': token.token,
  337. 'token_type': 'bearer'
  338. }
  339. if 'openid' in scopes:
  340. response['id_token'] = self.__create_id_token(req, user_id, client, {})
  341. return response
  342. def __handle_grant_type_client_credentials(self, req, **query):
  343. client = self.__validate_client(req, **query)
  344. self.__validate_client_secret(client, req, **query)
  345. token = req.env['galicea_openid_connect.client_access_token'].sudo().retrieve_or_create(client.id)
  346. return {
  347. 'access_token': token.token,
  348. 'token_type': 'bearer'
  349. }
  350. def __create_id_token(self, req, user_id, client, extra_claims):
  351. claims = {
  352. 'iss': http.request.httprequest.host_url,
  353. 'sub': str(user_id),
  354. 'aud': client.client_id,
  355. 'iat': int(time.time()),
  356. 'exp': int(time.time()) + 15 * 60
  357. }
  358. auth_time = extra_claims.get('sid') and http.root.session_store.get(extra_claims['sid']).get('auth_time')
  359. if auth_time:
  360. claims['auth_time'] = auth_time
  361. if 'nonce' in extra_claims:
  362. claims['nonce'] = extra_claims['nonce']
  363. if 'at_hash' in extra_claims:
  364. claims['at_hash'] = extra_claims['at_hash']
  365. key = self.__get_id_token_jwk(req)
  366. return jwt_encode(claims, key)
  367. def __redirect(self, url, params, response_mode):
  368. location = '{}{}{}'.format(
  369. url,
  370. '?' if response_mode == 'query' else '#',
  371. werkzeug.url_encode(params)
  372. )
  373. return werkzeug.Response(
  374. headers={'Location': location},
  375. response=None,
  376. status=302,
  377. )