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.

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