~samwhited/xmpp

ref: 467e8c4a0b977d765eadf64f02ebb5edee0ce805 xmpp/internal/integration/ejabberd/ejabberd.go -rw-r--r-- 6.0 KiB
467e8c4aSam Whited component: add integration tests 11 months ago
                                                                                
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
// Copyright 2020 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

// Package ejabberd facilitates integration testing against Ejabberd.
package ejabberd // import "mellium.im/xmpp/internal/integration/ejabberd"

import (
	"context"
	"fmt"
	"io"
	"net"
	"os/exec"
	"path/filepath"
	"testing"

	"mellium.im/xmpp/internal/integration"
	"mellium.im/xmpp/jid"
)

const (
	cfgFileName = "ejabberd.yml"
	cmdName     = "ejabberdctl"
	configFlag  = "--config-dir"
	logsFlag    = "--logs"
	spoolFlag   = "--spool"
)

// New creates a new, unstarted, ejabberd daemon.
//
// The provided context is used to kill the process (by calling os.Process.Kill)
// if the context becomes done before the command completes on its own.
func New(ctx context.Context, opts ...integration.Option) (*integration.Cmd, error) {
	opts = append(opts, foreground)
	cmd, err := integration.New(
		ctx, cmdName,
		opts...,
	)
	return cmd, err
}

// ConfigFile is an option that can be used to write a temporary Ejabberd config
// file.
// This will overwrite the existing config file and make most of the other
// options in this package noops.
// This option only exists for the rare occasion that you need complete control
// over the config file.
func ConfigFile(cfg Config) integration.Option {
	return func(cmd *integration.Cmd) error {
		cmd.Config = cfg
		err := integration.TempFile(cfgFileName, func(cmd *integration.Cmd, w io.Writer) error {
			return cfgTmpl.Execute(w, struct {
				Config
				ConfigDir string
			}{
				Config:    cfg,
				ConfigDir: cmd.ConfigDir(),
			})
		})(cmd)
		if err != nil {
			return err
		}
		err = integration.Args(configFlag, cmd.ConfigDir())(cmd)
		if err != nil {
			return err
		}
		err = integration.Args(logsFlag, cmd.ConfigDir())(cmd)
		if err != nil {
			return err
		}
		return integration.Args(spoolFlag, cmd.ConfigDir())(cmd)
	}
}

func getConfig(cmd *integration.Cmd) Config {
	if cmd.Config == nil {
		cmd.Config = Config{}
	}
	return cmd.Config.(Config)
}

// ListenC2S listens for client-to-server (c2s) connections on a Unix domain
// socket.
func ListenC2S() integration.Option {
	return func(cmd *integration.Cmd) error {
		c2sListener, err := cmd.C2SListen("unix", filepath.Join(cmd.ConfigDir(), "c2s.socket"))
		if err != nil {
			return err
		}
		c2sSocket := c2sListener.Addr().(*net.UnixAddr).Name
		err = c2sListener.Close()
		if err != nil {
			return err
		}

		cfg := getConfig(cmd)
		cfg.C2SSocket = c2sSocket
		cmd.Config = cfg
		return nil
	}
}

// ListenS2S listens for server-to-server (s2s) connections on a Unix domain
// socket.
func ListenS2S() integration.Option {
	return func(cmd *integration.Cmd) error {
		s2sListener, err := cmd.S2SListen("unix", filepath.Join(cmd.ConfigDir(), "s2s.socket"))
		if err != nil {
			return err
		}
		s2sSocket := s2sListener.Addr().(*net.UnixAddr).Name

		cfg := getConfig(cmd)
		cfg.S2SSocket = s2sSocket
		cmd.Config = cfg
		return nil
	}
}

// VHost configures one or more virtual hosts.
// The default if this option is not provided is to create a single vhost called
// "localhost" and create a self-signed cert for it (if VHost is specified certs
// must be manually created).
func VHost(hosts ...string) integration.Option {
	return func(cmd *integration.Cmd) error {
		cfg := getConfig(cmd)
		cfg.VHosts = append(cfg.VHosts, hosts...)
		cmd.Config = cfg
		return nil
	}
}

func defaultConfig(cmd *integration.Cmd) error {
	for _, arg := range cmd.Cmd.Args {
		if arg == configFlag {
			return nil
		}
	}

	cfg := getConfig(cmd)
	if len(cfg.VHosts) == 0 {
		const vhost = "localhost"
		cfg.VHosts = append(cfg.VHosts, vhost)
		err := integration.Cert(vhost)(cmd)
		if err != nil {
			return err
		}
	}
	cmd.Config = cfg
	if j, _ := cmd.User(); j.Equal(jid.JID{}) {
		err := CreateUser(context.TODO(), "me@"+cfg.VHosts[0], "password")(cmd)
		if err != nil {
			return err
		}
	}

	return ConfigFile(cfg)(cmd)
}

func inetrcFile(cmd *integration.Cmd) error {
	return integration.TempFile("inetrc", func(_ *integration.Cmd, w io.Writer) error {
		_, err := fmt.Fprint(w, inetrc)
		return err
	})(cmd)
}

func foreground(cmd *integration.Cmd) error {
	return integration.Args("foreground")(cmd)
}

// Ctl returns an option that calls ejabberdctl with the provided args after the
// config has been written.
// It automatically points ejabberdctl at the config file path.
func Ctl(ctx context.Context, args ...string) integration.Option {
	return integration.Defer(ctlFunc(ctx, args...))
}

func ctlFunc(ctx context.Context, args ...string) func(*integration.Cmd) error {
	return func(cmd *integration.Cmd) error {
		cfgFilePath := cmd.ConfigDir()
		/* #nosec */
		ejabberdCtl := exec.CommandContext(ctx, "ejabberdctl",
			configFlag, cfgFilePath, logsFlag, cfgFilePath, spoolFlag, cfgFilePath)
		ejabberdCtl.Args = append(ejabberdCtl.Args, args...)
		return ejabberdCtl.Run()
	}
}

// CreateUser returns an option that calls ejabberdctl to create a user.
// It is equivalent to calling:
// Ctl(ctx, "register", "localpart", "domainpart", "password") except that it
// also configures the underlying Cmd to know about the user.
func CreateUser(ctx context.Context, addr, pass string) integration.Option {
	return func(cmd *integration.Cmd) error {
		j, err := jid.Parse(addr)
		if err != nil {
			return err
		}
		err = Ctl(ctx, "register", j.Localpart(), j.Domainpart(), pass)(cmd)
		if err != nil {
			return err
		}
		return integration.User(j, pass)(cmd)
	}
}

// Test starts an Ejabberd instance and returns a function that runs f as a
// subtest using t.Run.
// Multiple calls to the returned function will result in uniquely named
// subtests.
// When all subtests have completed, the daemon is stopped.
func Test(ctx context.Context, t *testing.T, opts ...integration.Option) integration.SubtestRunner {
	opts = append(opts, defaultConfig, inetrcFile, foreground,
		integration.Shutdown(func(cmd *integration.Cmd) error {
			err := ctlFunc(ctx, "stop")(cmd)
			if err != nil {
				return err
			}
			return ctlFunc(ctx, "stopped")(cmd)
		}))
	return integration.Test(ctx, cmdName, t, opts...)
}