handlers_test.go (5342B)
1 package main 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "net/http/httptest" 7 "os" 8 "path/filepath" 9 "strconv" 10 "strings" 11 "testing" 12 ) 13 14 // Tokens known by the fake auth service, and the users that own them. 15 var sessions = map[string]string{ 16 "token-ana": "ana", 17 "token-bob": "bob", 18 } 19 20 // The fake event service knows only this event. 21 const knownEvent = 1 22 23 var server *httptest.Server 24 25 func TestMain(m *testing.M) { 26 dir, err := os.MkdirTemp("", "siga-signups") 27 if err != nil { 28 panic(err) 29 } 30 if err := openDB(filepath.Join(dir, "test.db")); err != nil { 31 panic(err) 32 } 33 34 fakeAuth := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 35 username, ok := sessions[strings.TrimPrefix(r.URL.Path, "/")] 36 if !ok { 37 http.Error(w, "invalid token", http.StatusUnauthorized) 38 return 39 } 40 json.NewEncoder(w).Encode(map[string]string{"Username": username}) 41 })) 42 fakeEvents := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 43 if _, ok := sessions[bearer(r)]; !ok { 44 http.Error(w, "invalid token", http.StatusUnauthorized) 45 return 46 } 47 if r.URL.Path != "/event/1" { 48 http.NotFound(w, r) 49 return 50 } 51 w.Write([]byte(`{"id": 1, "name": "Semana"}`)) 52 })) 53 authURL, eventURL = fakeAuth.URL, fakeEvents.URL 54 55 router() 56 server = httptest.NewServer(http.DefaultServeMux) 57 58 code := m.Run() 59 60 server.Close() 61 fakeAuth.Close() 62 fakeEvents.Close() 63 db.Close() 64 os.RemoveAll(dir) 65 os.Exit(code) 66 } 67 68 func request(t *testing.T, method, path, token, body string) *http.Response { 69 t.Helper() 70 req, err := http.NewRequest(method, server.URL+path, strings.NewReader(body)) 71 if err != nil { 72 t.Fatal(err) 73 } 74 if token != "" { 75 req.Header.Set("Authorization", "Bearer "+token) 76 } 77 res, err := server.Client().Do(req) 78 if err != nil { 79 t.Fatal(err) 80 } 81 t.Cleanup(func() { res.Body.Close() }) 82 return res 83 } 84 85 func expectStatus(t *testing.T, res *http.Response, want int) { 86 t.Helper() 87 if res.StatusCode != want { 88 t.Fatalf("%s %s: status %d, want %d", 89 res.Request.Method, res.Request.URL.Path, res.StatusCode, want) 90 } 91 } 92 93 func decodeSignup(t *testing.T, res *http.Response) Signup { 94 t.Helper() 95 var s Signup 96 if err := json.NewDecoder(res.Body).Decode(&s); err != nil { 97 t.Fatalf("decoding signup: %v", err) 98 } 99 return s 100 } 101 102 func TestSignupUsesTheOwnerOfTheToken(t *testing.T) { 103 res := request(t, "POST", "/signup", "token-ana", `{"event_id": 1}`) 104 expectStatus(t, res, http.StatusCreated) 105 s := decodeSignup(t, res) 106 if s.Username != "ana" || s.EventID != knownEvent || s.PresenceConfirmed != 0 { 107 t.Fatalf("created %+v, want ana in event 1 without presence", s) 108 } 109 110 res = request(t, "GET", "/signup/"+strconv.FormatInt(s.ID, 10), "token-ana", "") 111 expectStatus(t, res, http.StatusOK) 112 if got := decodeSignup(t, res); got != s { 113 t.Errorf("GET returned %+v, want %+v", got, s) 114 } 115 116 // Same user and event again. 117 expectStatus(t, request(t, "POST", "/signup", "token-ana", `{"event_id": 1}`), http.StatusConflict) 118 } 119 120 func TestCannotSignUpAnotherUser(t *testing.T) { 121 res := request(t, "POST", "/signup", "token-bob", `{"username": "ana", "event_id": 1}`) 122 expectStatus(t, res, http.StatusForbidden) 123 124 // Naming yourself is fine. 125 res = request(t, "POST", "/signup", "token-bob", `{"username": "bob", "event_id": 1}`) 126 expectStatus(t, res, http.StatusCreated) 127 if s := decodeSignup(t, res); s.Username != "bob" { 128 t.Errorf("signed up %q, want bob", s.Username) 129 } 130 } 131 132 func TestPresenceOnlyOnOwnSignup(t *testing.T) { 133 res := request(t, "POST", "/signup", "token-ana", `{"event_id": 1}`) 134 if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusConflict { 135 t.Fatalf("signing ana up: status %d", res.StatusCode) 136 } 137 138 body := `{"username": "ana", "event_id": 1, "presence_confirmed": 1}` 139 expectStatus(t, request(t, "PUT", "/presence", "token-bob", body), http.StatusForbidden) 140 141 expectStatus(t, request(t, "PUT", "/presence", "token-ana", `{"event_id": 1, "presence_confirmed": 1}`), http.StatusOK) 142 expectStatus(t, request(t, "PUT", "/presence", "token-ana", `{"event_id": 1, "presence_confirmed": 2}`), http.StatusBadRequest) 143 } 144 145 func TestPresenceWithoutSignup(t *testing.T) { 146 // bob has a token but no signup in event 2. 147 body := `{"event_id": 2, "presence_confirmed": 1}` 148 expectStatus(t, request(t, "PUT", "/presence", "token-bob", body), http.StatusNotFound) 149 } 150 151 func TestAuthentication(t *testing.T) { 152 expectStatus(t, request(t, "POST", "/signup", "", `{"event_id": 1}`), http.StatusUnauthorized) 153 expectStatus(t, request(t, "POST", "/signup", "lixo", `{"event_id": 1}`), http.StatusUnauthorized) 154 expectStatus(t, request(t, "GET", "/signup/1", "lixo", ""), http.StatusUnauthorized) 155 } 156 157 func TestInvalidRequests(t *testing.T) { 158 expectStatus(t, request(t, "POST", "/signup", "token-ana", `{"event_id": 99}`), http.StatusNotFound) 159 expectStatus(t, request(t, "POST", "/signup", "token-ana", `{"event_id": "1"}`), http.StatusBadRequest) 160 expectStatus(t, request(t, "GET", "/signup/abc", "token-ana", ""), http.StatusBadRequest) 161 expectStatus(t, request(t, "GET", "/signup/9999", "token-ana", ""), http.StatusNotFound) 162 } 163 164 func TestAuthUnavailable(t *testing.T) { 165 saved := authURL 166 authURL = "http://127.0.0.1:1" 167 defer func() { authURL = saved }() 168 169 expectStatus(t, request(t, "POST", "/signup", "token-ana", `{"event_id": 1}`), http.StatusServiceUnavailable) 170 }