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.

355 lines
13 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. def __init__(self, message, type):
  42. super(Exception, self).__init__(message)
  43. self.type = type
  44. class Main(http.Controller):
  45. def __get_authorization_code_jwk(self, req):
  46. return jwk_from_json(req.env['ir.config_parameter'].sudo().get_param(
  47. 'galicea_openid_connect.authorization_code_jwk'
  48. ))
  49. def __get_id_token_jwk(self, req):
  50. return jwk_from_json(req.env['ir.config_parameter'].sudo().get_param(
  51. 'galicea_openid_connect.id_token_jwk'
  52. ))
  53. def __validate_client(self, req, **query):
  54. if 'client_id' not in query:
  55. raise OAuthException(
  56. 'client_id param is missing',
  57. OAuthException.INVALID_CLIENT,
  58. )
  59. client_id = query['client_id']
  60. client = req.env['galicea_openid_connect.client'].sudo().search(
  61. [('client_id', '=', client_id)]
  62. )
  63. if not client:
  64. raise OAuthException(
  65. 'client_id param is invalid',
  66. OAuthException.INVALID_CLIENT,
  67. )
  68. return client
  69. def __validate_redirect_uri(self, client, req, **query):
  70. if 'redirect_uri' not in query:
  71. raise OAuthException(
  72. 'redirect_uri param is missing',
  73. OAuthException.INVALID_GRANT,
  74. )
  75. redirect_uri = query['redirect_uri']
  76. if client.auth_redirect_uri != redirect_uri:
  77. raise OAuthException(
  78. 'redirect_uri param doesn\'t match the pre-configured redirect URI',
  79. OAuthException.INVALID_GRANT,
  80. )
  81. return redirect_uri
  82. def __validate_client_secret(self, client, req, **query):
  83. if 'client_secret' not in query or query['client_secret'] != client.secret:
  84. raise OAuthException(
  85. 'client_secret param is not valid',
  86. OAuthException.INVALID_CLIENT,
  87. )
  88. @http.route('/.well-known/openid-configuration', auth='public', type='http')
  89. def metadata(self, req, **query):
  90. base_url = http.request.httprequest.host_url
  91. data = {
  92. 'issuer': base_url,
  93. 'authorization_endpoint': base_url + 'oauth/authorize',
  94. 'token_endpoint': base_url + 'oauth/token',
  95. 'userinfo_endpoint': base_url + 'oauth/userinfo',
  96. 'jwks_uri': base_url + 'oauth/jwks',
  97. 'scopes_supported': ['openid'],
  98. 'response_types_supported': RESPONSE_TYPES_SUPPORTED,
  99. 'grant_types_supported': ['authorization_code', 'implicit'],
  100. 'subject_types_supported': ['public'],
  101. 'id_token_signing_alg_values_supported': ['RS256'],
  102. 'token_endpoint_auth_methods_supported': ['client_secret_post']
  103. }
  104. return json.dumps(data)
  105. @http.route('/oauth/jwks', auth='public', type='http')
  106. def jwks(self, req, **query):
  107. keyset = jwk.JWKSet()
  108. keyset.add(self.__get_id_token_jwk(req))
  109. return keyset.export(private_keys=False)
  110. @resource('/oauth/userinfo', method='GET')
  111. def userinfo(self, req, **query):
  112. user = req.env.user
  113. values = {
  114. 'sub': str(user.id),
  115. # Needed in case the client is another Odoo instance
  116. 'user_id': str(user.id),
  117. 'name': user.name,
  118. }
  119. if user.email:
  120. values['email'] = user.email
  121. return values
  122. @resource('/oauth/clientinfo', method='GET', auth='client')
  123. def clientinfo(self, req, **query):
  124. client = req.env['galicea_openid_connect.client'].browse(req.context['client_id'])
  125. return {
  126. 'name': client.name
  127. }
  128. @http.route('/oauth/authorize', auth='public', type='http', csrf=False)
  129. def authorize(self, req, **query):
  130. # First, validate client_id and redirect_uri params.
  131. try:
  132. client = self.__validate_client(req, **query)
  133. redirect_uri = self.__validate_redirect_uri(client, req, **query)
  134. except OAuthException as e:
  135. # If those are not valid, we must not redirect back to the client
  136. # - instead, we display a message to the user
  137. return req.render('galicea_openid_connect.error', {'exception': e})
  138. scopes = query['scope'].split(' ') if query.get('scope') else []
  139. is_openid_request = 'openid' in scopes
  140. # state, if present, is just mirrored back to the client
  141. response_params = {}
  142. if 'state' in query:
  143. response_params['state'] = query['state']
  144. response_mode = query.get('response_mode')
  145. try:
  146. if response_mode and response_mode not in ['query', 'fragment']:
  147. response_mode = None
  148. raise OAuthException(
  149. 'The only supported response_modes are \'query\' and \'fragment\'',
  150. OAuthException.INVALID_REQUEST
  151. )
  152. if 'response_type' not in query:
  153. raise OAuthException(
  154. 'response_type param is missing',
  155. OAuthException.INVALID_REQUEST,
  156. )
  157. response_type = query['response_type']
  158. if response_type not in RESPONSE_TYPES_SUPPORTED:
  159. raise OAuthException(
  160. 'The only supported response_types are: {}'.format(', '.join(RESPONSE_TYPES_SUPPORTED)),
  161. OAuthException.UNSUPPORTED_RESPONSE_TYPE,
  162. )
  163. except OAuthException as e:
  164. response_params['error'] = e.type
  165. response_params['error_description'] = e.message
  166. return self.__redirect(redirect_uri, response_params, response_mode or 'query')
  167. if not response_mode:
  168. response_mode = 'query' if response_type == 'code' else 'fragment'
  169. user = req.env.user
  170. # In case user is not logged in, we redirect to the login page and come back
  171. needs_login = user.login == 'public'
  172. # Also if they didn't authenticate recently enough
  173. if 'max_age' in query and http.request.session.get('auth_time', 0) + int(query['max_age']) < time.time():
  174. needs_login = True
  175. if needs_login:
  176. params = {
  177. 'force_auth_and_redirect': '/oauth/authorize?{}'.format(werkzeug.url_encode(query))
  178. }
  179. return self.__redirect('/web/login', params, 'query')
  180. response_types = response_type.split()
  181. extra_claims = {
  182. 'sid': http.request.httprequest.session.sid,
  183. }
  184. if 'nonce' in query:
  185. extra_claims['nonce'] = query['nonce']
  186. if 'code' in response_types:
  187. # Generate code that can be used by the client server to retrieve
  188. # the token. It's set to be valid for 60 seconds only.
  189. # TODO: The spec says the code should be single-use. We're not enforcing
  190. # that here.
  191. payload = {
  192. 'redirect_uri': redirect_uri,
  193. 'client_id': client.client_id,
  194. 'user_id': user.id,
  195. 'scopes': scopes,
  196. 'exp': int(time.time()) + 60
  197. }
  198. payload.update(extra_claims)
  199. key = self.__get_authorization_code_jwk(req)
  200. response_params['code'] = jwt_encode(payload, key)
  201. if 'token' in response_types:
  202. access_token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  203. user.id,
  204. client.id
  205. ).token
  206. response_params['access_token'] = access_token
  207. response_params['token_type'] = 'bearer'
  208. digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
  209. digest.update(access_token.encode('ascii'))
  210. at_hash = digest.finalize()
  211. extra_claims['at_hash'] = base64.urlsafe_b64encode(at_hash[:16]).strip('=')
  212. if 'id_token' in response_types:
  213. response_params['id_token'] = self.__create_id_token(req, user.id, client, extra_claims)
  214. return self.__redirect(redirect_uri, response_params, response_mode)
  215. @http.route('/oauth/token', auth='public', type='http', methods=['POST'], csrf=False)
  216. def token(self, req, **query):
  217. try:
  218. if 'grant_type' not in query:
  219. raise OAuthException(
  220. 'grant_type param is missing',
  221. OAuthException.INVALID_REQUEST,
  222. )
  223. if query['grant_type'] == 'authorization_code':
  224. return json.dumps(self.__handle_grant_type_authorization_code(req, **query))
  225. elif query['grant_type'] == 'client_credentials':
  226. return json.dumps(self.__handle_grant_type_client_credentials(req, **query))
  227. else:
  228. raise OAuthException(
  229. 'Unsupported grant_type param: \'{}\''.format(query['grant_type']),
  230. OAuthException.UNSUPPORTED_GRANT_TYPE,
  231. )
  232. except OAuthException as e:
  233. body = json.dumps({'error': e.type, 'error_description': e.message})
  234. return werkzeug.Response(response=body, status=400)
  235. def __handle_grant_type_authorization_code(self, req, **query):
  236. client = self.__validate_client(req, **query)
  237. redirect_uri = self.__validate_redirect_uri(client, req, **query)
  238. self.__validate_client_secret(client, req, **query)
  239. if 'code' not in query:
  240. raise OAuthException(
  241. 'code param is missing',
  242. OAuthException.INVALID_GRANT,
  243. )
  244. try:
  245. payload = jwt_decode(query['code'], self.__get_authorization_code_jwk(req))
  246. except jwt.JWTExpired:
  247. raise OAuthException(
  248. 'Code expired',
  249. OAuthException.INVALID_GRANT,
  250. )
  251. except ValueError:
  252. raise OAuthException(
  253. 'code malformed',
  254. OAuthException.INVALID_GRANT,
  255. )
  256. if payload['client_id'] != client.client_id:
  257. raise OAuthException(
  258. 'client_id doesn\'t match the authorization request',
  259. OAuthException.INVALID_GRANT,
  260. )
  261. if payload['redirect_uri'] != redirect_uri:
  262. raise OAuthException(
  263. 'redirect_uri doesn\'t match the authorization request',
  264. OAuthException.INVALID_GRANT,
  265. )
  266. # Retrieve/generate access token. We currently only store one per user/client
  267. token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  268. payload['user_id'],
  269. client.id
  270. )
  271. response = {
  272. 'access_token': token.token,
  273. 'token_type': 'bearer'
  274. }
  275. if 'openid' in payload['scopes']:
  276. extra_claims = { name: payload[name] for name in payload if name in ['sid', 'nonce'] }
  277. response['id_token'] = self.__create_id_token(req, payload['user_id'], client, extra_claims)
  278. return response
  279. def __handle_grant_type_client_credentials(self, req, **query):
  280. client = self.__validate_client(req, **query)
  281. self.__validate_client_secret(client, req, **query)
  282. token = req.env['galicea_openid_connect.client_access_token'].sudo().retrieve_or_create(client.id)
  283. return {
  284. 'access_token': token.token,
  285. 'token_type': 'bearer'
  286. }
  287. def __create_id_token(self, req, user_id, client, extra_claims):
  288. claims = {
  289. 'iss': http.request.httprequest.host_url,
  290. 'sub': str(user_id),
  291. 'aud': client.client_id,
  292. 'iat': int(time.time()),
  293. 'exp': int(time.time()) + 15 * 60
  294. }
  295. auth_time = extra_claims.get('sid') and http.root.session_store.get(extra_claims['sid']).get('auth_time')
  296. if auth_time:
  297. claims['auth_time'] = auth_time
  298. if 'nonce' in extra_claims:
  299. claims['nonce'] = extra_claims['nonce']
  300. if 'at_hash' in extra_claims:
  301. claims['at_hash'] = extra_claims['at_hash']
  302. key = self.__get_id_token_jwk(req)
  303. return jwt_encode(claims, key)
  304. def __redirect(self, url, params, response_mode):
  305. location = '{}{}{}'.format(
  306. url,
  307. '?' if response_mode == 'query' else '#',
  308. werkzeug.url_encode(params)
  309. )
  310. return werkzeug.Response(
  311. headers={'Location': location},
  312. response=None,
  313. status=302,
  314. )