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.

411 lines
16 KiB

5 years ago
  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', 'password', 'client_credentials'],
  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', 'OPTIONS'], csrf=False)
  216. def token(self, req, **query):
  217. cors_headers = {
  218. 'Access-Control-Allow-Origin': '*',
  219. 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-Debug-Mode, Authorization',
  220. 'Access-Control-Max-Age': 60 * 60 * 24,
  221. }
  222. if req.httprequest.method == 'OPTIONS':
  223. return http.Response(
  224. status=200,
  225. headers=cors_headers
  226. )
  227. try:
  228. if 'grant_type' not in query:
  229. raise OAuthException(
  230. 'grant_type param is missing',
  231. OAuthException.INVALID_REQUEST,
  232. )
  233. if query['grant_type'] == 'authorization_code':
  234. return json.dumps(self.__handle_grant_type_authorization_code(req, **query))
  235. elif query['grant_type'] == 'client_credentials':
  236. return json.dumps(self.__handle_grant_type_client_credentials(req, **query))
  237. elif query['grant_type'] == 'password':
  238. return werkzeug.Response(
  239. response=json.dumps(self.__handle_grant_type_password(req, **query)),
  240. headers=cors_headers
  241. )
  242. else:
  243. raise OAuthException(
  244. 'Unsupported grant_type param: \'{}\''.format(query['grant_type']),
  245. OAuthException.UNSUPPORTED_GRANT_TYPE,
  246. )
  247. except OAuthException as e:
  248. body = json.dumps({'error': e.type, 'error_description': e.message})
  249. return werkzeug.Response(response=body, status=400, headers=cors_headers)
  250. def __handle_grant_type_authorization_code(self, req, **query):
  251. client = self.__validate_client(req, **query)
  252. redirect_uri = self.__validate_redirect_uri(client, req, **query)
  253. self.__validate_client_secret(client, req, **query)
  254. if 'code' not in query:
  255. raise OAuthException(
  256. 'code param is missing',
  257. OAuthException.INVALID_GRANT,
  258. )
  259. try:
  260. payload = jwt_decode(query['code'], self.__get_authorization_code_jwk(req))
  261. except jwt.JWTExpired:
  262. raise OAuthException(
  263. 'Code expired',
  264. OAuthException.INVALID_GRANT,
  265. )
  266. except ValueError:
  267. raise OAuthException(
  268. 'code malformed',
  269. OAuthException.INVALID_GRANT,
  270. )
  271. if payload['client_id'] != client.client_id:
  272. raise OAuthException(
  273. 'client_id doesn\'t match the authorization request',
  274. OAuthException.INVALID_GRANT,
  275. )
  276. if payload['redirect_uri'] != redirect_uri:
  277. raise OAuthException(
  278. 'redirect_uri doesn\'t match the authorization request',
  279. OAuthException.INVALID_GRANT,
  280. )
  281. # Retrieve/generate access token. We currently only store one per user/client
  282. token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  283. payload['user_id'],
  284. client.id
  285. )
  286. response = {
  287. 'access_token': token.token,
  288. 'token_type': 'bearer'
  289. }
  290. if 'openid' in payload['scopes']:
  291. extra_claims = { name: payload[name] for name in payload if name in ['sid', 'nonce'] }
  292. response['id_token'] = self.__create_id_token(req, payload['user_id'], client, extra_claims)
  293. return response
  294. def __handle_grant_type_password(self, req, **query):
  295. client = self.__validate_client(req, **query)
  296. if not client.allow_password_grant:
  297. raise OAuthException(
  298. 'This client is not allowed to perform password flow',
  299. OAuthException.UNSUPPORTED_GRANT_TYPE
  300. )
  301. for param in ['username', 'password']:
  302. if param not in query:
  303. raise OAuthException(
  304. '{} is required'.format(param),
  305. OAuthException.INVALID_REQUEST
  306. )
  307. user_id = req.env['res.users'].authenticate(
  308. req.env.cr.dbname,
  309. query['username'],
  310. query['password'],
  311. None
  312. )
  313. if not user_id:
  314. raise OAuthException(
  315. 'Invalid username or password',
  316. OAuthException.INVALID_REQUEST
  317. )
  318. scopes = query['scope'].split(' ') if query.get('scope') else []
  319. # Retrieve/generate access token. We currently only store one per user/client
  320. token = req.env['galicea_openid_connect.access_token'].sudo().retrieve_or_create(
  321. user_id,
  322. client.id
  323. )
  324. response = {
  325. 'access_token': token.token,
  326. 'token_type': 'bearer'
  327. }
  328. if 'openid' in scopes:
  329. response['id_token'] = self.__create_id_token(req, user_id, client, {})
  330. return response
  331. def __handle_grant_type_client_credentials(self, req, **query):
  332. client = self.__validate_client(req, **query)
  333. self.__validate_client_secret(client, req, **query)
  334. token = req.env['galicea_openid_connect.client_access_token'].sudo().retrieve_or_create(client.id)
  335. return {
  336. 'access_token': token.token,
  337. 'token_type': 'bearer'
  338. }
  339. def __create_id_token(self, req, user_id, client, extra_claims):
  340. claims = {
  341. 'iss': http.request.httprequest.host_url,
  342. 'sub': str(user_id),
  343. 'aud': client.client_id,
  344. 'iat': int(time.time()),
  345. 'exp': int(time.time()) + 15 * 60
  346. }
  347. auth_time = extra_claims.get('sid') and http.root.session_store.get(extra_claims['sid']).get('auth_time')
  348. if auth_time:
  349. claims['auth_time'] = auth_time
  350. if 'nonce' in extra_claims:
  351. claims['nonce'] = extra_claims['nonce']
  352. if 'at_hash' in extra_claims:
  353. claims['at_hash'] = extra_claims['at_hash']
  354. key = self.__get_id_token_jwk(req)
  355. return jwt_encode(claims, key)
  356. def __redirect(self, url, params, response_mode):
  357. location = '{}{}{}'.format(
  358. url,
  359. '?' if response_mode == 'query' else '#',
  360. werkzeug.url_encode(params)
  361. )
  362. return werkzeug.Response(
  363. headers={'Location': location},
  364. response=None,
  365. status=302,
  366. )