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.

739 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. "support_email": settings.SUPPORT_EMAIL,
  128. }
  129. return render(request, "accounts/login.html", ctx)
  130. def logout(request):
  131. auth_logout(request)
  132. return redirect("hc-index")
  133. @require_POST
  134. @csrf_exempt
  135. def signup(request):
  136. if not settings.REGISTRATION_OPEN:
  137. return HttpResponseForbidden()
  138. ctx = {}
  139. form = forms.AvailableEmailForm(request.POST)
  140. if form.is_valid():
  141. email = form.cleaned_data["identity"]
  142. user = _make_user(email)
  143. profile = Profile.objects.for_user(user)
  144. profile.send_instant_login_link()
  145. ctx["created"] = True
  146. else:
  147. ctx = {"form": form}
  148. response = render(request, "accounts/signup_result.html", ctx)
  149. if ctx.get("created"):
  150. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  151. return response
  152. def login_link_sent(request):
  153. return render(request, "accounts/login_link_sent.html")
  154. def check_token(request, username, token):
  155. if request.user.is_authenticated and request.user.username == username:
  156. # User is already logged in
  157. return _redirect_after_login(request)
  158. # Some email servers open links in emails to check for malicious content.
  159. # To work around this, we sign user in if the method is POST
  160. # *or* if the browser presents a cookie we had set when sending the login link.
  161. #
  162. # If the method is GET and the auto-login cookie isn't present, we serve
  163. # a HTML form with a submit button.
  164. if request.method == "POST" or "auto-login" in request.COOKIES:
  165. user = authenticate(username=username, token=token)
  166. if user is not None and user.is_active:
  167. user.profile.token = ""
  168. user.profile.save()
  169. return _check_2fa(request, user)
  170. request.session["bad_link"] = True
  171. return redirect("hc-login")
  172. return render(request, "accounts/check_token_submit.html")
  173. @login_required
  174. def profile(request):
  175. profile = request.profile
  176. ctx = {
  177. "page": "profile",
  178. "profile": profile,
  179. "my_projects_status": "default",
  180. "2fa_status": "default",
  181. "added_credential_name": request.session.pop("added_credential_name", ""),
  182. "removed_credential_name": request.session.pop("removed_credential_name", ""),
  183. "credentials": list(request.user.credentials.order_by("id")),
  184. "use_2fa": settings.RP_ID,
  185. }
  186. if ctx["added_credential_name"]:
  187. ctx["2fa_status"] = "success"
  188. if ctx["removed_credential_name"]:
  189. ctx["2fa_status"] = "info"
  190. if request.session.pop("changed_password", False):
  191. ctx["changed_password"] = True
  192. ctx["email_password_status"] = "success"
  193. if request.method == "POST" and "leave_project" in request.POST:
  194. code = request.POST["code"]
  195. try:
  196. project = Project.objects.get(code=code, member__user=request.user)
  197. except Project.DoesNotExist:
  198. return HttpResponseBadRequest()
  199. Member.objects.filter(project=project, user=request.user).delete()
  200. ctx["left_project"] = project
  201. ctx["my_projects_status"] = "info"
  202. return render(request, "accounts/profile.html", ctx)
  203. @login_required
  204. @require_POST
  205. def add_project(request):
  206. form = forms.ProjectNameForm(request.POST)
  207. if not form.is_valid():
  208. return HttpResponseBadRequest()
  209. project = Project(owner=request.user)
  210. project.code = project.badge_key = str(uuid.uuid4())
  211. project.name = form.cleaned_data["name"]
  212. project.save()
  213. return redirect("hc-checks", project.code)
  214. @login_required
  215. def project(request, code):
  216. project = get_object_or_404(Project, code=code)
  217. is_owner = project.owner_id == request.user.id
  218. if request.user.is_superuser or is_owner:
  219. rw = True
  220. else:
  221. membership = get_object_or_404(Member, project=project, user=request.user)
  222. rw = membership.rw
  223. ctx = {
  224. "page": "project",
  225. "rw": rw,
  226. "project": project,
  227. "is_owner": is_owner,
  228. "show_api_keys": "show_api_keys" in request.GET,
  229. }
  230. if request.method == "POST":
  231. if not rw:
  232. return HttpResponseForbidden()
  233. if "create_api_keys" in request.POST:
  234. project.set_api_keys()
  235. project.save()
  236. ctx["show_api_keys"] = True
  237. ctx["api_keys_created"] = True
  238. ctx["api_status"] = "success"
  239. elif "revoke_api_keys" in request.POST:
  240. project.api_key = ""
  241. project.api_key_readonly = ""
  242. project.save()
  243. ctx["api_keys_revoked"] = True
  244. ctx["api_status"] = "info"
  245. elif "show_api_keys" in request.POST:
  246. ctx["show_api_keys"] = True
  247. elif "invite_team_member" in request.POST:
  248. if not is_owner:
  249. return HttpResponseForbidden()
  250. form = forms.InviteTeamMemberForm(request.POST)
  251. if form.is_valid():
  252. email = form.cleaned_data["email"]
  253. invite_suggestions = project.invite_suggestions()
  254. if not invite_suggestions.filter(email=email).exists():
  255. # We're inviting a new user. Are we within team size limit?
  256. if not project.can_invite_new_users():
  257. return HttpResponseForbidden()
  258. # And are we not hitting a rate limit?
  259. if not TokenBucket.authorize_invite(request.user):
  260. return render(request, "try_later.html")
  261. try:
  262. user = User.objects.get(email=email)
  263. except User.DoesNotExist:
  264. user = _make_user(email, with_project=False)
  265. if project.invite(user, rw=form.cleaned_data["rw"]):
  266. ctx["team_member_invited"] = email
  267. ctx["team_status"] = "success"
  268. else:
  269. ctx["team_member_duplicate"] = email
  270. ctx["team_status"] = "info"
  271. elif "remove_team_member" in request.POST:
  272. if not is_owner:
  273. return HttpResponseForbidden()
  274. form = forms.RemoveTeamMemberForm(request.POST)
  275. if form.is_valid():
  276. q = User.objects
  277. q = q.filter(email=form.cleaned_data["email"])
  278. q = q.filter(memberships__project=project)
  279. farewell_user = q.first()
  280. if farewell_user is None:
  281. return HttpResponseBadRequest()
  282. Member.objects.filter(project=project, user=farewell_user).delete()
  283. ctx["team_member_removed"] = form.cleaned_data["email"]
  284. ctx["team_status"] = "info"
  285. elif "set_project_name" in request.POST:
  286. form = forms.ProjectNameForm(request.POST)
  287. if form.is_valid():
  288. project.name = form.cleaned_data["name"]
  289. project.save()
  290. ctx["project_name_updated"] = True
  291. ctx["project_name_status"] = "success"
  292. elif "transfer_project" in request.POST:
  293. if not is_owner:
  294. return HttpResponseForbidden()
  295. form = forms.TransferForm(request.POST)
  296. if form.is_valid():
  297. # Look up the proposed new owner
  298. email = form.cleaned_data["email"]
  299. try:
  300. membership = project.member_set.filter(user__email=email).get()
  301. except Member.DoesNotExist:
  302. return HttpResponseBadRequest()
  303. # Revoke any previous transfer requests
  304. project.member_set.update(transfer_request_date=None)
  305. # Initiate the new request
  306. membership.transfer_request_date = now()
  307. membership.save()
  308. # Send an email notification
  309. profile = Profile.objects.for_user(membership.user)
  310. profile.send_transfer_request(project)
  311. ctx["transfer_initiated"] = True
  312. ctx["transfer_status"] = "success"
  313. elif "cancel_transfer" in request.POST:
  314. if not is_owner:
  315. return HttpResponseForbidden()
  316. project.member_set.update(transfer_request_date=None)
  317. ctx["transfer_cancelled"] = True
  318. ctx["transfer_status"] = "success"
  319. elif "accept_transfer" in request.POST:
  320. tr = project.transfer_request()
  321. if not tr or tr.user != request.user:
  322. return HttpResponseForbidden()
  323. if not tr.can_accept():
  324. return HttpResponseBadRequest()
  325. with transaction.atomic():
  326. # 1. Reuse the existing membership, and change its user
  327. tr.user = project.owner
  328. tr.transfer_request_date = None
  329. tr.save()
  330. # 2. Change project's owner
  331. project.owner = request.user
  332. project.save()
  333. ctx["is_owner"] = True
  334. messages.success(request, "You are now the owner of this project!")
  335. elif "reject_transfer" in request.POST:
  336. tr = project.transfer_request()
  337. if not tr or tr.user != request.user:
  338. return HttpResponseForbidden()
  339. tr.transfer_request_date = None
  340. tr.save()
  341. return render(request, "accounts/project.html", ctx)
  342. @login_required
  343. def notifications(request):
  344. profile = request.profile
  345. ctx = {"status": "default", "page": "profile", "profile": profile}
  346. if request.method == "POST":
  347. form = forms.ReportSettingsForm(request.POST)
  348. if form.is_valid():
  349. if profile.reports_allowed != form.cleaned_data["reports_allowed"]:
  350. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  351. if profile.reports_allowed:
  352. profile.next_report_date = choose_next_report_date()
  353. else:
  354. profile.next_report_date = None
  355. if profile.nag_period != form.cleaned_data["nag_period"]:
  356. # Set the new nag period
  357. profile.nag_period = form.cleaned_data["nag_period"]
  358. # and schedule next_nag_date:
  359. if profile.nag_period:
  360. profile.next_nag_date = now() + profile.nag_period
  361. else:
  362. profile.next_nag_date = None
  363. profile.save()
  364. ctx["status"] = "info"
  365. return render(request, "accounts/notifications.html", ctx)
  366. @login_required
  367. @require_sudo_mode
  368. def set_password(request):
  369. if request.method == "POST":
  370. form = forms.SetPasswordForm(request.POST)
  371. if form.is_valid():
  372. password = form.cleaned_data["password"]
  373. request.user.set_password(password)
  374. request.user.save()
  375. request.profile.token = ""
  376. request.profile.save()
  377. # update the session with the new password hash so that
  378. # the user doesn't get logged out
  379. update_session_auth_hash(request, request.user)
  380. request.session["changed_password"] = True
  381. return redirect("hc-profile")
  382. return render(request, "accounts/set_password.html", {})
  383. @login_required
  384. @require_sudo_mode
  385. def change_email(request):
  386. if request.method == "POST":
  387. form = forms.ChangeEmailForm(request.POST)
  388. if form.is_valid():
  389. request.user.email = form.cleaned_data["email"]
  390. request.user.set_unusable_password()
  391. request.user.save()
  392. request.profile.token = ""
  393. request.profile.save()
  394. return redirect("hc-change-email-done")
  395. else:
  396. form = forms.ChangeEmailForm()
  397. return render(request, "accounts/change_email.html", {"form": form})
  398. def change_email_done(request):
  399. return render(request, "accounts/change_email_done.html")
  400. @csrf_exempt
  401. def unsubscribe_reports(request, signed_username):
  402. # Some email servers open links in emails to check for malicious content.
  403. # To work around this, for GET requests we serve a confirmation form.
  404. # If the signature is more than 5 minutes old, we also include JS code to
  405. # auto-submit the form.
  406. ctx = {}
  407. signer = signing.TimestampSigner(salt="reports")
  408. # First, check the signature without looking at the timestamp:
  409. try:
  410. username = signer.unsign(signed_username)
  411. except signing.BadSignature:
  412. return render(request, "bad_link.html")
  413. # Check if timestamp is older than 5 minutes:
  414. try:
  415. username = signer.unsign(signed_username, max_age=300)
  416. except signing.SignatureExpired:
  417. ctx["autosubmit"] = True
  418. if request.method != "POST":
  419. return render(request, "accounts/unsubscribe_submit.html", ctx)
  420. user = User.objects.get(username=username)
  421. profile = Profile.objects.for_user(user)
  422. profile.reports_allowed = False
  423. profile.next_report_date = None
  424. profile.nag_period = td()
  425. profile.next_nag_date = None
  426. profile.save()
  427. return render(request, "accounts/unsubscribed.html")
  428. @login_required
  429. @require_sudo_mode
  430. def close(request):
  431. user = request.user
  432. if request.method == "POST":
  433. if request.POST.get("confirmation") == request.user.email:
  434. # Cancel their subscription:
  435. sub = Subscription.objects.filter(user=user).first()
  436. if sub:
  437. sub.cancel()
  438. # Deleting user also deletes its profile, checks, channels etc.
  439. user.delete()
  440. request.session.flush()
  441. return redirect("hc-index")
  442. ctx = {}
  443. if "confirmation" in request.POST:
  444. ctx["wrong_confirmation"] = True
  445. return render(request, "accounts/close_account.html", ctx)
  446. @require_POST
  447. @login_required
  448. def remove_project(request, code):
  449. project = get_object_or_404(Project, code=code, owner=request.user)
  450. project.delete()
  451. return redirect("hc-index")
  452. def _get_credential_data(request, form):
  453. """ Complete WebAuthn registration, return binary credential data.
  454. This function is an interface to the fido2 library. It is separated
  455. out so that we don't need to mock ClientData, AttestationObject,
  456. register_complete separately in tests.
  457. """
  458. try:
  459. auth_data = FIDO2_SERVER.register_complete(
  460. request.session["state"],
  461. ClientData(form.cleaned_data["client_data_json"]),
  462. AttestationObject(form.cleaned_data["attestation_object"]),
  463. )
  464. except ValueError:
  465. return None
  466. return auth_data.credential_data
  467. @login_required
  468. @require_sudo_mode
  469. def add_credential(request):
  470. if not settings.RP_ID:
  471. return HttpResponse(status=404)
  472. if request.method == "POST":
  473. form = forms.AddCredentialForm(request.POST)
  474. if not form.is_valid():
  475. return HttpResponseBadRequest()
  476. credential_data = _get_credential_data(request, form)
  477. if not credential_data:
  478. return HttpResponseBadRequest()
  479. c = Credential(user=request.user)
  480. c.name = form.cleaned_data["name"]
  481. c.data = credential_data
  482. c.save()
  483. request.session["added_credential_name"] = c.name
  484. return redirect("hc-profile")
  485. credentials = [c.unpack() for c in request.user.credentials.all()]
  486. # User handle is used in a username-less authentication, to map a credential
  487. # received from browser with an user account in the database.
  488. # Since we only use security keys as a second factor,
  489. # the user handle is not of much use to us.
  490. #
  491. # The user handle:
  492. # - must not be blank,
  493. # - must not be a constant value,
  494. # - must not contain personally identifiable information.
  495. # So we use random bytes, and don't store them on our end:
  496. options, state = FIDO2_SERVER.register_begin(
  497. {
  498. "id": token_bytes(16),
  499. "name": request.user.email,
  500. "displayName": request.user.email,
  501. },
  502. credentials,
  503. )
  504. request.session["state"] = state
  505. ctx = {"options": base64.b64encode(cbor.encode(options)).decode()}
  506. return render(request, "accounts/add_credential.html", ctx)
  507. @login_required
  508. @require_sudo_mode
  509. def remove_credential(request, code):
  510. if not settings.RP_ID:
  511. return HttpResponse(status=404)
  512. try:
  513. credential = Credential.objects.get(user=request.user, code=code)
  514. except Credential.DoesNotExist:
  515. return HttpResponseBadRequest()
  516. if request.method == "POST" and "remove_credential" in request.POST:
  517. request.session["removed_credential_name"] = credential.name
  518. credential.delete()
  519. return redirect("hc-profile")
  520. ctx = {"credential": credential, "is_last": request.user.credentials.count() == 1}
  521. return render(request, "accounts/remove_credential.html", ctx)
  522. def _check_credential(request, form, credentials):
  523. """ Complete WebAuthn authentication, return True on success.
  524. This function is an interface to the fido2 library. It is separated
  525. out so that we don't need to mock ClientData, AuthenticatorData,
  526. authenticate_complete separately in tests.
  527. """
  528. try:
  529. FIDO2_SERVER.authenticate_complete(
  530. request.session["state"],
  531. credentials,
  532. form.cleaned_data["credential_id"],
  533. ClientData(form.cleaned_data["client_data_json"]),
  534. AuthenticatorData(form.cleaned_data["authenticator_data"]),
  535. form.cleaned_data["signature"],
  536. )
  537. except ValueError:
  538. return False
  539. return True
  540. def login_webauthn(request):
  541. # We require RP_ID. Fail predicably if it is not set:
  542. if not settings.RP_ID:
  543. return HttpResponse(status=500)
  544. # Expect an unauthenticated user
  545. if request.user.is_authenticated:
  546. return HttpResponseBadRequest()
  547. if "2fa_user" not in request.session:
  548. return HttpResponseBadRequest()
  549. user_id, email, timestamp = request.session["2fa_user"]
  550. if timestamp + 300 < time.time():
  551. return redirect("hc-login")
  552. try:
  553. user = User.objects.get(id=user_id, email=email)
  554. except User.DoesNotExist:
  555. return HttpResponseBadRequest()
  556. credentials = [c.unpack() for c in user.credentials.all()]
  557. if request.method == "POST":
  558. form = forms.WebAuthnForm(request.POST)
  559. if not form.is_valid():
  560. return HttpResponseBadRequest()
  561. if not _check_credential(request, form, credentials):
  562. return HttpResponseBadRequest()
  563. request.session.pop("state")
  564. request.session.pop("2fa_user")
  565. auth_login(request, user, "hc.accounts.backends.EmailBackend")
  566. return _redirect_after_login(request)
  567. options, state = FIDO2_SERVER.authenticate_begin(credentials)
  568. request.session["state"] = state
  569. ctx = {"options": base64.b64encode(cbor.encode(options)).decode()}
  570. return render(request, "accounts/login_webauthn.html", ctx)