integration_test.go 4.57 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
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)
		}
	}
}

// Verify that authentication on GetResource works as expected:
// - users can fetch their own data but not other users'
// - admins can read everything.
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"),
			},
			CurPassword: "password",
		},
		Password: "new_password",
	}, nil)

	if err != nil {
		t.Fatal("ChangePassword", err)
	}
}