integration_test.go 5.83 KB
Newer Older
ale's avatar
ale committed
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
package integrationtest

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
	"time"

	"git.autistici.org/ai3/accountserver"
	"git.autistici.org/ai3/accountserver/backend"
	"git.autistici.org/ai3/accountserver/ldaptest"
	"git.autistici.org/ai3/accountserver/server"
	sso "git.autistici.org/id/go-sso"
	"golang.org/x/crypto/ed25519"
)

const (
	testLDAPPort = 42872
	testLDAPAddr = "ldap://127.0.0.1:42872"

	testSSODomain  = "domain"
	testSSOService = "accountserver.domain/"
	testAdminUser  = "admin"
	testAdminGroup = "admins"
)

func withSSO(t testing.TB) (func(), sso.Signer, string) {
	tmpf, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}

	pub, priv, err := ed25519.GenerateKey(nil)
	if err != nil {
		t.Fatal(err)
	}
	tmpf.Write(pub)
	tmpf.Close()

	signer, err := sso.NewSigner(priv)
	if err != nil {
		t.Fatal(err)
	}

	return func() {
		os.Remove(tmpf.Name())
	}, signer, tmpf.Name()
}

type testClient struct {
	srvURL string
	signer sso.Signer
}

func (c *testClient) ssoTicket(username string) string {
	var groups []string
	if username == testAdminUser {
		groups = append(groups, testAdminGroup)
	}
	signed, err := c.signer.Sign(sso.NewTicket(username, testSSOService, testSSODomain, "", groups, 1*time.Hour))
	if err != nil {
		panic(err)
	}
	return signed
}

func (c *testClient) request(uri string, req, out interface{}) error {
	data, _ := json.Marshal(req)
	resp, err := http.Post(c.srvURL+uri, "application/json", bytes.NewReader(data))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf("http status code %d", resp.StatusCode)
	}
	if resp.Header.Get("Content-Type") != "application/json" {
		return fmt.Errorf("unexpected content-type %s", resp.Header.Get("Content-Type"))
	}
	data, _ = ioutil.ReadAll(resp.Body)

	log.Printf("response:\n%s\n", string(data))

	if out == nil {
		return nil
	}
	return json.Unmarshal(data, out)
}

func startService(t testing.TB) (func(), *testClient) {
	stop := ldaptest.StartServer(t, &ldaptest.Config{
		Dir:   "../ldaptest",
		Port:  testLDAPPort,
		Base:  "dc=example,dc=com",
		LDIFs: []string{"testdata/base.ldif", "testdata/test1.ldif"},
	})

	be, err := backend.NewLDAPBackend(testLDAPAddr, "cn=manager,dc=example,dc=com", "password", "dc=example,dc=com")
	if err != nil {
		t.Fatal("NewLDAPBackend", err)
	}

	ssoStop, signer, ssoPubKeyFile := withSSO(t)

	var svcConfig accountserver.Config
	svcConfig.SSO.PublicKeyFile = ssoPubKeyFile
	svcConfig.SSO.Domain = testSSODomain
	svcConfig.SSO.Service = testSSOService
	svcConfig.SSO.AdminGroup = testAdminGroup
	svcConfig.AvailableDomains = map[string][]string{
		accountserver.ResourceTypeEmail: []string{"example.com"},
	}

	service, err := accountserver.NewAccountService(be, &svcConfig)
	if err != nil {
		stop()
		t.Fatal("NewAccountService", err)
	}

	as := server.New(service, be)
	srv := httptest.NewServer(as.Handler())

	c := &testClient{
		srvURL: srv.URL,
		signer: signer,
	}

	return func() {
		stop()
		srv.Close()
		ssoStop()
	}, c
}

// Verify that authentication on GetUser works as expected:
// - users can fetch their own data but not other users'
// - admins can read everything.
func TestIntegration_GetUser_Auth(t *testing.T) {
	stop, c := startService(t)
	defer stop()

	testdata := []struct {
		authUser   string
		expectedOk bool
	}{
		{"uno@investici.org", true},
		{"due@investici.org", false},
		{testAdminUser, true},
	}

	for _, td := range testdata {
		var user accountserver.User
		err := c.request("/api/user/get", &accountserver.GetUserRequest{
			RequestBase: accountserver.RequestBase{
				Username: "uno@investici.org",
				SSO:      c.ssoTicket(td.authUser),
			},
		}, &user)
		if td.expectedOk && err != nil {
			t.Errorf("access error for user %s: expected ok, got error: %v", td.authUser, err)
		} else if !td.expectedOk && err == nil {
			t.Errorf("access error for user %s: expected error, got ok", td.authUser)
		}
	}
}

173
// Verify that a user can change their password.
ale's avatar
ale committed
174 175 176 177 178 179 180 181 182 183
func TestIntegration_ChangeUserPassword(t *testing.T) {
	stop, c := startService(t)
	defer stop()

	err := c.request("/api/user/change_password", &accountserver.ChangeUserPasswordRequest{
		PrivilegedRequestBase: accountserver.PrivilegedRequestBase{
			RequestBase: accountserver.RequestBase{
				Username: "uno@investici.org",
				SSO:      c.ssoTicket("uno@investici.org"),
			},
184 185 186 187 188
			// Since the user in the test fixture does
			// *not* have encryption key, and
			// authenticateWithPassword is currently a
			// no-op, this test will pass.
			CurPassword: "ha ha, really not the current password",
ale's avatar
ale committed
189 190 191 192 193 194 195 196
		},
		Password: "new_password",
	}, nil)

	if err != nil {
		t.Fatal("ChangePassword", err)
	}
}
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

// Verify that changing the password sets user encryption keys.
func TestIntegration_ChangeUserPassword_SetsEncryptionKeys(t *testing.T) {
	stop, c := startService(t)
	defer stop()

	testdata := []struct {
		password    string
		newPassword string
		expectedOk  bool
	}{
		// Ordering is important as it is meant to emulate
		// setting the password, failing to reset it, then
		// succeeding.
		{"password", "new_password", true},
		{"BADPASS", "new_password_2", false},
		{"new_password", "new_password_2", true},
	}
	for _, td := range testdata {
		err := c.request("/api/user/change_password", &accountserver.ChangeUserPasswordRequest{
			PrivilegedRequestBase: accountserver.PrivilegedRequestBase{
				RequestBase: accountserver.RequestBase{
					Username: "uno@investici.org",
					SSO:      c.ssoTicket("uno@investici.org"),
				},
				CurPassword: td.password,
			},
			Password: td.newPassword,
		}, nil)
		if err == nil && !td.expectedOk {
			t.Fatalf("ChangeUserPassword(old=%s new=%s) should have failed but didn't", td.password, td.newPassword)
		} else if err != nil && td.expectedOk {
			t.Fatalf("ChangeUserPassword(old=%s new=%s) failed: %v", td.password, td.newPassword, err)
		}
	}
}