Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

625 linhas
19 KiB

  1. import base64
  2. import datetime
  3. import hashlib
  4. import re
  5. from http import cookies
  6. from urllib.parse import unquote, urlparse
  7. import jwt
  8. import pytz
  9. from oauthlib.openid import RequestValidator
  10. import frappe
  11. from frappe.auth import LoginManager
  12. class OAuthWebRequestValidator(RequestValidator):
  13. # Pre- and post-authorization.
  14. def validate_client_id(self, client_id, request, *args, **kwargs):
  15. # Simple validity check, does client exist? Not banned?
  16. cli_id = frappe.db.get_value("OAuth Client", {"name": client_id})
  17. if cli_id:
  18. request.client = frappe.get_doc("OAuth Client", client_id).as_dict()
  19. return True
  20. else:
  21. return False
  22. def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):
  23. # Is the client allowed to use the supplied redirect_uri? i.e. has
  24. # the client previously registered this EXACT redirect uri.
  25. redirect_uris = frappe.db.get_value("OAuth Client", client_id, "redirect_uris").split(
  26. get_url_delimiter()
  27. )
  28. if redirect_uri in redirect_uris:
  29. return True
  30. else:
  31. return False
  32. def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
  33. # The redirect used if none has been supplied.
  34. # Prefer your clients to pre register a redirect uri rather than
  35. # supplying one on each authorization request.
  36. redirect_uri = frappe.db.get_value("OAuth Client", client_id, "default_redirect_uri")
  37. return redirect_uri
  38. def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
  39. # Is the client allowed to access the requested scopes?
  40. allowed_scopes = get_client_scopes(client_id)
  41. return all(scope in allowed_scopes for scope in scopes)
  42. def get_default_scopes(self, client_id, request, *args, **kwargs):
  43. # Scopes a client will authorize for if none are supplied in the
  44. # authorization request.
  45. scopes = get_client_scopes(client_id)
  46. request.scopes = scopes # Apparently this is possible.
  47. return scopes
  48. def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):
  49. allowed_response_types = [
  50. # From OAuth Client response_type field
  51. client.response_type.lower(),
  52. # OIDC
  53. "id_token",
  54. "id_token token",
  55. "code id_token",
  56. "code token id_token",
  57. ]
  58. return response_type in allowed_response_types
  59. # Post-authorization
  60. def save_authorization_code(self, client_id, code, request, *args, **kwargs):
  61. cookie_dict = get_cookie_dict_from_headers(request)
  62. oac = frappe.new_doc("OAuth Authorization Code")
  63. oac.scopes = get_url_delimiter().join(request.scopes)
  64. oac.redirect_uri_bound_to_authorization_code = request.redirect_uri
  65. oac.client = client_id
  66. oac.user = unquote(cookie_dict["user_id"].value)
  67. oac.authorization_code = code["code"]
  68. if request.nonce:
  69. oac.nonce = request.nonce
  70. if request.code_challenge and request.code_challenge_method:
  71. oac.code_challenge = request.code_challenge
  72. oac.code_challenge_method = request.code_challenge_method.lower()
  73. oac.save(ignore_permissions=True)
  74. frappe.db.commit()
  75. def authenticate_client(self, request, *args, **kwargs):
  76. # Get ClientID in URL
  77. if request.client_id:
  78. oc = frappe.get_doc("OAuth Client", request.client_id)
  79. else:
  80. # Extract token, instantiate OAuth Bearer Token and use clientid from there.
  81. if "refresh_token" in frappe.form_dict:
  82. oc = frappe.get_doc(
  83. "OAuth Client",
  84. frappe.db.get_value(
  85. "OAuth Bearer Token",
  86. {"refresh_token": frappe.form_dict["refresh_token"]},
  87. "client",
  88. ),
  89. )
  90. elif "token" in frappe.form_dict:
  91. oc = frappe.get_doc(
  92. "OAuth Client",
  93. frappe.db.get_value("OAuth Bearer Token", frappe.form_dict["token"], "client"),
  94. )
  95. else:
  96. oc = frappe.get_doc(
  97. "OAuth Client",
  98. frappe.db.get_value(
  99. "OAuth Bearer Token",
  100. frappe.get_request_header("Authorization").split(" ")[1],
  101. "client",
  102. ),
  103. )
  104. try:
  105. request.client = request.client or oc.as_dict()
  106. except Exception as e:
  107. return generate_json_error_response(e)
  108. cookie_dict = get_cookie_dict_from_headers(request)
  109. user_id = unquote(cookie_dict.get("user_id").value) if "user_id" in cookie_dict else "Guest"
  110. return frappe.session.user == user_id
  111. def authenticate_client_id(self, client_id, request, *args, **kwargs):
  112. cli_id = frappe.db.get_value("OAuth Client", client_id, "name")
  113. if not cli_id:
  114. # Don't allow public (non-authenticated) clients
  115. return False
  116. else:
  117. request["client"] = frappe.get_doc("OAuth Client", cli_id)
  118. return True
  119. def validate_code(self, client_id, code, client, request, *args, **kwargs):
  120. # Validate the code belongs to the client. Add associated scopes,
  121. # state and user to request.scopes and request.user.
  122. validcodes = frappe.get_all(
  123. "OAuth Authorization Code",
  124. filters={"client": client_id, "validity": "Valid"},
  125. )
  126. checkcodes = []
  127. for vcode in validcodes:
  128. checkcodes.append(vcode["name"])
  129. if code in checkcodes:
  130. request.scopes = frappe.db.get_value("OAuth Authorization Code", code, "scopes").split(
  131. get_url_delimiter()
  132. )
  133. request.user = frappe.db.get_value("OAuth Authorization Code", code, "user")
  134. code_challenge_method = frappe.db.get_value(
  135. "OAuth Authorization Code", code, "code_challenge_method"
  136. )
  137. code_challenge = frappe.db.get_value("OAuth Authorization Code", code, "code_challenge")
  138. if code_challenge and not request.code_verifier:
  139. if frappe.db.exists("OAuth Authorization Code", code):
  140. frappe.delete_doc("OAuth Authorization Code", code, ignore_permissions=True)
  141. frappe.db.commit()
  142. return False
  143. if code_challenge_method == "s256":
  144. m = hashlib.sha256()
  145. m.update(bytes(request.code_verifier, "utf-8"))
  146. code_verifier = base64.b64encode(m.digest()).decode("utf-8")
  147. code_verifier = re.sub(r"\+", "-", code_verifier)
  148. code_verifier = re.sub(r"\/", "_", code_verifier)
  149. code_verifier = re.sub(r"=", "", code_verifier)
  150. return code_challenge == code_verifier
  151. elif code_challenge_method == "plain":
  152. return code_challenge == request.code_verifier
  153. return True
  154. return False
  155. def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs):
  156. saved_redirect_uri = frappe.db.get_value("OAuth Client", client_id, "default_redirect_uri")
  157. redirect_uris = frappe.db.get_value("OAuth Client", client_id, "redirect_uris")
  158. if redirect_uris:
  159. redirect_uris = redirect_uris.split(get_url_delimiter())
  160. return redirect_uri in redirect_uris
  161. return saved_redirect_uri == redirect_uri
  162. def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
  163. # Clients should only be allowed to use one type of grant.
  164. # In this case, it must be "authorization_code" or "refresh_token"
  165. return grant_type in ["authorization_code", "refresh_token", "password"]
  166. def save_bearer_token(self, token, request, *args, **kwargs):
  167. # Remember to associate it with request.scopes, request.user and
  168. # request.client. The two former will be set when you validate
  169. # the authorization code. Don't forget to save both the
  170. # access_token and the refresh_token and set expiration for the
  171. # access_token to now + expires_in seconds.
  172. otoken = frappe.new_doc("OAuth Bearer Token")
  173. otoken.client = request.client["name"]
  174. try:
  175. otoken.user = (
  176. request.user
  177. if request.user
  178. else frappe.db.get_value(
  179. "OAuth Bearer Token",
  180. {"refresh_token": request.body.get("refresh_token")},
  181. "user",
  182. )
  183. )
  184. except Exception:
  185. otoken.user = frappe.session.user
  186. otoken.scopes = get_url_delimiter().join(request.scopes)
  187. otoken.access_token = token["access_token"]
  188. otoken.refresh_token = token.get("refresh_token")
  189. otoken.expires_in = token["expires_in"]
  190. otoken.save(ignore_permissions=True)
  191. frappe.db.commit()
  192. default_redirect_uri = frappe.db.get_value(
  193. "OAuth Client", request.client["name"], "default_redirect_uri"
  194. )
  195. return default_redirect_uri
  196. def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):
  197. # Authorization codes are use once, invalidate it when a Bearer token
  198. # has been acquired.
  199. frappe.db.set_value("OAuth Authorization Code", code, "validity", "Invalid")
  200. frappe.db.commit()
  201. # Protected resource request
  202. def validate_bearer_token(self, token, scopes, request):
  203. # Remember to check expiration and scope membership
  204. otoken = frappe.get_doc("OAuth Bearer Token", token)
  205. token_expiration_local = otoken.expiration_time.replace(
  206. tzinfo=pytz.timezone(frappe.utils.get_time_zone())
  207. )
  208. token_expiration_utc = token_expiration_local.astimezone(pytz.utc)
  209. is_token_valid = (
  210. frappe.utils.datetime.datetime.utcnow().replace(tzinfo=pytz.utc) < token_expiration_utc
  211. ) and otoken.status != "Revoked"
  212. client_scopes = frappe.db.get_value("OAuth Client", otoken.client, "scopes").split(
  213. get_url_delimiter()
  214. )
  215. are_scopes_valid = True
  216. for scp in scopes:
  217. are_scopes_valid = are_scopes_valid and True if scp in client_scopes else False
  218. return is_token_valid and are_scopes_valid
  219. # Token refresh request
  220. def get_original_scopes(self, refresh_token, request, *args, **kwargs):
  221. # Obtain the token associated with the given refresh_token and
  222. # return its scopes, these will be passed on to the refreshed
  223. # access token if the client did not specify a scope during the
  224. # request.
  225. obearer_token = frappe.get_doc("OAuth Bearer Token", {"refresh_token": refresh_token})
  226. return obearer_token.scopes
  227. def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
  228. """Revoke an access or refresh token.
  229. :param token: The token string.
  230. :param token_type_hint: access_token or refresh_token.
  231. :param request: The HTTP Request (oauthlib.common.Request)
  232. Method is used by:
  233. - Revocation Endpoint
  234. """
  235. if token_type_hint == "access_token":
  236. frappe.db.set_value("OAuth Bearer Token", token, "status", "Revoked")
  237. elif token_type_hint == "refresh_token":
  238. frappe.db.set_value("OAuth Bearer Token", {"refresh_token": token}, "status", "Revoked")
  239. else:
  240. frappe.db.set_value("OAuth Bearer Token", token, "status", "Revoked")
  241. frappe.db.commit()
  242. def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):
  243. """Ensure the Bearer token is valid and authorized access to scopes.
  244. OBS! The request.user attribute should be set to the resource owner
  245. associated with this refresh token.
  246. :param refresh_token: Unicode refresh token
  247. :param client: Client object set by you, see authenticate_client.
  248. :param request: The HTTP Request (oauthlib.common.Request)
  249. :rtype: True or False
  250. Method is used by:
  251. - Authorization Code Grant (indirectly by issuing refresh tokens)
  252. - Resource Owner Password Credentials Grant (also indirectly)
  253. - Refresh Token Grant
  254. """
  255. otoken = frappe.get_doc(
  256. "OAuth Bearer Token", {"refresh_token": refresh_token, "status": "Active"}
  257. )
  258. if not otoken:
  259. return False
  260. else:
  261. return True
  262. # OpenID Connect
  263. def finalize_id_token(self, id_token, token, token_handler, request):
  264. # Check whether frappe server URL is set
  265. id_token_header = {"typ": "jwt", "alg": "HS256"}
  266. user = frappe.get_doc(
  267. "User",
  268. frappe.session.user,
  269. )
  270. if request.nonce:
  271. id_token["nonce"] = request.nonce
  272. userinfo = get_userinfo(user)
  273. if userinfo.get("iss"):
  274. id_token["iss"] = userinfo.get("iss")
  275. if "openid" in request.scopes:
  276. id_token.update(userinfo)
  277. id_token_encoded = jwt.encode(
  278. payload=id_token,
  279. key=request.client.client_secret,
  280. algorithm="HS256",
  281. headers=id_token_header,
  282. )
  283. return frappe.safe_decode(id_token_encoded)
  284. def get_authorization_code_nonce(self, client_id, code, redirect_uri, request):
  285. if frappe.get_value("OAuth Authorization Code", code, "validity") == "Valid":
  286. return frappe.get_value("OAuth Authorization Code", code, "nonce")
  287. return None
  288. def get_authorization_code_scopes(self, client_id, code, redirect_uri, request):
  289. scope = frappe.get_value("OAuth Client", client_id, "scopes")
  290. if not scope:
  291. scope = []
  292. else:
  293. scope = scope.split(get_url_delimiter())
  294. return scope
  295. def get_jwt_bearer_token(self, token, token_handler, request):
  296. now = datetime.datetime.now()
  297. id_token = dict(
  298. aud=token.client_id,
  299. iat=round(now.timestamp()),
  300. at_hash=calculate_at_hash(token.access_token, hashlib.sha256),
  301. )
  302. return self.finalize_id_token(id_token, token, token_handler, request)
  303. def get_userinfo_claims(self, request):
  304. user = frappe.get_doc("User", frappe.session.user)
  305. userinfo = get_userinfo(user)
  306. return userinfo
  307. def validate_id_token(self, token, scopes, request):
  308. try:
  309. id_token = frappe.get_doc("OAuth Bearer Token", token)
  310. if id_token.status == "Active":
  311. return True
  312. except Exception:
  313. return False
  314. return False
  315. def validate_jwt_bearer_token(self, token, scopes, request):
  316. try:
  317. jwt = frappe.get_doc("OAuth Bearer Token", token)
  318. if jwt.status == "Active":
  319. return True
  320. except Exception:
  321. return False
  322. return False
  323. def validate_silent_authorization(self, request):
  324. """Ensure the logged in user has authorized silent OpenID authorization.
  325. Silent OpenID authorization allows access tokens and id tokens to be
  326. granted to clients without any user prompt or interaction.
  327. :param request: The HTTP Request (oauthlib.common.Request)
  328. :rtype: True or False
  329. Method is used by:
  330. - OpenIDConnectAuthCode
  331. - OpenIDConnectImplicit
  332. - OpenIDConnectHybrid
  333. """
  334. if request.prompt == "login":
  335. False
  336. else:
  337. True
  338. def validate_silent_login(self, request):
  339. """Ensure session user has authorized silent OpenID login.
  340. If no user is logged in or has not authorized silent login, this
  341. method should return False.
  342. If the user is logged in but associated with multiple accounts and
  343. not selected which one to link to the token then this method should
  344. raise an oauthlib.oauth2.AccountSelectionRequired error.
  345. :param request: The HTTP Request (oauthlib.common.Request)
  346. :rtype: True or False
  347. Method is used by:
  348. - OpenIDConnectAuthCode
  349. - OpenIDConnectImplicit
  350. - OpenIDConnectHybrid
  351. """
  352. if frappe.session.user == "Guest" or request.prompt.lower() == "login":
  353. return False
  354. else:
  355. return True
  356. def validate_user_match(self, id_token_hint, scopes, claims, request):
  357. """Ensure client supplied user id hint matches session user.
  358. If the sub claim or id_token_hint is supplied then the session
  359. user must match the given ID.
  360. :param id_token_hint: User identifier string.
  361. :param scopes: List of OAuth 2 scopes and OpenID claims (strings).
  362. :param claims: OpenID Connect claims dict.
  363. :param request: The HTTP Request (oauthlib.common.Request)
  364. :rtype: True or False
  365. Method is used by:
  366. - OpenIDConnectAuthCode
  367. - OpenIDConnectImplicit
  368. - OpenIDConnectHybrid
  369. """
  370. if id_token_hint:
  371. try:
  372. user = None
  373. payload = jwt.decode(
  374. id_token_hint,
  375. algorithms=["HS256"],
  376. options={
  377. "verify_signature": False,
  378. "verify_aud": False,
  379. },
  380. )
  381. client_id, client_secret = frappe.get_value(
  382. "OAuth Client",
  383. payload.get("aud"),
  384. ["client_id", "client_secret"],
  385. )
  386. if payload.get("sub") and client_id and client_secret:
  387. user = frappe.db.get_value(
  388. "User Social Login",
  389. {"userid": payload.get("sub"), "provider": "frappe"},
  390. "parent",
  391. )
  392. user = frappe.get_doc("User", user)
  393. verified_payload = jwt.decode(
  394. id_token_hint,
  395. key=client_secret,
  396. audience=client_id,
  397. algorithms=["HS256"],
  398. options={
  399. "verify_exp": False,
  400. },
  401. )
  402. if verified_payload:
  403. return user.name == frappe.session.user
  404. except Exception:
  405. return False
  406. elif frappe.session.user != "Guest":
  407. return True
  408. return False
  409. def validate_user(self, username, password, client, request, *args, **kwargs):
  410. """Ensure the username and password is valid.
  411. Method is used by:
  412. - Resource Owner Password Credentials Grant
  413. """
  414. login_manager = LoginManager()
  415. login_manager.authenticate(username, password)
  416. if login_manager.user == "Guest":
  417. return False
  418. request.user = login_manager.user
  419. return True
  420. def get_cookie_dict_from_headers(r):
  421. cookie = cookies.BaseCookie()
  422. if r.headers.get("Cookie"):
  423. cookie.load(r.headers.get("Cookie"))
  424. return cookie
  425. def calculate_at_hash(access_token, hash_alg):
  426. """Helper method for calculating an access token
  427. hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  428. Its value is the base64url encoding of the left-most half of the hash of the octets
  429. of the ASCII representation of the access_token value, where the hash algorithm
  430. used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE
  431. Header. For instance, if the alg is RS256, hash the access_token value with SHA-256,
  432. then take the left-most 128 bits and base64url encode them. The at_hash value is a
  433. case sensitive string.
  434. Args:
  435. access_token (str): An access token string.
  436. hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256
  437. """
  438. hash_digest = hash_alg(access_token.encode("utf-8")).digest()
  439. cut_at = int(len(hash_digest) / 2)
  440. truncated = hash_digest[:cut_at]
  441. from jwt.utils import base64url_encode
  442. at_hash = base64url_encode(truncated)
  443. return at_hash.decode("utf-8")
  444. def delete_oauth2_data():
  445. # Delete Invalid Authorization Code and Revoked Token
  446. commit_code, commit_token = False, False
  447. code_list = frappe.get_all("OAuth Authorization Code", filters={"validity": "Invalid"})
  448. token_list = frappe.get_all("OAuth Bearer Token", filters={"status": "Revoked"})
  449. if len(code_list) > 0:
  450. commit_code = True
  451. if len(token_list) > 0:
  452. commit_token = True
  453. for code in code_list:
  454. frappe.delete_doc("OAuth Authorization Code", code["name"])
  455. for token in token_list:
  456. frappe.delete_doc("OAuth Bearer Token", token["name"])
  457. if commit_code or commit_token:
  458. frappe.db.commit()
  459. def get_client_scopes(client_id):
  460. scopes_string = frappe.db.get_value("OAuth Client", client_id, "scopes")
  461. return scopes_string.split()
  462. def get_userinfo(user):
  463. picture = None
  464. frappe_server_url = get_server_url()
  465. valid_url_schemes = ("http", "https", "ftp", "ftps")
  466. if user.user_image:
  467. if frappe.utils.validate_url(user.user_image, valid_schemes=valid_url_schemes):
  468. picture = user.user_image
  469. else:
  470. picture = frappe_server_url + "/" + user.user_image
  471. userinfo = frappe._dict(
  472. {
  473. "sub": frappe.db.get_value(
  474. "User Social Login",
  475. {"parent": user.name, "provider": "frappe"},
  476. "userid",
  477. ),
  478. "name": " ".join(filter(None, [user.first_name, user.last_name])),
  479. "given_name": user.first_name,
  480. "family_name": user.last_name,
  481. "email": user.email,
  482. "picture": picture,
  483. "roles": frappe.get_roles(user.name),
  484. "iss": frappe_server_url,
  485. }
  486. )
  487. return userinfo
  488. def get_url_delimiter(separator_character=" "):
  489. return separator_character
  490. def generate_json_error_response(e):
  491. if not e:
  492. e = frappe._dict({})
  493. frappe.local.response = frappe._dict(
  494. {
  495. "description": getattr(e, "description", "Internal Server Error"),
  496. "status_code": getattr(e, "status_code", 500),
  497. "error": getattr(e, "error", "internal_server_error"),
  498. }
  499. )
  500. frappe.local.response["http_status_code"] = getattr(e, "status_code", 500)
  501. return
  502. def get_server_url():
  503. request_url = urlparse(frappe.request.url)
  504. request_url = f"{request_url.scheme}://{request_url.netloc}"
  505. return frappe.get_value("Social Login Key", "frappe", "base_url") or request_url