blob: e4cee83bacf28498b6fdb38477ab8c9e19a3a563 [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
37type fakeZoneStatusFetcher struct {
38 t *testing.T
39}
40
41func (f fakeZoneStatusFetcher) Fetch(addr string) (string, error) {
42 f.t.Logf("Fetching status: %s", addr)
43 return addr, nil
44}
45
46type mockRepoIO struct {
47 soft.RepoFS
48 addr string
49 t *testing.T
50 l sync.Locker
51}
52
53func (r mockRepoIO) FullAddress() string {
54 return r.addr
55}
56
57func (r mockRepoIO) Pull() error {
58 r.t.Logf("Pull: %s", r.addr)
59 return nil
60}
61
62func (r mockRepoIO) CommitAndPush(message string) error {
63 r.t.Logf("Commit and push: %s", message)
64 return nil
65}
66
67func (r mockRepoIO) Do(op soft.DoFn, _ ...soft.DoOption) error {
68 r.l.Lock()
69 defer r.l.Unlock()
70 msg, err := op(r)
71 if err != nil {
72 return err
73 }
74 return r.CommitAndPush(msg)
75}
76
77type fakeSoftServeClient struct {
78 t *testing.T
79 envFS billy.Filesystem
80}
81
82func (f fakeSoftServeClient) Address() string {
83 return ""
84}
85
86func (f fakeSoftServeClient) Signer() ssh.Signer {
87 return nil
88}
89
90func (f fakeSoftServeClient) GetPublicKeys() ([]string, error) {
91 return []string{}, nil
92}
93
94func (f fakeSoftServeClient) GetRepo(name string) (soft.RepoIO, error) {
95 var l sync.Mutex
96 return mockRepoIO{soft.NewBillyRepoFS(f.envFS), "foo.bar", f.t, &l}, nil
97}
98
99func (f fakeSoftServeClient) GetRepoAddress(name string) string {
100 return ""
101}
102
103func (f fakeSoftServeClient) AddRepository(name string) error {
104 return nil
105}
106
107func (f fakeSoftServeClient) AddUser(name, pubKey string) error {
108 return nil
109}
110
111func (f fakeSoftServeClient) AddPublicKey(user string, pubKey string) error {
112 return nil
113}
114
115func (f fakeSoftServeClient) RemovePublicKey(user string, pubKey string) error {
116 return nil
117}
118
119func (f fakeSoftServeClient) MakeUserAdmin(name string) error {
120 return nil
121}
122
123func (f fakeSoftServeClient) AddReadWriteCollaborator(repo, user string) error {
124 return nil
125}
126
127func (f fakeSoftServeClient) AddReadOnlyCollaborator(repo, user string) error {
128 return nil
129}
130
131type fakeClientGetter struct {
132 t *testing.T
133 envFS billy.Filesystem
134}
135
136func (f fakeClientGetter) Get(addr string, clientPrivateKey []byte, log *log.Logger) (soft.Client, error) {
137 return fakeSoftServeClient{f.t, f.envFS}, nil
138}
139
140const infraConfig = `
141infraAdminPublicKey: Zm9vYmFyCg==
142namespacePrefix: infra-
143pcloudEnvName: infra
144publicIP:
145- 1.1.1.1
146- 2.2.2.2
147`
148
149const envCidrs = ``
150
151type fixedNameGenerator struct{}
152
153func (f fixedNameGenerator) Generate() (string, error) {
154 return "test", nil
155}
156
157type fakeHttpClient struct {
158 t *testing.T
159 counts map[string]int
160}
161
162func (f fakeHttpClient) Get(addr string) (*http.Response, error) {
163 f.t.Logf("HTTP GET: %s", addr)
164 cnt, ok := f.counts[addr]
165 if !ok {
166 cnt = 0
167 }
168 f.counts[addr] = cnt + 1
169 return &http.Response{
170 Status: "200 OK",
171 StatusCode: http.StatusOK,
172 Proto: "HTTP/1.0",
173 ProtoMajor: 1,
174 ProtoMinor: 0,
175 Body: io.NopCloser(strings.NewReader("ok")),
176 }, nil
177}
178
179type fakeDnsClient struct {
180 t *testing.T
181 counts map[string]int
182}
183
184func (f fakeDnsClient) Lookup(host string) ([]net.IP, error) {
185 f.t.Logf("HTTP GET: %s", host)
186 return []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("2.2.2.2")}, nil
187}
188
giod9c398e2024-06-06 13:33:03 +0400189type onDoneTaskMap struct {
190 m tasks.TaskManager
191 onDone tasks.TaskDoneListener
192}
193
194func (m *onDoneTaskMap) Add(name string, task tasks.Task) error {
195 if err := m.m.Add(name, task); err != nil {
196 return err
197 } else {
198 task.OnDone(m.onDone)
199 return nil
200 }
201}
202
203func (m *onDoneTaskMap) Get(name string) (tasks.Task, error) {
204 return m.m.Get(name)
205}
206
gioe72b54f2024-04-22 10:44:41 +0400207func TestCreateNewEnv(t *testing.T) {
208 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
209 infraFS := memfs.New()
210 envFS := memfs.New()
211 nsCreator := fakeNSCreator{t}
212 infraRepo := mockRepoIO{soft.NewBillyRepoFS(infraFS), "foo.bar", t, &sync.Mutex{}}
213 infraMgr, err := installer.NewInfraAppManager(infraRepo, nsCreator)
214 if err != nil {
215 t.Fatal(err)
216 }
217 if err := util.WriteFile(infraFS, "config.yaml", []byte(infraConfig), fs.ModePerm); err != nil {
218 t.Fatal(err)
219 }
220 if err := util.WriteFile(infraFS, "env-cidrs.yaml", []byte(envCidrs), fs.ModePerm); err != nil {
221 t.Fatal(err)
222 }
223 {
224 app, err := installer.FindInfraApp(apps, "dns-gateway")
225 if err != nil {
226 t.Fatal(err)
227 }
gio778577f2024-04-29 09:44:38 +0400228 if _, err := infraMgr.Install(app, "/infrastructure/dns-gateway", "dns-gateway", map[string]any{
gioe72b54f2024-04-22 10:44:41 +0400229 "servers": []installer.EnvDNS{},
230 }); err != nil {
231 t.Fatal(err)
232 }
233 }
234 cg := fakeClientGetter{t, envFS}
235 httpClient := fakeHttpClient{t, make(map[string]int)}
236 dnsClient := fakeDnsClient{t, make(map[string]int)}
giod9c398e2024-06-06 13:33:03 +0400237 var done sync.WaitGroup
238 done.Add(1)
239 var taskErr error
240 tm := &onDoneTaskMap{
241 tasks.NewTaskMap(),
242 func(err error) {
243 taskErr = err
244 done.Done()
245 },
246 }
gioe72b54f2024-04-22 10:44:41 +0400247 s := NewEnvServer(
248 8181,
249 fakeSoftServeClient{t, envFS},
250 infraRepo,
251 cg,
252 nsCreator,
253 fakeZoneStatusFetcher{t},
254 fixedNameGenerator{},
255 httpClient,
256 dnsClient,
giod9c398e2024-06-06 13:33:03 +0400257 tm,
gioe72b54f2024-04-22 10:44:41 +0400258 )
259 go s.Start()
giod9c398e2024-06-06 13:33:03 +0400260 time.Sleep(1 * time.Second) // Let server start
gioe72b54f2024-04-22 10:44:41 +0400261 req := createEnvReq{
262 Name: "test",
263 ContactEmail: "test@test.t",
264 Domain: "test.t",
265 AdminPublicKey: "test",
266 SecretToken: "test",
267 }
268 var buf bytes.Buffer
269 if err := json.NewEncoder(&buf).Encode(req); err != nil {
270 t.Fatal(err)
271 }
272 resp, err := http.Post("http://localhost:8181/", "application/json", &buf)
gioe72b54f2024-04-22 10:44:41 +0400273 if err != nil {
274 t.Fatal(err)
275 }
276 if resp.StatusCode != http.StatusOK {
277 var buf bytes.Buffer
278 io.Copy(&buf, resp.Body)
279 t.Fatal(buf.String())
280 }
281 done.Wait()
282 http.Get("http://localhost:8181/env/test")
283 debugFS(infraFS, t, "/infrastructure/dns-gateway/resources/coredns.yaml")
284 debugFS(envFS, t)
285 if taskErr != nil {
286 t.Fatal(taskErr)
287 }
288 expected := []string{
289 "https://accounts-ui.test.t",
290 "https://welcome.test.t",
291 "https://memberships.p.test.t",
gio09a3e5b2024-04-26 14:11:06 +0400292 "https://launcher.test.t",
gioe72b54f2024-04-22 10:44:41 +0400293 "https://headscale.test.t/apple",
294 }
295 for _, e := range expected {
296 if cnt, ok := httpClient.counts[e]; !ok || cnt != 1 {
297 t.Fatal(httpClient.counts)
298 }
299 }
gio09a3e5b2024-04-26 14:11:06 +0400300 if len(httpClient.counts) != 5 {
gioe72b54f2024-04-22 10:44:41 +0400301 t.Fatal(httpClient.counts)
302 }
303}
304
305func debugFS(bfs billy.Filesystem, t *testing.T, files ...string) {
306 f := map[string]struct{}{}
307 for _, i := range files {
308 f[i] = struct{}{}
309 }
310 t.Log("----- START ------")
311 err := util.Walk(bfs, "/", func(path string, info fs.FileInfo, err error) error {
312 t.Logf("%s %t\n", path, info.IsDir())
313 if _, ok := f[path]; ok && !info.IsDir() {
314 contents, err := util.ReadFile(bfs, path)
315 if err != nil {
316 return err
317 }
318 t.Log(string(contents))
319 }
320 return nil
321 })
322 if err != nil {
323 t.Fatal(err)
324 }
325 t.Log("----- END ------")
326}