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.

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