blob: 4acc5760572a2ddfb2e10d1a912af9325dfa829f [file] [log] [blame]
gioe72b54f2024-04-22 10:44:41 +04001package welcome
2
3import (
4 "bytes"
5 "encoding/json"
6 "golang.org/x/crypto/ssh"
7 "io"
8 "io/fs"
9 "log"
10 "net"
11 "net/http"
12 "strings"
13 "sync"
14 "testing"
giod9c398e2024-06-06 13:33:03 +040015 "time"
gioe72b54f2024-04-22 10:44:41 +040016
17 "github.com/go-git/go-billy/v5"
18 "github.com/go-git/go-billy/v5/memfs"
19 "github.com/go-git/go-billy/v5/util"
20 // "github.com/go-git/go-git/v5"
21 // "github.com/go-git/go-git/v5/storage/memory"
22
23 "github.com/giolekva/pcloud/core/installer"
24 "github.com/giolekva/pcloud/core/installer/soft"
giod9c398e2024-06-06 13:33:03 +040025 "github.com/giolekva/pcloud/core/installer/tasks"
gioe72b54f2024-04-22 10:44:41 +040026)
27
28type fakeNSCreator struct {
29 t *testing.T
30}
31
32func (f fakeNSCreator) Create(name string) error {
33 f.t.Logf("Create namespace: %s", name)
34 return nil
35}
36
giof8843412024-05-22 16:38:05 +040037type fakeJobCreator struct {
38 t *testing.T
39}
40
41func (f fakeJobCreator) Create(name, namespace string, image string, cmd []string) error {
42 f.t.Logf("Create job: %s/%s %s \"%s\"", namespace, name, image, strings.Join(cmd, " "))
43 return nil
44}
45
46type fakeHelmFetcher struct {
47 t *testing.T
48}
49
50func (f fakeHelmFetcher) Pull(chart installer.HelmChartGitRepo, rfs soft.RepoFS, root string) error {
51 f.t.Logf("Helm pull: %+v", chart)
52 return nil
53}
54
gioe72b54f2024-04-22 10:44:41 +040055type fakeZoneStatusFetcher struct {
56 t *testing.T
57}
58
59func (f fakeZoneStatusFetcher) Fetch(addr string) (string, error) {
60 f.t.Logf("Fetching status: %s", addr)
61 return addr, nil
62}
63
64type mockRepoIO struct {
65 soft.RepoFS
66 addr string
67 t *testing.T
68 l sync.Locker
69}
70
71func (r mockRepoIO) FullAddress() string {
72 return r.addr
73}
74
75func (r mockRepoIO) Pull() error {
76 r.t.Logf("Pull: %s", r.addr)
77 return nil
78}
79
gio0eaf2712024-04-14 13:08:46 +040080func (r mockRepoIO) CommitAndPush(message string, opts ...soft.PushOption) error {
gioe72b54f2024-04-22 10:44:41 +040081 r.t.Logf("Commit and push: %s", message)
82 return nil
83}
84
85func (r mockRepoIO) Do(op soft.DoFn, _ ...soft.DoOption) error {
86 r.l.Lock()
87 defer r.l.Unlock()
88 msg, err := op(r)
89 if err != nil {
90 return err
91 }
92 return r.CommitAndPush(msg)
93}
94
95type fakeSoftServeClient struct {
96 t *testing.T
97 envFS billy.Filesystem
98}
99
100func (f fakeSoftServeClient) Address() string {
101 return ""
102}
103
104func (f fakeSoftServeClient) Signer() ssh.Signer {
105 return nil
106}
107
108func (f fakeSoftServeClient) GetPublicKeys() ([]string, error) {
109 return []string{}, nil
110}
111
gio33059762024-07-05 13:19:07 +0400112func (f fakeSoftServeClient) RepoExists(name string) (bool, error) {
113 return false, nil
114}
115
gioe72b54f2024-04-22 10:44:41 +0400116func (f fakeSoftServeClient) GetRepo(name string) (soft.RepoIO, error) {
117 var l sync.Mutex
118 return mockRepoIO{soft.NewBillyRepoFS(f.envFS), "foo.bar", f.t, &l}, nil
119}
120
121func (f fakeSoftServeClient) GetRepoAddress(name string) string {
122 return ""
123}
124
125func (f fakeSoftServeClient) AddRepository(name string) error {
126 return nil
127}
128
gio33059762024-07-05 13:19:07 +0400129func (f fakeSoftServeClient) UserExists(name string) (bool, error) {
130 return false, nil
131}
132func (f fakeSoftServeClient) FindUser(pubKey string) (string, error) {
133 return "", nil
134}
135
gioe72b54f2024-04-22 10:44:41 +0400136func (f fakeSoftServeClient) AddUser(name, pubKey string) error {
137 return nil
138}
139
140func (f fakeSoftServeClient) AddPublicKey(user string, pubKey string) error {
141 return nil
142}
143
144func (f fakeSoftServeClient) RemovePublicKey(user string, pubKey string) error {
145 return nil
146}
147
148func (f fakeSoftServeClient) MakeUserAdmin(name string) error {
149 return nil
150}
151
152func (f fakeSoftServeClient) AddReadWriteCollaborator(repo, user string) error {
153 return nil
154}
155
156func (f fakeSoftServeClient) AddReadOnlyCollaborator(repo, user string) error {
157 return nil
158}
159
gio0eaf2712024-04-14 13:08:46 +0400160func (f fakeSoftServeClient) AddWebhook(repo, url string, opts ...string) error {
161 return nil
162}
163
gioe72b54f2024-04-22 10:44:41 +0400164type fakeClientGetter struct {
165 t *testing.T
166 envFS billy.Filesystem
167}
168
169func (f fakeClientGetter) Get(addr string, clientPrivateKey []byte, log *log.Logger) (soft.Client, error) {
170 return fakeSoftServeClient{f.t, f.envFS}, nil
171}
172
173const infraConfig = `
174infraAdminPublicKey: Zm9vYmFyCg==
175namespacePrefix: infra-
176pcloudEnvName: infra
177publicIP:
178- 1.1.1.1
179- 2.2.2.2
180`
181
182const envCidrs = ``
183
184type fixedNameGenerator struct{}
185
186func (f fixedNameGenerator) Generate() (string, error) {
187 return "test", nil
188}
189
190type fakeHttpClient struct {
191 t *testing.T
192 counts map[string]int
193}
194
195func (f fakeHttpClient) Get(addr string) (*http.Response, error) {
196 f.t.Logf("HTTP GET: %s", addr)
197 cnt, ok := f.counts[addr]
198 if !ok {
199 cnt = 0
200 }
201 f.counts[addr] = cnt + 1
202 return &http.Response{
203 Status: "200 OK",
204 StatusCode: http.StatusOK,
205 Proto: "HTTP/1.0",
206 ProtoMajor: 1,
207 ProtoMinor: 0,
208 Body: io.NopCloser(strings.NewReader("ok")),
209 }, nil
210}
211
212type fakeDnsClient struct {
213 t *testing.T
214 counts map[string]int
215}
216
217func (f fakeDnsClient) Lookup(host string) ([]net.IP, error) {
218 f.t.Logf("HTTP GET: %s", host)
219 return []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("2.2.2.2")}, nil
220}
221
giod9c398e2024-06-06 13:33:03 +0400222type onDoneTaskMap struct {
223 m tasks.TaskManager
224 onDone tasks.TaskDoneListener
225}
226
227func (m *onDoneTaskMap) Add(name string, task tasks.Task) error {
228 if err := m.m.Add(name, task); err != nil {
229 return err
230 } else {
231 task.OnDone(m.onDone)
232 return nil
233 }
234}
235
236func (m *onDoneTaskMap) Get(name string) (tasks.Task, error) {
237 return m.m.Get(name)
238}
239
gioe72b54f2024-04-22 10:44:41 +0400240func TestCreateNewEnv(t *testing.T) {
241 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
242 infraFS := memfs.New()
243 envFS := memfs.New()
244 nsCreator := fakeNSCreator{t}
giof8843412024-05-22 16:38:05 +0400245 jc := fakeJobCreator{t}
246 hf := fakeHelmFetcher{t}
247 lg := installer.GitRepositoryLocalChartGenerator{"foo", "bar"}
gioe72b54f2024-04-22 10:44:41 +0400248 infraRepo := mockRepoIO{soft.NewBillyRepoFS(infraFS), "foo.bar", t, &sync.Mutex{}}
giof8843412024-05-22 16:38:05 +0400249 infraMgr, err := installer.NewInfraAppManager(infraRepo, nsCreator, hf, lg)
gioe72b54f2024-04-22 10:44:41 +0400250 if err != nil {
251 t.Fatal(err)
252 }
253 if err := util.WriteFile(infraFS, "config.yaml", []byte(infraConfig), fs.ModePerm); err != nil {
254 t.Fatal(err)
255 }
256 if err := util.WriteFile(infraFS, "env-cidrs.yaml", []byte(envCidrs), fs.ModePerm); err != nil {
257 t.Fatal(err)
258 }
259 {
260 app, err := installer.FindInfraApp(apps, "dns-gateway")
261 if err != nil {
262 t.Fatal(err)
263 }
gio778577f2024-04-29 09:44:38 +0400264 if _, err := infraMgr.Install(app, "/infrastructure/dns-gateway", "dns-gateway", map[string]any{
gioe72b54f2024-04-22 10:44:41 +0400265 "servers": []installer.EnvDNS{},
266 }); err != nil {
267 t.Fatal(err)
268 }
269 }
270 cg := fakeClientGetter{t, envFS}
271 httpClient := fakeHttpClient{t, make(map[string]int)}
272 dnsClient := fakeDnsClient{t, make(map[string]int)}
giod9c398e2024-06-06 13:33:03 +0400273 var done sync.WaitGroup
274 done.Add(1)
275 var taskErr error
276 tm := &onDoneTaskMap{
277 tasks.NewTaskMap(),
278 func(err error) {
279 taskErr = err
280 done.Done()
281 },
282 }
gioe72b54f2024-04-22 10:44:41 +0400283 s := NewEnvServer(
284 8181,
285 fakeSoftServeClient{t, envFS},
286 infraRepo,
287 cg,
288 nsCreator,
giof8843412024-05-22 16:38:05 +0400289 jc,
290 hf,
gioe72b54f2024-04-22 10:44:41 +0400291 fakeZoneStatusFetcher{t},
292 fixedNameGenerator{},
293 httpClient,
294 dnsClient,
giod9c398e2024-06-06 13:33:03 +0400295 tm,
gioe72b54f2024-04-22 10:44:41 +0400296 )
297 go s.Start()
giod9c398e2024-06-06 13:33:03 +0400298 time.Sleep(1 * time.Second) // Let server start
gioe72b54f2024-04-22 10:44:41 +0400299 req := createEnvReq{
300 Name: "test",
301 ContactEmail: "test@test.t",
302 Domain: "test.t",
303 AdminPublicKey: "test",
304 SecretToken: "test",
305 }
306 var buf bytes.Buffer
307 if err := json.NewEncoder(&buf).Encode(req); err != nil {
308 t.Fatal(err)
309 }
310 resp, err := http.Post("http://localhost:8181/", "application/json", &buf)
gioe72b54f2024-04-22 10:44:41 +0400311 if err != nil {
312 t.Fatal(err)
313 }
314 if resp.StatusCode != http.StatusOK {
315 var buf bytes.Buffer
316 io.Copy(&buf, resp.Body)
317 t.Fatal(buf.String())
318 }
319 done.Wait()
320 http.Get("http://localhost:8181/env/test")
321 debugFS(infraFS, t, "/infrastructure/dns-gateway/resources/coredns.yaml")
322 debugFS(envFS, t)
323 if taskErr != nil {
324 t.Fatal(taskErr)
325 }
326 expected := []string{
327 "https://accounts-ui.test.t",
328 "https://welcome.test.t",
329 "https://memberships.p.test.t",
gio09a3e5b2024-04-26 14:11:06 +0400330 "https://launcher.test.t",
gioe72b54f2024-04-22 10:44:41 +0400331 "https://headscale.test.t/apple",
332 }
333 for _, e := range expected {
334 if cnt, ok := httpClient.counts[e]; !ok || cnt != 1 {
335 t.Fatal(httpClient.counts)
336 }
337 }
gio09a3e5b2024-04-26 14:11:06 +0400338 if len(httpClient.counts) != 5 {
gioe72b54f2024-04-22 10:44:41 +0400339 t.Fatal(httpClient.counts)
340 }
341}
342
343func debugFS(bfs billy.Filesystem, t *testing.T, files ...string) {
344 f := map[string]struct{}{}
345 for _, i := range files {
346 f[i] = struct{}{}
347 }
348 t.Log("----- START ------")
349 err := util.Walk(bfs, "/", func(path string, info fs.FileInfo, err error) error {
gioe72b54f2024-04-22 10:44:41 +0400350 if _, ok := f[path]; ok && !info.IsDir() {
351 contents, err := util.ReadFile(bfs, path)
352 if err != nil {
353 return err
354 }
355 t.Log(string(contents))
356 }
357 return nil
358 })
359 if err != nil {
360 t.Fatal(err)
361 }
362 t.Log("----- END ------")
363}