blob: 439fdf26a61eb15d9caf371f1c47b191c9f80647 [file] [log] [blame]
gioe72b54f2024-04-22 10:44:41 +04001package welcome
2
3import (
4 "bytes"
5 "encoding/json"
giof6ad2982024-08-23 17:42:49 +04006 "fmt"
gioe72b54f2024-04-22 10:44:41 +04007 "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
Davit Tabidzea5ea5092024-08-01 15:28:09 +040017 "golang.org/x/crypto/ssh"
18
gio7fbd4ad2024-08-27 10:06:39 +040019 "cuelang.org/go/cue/errors"
gioe72b54f2024-04-22 10:44:41 +040020 "github.com/go-git/go-billy/v5"
21 "github.com/go-git/go-billy/v5/memfs"
22 "github.com/go-git/go-billy/v5/util"
gioe72b54f2024-04-22 10:44:41 +040023
24 "github.com/giolekva/pcloud/core/installer"
25 "github.com/giolekva/pcloud/core/installer/soft"
giod9c398e2024-06-06 13:33:03 +040026 "github.com/giolekva/pcloud/core/installer/tasks"
gioe72b54f2024-04-22 10:44:41 +040027)
28
29type fakeNSCreator struct {
30 t *testing.T
31}
32
33func (f fakeNSCreator) Create(name string) error {
34 f.t.Logf("Create namespace: %s", name)
35 return nil
36}
37
giof8843412024-05-22 16:38:05 +040038type fakeJobCreator struct {
39 t *testing.T
40}
41
42func (f fakeJobCreator) Create(name, namespace string, image string, cmd []string) error {
43 f.t.Logf("Create job: %s/%s %s \"%s\"", namespace, name, image, strings.Join(cmd, " "))
44 return nil
45}
46
47type fakeHelmFetcher struct {
48 t *testing.T
49}
50
51func (f fakeHelmFetcher) Pull(chart installer.HelmChartGitRepo, rfs soft.RepoFS, root string) error {
52 f.t.Logf("Helm pull: %+v", chart)
53 return nil
54}
55
gioe72b54f2024-04-22 10:44:41 +040056type fakeZoneStatusFetcher struct {
57 t *testing.T
58}
59
60func (f fakeZoneStatusFetcher) Fetch(addr string) (string, error) {
61 f.t.Logf("Fetching status: %s", addr)
62 return addr, nil
63}
64
65type mockRepoIO struct {
66 soft.RepoFS
67 addr string
68 t *testing.T
69 l sync.Locker
70}
71
72func (r mockRepoIO) FullAddress() string {
73 return r.addr
74}
75
76func (r mockRepoIO) Pull() error {
77 r.t.Logf("Pull: %s", r.addr)
78 return nil
79}
80
giob4a3a192024-08-19 09:55:47 +040081func (r mockRepoIO) CommitAndPush(message string, opts ...soft.PushOption) (string, error) {
gioe72b54f2024-04-22 10:44:41 +040082 r.t.Logf("Commit and push: %s", message)
giob4a3a192024-08-19 09:55:47 +040083 return "", nil
gioe72b54f2024-04-22 10:44:41 +040084}
85
giob4a3a192024-08-19 09:55:47 +040086func (r mockRepoIO) Do(op soft.DoFn, _ ...soft.DoOption) (string, error) {
gioe72b54f2024-04-22 10:44:41 +040087 r.l.Lock()
88 defer r.l.Unlock()
89 msg, err := op(r)
90 if err != nil {
giob4a3a192024-08-19 09:55:47 +040091 return "", err
gioe72b54f2024-04-22 10:44:41 +040092 }
93 return r.CommitAndPush(msg)
94}
95
96type fakeSoftServeClient struct {
97 t *testing.T
98 envFS billy.Filesystem
99}
100
101func (f fakeSoftServeClient) Address() string {
102 return ""
103}
104
105func (f fakeSoftServeClient) Signer() ssh.Signer {
106 return nil
107}
108
109func (f fakeSoftServeClient) GetPublicKeys() ([]string, error) {
110 return []string{}, nil
111}
112
gio33059762024-07-05 13:19:07 +0400113func (f fakeSoftServeClient) RepoExists(name string) (bool, error) {
114 return false, nil
115}
116
gioe72b54f2024-04-22 10:44:41 +0400117func (f fakeSoftServeClient) GetRepo(name string) (soft.RepoIO, error) {
118 var l sync.Mutex
119 return mockRepoIO{soft.NewBillyRepoFS(f.envFS), "foo.bar", f.t, &l}, nil
120}
121
gio7fbd4ad2024-08-27 10:06:39 +0400122func (f fakeSoftServeClient) GetRepoBranch(name, branch string) (soft.RepoIO, error) {
123 return f.GetRepo(name)
124}
125
giocafd4e62024-07-31 10:53:40 +0400126func (f fakeSoftServeClient) GetAllRepos() ([]string, error) {
127 return []string{}, nil
128}
129
gioe72b54f2024-04-22 10:44:41 +0400130func (f fakeSoftServeClient) GetRepoAddress(name string) string {
131 return ""
132}
133
134func (f fakeSoftServeClient) AddRepository(name string) error {
135 return nil
136}
137
gio33059762024-07-05 13:19:07 +0400138func (f fakeSoftServeClient) UserExists(name string) (bool, error) {
139 return false, nil
140}
141func (f fakeSoftServeClient) FindUser(pubKey string) (string, error) {
142 return "", nil
143}
144
Davit Tabidzea5ea5092024-08-01 15:28:09 +0400145func (f fakeSoftServeClient) GetAllUsers() ([]string, error) {
146 return []string{}, nil
147}
148
gioe72b54f2024-04-22 10:44:41 +0400149func (f fakeSoftServeClient) AddUser(name, pubKey string) error {
150 return nil
151}
152
Davit Tabidzea5ea5092024-08-01 15:28:09 +0400153func (f fakeSoftServeClient) RemoveUser(name string) error {
154 return nil
155}
156
gioe72b54f2024-04-22 10:44:41 +0400157func (f fakeSoftServeClient) AddPublicKey(user string, pubKey string) error {
158 return nil
159}
160
Davit Tabidzea5ea5092024-08-01 15:28:09 +0400161func (f fakeSoftServeClient) GetUserPublicKeys(username string) ([]string, error) {
162 return []string{}, nil
163}
164
gioe72b54f2024-04-22 10:44:41 +0400165func (f fakeSoftServeClient) RemovePublicKey(user string, pubKey string) error {
166 return nil
167}
168
169func (f fakeSoftServeClient) MakeUserAdmin(name string) error {
170 return nil
171}
172
173func (f fakeSoftServeClient) AddReadWriteCollaborator(repo, user string) error {
174 return nil
175}
176
177func (f fakeSoftServeClient) AddReadOnlyCollaborator(repo, user string) error {
178 return nil
179}
180
gio0eaf2712024-04-14 13:08:46 +0400181func (f fakeSoftServeClient) AddWebhook(repo, url string, opts ...string) error {
182 return nil
183}
184
gio7fbd4ad2024-08-27 10:06:39 +0400185func (f fakeSoftServeClient) DisableAnonAccess() error {
186 return nil
187}
188
189func (f fakeSoftServeClient) DisableKeyless() error {
190 return nil
191}
192
gioe72b54f2024-04-22 10:44:41 +0400193type fakeClientGetter struct {
194 t *testing.T
195 envFS billy.Filesystem
196}
197
198func (f fakeClientGetter) Get(addr string, clientPrivateKey []byte, log *log.Logger) (soft.Client, error) {
199 return fakeSoftServeClient{f.t, f.envFS}, nil
200}
201
202const infraConfig = `
203infraAdminPublicKey: Zm9vYmFyCg==
204namespacePrefix: infra-
205pcloudEnvName: infra
206publicIP:
207- 1.1.1.1
208- 2.2.2.2
209`
210
211const envCidrs = ``
212
213type fixedNameGenerator struct{}
214
215func (f fixedNameGenerator) Generate() (string, error) {
216 return "test", nil
217}
218
219type fakeHttpClient struct {
220 t *testing.T
221 counts map[string]int
222}
223
224func (f fakeHttpClient) Get(addr string) (*http.Response, error) {
225 f.t.Logf("HTTP GET: %s", addr)
226 cnt, ok := f.counts[addr]
227 if !ok {
228 cnt = 0
229 }
230 f.counts[addr] = cnt + 1
231 return &http.Response{
232 Status: "200 OK",
233 StatusCode: http.StatusOK,
234 Proto: "HTTP/1.0",
235 ProtoMajor: 1,
236 ProtoMinor: 0,
237 Body: io.NopCloser(strings.NewReader("ok")),
238 }, nil
239}
240
241type fakeDnsClient struct {
242 t *testing.T
243 counts map[string]int
244}
245
246func (f fakeDnsClient) Lookup(host string) ([]net.IP, error) {
247 f.t.Logf("HTTP GET: %s", host)
248 return []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("2.2.2.2")}, nil
249}
250
giod9c398e2024-06-06 13:33:03 +0400251type onDoneTaskMap struct {
252 m tasks.TaskManager
253 onDone tasks.TaskDoneListener
254}
255
256func (m *onDoneTaskMap) Add(name string, task tasks.Task) error {
257 if err := m.m.Add(name, task); err != nil {
258 return err
259 } else {
giof6ad2982024-08-23 17:42:49 +0400260 task.OnDone(func(err error) {
261 if err == nil {
262 m.onDone(nil)
263 } else {
264 m.onDone(fmt.Errorf("%s: %s", name, err))
265 }
266 })
giod9c398e2024-06-06 13:33:03 +0400267 return nil
268 }
269}
270
271func (m *onDoneTaskMap) Get(name string) (tasks.Task, error) {
272 return m.m.Get(name)
273}
274
gioe72b54f2024-04-22 10:44:41 +0400275func TestCreateNewEnv(t *testing.T) {
276 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
277 infraFS := memfs.New()
278 envFS := memfs.New()
279 nsCreator := fakeNSCreator{t}
giof8843412024-05-22 16:38:05 +0400280 jc := fakeJobCreator{t}
281 hf := fakeHelmFetcher{t}
282 lg := installer.GitRepositoryLocalChartGenerator{"foo", "bar"}
gioc76baed2024-08-19 22:04:57 +0400283 infraRepo := soft.NewMockRepoIO(soft.NewBillyRepoFS(infraFS), "foo.bar", t)
giof8843412024-05-22 16:38:05 +0400284 infraMgr, err := installer.NewInfraAppManager(infraRepo, nsCreator, hf, lg)
gioe72b54f2024-04-22 10:44:41 +0400285 if err != nil {
286 t.Fatal(err)
287 }
288 if err := util.WriteFile(infraFS, "config.yaml", []byte(infraConfig), fs.ModePerm); err != nil {
289 t.Fatal(err)
290 }
291 if err := util.WriteFile(infraFS, "env-cidrs.yaml", []byte(envCidrs), fs.ModePerm); err != nil {
292 t.Fatal(err)
293 }
294 {
295 app, err := installer.FindInfraApp(apps, "dns-gateway")
296 if err != nil {
297 t.Fatal(err)
298 }
gio778577f2024-04-29 09:44:38 +0400299 if _, err := infraMgr.Install(app, "/infrastructure/dns-gateway", "dns-gateway", map[string]any{
gioe72b54f2024-04-22 10:44:41 +0400300 "servers": []installer.EnvDNS{},
301 }); err != nil {
gio7fbd4ad2024-08-27 10:06:39 +0400302 for _, e := range errors.Errors(err) {
303 t.Log(e)
304 }
gioe72b54f2024-04-22 10:44:41 +0400305 t.Fatal(err)
306 }
307 }
308 cg := fakeClientGetter{t, envFS}
309 httpClient := fakeHttpClient{t, make(map[string]int)}
310 dnsClient := fakeDnsClient{t, make(map[string]int)}
giod9c398e2024-06-06 13:33:03 +0400311 var done sync.WaitGroup
312 done.Add(1)
313 var taskErr error
314 tm := &onDoneTaskMap{
315 tasks.NewTaskMap(),
316 func(err error) {
317 taskErr = err
318 done.Done()
319 },
320 }
gioe72b54f2024-04-22 10:44:41 +0400321 s := NewEnvServer(
322 8181,
323 fakeSoftServeClient{t, envFS},
324 infraRepo,
325 cg,
326 nsCreator,
giof8843412024-05-22 16:38:05 +0400327 jc,
328 hf,
gioe72b54f2024-04-22 10:44:41 +0400329 fakeZoneStatusFetcher{t},
330 fixedNameGenerator{},
331 httpClient,
332 dnsClient,
giod9c398e2024-06-06 13:33:03 +0400333 tm,
gioe72b54f2024-04-22 10:44:41 +0400334 )
335 go s.Start()
giod9c398e2024-06-06 13:33:03 +0400336 time.Sleep(1 * time.Second) // Let server start
gioe72b54f2024-04-22 10:44:41 +0400337 req := createEnvReq{
gio7841f4f2024-07-26 19:53:49 +0400338 Name: "test",
339 ContactEmail: "test@test.t",
340 Domain: "test.t",
341 PrivateNetworkSubdomain: "p",
342 AdminPublicKey: "test",
343 SecretToken: "test",
gioe72b54f2024-04-22 10:44:41 +0400344 }
345 var buf bytes.Buffer
346 if err := json.NewEncoder(&buf).Encode(req); err != nil {
347 t.Fatal(err)
348 }
349 resp, err := http.Post("http://localhost:8181/", "application/json", &buf)
gioe72b54f2024-04-22 10:44:41 +0400350 if err != nil {
351 t.Fatal(err)
352 }
353 if resp.StatusCode != http.StatusOK {
354 var buf bytes.Buffer
355 io.Copy(&buf, resp.Body)
356 t.Fatal(buf.String())
357 }
358 done.Wait()
359 http.Get("http://localhost:8181/env/test")
360 debugFS(infraFS, t, "/infrastructure/dns-gateway/resources/coredns.yaml")
361 debugFS(envFS, t)
362 if taskErr != nil {
363 t.Fatal(taskErr)
364 }
365 expected := []string{
giob79db3a2024-08-01 14:20:42 +0400366 "https://apps.p.test.t",
gioe72b54f2024-04-22 10:44:41 +0400367 "https://accounts-ui.test.t",
368 "https://welcome.test.t",
369 "https://memberships.p.test.t",
gio09a3e5b2024-04-26 14:11:06 +0400370 "https://launcher.test.t",
gioe72b54f2024-04-22 10:44:41 +0400371 "https://headscale.test.t/apple",
372 }
373 for _, e := range expected {
374 if cnt, ok := httpClient.counts[e]; !ok || cnt != 1 {
375 t.Fatal(httpClient.counts)
376 }
377 }
giob79db3a2024-08-01 14:20:42 +0400378 if len(httpClient.counts) != 6 {
gioe72b54f2024-04-22 10:44:41 +0400379 t.Fatal(httpClient.counts)
380 }
381}
382
383func debugFS(bfs billy.Filesystem, t *testing.T, files ...string) {
384 f := map[string]struct{}{}
385 for _, i := range files {
386 f[i] = struct{}{}
387 }
388 t.Log("----- START ------")
389 err := util.Walk(bfs, "/", func(path string, info fs.FileInfo, err error) error {
gioe72b54f2024-04-22 10:44:41 +0400390 if _, ok := f[path]; ok && !info.IsDir() {
391 contents, err := util.ReadFile(bfs, path)
392 if err != nil {
393 return err
394 }
395 t.Log(string(contents))
396 }
397 return nil
398 })
399 if err != nil {
400 t.Fatal(err)
401 }
402 t.Log("----- END ------")
403}