summaryrefslogtreecommitdiff
path: root/test/elixir/test/users_db_test.exs
blob: 7c678c4f095c73a363ff2300ee4a47ce08ba173b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
defmodule UsersDbTest do
  use CouchTestCase

  @moduletag :authentication
  @moduletag kind: :single_node

  @users_db_name "_users"

  @moduletag config: [
               {
                 "chttpd_auth",
                 "authentication_db",
                 @users_db_name
               },
               {
                 "couch_httpd_auth",
                 "authentication_db",
                 @users_db_name
               },
               {
                 "couch_httpd_auth",
                 "iterations",
                 "1"
               },
               {
                 "admins",
                 "jan",
                 "apple"
               }
             ]

  setup do
    # Create db if not exists
    Couch.put("/#{@users_db_name}")

    resp =
      Couch.get(
        "/#{@users_db_name}/_changes",
        query: [feed: "longpoll", timeout: 5000, filter: "_design"]
      )

    assert resp.body

    on_exit(&tear_down/0)

    :ok
  end

  defp tear_down do
    delete_db(@users_db_name)
    create_db(@users_db_name)
  end

  defp save_as(db_name, doc, options) do
    session = Keyword.get(options, :use_session)
    expect_response = Keyword.get(options, :expect_response, [201, 202])
    expect_message = Keyword.get(options, :error_message)
    expect_reason = Keyword.get(options, :error_reason)

    headers =
      if session != nil do
        [
          Cookie: session.cookie,
          "X-CouchDB-www-Authenticate": "Cookie"
        ]
      else
        []
      end

    resp =
      Couch.put(
        "/#{db_name}/#{URI.encode(doc["_id"])}",
        headers: headers,
        body: doc
      )

    if is_list(expect_response) do
      assert resp.status_code in expect_response
    else
      assert resp.status_code == expect_response
    end

    if expect_message != nil do
      assert resp.body["error"] == expect_message
    end

    if expect_reason != nil do
      assert resp.body["reason"] == expect_reason
    end

    resp
  end

  defp login(user, password) do
    sess = Couch.login(user, password)
    assert sess.cookie, "Login correct is expected"
    sess
  end

  defp logout(session) do
    assert Couch.Session.logout(session).body["ok"]
  end

  @tag :with_db
  test "users db", context do
    db_name = context[:db_name]
    # test that the users db is born with the auth ddoc
    ddoc = Couch.get("/#{@users_db_name}/_design/_auth")
    assert ddoc.body["validate_doc_update"] != nil

    jchris_user_doc =
      prepare_user_doc([
        {:name, "jchris@apache.org"},
        {:password, "funnybone"}
      ])

    {:ok, resp} = create_doc(@users_db_name, jchris_user_doc)
    jchris_rev = resp.body["rev"]

    resp =
      Couch.get(
        "/_session",
        headers: [authorization: "Basic #{:base64.encode("jchris@apache.org:funnybone")}"]
      )

    assert resp.body["userCtx"]["name"] == "jchris@apache.org"
    assert resp.body["info"]["authenticated"] == "default"
    assert resp.body["info"]["authentication_db"] == @users_db_name
    assert Enum.member?(resp.body["info"]["authentication_handlers"], "cookie")
    assert Enum.member?(resp.body["info"]["authentication_handlers"], "default")

    resp =
      Couch.get(
        "/_session",
        headers: [authorization: "Basic Xzpf"]
      )

    assert resp.body["userCtx"]["name"] == :null
    assert not Enum.member?(resp.body["info"], "authenticated")

    # ok, now create a conflicting edit on the jchris doc, and make sure there's no login.
    # (use replication to create the conflict) - need 2 be admin
    session = login("jan", "apple")
    replicate(@users_db_name, db_name)

    jchris_user_doc = Map.put(jchris_user_doc, "_rev", jchris_rev)

    jchris_user_doc2 = Map.put(jchris_user_doc, "foo", "bar")

    save_as(@users_db_name, jchris_user_doc2, use_session: session)
    save_as(@users_db_name, jchris_user_doc, use_session: session, expect_response: 409)

    # then in the other
    jchris_user_doc3 = Map.put(jchris_user_doc, "foo", "barrrr")
    save_as(db_name, jchris_user_doc3, use_session: session)
    replicate(db_name, @users_db_name)
    # now we should have a conflict

    resp =
      Couch.get(
        "/#{@users_db_name}/#{jchris_user_doc3["_id"]}",
        query: [conflicts: true]
      )

    assert length(resp.body["_conflicts"]) == 1
    jchris_with_conflict = resp.body

    logout(session)

    # wait for auth_cache invalidation
    retry_until(
      fn ->
        resp =
          Couch.get(
            "/_session",
            headers: [
              authorization: "Basic #{:base64.encode("jchris@apache.org:funnybone")}"
            ]
          )

        assert resp.body["error"] == "unauthorized"
        assert String.contains?(resp.body["reason"], "conflict")
        resp
      end,
      500,
      20_000
    )

    # You can delete a user doc
    session = login("jan", "apple")
    info = Couch.Session.info(session)
    assert Enum.member?(info["userCtx"]["roles"], "_admin")

    resp =
      Couch.delete(
        "/#{@users_db_name}/#{jchris_with_conflict["_id"]}",
        query: [rev: jchris_with_conflict["_rev"]],
        headers: [
          Cookie: session.cookie,
          "X-CouchDB-www-Authenticate": "Cookie"
        ]
      )

    assert resp.body["ok"]

    # you can't change doc from type "user"
    resp =
      Couch.get(
        "/#{@users_db_name}/#{jchris_user_doc["_id"]}",
        headers: [
          Cookie: session.cookie,
          "X-CouchDB-www-Authenticate": "Cookie"
        ]
      )

    assert resp.status_code == 200

    jchris_user_doc = Map.replace!(resp.body, "type", "not user")

    save_as(
      @users_db_name,
      jchris_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "doc.type must be user"
    )

    # "roles" must be an array
    jchris_user_doc =
      jchris_user_doc
      |> Map.replace!("type", "user")
      |> Map.replace!("roles", "not an array")

    save_as(
      @users_db_name,
      jchris_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "doc.roles must be an array"
    )

    # "roles" must be and array of strings
    jchris_user_doc = Map.replace!(jchris_user_doc, "roles", [12])

    save_as(
      @users_db_name,
      jchris_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "doc.roles can only contain strings"
    )

    # "roles" must exist
    jchris_user_doc = Map.drop(jchris_user_doc, ["roles"])

    save_as(
      @users_db_name,
      jchris_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "doc.roles must exist"
    )

    # character : is not allowed in usernames
    joe_user_doc =
      prepare_user_doc([
        {:name, "joe:erlang"},
        {:password, "querty"}
      ])

    save_as(
      @users_db_name,
      joe_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "Character `:` is not allowed in usernames."
    )

    # test that you can login as a user with a password starting with :
    joe_user_doc =
      prepare_user_doc([
        {:name, "foo@example.org"},
        {:password, ":bar"}
      ])

    {:ok, _} = create_doc(@users_db_name, joe_user_doc)
    logout(session)

    resp =
      Couch.get(
        "/_session",
        headers: [authorization: "Basic #{:base64.encode("foo@example.org::bar")}"]
      )

    assert resp.body["userCtx"]["name"] == "foo@example.org"
  end

  test "users password requirements", _context do
    set_config({
      "couch_httpd_auth",
      "password_regexp",
      Enum.join(
        [
          "[{\".{10,}\"},", # 10 chars
          "{\"[A-Z]+\", \"Requirement 2.\"},", # a uppercase char
          "{\"[a-z]+\", \"\"},", # a lowercase char
          "{\"\\\\d+\", \"Req 4.\"},", # A number
          "\"[!\.,\(\)]+\"]" # A special char
        ],
        " "
      )
    })

    session = login("jan", "apple")

    # With password that doesn't confirm to any requirement.
    # Requirement doesn't have a reason text.
    jchris_user_doc =
      prepare_user_doc([
        {:name, "jchris@apache.org"},
        {:password, "funnybone"}
      ])
    save_as(
      @users_db_name,
      jchris_user_doc,
      use_session: session,
      expect_response: 400,
      error_message: "bad_request",
      error_reason: "Password does not conform to requirements."
    )

    # With password that match the first requirement.
    # Requirement does have a reason text.
    jchris_user_doc2 = Map.put(jchris_user_doc, "password", "funnnnnybone")
    save_as(
      @users_db_name,
      jchris_user_doc2,
      use_session: session,
      expect_response: 400,
      error_message: "bad_request",
      error_reason: "Password does not conform to requirements. Requirement 2."
    )

    # With password that match the first two requirements.
    # Requirement does have an empty string as reason text.
    jchris_user_doc3 = Map.put(jchris_user_doc, "password", "FUNNNNNYBONE")
    save_as(
      @users_db_name,
      jchris_user_doc3,
      use_session: session,
      expect_response: 400,
      error_message: "bad_request",
      error_reason: "Password does not conform to requirements."
    )

    # With password that match the first three requirements.
    # Requirement does have a reason text.
    jchris_user_doc4 = Map.put(jchris_user_doc, "password", "funnnnnyBONE")
    save_as(
      @users_db_name,
      jchris_user_doc4,
      use_session: session,
      expect_response: 400,
      error_message: "bad_request",
      error_reason: "Password does not conform to requirements. Req 4."
    )

    # With password that match all but the last requirements.
    # Requirement does have a reason text.
    jchris_user_doc5 = Map.put(jchris_user_doc, "password", "funnnnnyB0N3")
    save_as(
      @users_db_name,
      jchris_user_doc5,
      use_session: session,
      expect_response: 400,
      error_message: "bad_request",
      error_reason: "Password does not conform to requirements."
    )

    # With password that match all requirements.
    jchris_user_doc6 = Map.put(jchris_user_doc, "password", "funnnnnyB0N3!")
    save_as(@users_db_name, jchris_user_doc6, use_session: session, expect_response: 201)

    # with non list value
    set_config({
      "couch_httpd_auth",
      "password_regexp",
      "{{\".{10,}\"}}"
    })

    joe_user_doc =
      prepare_user_doc([
        {:name, "joe_erlang"},
        {:password, "querty"}
      ])

    save_as(
      @users_db_name,
      joe_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "Server cannot hash passwords at this time."
    )

    # Not correct syntax
    set_config({
      "couch_httpd_auth",
      "password_regexp",
      "[{\".{10,}\"]"
    })

    save_as(
      @users_db_name,
      joe_user_doc,
      use_session: session,
      expect_response: 403,
      error_message: "forbidden",
      error_reason: "Server cannot hash passwords at this time."
    )
  end
end