eleven / messenger Public

Clone
git clone https://amadan.net/eleven/messenger

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "encoding/json"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9)
10
11// twoRegions wires s with an ie + fi provisioner pointed at the given fake
12// clouds, default ie — the per-country shape the dev mesh runs.
13func twoRegions(s *Server, ieURL, fiURL string) {
14 s.regions = []cloudRegion{
15 {Code: "ie", Name: "Ireland", prov: newCloudProvisioner(ieURL, "ie-tok")},
16 {Code: "fi", Name: "Finland", prov: newCloudProvisioner(fiURL, "fi-tok")},
17 }
18 s.defaultRegion = "ie"
19 s.cloud = s.cloudForRegion("ie")
20}
21
22func postSpacesJSON(t *testing.T, ts *httptest.Server, token, body string) *http.Response {
23 t.Helper()
24 req, _ := http.NewRequest("POST", ts.URL+"/api/spaces", strings.NewReader(body))
25 req.Header.Set("Authorization", "Bearer "+token)
26 req.Header.Set("Content-Type", "application/json")
27 resp, err := http.DefaultClient.Do(req)
28 if err != nil {
29 t.Fatal(err)
30 }
31 t.Cleanup(func() { resp.Body.Close() })
32 return resp
33}
34
35func createdHost(t *testing.T, resp *http.Response) string {
36 t.Helper()
37 if resp.StatusCode != http.StatusCreated {
38 t.Fatalf("create status = %d, want 201", resp.StatusCode)
39 }
40 var m map[string]any
41 json.NewDecoder(resp.Body).Decode(&m)
42 host, _ := m["host"].(string)
43 return host
44}
45
46func TestParseCloudRegions(t *testing.T) {
47 // Empty → single-region: no regions, no default, no error.
48 if regs, def, err := parseCloudRegions("", ""); err != nil || regs != nil || def != "" {
49 t.Errorf("empty: got regs=%v def=%q err=%v", regs, def, err)
50 }
51
52 j := `[{"code":"ie","name":"Ireland","url":"https://cloud.ie","token":"a"},{"code":"fi","name":"Finland","url":"https://cloud.fi","token":"b"}]`
53 regs, def, err := parseCloudRegions(j, "fi")
54 if err != nil {
55 t.Fatalf("parse: %v", err)
56 }
57 if len(regs) != 2 || def != "fi" {
58 t.Fatalf("regs=%d default=%q", len(regs), def)
59 }
60 if regs[0].Code != "ie" || regs[0].Name != "Ireland" || regs[0].prov == nil {
61 t.Errorf("regs[0] = %+v", regs[0])
62 }
63
64 // Empty default → the first region.
65 if _, def2, err := parseCloudRegions(j, ""); err != nil || def2 != "ie" {
66 t.Errorf("empty default = %q (err %v), want ie", def2, err)
67 }
68 // A missing name defaults to the code.
69 if regs3, _, err := parseCloudRegions(`[{"code":"nl","url":"https://c","token":"t"}]`, ""); err != nil || regs3[0].Name != "nl" {
70 t.Errorf("missing name should default to code: %+v (err %v)", regs3, err)
71 }
72
73 for _, bad := range []struct{ j, def, why string }{
74 {`[{"code":"ie","url":"https://c"}]`, "", "missing token"},
75 {`[{"code":"ie","name":"x","token":"t"}]`, "", "missing url"},
76 {`[{"code":"ie","url":"u","token":"t"}]`, "zz", "unknown default"},
77 {`[{"code":"ie","url":"u","token":"t"},{"code":"ie","url":"u","token":"t"}]`, "", "duplicate code"},
78 {`not json`, "", "bad json"},
79 {`[{"url":"u","token":"t"}]`, "", "missing code"},
80 } {
81 if _, _, err := parseCloudRegions(bad.j, bad.def); err == nil {
82 t.Errorf("%s: expected an error, got nil", bad.why)
83 }
84 }
85}
86
87func TestCreateSpaceRoutesByRegion(t *testing.T) {
88 ts, s := newTestServer(t)
89 _, token := seedMember(t, s)
90
91 // Each region's fake reports a host in its own country, so the create
92 // response alone says which provisioner handled it — no capture ordering.
93 ieCloud, _, _ := fakeCloud(t, http.StatusCreated, map[string]any{
94 "host": "x.ie.example.com", "setup_link": "https://x.ie.example.com/join#S",
95 })
96 fiCloud, fiCaptured, fiBody := fakeCloud(t, http.StatusCreated, map[string]any{
97 "host": "x.fi.example.com", "setup_link": "https://x.fi.example.com/join#S",
98 })
99 twoRegions(s, ieCloud.URL, fiCloud.URL)
100
101 // Owner override: an explicit region places the space there.
102 if host := createdHost(t, postSpacesJSON(t, ts, token, `{"region":"fi"}`)); host != "x.fi.example.com" {
103 t.Errorf("region=fi landed on %q, want the fi cloud", host)
104 }
105 if got := fiCaptured.Header.Get("Authorization"); got != "Bearer fi-tok" {
106 t.Errorf("fi create used %q, want the fi region's own token", got)
107 }
108 // The region is home's routing concern — the provisioner still receives only
109 // the opaque requester, nothing else.
110 var sent map[string]string
111 json.Unmarshal(*fiBody, &sent)
112 if _, leaked := sent["region"]; leaked || len(sent) != 1 {
113 t.Errorf("provisioner saw %v, want just requester", sent)
114 }
115
116 // Auto-assign: no region → the default region (ie).
117 if host := createdHost(t, postSpacesJSON(t, ts, token, `{}`)); host != "x.ie.example.com" {
118 t.Errorf("no region landed on %q, want the default ie cloud", host)
119 }
120 // An unknown region quietly auto-assigns rather than failing.
121 if host := createdHost(t, postSpacesJSON(t, ts, token, `{"region":"zz"}`)); host != "x.ie.example.com" {
122 t.Errorf("unknown region landed on %q, want the default ie cloud", host)
123 }
124}
125
126func TestListSpacesFansOutAcrossRegions(t *testing.T) {
127 ts, s := newTestServer(t)
128 _, token := seedUser(t, s)
129
130 ieCloud, _, _ := fakeCloud(t, http.StatusOK, map[string]any{
131 "spaces": []map[string]any{{"host": "a.ie.example.com"}},
132 })
133 fiCloud, _, _ := fakeCloud(t, http.StatusOK, map[string]any{
134 "spaces": []map[string]any{{"host": "b.fi.example.com"}},
135 })
136 twoRegions(s, ieCloud.URL, fiCloud.URL)
137
138 req, _ := http.NewRequest("GET", ts.URL+"/api/spaces", nil)
139 req.Header.Set("Authorization", "Bearer "+token)
140 resp, err := http.DefaultClient.Do(req)
141 if err != nil {
142 t.Fatal(err)
143 }
144 defer resp.Body.Close()
145 var m struct{ Spaces []struct{ Host string } }
146 json.NewDecoder(resp.Body).Decode(&m)
147 if len(m.Spaces) != 2 {
148 t.Fatalf("merged spaces = %d, want 2 (one per region): %+v", len(m.Spaces), m.Spaces)
149 }
150 hosts := map[string]bool{m.Spaces[0].Host: true, m.Spaces[1].Host: true}
151 if !hosts["a.ie.example.com"] || !hosts["b.fi.example.com"] {
152 t.Errorf("merged hosts = %+v, want both regions", m.Spaces)
153 }
154}
155
156func TestListSpacesSurvivesOneRegionDown(t *testing.T) {
157 ts, s := newTestServer(t)
158 _, token := seedUser(t, s)
159
160 up, _, _ := fakeCloud(t, http.StatusOK, map[string]any{
161 "spaces": []map[string]any{{"host": "a.ie.example.com"}},
162 })
163 down, _, _ := fakeCloud(t, http.StatusBadGateway, map[string]any{"error": "boom"})
164 twoRegions(s, up.URL, down.URL) // ie up, fi failing
165
166 req, _ := http.NewRequest("GET", ts.URL+"/api/spaces", nil)
167 req.Header.Set("Authorization", "Bearer "+token)
168 resp, err := http.DefaultClient.Do(req)
169 if err != nil {
170 t.Fatal(err)
171 }
172 defer resp.Body.Close()
173 // One region up → still 200 with that region's spaces (best-effort).
174 if resp.StatusCode != http.StatusOK {
175 t.Fatalf("one region down: status = %d, want 200", resp.StatusCode)
176 }
177 var m struct{ Spaces []struct{ Host string } }
178 json.NewDecoder(resp.Body).Decode(&m)
179 if len(m.Spaces) != 1 || m.Spaces[0].Host != "a.ie.example.com" {
180 t.Errorf("spaces = %+v, want just the healthy region's", m.Spaces)
181 }
182}
183
184// listSpaces returns the decoded /api/spaces response body.
185func listSpaces(t *testing.T, ts *httptest.Server, token string) map[string]any {
186 t.Helper()
187 req, _ := http.NewRequest("GET", ts.URL+"/api/spaces", nil)
188 req.Header.Set("Authorization", "Bearer "+token)
189 resp, err := http.DefaultClient.Do(req)
190 if err != nil {
191 t.Fatal(err)
192 }
193 defer resp.Body.Close()
194 if resp.StatusCode != http.StatusOK {
195 t.Fatalf("list status = %d, want 200", resp.StatusCode)
196 }
197 var m map[string]any
198 json.NewDecoder(resp.Body).Decode(&m)
199 return m
200}
201
202// tierKey digs the first tier's key out of a list response's billing block.
203func tierKey(t *testing.T, m map[string]any) string {
204 t.Helper()
205 b, ok := m["billing"].(map[string]any)
206 if !ok {
207 t.Fatalf("no billing in list response: %v", m)
208 }
209 tiers, _ := b["tiers"].([]any)
210 if len(tiers) == 0 {
211 t.Fatalf("billing has no tiers: %v", b)
212 }
213 first, _ := tiers[0].(map[string]any)
214 key, _ := first["key"].(string)
215 return key
216}
217
218func TestListSpacesCarriesBilling(t *testing.T) {
219 ts, s := newTestServer(t)
220 _, token := seedUser(t, s)
221
222 ieCloud, _, _ := fakeCloud(t, http.StatusOK, map[string]any{
223 "spaces": []map[string]any{{"host": "a.ie.example.com"}},
224 "billing": map[string]any{"tiers": []map[string]any{{"key": "family"}}},
225 })
226 fiCloud, _, _ := fakeCloud(t, http.StatusOK, map[string]any{
227 "spaces": []map[string]any{},
228 "billing": map[string]any{"tiers": []map[string]any{{"key": "fi-only"}}},
229 })
230
231 // The production shape: one unpartitioned cloud with a price book. The book
232 // must ride the list response — home.js reads r.billing, and dropping it
233 // silently removes the Upgrade UI (the #1083 regression this test pins).
234 s.cloud = newCloudProvisioner(ieCloud.URL, "tok")
235 if got := tierKey(t, listSpaces(t, ts, token)); got != "family" {
236 t.Errorf("single region: tier = %q, want family", got)
237 }
238
239 // Partitioned: the DEFAULT region's book wins, wherever it sits in the
240 // fan-out order (ie deliberately listed last here).
241 s.regions = []cloudRegion{
242 {Code: "fi", Name: "Finland", prov: newCloudProvisioner(fiCloud.URL, "fi-tok")},
243 {Code: "ie", Name: "Ireland", prov: newCloudProvisioner(ieCloud.URL, "ie-tok")},
244 }
245 s.defaultRegion = "ie"
246 s.cloud = s.cloudForRegion("ie")
247 if got := tierKey(t, listSpaces(t, ts, token)); got != "family" {
248 t.Errorf("two regions: tier = %q, want the default region's family", got)
249 }
250
251 // Default region billing-less (reports false) → another region's book is
252 // the fallback rather than no Upgrade UI at all.
253 noBilling, _, _ := fakeCloud(t, http.StatusOK, map[string]any{
254 "spaces": []map[string]any{}, "billing": false,
255 })
256 s.regions = []cloudRegion{
257 {Code: "ie", Name: "Ireland", prov: newCloudProvisioner(noBilling.URL, "ie-tok")},
258 {Code: "fi", Name: "Finland", prov: newCloudProvisioner(fiCloud.URL, "fi-tok")},
259 }
260 s.defaultRegion = "ie"
261 s.cloud = s.cloudForRegion("ie")
262 if got := tierKey(t, listSpaces(t, ts, token)); got != "fi-only" {
263 t.Errorf("default billing-less: tier = %q, want the fi fallback", got)
264 }
265
266 // No cloud offers billing → the key is absent, not false/null (home.js
267 // treats absence as billing off).
268 s.regions = nil
269 s.defaultRegion = ""
270 s.cloud = newCloudProvisioner(noBilling.URL, "tok")
271 if m := listSpaces(t, ts, token); m["billing"] != nil {
272 t.Errorf("billing-less: billing = %v, want absent", m["billing"])
273 }
274}
275
276func TestManageRoutesByHostRegion(t *testing.T) {
277 ts, s := newTestServer(t)
278 uid, _ := seedUser(t, s)
279
280 ieCloud, ieCap, _ := fakeCloud(t, http.StatusOK, map[string]any{"ok": true})
281 fiCloud, fiCap, _ := fakeCloud(t, http.StatusOK, map[string]any{"ok": true})
282 twoRegions(s, ieCloud.URL, fiCloud.URL)
283
284 del := func(host string) {
285 req, _ := http.NewRequest("DELETE", ts.URL+"/api/spaces/"+host, nil)
286 req.Header.Set("X-Ceremony-Proof", s.keys.mintCeremonyProof(uid))
287 resp, err := http.DefaultClient.Do(req)
288 if err != nil {
289 t.Fatal(err)
290 }
291 resp.Body.Close()
292 if resp.StatusCode != http.StatusOK {
293 t.Fatalf("delete %s = %d, want 200", host, resp.StatusCode)
294 }
295 }
296
297 // A .fi host routes to the fi provisioner, and not the ie one.
298 del("y.fi.example.com")
299 if fiCap.Method != "DELETE" {
300 t.Error("delete of a .fi host did not reach the fi provisioner")
301 }
302 if ieCap.Method != "" {
303 t.Error("delete of a .fi host wrongly reached the ie provisioner")
304 }
305 // A .ie host routes to the ie provisioner.
306 del("z.ie.example.com")
307 if ieCap.Method != "DELETE" {
308 t.Error("delete of a .ie host did not reach the ie provisioner")
309 }
310}
311
312func TestFeaturesExposesRegions(t *testing.T) {
313 ts, s := newTestServer(t)
314
315 // Single-region: no regions key at all.
316 s.cloud = newCloudProvisioner("https://cloud.example.com", "tok")
317 var f map[string]any
318 getJSON(t, ts.URL+"/api/features", &f)
319 if _, ok := f["regions"]; ok {
320 t.Errorf("single-region features must not carry a regions key: %v", f)
321 }
322
323 // Multi-region: regions + default_region, code+name only — never url/token.
324 twoRegions(s, "https://cloud.ie", "https://cloud.fi")
325 var f2 map[string]any
326 getJSON(t, ts.URL+"/api/features", &f2)
327 if f2["default_region"] != "ie" {
328 t.Errorf("default_region = %v, want ie", f2["default_region"])
329 }
330 regs, ok := f2["regions"].([]any)
331 if !ok || len(regs) != 2 {
332 t.Fatalf("regions = %v, want 2", f2["regions"])
333 }
334 first, _ := regs[0].(map[string]any)
335 if first["code"] != "ie" || first["name"] != "Ireland" {
336 t.Errorf("region[0] = %v", first)
337 }
338 if _, leaked := first["url"]; leaked {
339 t.Errorf("features leaked a region url: %v", first)
340 }
341 if _, leaked := first["token"]; leaked {
342 t.Errorf("features leaked a region token: %v", first)
343 }
344}
345
346func getJSON(t *testing.T, url string, v any) {
347 t.Helper()
348 resp, err := http.Get(url)
349 if err != nil {
350 t.Fatal(err)
351 }
352 defer resp.Body.Close()
353 json.NewDecoder(resp.Body).Decode(v)
354}
355