Merge branch 'develop' into global-status-expiration
[akkoma] / test / captcha_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.CaptchaTest do
6 use Pleroma.DataCase
7
8 import Tesla.Mock
9
10 alias Pleroma.Captcha
11 alias Pleroma.Captcha.Kocaptcha
12 alias Pleroma.Captcha.Native
13
14 @ets_options [:ordered_set, :private, :named_table, {:read_concurrency, true}]
15 setup do: clear_config([Pleroma.Captcha, :enabled])
16
17 describe "Kocaptcha" do
18 setup do
19 ets_name = Kocaptcha.Ets
20 ^ets_name = :ets.new(ets_name, @ets_options)
21
22 mock(fn
23 %{method: :get, url: "https://captcha.kotobank.ch/new"} ->
24 json(%{
25 md5: "63615261b77f5354fb8c4e4986477555",
26 token: "afa1815e14e29355e6c8f6b143a39fa2",
27 url: "/captchas/afa1815e14e29355e6c8f6b143a39fa2.png"
28 })
29 end)
30
31 :ok
32 end
33
34 test "new and validate" do
35 new = Kocaptcha.new()
36
37 token = "afa1815e14e29355e6c8f6b143a39fa2"
38 url = "https://captcha.kotobank.ch/captchas/afa1815e14e29355e6c8f6b143a39fa2.png"
39
40 assert %{
41 answer_data: answer,
42 token: ^token,
43 url: ^url,
44 type: :kocaptcha
45 } = new
46
47 assert Kocaptcha.validate(token, "7oEy8c", answer) == :ok
48 end
49 end
50
51 describe "Native" do
52 test "new and validate" do
53 new = Native.new()
54
55 assert %{
56 answer_data: answer,
57 token: token,
58 type: :native,
59 url: "data:image/png;base64," <> _
60 } = new
61
62 assert is_binary(answer)
63 assert :ok = Native.validate(token, answer, answer)
64 assert {:error, "Invalid CAPTCHA"} == Native.validate(token, answer, answer <> "foobar")
65 end
66 end
67
68 describe "Captcha Wrapper" do
69 test "validate" do
70 Pleroma.Config.put([Pleroma.Captcha, :enabled], true)
71
72 new = Captcha.new()
73
74 assert %{
75 answer_data: answer,
76 token: token
77 } = new
78
79 assert is_binary(answer)
80 assert :ok = Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", answer)
81 end
82
83 test "doesn't validate invalid answer" do
84 Pleroma.Config.put([Pleroma.Captcha, :enabled], true)
85
86 new = Captcha.new()
87
88 assert %{
89 answer_data: answer,
90 token: token
91 } = new
92
93 assert is_binary(answer)
94
95 assert {:error, "Invalid answer data"} =
96 Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", answer <> "foobar")
97 end
98
99 test "nil answer_data" do
100 Pleroma.Config.put([Pleroma.Captcha, :enabled], true)
101
102 new = Captcha.new()
103
104 assert %{
105 answer_data: answer,
106 token: token
107 } = new
108
109 assert is_binary(answer)
110
111 assert {:error, "Invalid answer data"} =
112 Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", nil)
113 end
114 end
115 end