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.

738 lines
24 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. import base64
  2. from datetime import timedelta as td
  3. from secrets import token_bytes
  4. from urllib.parse import urlparse
  5. import time
  6. import uuid
  7. from django.db import transaction
  8. from django.conf import settings
  9. from django.contrib import messages
  10. from django.contrib.auth import login as auth_login
  11. from django.contrib.auth import logout as auth_logout
  12. from django.contrib.auth import authenticate, update_session_auth_hash
  13. from django.contrib.auth.decorators import login_required
  14. from django.contrib.auth.models import User
  15. from django.core import signing
  16. from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest
  17. from django.shortcuts import get_object_or_404, redirect, render
  18. from django.utils.timezone import now
  19. from django.urls import resolve, reverse, Resolver404
  20. from django.views.decorators.csrf import csrf_exempt
  21. from django.views.decorators.http import require_POST
  22. from fido2.ctap2 import AttestationObject, AuthenticatorData
  23. from fido2.client import ClientData
  24. from fido2.server import Fido2Server
  25. from fido2.webauthn import PublicKeyCredentialRpEntity
  26. from fido2 import cbor
  27. from hc.accounts import forms
  28. from hc.accounts.decorators import require_sudo_mode
  29. from hc.accounts.models import Credential, Profile, Project, Member
  30. from hc.api.models import Channel, Check, TokenBucket
  31. from hc.lib.date import choose_next_report_date
  32. from hc.payments.models import Subscription
  33. POST_LOGIN_ROUTES = (
  34. "hc-checks",
  35. "hc-details",
  36. "hc-log",
  37. "hc-channels",
  38. "hc-add-slack",
  39. "hc-add-pushover",
  40. "hc-add-telegram",
  41. "hc-project-settings",
  42. )
  43. FIDO2_SERVER = Fido2Server(PublicKeyCredentialRpEntity(settings.RP_ID, "healthchecks"))
  44. def _allow_redirect(redirect_url):
  45. if not redirect_url:
  46. return False
  47. parsed = urlparse(redirect_url)
  48. try:
  49. match = resolve(parsed.path)
  50. except Resolver404:
  51. return False
  52. return match.url_name in POST_LOGIN_ROUTES
  53. def _make_user(email, with_project=True):
  54. username = str(uuid.uuid4())[:30]
  55. user = User(username=username, email=email)
  56. user.set_unusable_password()
  57. user.save()
  58. project = None
  59. if with_project:
  60. project = Project(owner=user)
  61. project.badge_key = user.username
  62. project.save()
  63. check = Check(project=project)
  64. check.name = "My First Check"
  65. check.save()
  66. channel = Channel(project=project)
  67. channel.kind = "email"
  68. channel.value = email
  69. channel.email_verified = True
  70. channel.save()
  71. channel.checks.add(check)
  72. # Ensure a profile gets created
  73. Profile.objects.for_user(user)
  74. return user
  75. def _redirect_after_login(request):
  76. """ Redirect to the URL indicated in ?next= query parameter. """
  77. redirect_url = request.GET.get("next")
  78. if _allow_redirect(redirect_url):
  79. return redirect(redirect_url)
  80. if request.user.project_set.count() == 1:
  81. project = request.user.project_set.first()
  82. return redirect("hc-checks", project.code)
  83. return redirect("hc-index")
  84. def _check_2fa(request, user):
  85. if user.credentials.exists():
  86. # We have verified user's password or token, and now must
  87. # verify their security key. We store the following in user's session:
  88. # - user.id, to look up the user in the login_webauthn view
  89. # - user.email, to make sure email was not changed between the auth steps
  90. # - timestamp, to limit the max time between the auth steps
  91. request.session["2fa_user"] = [user.id, user.email, int(time.time())]
  92. path = reverse("hc-login-webauthn")
  93. redirect_url = request.GET.get("next")
  94. if _allow_redirect(redirect_url):
  95. path += "?next=%s" % redirect_url
  96. return redirect(path)
  97. auth_login(request, user)
  98. return _redirect_after_login(request)
  99. def login(request):
  100. form = forms.PasswordLoginForm()
  101. magic_form = forms.EmailLoginForm()
  102. if request.method == "POST":
  103. if request.POST.get("action") == "login":
  104. form = forms.PasswordLoginForm(request.POST)
  105. if form.is_valid():
  106. return _check_2fa(request, form.user)
  107. else:
  108. magic_form = forms.EmailLoginForm(request.POST)
  109. if magic_form.is_valid():
  110. redirect_url = request.GET.get("next")
  111. if not _allow_redirect(redirect_url):
  112. redirect_url = None
  113. profile = Profile.objects.for_user(magic_form.user)
  114. profile.send_instant_login_link(redirect_url=redirect_url)
  115. response = redirect("hc-login-link-sent")
  116. # check_token_submit looks for this cookie to decide if
  117. # it needs to do the extra POST step.
  118. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  119. return response
  120. bad_link = request.session.pop("bad_link", None)
  121. ctx = {
  122. "page": "login",
  123. "form": form,
  124. "magic_form": magic_form,
  125. "bad_link": bad_link,
  126. "registration_open": settings.REGISTRATION_OPEN,
  127. }
  128. return render(request, "accounts/login.html", ctx)
  129. def logout(request):
  130. auth_logout(request)
  131. return redirect("hc-index")
  132. @require_POST
  133. @csrf_exempt
  134. def signup(request):
  135. if not settings.REGISTRATION_OPEN:
  136. return HttpResponseForbidden()
  137. ctx = {}
  138. form = forms.AvailableEmailForm(request.POST)
  139. if form.is_valid():
  140. email = form.cleaned_data["identity"]
  141. user = _make_user(email)
  142. profile = Profile.objects.for_user(user)
  143. profile.send_instant_login_link()
  144. ctx["created"] = True
  145. else:
  146. ctx = {"form": form}
  147. response = render(request, "accounts/signup_result.html", ctx)
  148. if ctx.get("created"):
  149. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  150. return response
  151. def login_link_sent(request):
  152. return render(request, "accounts/login_link_sent.html")
  153. def check_token(request, username, token):
  154. if request.user.is_authenticated and request.user.username == username:
  155. # User is already logged in
  156. return _redirect_after_login(request)
  157. # Some email servers open links in emails to check for malicious content.
  158. # To work around this, we sign user in if the method is POST
  159. # *or* if the browser presents a cookie we had set when sending the login link.
  160. #
  161. # If the method is GET and the auto-login cookie isn't present, we serve
  162. # a HTML form with a submit button.
  163. if request.method == "POST" or "auto-login" in request.COOKIES:
  164. user = authenticate(username=username, token=token)
  165. if user is not None and user.is_active:
  166. user.profile.token = ""
  167. user.profile.save()
  168. return _check_2fa(request, user)
  169. request.session["bad_link"] = True
  170. return redirect("hc-login")
  171. return render(request, "accounts/check_token_submit.html")
  172. @login_required
  173. def profile(request):
  174. profile = request.profile
  175. ctx = {
  176. "page": "profile",
  177. "profile": profile,
  178. "my_projects_status": "default",
  179. "2fa_status": "default",
  180. "added_credential_name": request.session.pop("added_credential_name", ""),
  181. "removed_credential_name": request.session.pop("removed_credential_name", ""),
  182. "credentials": list(request.user.credentials.order_by("id")),
  183. "use_2fa": settings.RP_ID,
  184. }
  185. if ctx["added_credential_name"]:
  186. ctx["2fa_status"] = "success"
  187. if ctx["removed_credential_name"]:
  188. ctx["2fa_status"] = "info"
  189. if request.session.pop("changed_password", False):
  190. ctx["changed_password"] = True
  191. ctx["email_password_status"] = "success"
  192. if request.method == "POST" and "leave_project" in request.POST:
  193. code = request.POST["code"]
  194. try:
  195. project = Project.objects.get(code=code, member__user=request.user)
  196. except Project.DoesNotExist:
  197. return HttpResponseBadRequest()
  198. Member.objects.filter(project=project, user=request.user).delete()
  199. ctx["left_project"] = project
  200. ctx["my_projects_status"] = "info"
  201. return render(request, "accounts/profile.html", ctx)
  202. @login_required
  203. @require_POST
  204. def add_project(request):
  205. form = forms.ProjectNameForm(request.POST)
  206. if not form.is_valid():
  207. return HttpResponseBadRequest()
  208. project = Project(owner=request.user)
  209. project.code = project.badge_key = str(uuid.uuid4())
  210. project.name = form.cleaned_data["name"]
  211. project.save()
  212. return redirect("hc-checks", project.code)
  213. @login_required
  214. def project(request, code):
  215. project = get_object_or_404(Project, code=code)
  216. is_owner = project.owner_id == request.user.id
  217. if request.user.is_superuser or is_owner:
  218. rw = True
  219. else:
  220. membership = get_object_or_404(Member, project=project, user=request.user)
  221. rw = membership.rw
  222. ctx = {
  223. "page": "project",
  224. "rw": rw,
  225. "project": project,
  226. "is_owner": is_owner,
  227. "show_api_keys": "show_api_keys" in request.GET,
  228. }
  229. if request.method == "POST":
  230. if not rw:
  231. return HttpResponseForbidden()
  232. if "create_api_keys" in request.POST:
  233. project.set_api_keys()
  234. project.save()
  235. ctx["show_api_keys"] = True
  236. ctx["api_keys_created"] = True
  237. ctx["api_status"] = "success"
  238. elif "revoke_api_keys" in request.POST:
  239. project.api_key = ""
  240. project.api_key_readonly = ""
  241. project.save()
  242. ctx["api_keys_revoked"] = True
  243. ctx["api_status"] = "info"
  244. elif "show_api_keys" in request.POST:
  245. ctx["show_api_keys"] = True
  246. elif "invite_team_member" in request.POST:
  247. if not is_owner:
  248. return HttpResponseForbidden()
  249. form = forms.InviteTeamMemberForm(request.POST)
  250. if form.is_valid():
  251. email = form.cleaned_data["email"]
  252. invite_suggestions = project.invite_suggestions()
  253. if not invite_suggestions.filter(email=email).exists():
  254. # We're inviting a new user. Are we within team size limit?
  255. if not project.can_invite_new_users():
  256. return HttpResponseForbidden()
  257. # And are we not hitting a rate limit?
  258. if not TokenBucket.authorize_invite(request.user):
  259. return render(request, "try_later.html")
  260. try:
  261. user = User.objects.get(email=email)
  262. except User.DoesNotExist:
  263. user = _make_user(email, with_project=False)
  264. if project.invite(user, rw=form.cleaned_data["rw"]):
  265. ctx["team_member_invited"] = email
  266. ctx["team_status"] = "success"
  267. else:
  268. ctx["team_member_duplicate"] = email
  269. ctx["team_status"] = "info"
  270. elif "remove_team_member" in request.POST:
  271. if not is_owner:
  272. return HttpResponseForbidden()
  273. form = forms.RemoveTeamMemberForm(request.POST)
  274. if form.is_valid():
  275. q = User.objects
  276. q = q.filter(email=form.cleaned_data["email"])
  277. q = q.filter(memberships__project=project)
  278. farewell_user = q.first()
  279. if farewell_user is None:
  280. return HttpResponseBadRequest()
  281. Member.objects.filter(project=project, user=farewell_user).delete()
  282. ctx["team_member_removed"] = form.cleaned_data["email"]
  283. ctx["team_status"] = "info"
  284. elif "set_project_name" in request.POST:
  285. form = forms.ProjectNameForm(request.POST)
  286. if form.is_valid():
  287. project.name = form.cleaned_data["name"]
  288. project.save()
  289. ctx["project_name_updated"] = True
  290. ctx["project_name_status"] = "success"
  291. elif "transfer_project" in request.POST:
  292. if not is_owner:
  293. return HttpResponseForbidden()
  294. form = forms.TransferForm(request.POST)
  295. if form.is_valid():
  296. # Look up the proposed new owner
  297. email = form.cleaned_data["email"]
  298. try:
  299. membership = project.member_set.filter(user__email=email).get()
  300. except Member.DoesNotExist:
  301. return HttpResponseBadRequest()
  302. # Revoke any previous transfer requests
  303. project.member_set.update(transfer_request_date=None)
  304. # Initiate the new request
  305. membership.transfer_request_date = now()
  306. membership.save()
  307. # Send an email notification
  308. profile = Profile.objects.for_user(membership.user)
  309. profile.send_transfer_request(project)
  310. ctx["transfer_initiated"] = True
  311. ctx["transfer_status"] = "success"
  312. elif "cancel_transfer" in request.POST:
  313. if not is_owner:
  314. return HttpResponseForbidden()
  315. project.member_set.update(transfer_request_date=None)
  316. ctx["transfer_cancelled"] = True
  317. ctx["transfer_status"] = "success"
  318. elif "accept_transfer" in request.POST:
  319. tr = project.transfer_request()
  320. if not tr or tr.user != request.user:
  321. return HttpResponseForbidden()
  322. if not tr.can_accept():
  323. return HttpResponseBadRequest()
  324. with transaction.atomic():
  325. # 1. Reuse the existing membership, and change its user
  326. tr.user = project.owner
  327. tr.transfer_request_date = None
  328. tr.save()
  329. # 2. Change project's owner
  330. project.owner = request.user
  331. project.save()
  332. ctx["is_owner"] = True
  333. messages.success(request, "You are now the owner of this project!")
  334. elif "reject_transfer" in request.POST:
  335. tr = project.transfer_request()
  336. if not tr or tr.user != request.user:
  337. return HttpResponseForbidden()
  338. tr.transfer_request_date = None
  339. tr.save()
  340. return render(request, "accounts/project.html", ctx)
  341. @login_required
  342. def notifications(request):
  343. profile = request.profile
  344. ctx = {"status": "default", "page": "profile", "profile": profile}
  345. if request.method == "POST":
  346. form = forms.ReportSettingsForm(request.POST)
  347. if form.is_valid():
  348. if profile.reports_allowed != form.cleaned_data["reports_allowed"]:
  349. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  350. if profile.reports_allowed:
  351. profile.next_report_date = choose_next_report_date()
  352. else:
  353. profile.next_report_date = None
  354. if profile.nag_period != form.cleaned_data["nag_period"]:
  355. # Set the new nag period
  356. profile.nag_period = form.cleaned_data["nag_period"]
  357. # and schedule next_nag_date:
  358. if profile.nag_period:
  359. profile.next_nag_date = now() + profile.nag_period
  360. else:
  361. profile.next_nag_date = None
  362. profile.save()
  363. ctx["status"] = "info"
  364. return render(request, "accounts/notifications.html", ctx)
  365. @login_required
  366. @require_sudo_mode
  367. def set_password(request):
  368. if request.method == "POST":
  369. form = forms.SetPasswordForm(request.POST)
  370. if form.is_valid():
  371. password = form.cleaned_data["password"]
  372. request.user.set_password(password)
  373. request.user.save()
  374. request.profile.token = ""
  375. request.profile.save()
  376. # update the session with the new password hash so that
  377. # the user doesn't get logged out
  378. update_session_auth_hash(request, request.user)
  379. request.session["changed_password"] = True
  380. return redirect("hc-profile")
  381. return render(request, "accounts/set_password.html", {})
  382. @login_required
  383. @require_sudo_mode
  384. def change_email(request):
  385. if request.method == "POST":
  386. form = forms.ChangeEmailForm(request.POST)
  387. if form.is_valid():
  388. request.user.email = form.cleaned_data["email"]
  389. request.user.set_unusable_password()
  390. request.user.save()
  391. request.profile.token = ""
  392. request.profile.save()
  393. return redirect("hc-change-email-done")
  394. else:
  395. form = forms.ChangeEmailForm()
  396. return render(request, "accounts/change_email.html", {"form": form})
  397. def change_email_done(request):
  398. return render(request, "accounts/change_email_done.html")
  399. @csrf_exempt
  400. def unsubscribe_reports(request, signed_username):
  401. # Some email servers open links in emails to check for malicious content.
  402. # To work around this, for GET requests we serve a confirmation form.
  403. # If the signature is more than 5 minutes old, we also include JS code to
  404. # auto-submit the form.
  405. ctx = {}
  406. signer = signing.TimestampSigner(salt="reports")
  407. # First, check the signature without looking at the timestamp:
  408. try:
  409. username = signer.unsign(signed_username)
  410. except signing.BadSignature:
  411. return render(request, "bad_link.html")
  412. # Check if timestamp is older than 5 minutes:
  413. try:
  414. username = signer.unsign(signed_username, max_age=300)
  415. except signing.SignatureExpired:
  416. ctx["autosubmit"] = True
  417. if request.method != "POST":
  418. return render(request, "accounts/unsubscribe_submit.html", ctx)
  419. user = User.objects.get(username=username)
  420. profile = Profile.objects.for_user(user)
  421. profile.reports_allowed = False
  422. profile.next_report_date = None
  423. profile.nag_period = td()
  424. profile.next_nag_date = None
  425. profile.save()
  426. return render(request, "accounts/unsubscribed.html")
  427. @login_required
  428. @require_sudo_mode
  429. def close(request):
  430. user = request.user
  431. if request.method == "POST":
  432. if request.POST.get("confirmation") == request.user.email:
  433. # Cancel their subscription:
  434. sub = Subscription.objects.filter(user=user).first()
  435. if sub:
  436. sub.cancel()
  437. # Deleting user also deletes its profile, checks, channels etc.
  438. user.delete()
  439. request.session.flush()
  440. return redirect("hc-index")
  441. ctx = {}
  442. if "confirmation" in request.POST:
  443. ctx["wrong_confirmation"] = True
  444. return render(request, "accounts/close_account.html", ctx)
  445. @require_POST
  446. @login_required
  447. def remove_project(request, code):
  448. project = get_object_or_404(Project, code=code, owner=request.user)
  449. project.delete()
  450. return redirect("hc-index")
  451. def _get_credential_data(request, form):
  452. """ Complete WebAuthn registration, return binary credential data.
  453. This function is an interface to the fido2 library. It is separated
  454. out so that we don't need to mock ClientData, AttestationObject,
  455. register_complete separately in tests.
  456. """
  457. try:
  458. auth_data = FIDO2_SERVER.register_complete(
  459. request.session["state"],
  460. ClientData(form.cleaned_data["client_data_json"]),
  461. AttestationObject(form.cleaned_data["attestation_object"]),
  462. )
  463. except ValueError:
  464. return None
  465. return auth_data.credential_data
  466. @login_required
  467. @require_sudo_mode
  468. def add_credential(request):
  469. if not settings.RP_ID:
  470. return HttpResponse(status=404)
  471. if request.method == "POST":
  472. form = forms.AddCredentialForm(request.POST)
  473. if not form.is_valid():
  474. return HttpResponseBadRequest()
  475. credential_data = _get_credential_data(request, form)
  476. if not credential_data:
  477. return HttpResponseBadRequest()
  478. c = Credential(user=request.user)
  479. c.name = form.cleaned_data["name"]
  480. c.data = credential_data
  481. c.save()
  482. request.session["added_credential_name"] = c.name
  483. return redirect("hc-profile")
  484. credentials = [c.unpack() for c in request.user.credentials.all()]
  485. # User handle is used in a username-less authentication, to map a credential
  486. # received from browser with an user account in the database.
  487. # Since we only use security keys as a second factor,
  488. # the user handle is not of much use to us.
  489. #
  490. # The user handle:
  491. # - must not be blank,
  492. # - must not be a constant value,
  493. # - must not contain personally identifiable information.
  494. # So we use random bytes, and don't store them on our end:
  495. options, state = FIDO2_SERVER.register_begin(
  496. {
  497. "id": token_bytes(16),
  498. "name": request.user.email,
  499. "displayName": request.user.email,
  500. },
  501. credentials,
  502. )
  503. request.session["state"] = state
  504. ctx = {"options": base64.b64encode(cbor.encode(options)).decode()}
  505. return render(request, "accounts/add_credential.html", ctx)
  506. @login_required
  507. @require_sudo_mode
  508. def remove_credential(request, code):
  509. if not settings.RP_ID:
  510. return HttpResponse(status=404)
  511. try:
  512. credential = Credential.objects.get(user=request.user, code=code)
  513. except Credential.DoesNotExist:
  514. return HttpResponseBadRequest()
  515. if request.method == "POST" and "remove_credential" in request.POST:
  516. request.session["removed_credential_name"] = credential.name
  517. credential.delete()
  518. return redirect("hc-profile")
  519. ctx = {"credential": credential, "is_last": request.user.credentials.count() == 1}
  520. return render(request, "accounts/remove_credential.html", ctx)
  521. def _check_credential(request, form, credentials):
  522. """ Complete WebAuthn authentication, return True on success.
  523. This function is an interface to the fido2 library. It is separated
  524. out so that we don't need to mock ClientData, AuthenticatorData,
  525. authenticate_complete separately in tests.
  526. """
  527. try:
  528. FIDO2_SERVER.authenticate_complete(
  529. request.session["state"],
  530. credentials,
  531. form.cleaned_data["credential_id"],
  532. ClientData(form.cleaned_data["client_data_json"]),
  533. AuthenticatorData(form.cleaned_data["authenticator_data"]),
  534. form.cleaned_data["signature"],
  535. )
  536. except ValueError:
  537. return False
  538. return True
  539. def login_webauthn(request):
  540. # We require RP_ID. Fail predicably if it is not set:
  541. if not settings.RP_ID:
  542. return HttpResponse(status=500)
  543. # Expect an unauthenticated user
  544. if request.user.is_authenticated:
  545. return HttpResponseBadRequest()
  546. if "2fa_user" not in request.session:
  547. return HttpResponseBadRequest()
  548. user_id, email, timestamp = request.session["2fa_user"]
  549. if timestamp + 300 < time.time():
  550. return redirect("hc-login")
  551. try:
  552. user = User.objects.get(id=user_id, email=email)
  553. except User.DoesNotExist:
  554. return HttpResponseBadRequest()
  555. credentials = [c.unpack() for c in user.credentials.all()]
  556. if request.method == "POST":
  557. form = forms.WebAuthnForm(request.POST)
  558. if not form.is_valid():
  559. return HttpResponseBadRequest()
  560. if not _check_credential(request, form, credentials):
  561. return HttpResponseBadRequest()
  562. request.session.pop("state")
  563. request.session.pop("2fa_user")
  564. auth_login(request, user, "hc.accounts.backends.EmailBackend")
  565. return _redirect_after_login(request)
  566. options, state = FIDO2_SERVER.authenticate_begin(credentials)
  567. request.session["state"] = state
  568. ctx = {"options": base64.b64encode(cbor.encode(options)).decode()}
  569. return render(request, "accounts/login_webauthn.html", ctx)