blob: 1ab6b399b011fbcd66815b27153cfa8e5a2cc5ef [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
giocafd4e62024-07-31 10:53:40 +0400121func (f fakeSoftServeClient) GetAllRepos() ([]string, error) {
122 return []string{}, nil
123}
124
gioe72b54f2024-04-22 10:44:41 +0400125func (f fakeSoftServeClient) GetRepoAddress(name string) string {
126 return ""
127}
128
129func (f fakeSoftServeClient) AddRepository(name string) error {
130 return nil
131}
132
gio33059762024-07-05 13:19:07 +0400133func (f fakeSoftServeClient) UserExists(name string) (bool, error) {
134 return false, nil
135}
136func (f fakeSoftServeClient) FindUser(pubKey string) (string, error) {
137 return "", nil
138}
139
gioe72b54f2024-04-22 10:44:41 +0400140func (f fakeSoftServeClient) AddUser(name, pubKey string) error {
141 return nil
142}
143
144func (f fakeSoftServeClient) AddPublicKey(user string, pubKey string) error {
145 return nil
146}
147
148func (f fakeSoftServeClient) RemovePublicKey(user string, pubKey string) error {
149 return nil
150}
151
152func (f fakeSoftServeClient) MakeUserAdmin(name string) error {
153 return nil
154}
155
156func (f fakeSoftServeClient) AddReadWriteCollaborator(repo, user string) error {
157 return nil
158}
159
160func (f fakeSoftServeClient) AddReadOnlyCollaborator(repo, user string) error {
161 return nil
162}
163
gio0eaf2712024-04-14 13:08:46 +0400164func (f fakeSoftServeClient) AddWebhook(repo, url string, opts ...string) error {
165 return nil
166}
167
gioe72b54f2024-04-22 10:44:41 +0400168type fakeClientGetter struct {
169 t *testing.T
170 envFS billy.Filesystem
171}
172
173func (f fakeClientGetter) Get(addr string, clientPrivateKey []byte, log *log.Logger) (soft.Client, error) {
174 return fakeSoftServeClient{f.t, f.envFS}, nil
175}
176
177const infraConfig = `
178infraAdminPublicKey: Zm9vYmFyCg==
179namespacePrefix: infra-
180pcloudEnvName: infra
181publicIP:
182- 1.1.1.1
183- 2.2.2.2
184`
185
186const envCidrs = ``
187
188type fixedNameGenerator struct{}
189
190func (f fixedNameGenerator) Generate() (string, error) {
191 return "test", nil
192}
193
194type fakeHttpClient struct {
195 t *testing.T
196 counts map[string]int
197}
198
199func (f fakeHttpClient) Get(addr string) (*http.Response, error) {
200 f.t.Logf("HTTP GET: %s", addr)
201 cnt, ok := f.counts[addr]
202 if !ok {
203 cnt = 0
204 }
205 f.counts[addr] = cnt + 1
206 return &http.Response{
207 Status: "200 OK",
208 StatusCode: http.StatusOK,
209 Proto: "HTTP/1.0",
210 ProtoMajor: 1,
211 ProtoMinor: 0,
212 Body: io.NopCloser(strings.NewReader("ok")),
213 }, nil
214}
215
216type fakeDnsClient struct {
217 t *testing.T
218 counts map[string]int
219}
220
221func (f fakeDnsClient) Lookup(host string) ([]net.IP, error) {
222 f.t.Logf("HTTP GET: %s", host)
223 return []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("2.2.2.2")}, nil
224}
225
giod9c398e2024-06-06 13:33:03 +0400226type onDoneTaskMap struct {
227 m tasks.TaskManager
228 onDone tasks.TaskDoneListener
229}
230
231func (m *onDoneTaskMap) Add(name string, task tasks.Task) error {
232 if err := m.m.Add(name, task); err != nil {
233 return err
234 } else {
235 task.OnDone(m.onDone)
236 return nil
237 }
238}
239
240func (m *onDoneTaskMap) Get(name string) (tasks.Task, error) {
241 return m.m.Get(name)
242}
243
gioe72b54f2024-04-22 10:44:41 +0400244func TestCreateNewEnv(t *testing.T) {
245 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
246 infraFS := memfs.New()
247 envFS := memfs.New()
248 nsCreator := fakeNSCreator{t}
giof8843412024-05-22 16:38:05 +0400249 jc := fakeJobCreator{t}
250 hf := fakeHelmFetcher{t}
251 lg := installer.GitRepositoryLocalChartGenerator{"foo", "bar"}
gioe72b54f2024-04-22 10:44:41 +0400252 infraRepo := mockRepoIO{soft.NewBillyRepoFS(infraFS), "foo.bar", t, &sync.Mutex{}}
giof8843412024-05-22 16:38:05 +0400253 infraMgr, err := installer.NewInfraAppManager(infraRepo, nsCreator, hf, lg)
gioe72b54f2024-04-22 10:44:41 +0400254 if err != nil {
255 t.Fatal(err)
256 }
257 if err := util.WriteFile(infraFS, "config.yaml", []byte(infraConfig), fs.ModePerm); err != nil {
258 t.Fatal(err)
259 }
260 if err := util.WriteFile(infraFS, "env-cidrs.yaml", []byte(envCidrs), fs.ModePerm); err != nil {
261 t.Fatal(err)
262 }
263 {
264 app, err := installer.FindInfraApp(apps, "dns-gateway")
265 if err != nil {
266 t.Fatal(err)
267 }
gio778577f2024-04-29 09:44:38 +0400268 if _, err := infraMgr.Install(app, "/infrastructure/dns-gateway", "dns-gateway", map[string]any{
gioe72b54f2024-04-22 10:44:41 +0400269 "servers": []installer.EnvDNS{},
270 }); err != nil {
271 t.Fatal(err)
272 }
273 }
274 cg := fakeClientGetter{t, envFS}
275 httpClient := fakeHttpClient{t, make(map[string]int)}
276 dnsClient := fakeDnsClient{t, make(map[string]int)}
giod9c398e2024-06-06 13:33:03 +0400277 var done sync.WaitGroup
278 done.Add(1)
279 var taskErr error
280 tm := &onDoneTaskMap{
281 tasks.NewTaskMap(),
282 func(err error) {
283 taskErr = err
284 done.Done()
285 },
286 }
gioe72b54f2024-04-22 10:44:41 +0400287 s := NewEnvServer(
288 8181,
289 fakeSoftServeClient{t, envFS},
290 infraRepo,
291 cg,
292 nsCreator,
giof8843412024-05-22 16:38:05 +0400293 jc,
294 hf,
gioe72b54f2024-04-22 10:44:41 +0400295 fakeZoneStatusFetcher{t},
296 fixedNameGenerator{},
297 httpClient,
298 dnsClient,
giod9c398e2024-06-06 13:33:03 +0400299 tm,
gioe72b54f2024-04-22 10:44:41 +0400300 )
301 go s.Start()
giod9c398e2024-06-06 13:33:03 +0400302 time.Sleep(1 * time.Second) // Let server start
gioe72b54f2024-04-22 10:44:41 +0400303 req := createEnvReq{
gio7841f4f2024-07-26 19:53:49 +0400304 Name: "test",
305 ContactEmail: "test@test.t",
306 Domain: "test.t",
307 PrivateNetworkSubdomain: "p",
308 AdminPublicKey: "test",
309 SecretToken: "test",
gioe72b54f2024-04-22 10:44:41 +0400310 }
311 var buf bytes.Buffer
312 if err := json.NewEncoder(&buf).Encode(req); err != nil {
313 t.Fatal(err)
314 }
315 resp, err := http.Post("http://localhost:8181/", "application/json", &buf)
gioe72b54f2024-04-22 10:44:41 +0400316 if err != nil {
317 t.Fatal(err)
318 }
319 if resp.StatusCode != http.StatusOK {
320 var buf bytes.Buffer
321 io.Copy(&buf, resp.Body)
322 t.Fatal(buf.String())
323 }
324 done.Wait()
325 http.Get("http://localhost:8181/env/test")
326 debugFS(infraFS, t, "/infrastructure/dns-gateway/resources/coredns.yaml")
327 debugFS(envFS, t)
328 if taskErr != nil {
329 t.Fatal(taskErr)
330 }
331 expected := []string{
giob79db3a2024-08-01 14:20:42 +0400332 "https://apps.p.test.t",
gioe72b54f2024-04-22 10:44:41 +0400333 "https://accounts-ui.test.t",
334 "https://welcome.test.t",
335 "https://memberships.p.test.t",
gio09a3e5b2024-04-26 14:11:06 +0400336 "https://launcher.test.t",
gioe72b54f2024-04-22 10:44:41 +0400337 "https://headscale.test.t/apple",
338 }
339 for _, e := range expected {
340 if cnt, ok := httpClient.counts[e]; !ok || cnt != 1 {
341 t.Fatal(httpClient.counts)
342 }
343 }
giob79db3a2024-08-01 14:20:42 +0400344 if len(httpClient.counts) != 6 {
gioe72b54f2024-04-22 10:44:41 +0400345 t.Fatal(httpClient.counts)
346 }
347}
348
349func debugFS(bfs billy.Filesystem, t *testing.T, files ...string) {
350 f := map[string]struct{}{}
351 for _, i := range files {
352 f[i] = struct{}{}
353 }
354 t.Log("----- START ------")
355 err := util.Walk(bfs, "/", func(path string, info fs.FileInfo, err error) error {
gioe72b54f2024-04-22 10:44:41 +0400356 if _, ok := f[path]; ok && !info.IsDir() {
357 contents, err := util.ReadFile(bfs, path)
358 if err != nil {
359 return err
360 }
361 t.Log(string(contents))
362 }
363 return nil
364 })
365 if err != nil {
366 t.Fatal(err)
367 }
368 t.Log("----- END ------")
369}