aboutsummaryrefslogtreecommitdiff
path: root/lib/api/api_auth_test.go
blob: e4e207a09a51c543fa1ad8fa6bdf3f9cba61a5bc (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
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package api

import (
	"testing"

	"github.com/syncthing/syncthing/lib/config"
)

var guiCfg config.GUIConfiguration

func init() {
	guiCfg.User = "user"
	guiCfg.SetPassword("pass")
}

func TestStaticAuthOK(t *testing.T) {
	t.Parallel()

	ok := authStatic("user", "pass", guiCfg)
	if !ok {
		t.Fatalf("should pass auth")
	}
}

func TestSimpleAuthUsernameFail(t *testing.T) {
	t.Parallel()

	ok := authStatic("userWRONG", "pass", guiCfg)
	if ok {
		t.Fatalf("should fail auth")
	}
}

func TestStaticAuthPasswordFail(t *testing.T) {
	t.Parallel()

	ok := authStatic("user", "passWRONG", guiCfg)
	if ok {
		t.Fatalf("should fail auth")
	}
}

func TestFormatOptionalPercentS(t *testing.T) {
	t.Parallel()

	cases := []struct {
		template string
		username string
		expected string
	}{
		{"cn=%s,dc=some,dc=example,dc=com", "username", "cn=username,dc=some,dc=example,dc=com"},
		{"cn=fixedusername,dc=some,dc=example,dc=com", "username", "cn=fixedusername,dc=some,dc=example,dc=com"},
		{"cn=%%s,dc=%s,dc=example,dc=com", "username", "cn=%s,dc=username,dc=example,dc=com"},
		{"cn=%%s,dc=%%s,dc=example,dc=com", "username", "cn=%s,dc=%s,dc=example,dc=com"},
		{"cn=%s,dc=%s,dc=example,dc=com", "username", "cn=username,dc=username,dc=example,dc=com"},
	}

	for _, c := range cases {
		templatedDn := formatOptionalPercentS(c.template, c.username)
		if c.expected != templatedDn {
			t.Fatalf("result should be %s != %s", c.expected, templatedDn)
		}
	}
}

func TestEscapeForLDAPFilter(t *testing.T) {
	t.Parallel()

	cases := []struct {
		in  string
		out string
	}{
		{"username", `username`},
		{"user(name", `user\28name`},
		{"user)name", `user\29name`},
		{"user\\name", `user\5Cname`},
		{"user*name", `user\2Aname`},
		{"*,CN=asdf", `\2A,CN=asdf`},
	}

	for _, c := range cases {
		res := escapeForLDAPFilter(c.in)
		if c.out != res {
			t.Fatalf("result should be %s != %s", c.out, res)
		}
	}
}

func TestEscapeForLDAPDN(t *testing.T) {
	t.Parallel()

	cases := []struct {
		in  string
		out string
	}{
		{"username", `username`},
		{"* ,CN=asdf", `*\20\2CCN\3Dasdf`},
	}

	for _, c := range cases {
		res := escapeForLDAPDN(c.in)
		if c.out != res {
			t.Fatalf("result should be %s != %s", c.out, res)
		}
	}
}