auth_test.go (4491B)
1 package main 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "net/http/httptest" 7 "os" 8 "path/filepath" 9 "strings" 10 "testing" 11 "uuid" 12 13 "github.com/gboncoffee/siga/auth/repository" 14 ) 15 16 // server answers requests through the real routes of the service, backed by 17 // a temporary database. 18 var server *httptest.Server 19 20 func TestMain(m *testing.M) { 21 dir, err := os.MkdirTemp("", "siga-auth") 22 if err != nil { 23 panic(err) 24 } 25 if err := repository.Open(filepath.Join(dir, "test.db")); err != nil { 26 panic(err) 27 } 28 router() 29 server = httptest.NewServer(http.DefaultServeMux) 30 31 code := m.Run() 32 33 server.Close() 34 repository.Close() 35 os.RemoveAll(dir) 36 os.Exit(code) 37 } 38 39 func request(t *testing.T, method, path, body string) *http.Response { 40 t.Helper() 41 req, err := http.NewRequest(method, server.URL+path, strings.NewReader(body)) 42 if err != nil { 43 t.Fatal(err) 44 } 45 res, err := server.Client().Do(req) 46 if err != nil { 47 t.Fatal(err) 48 } 49 t.Cleanup(func() { res.Body.Close() }) 50 return res 51 } 52 53 func expectStatus(t *testing.T, res *http.Response, want int) { 54 t.Helper() 55 if res.StatusCode != want { 56 t.Fatalf("%s %s: status %d, want %d", 57 res.Request.Method, res.Request.URL.Path, res.StatusCode, want) 58 } 59 } 60 61 func createCredentials(t *testing.T, username, password string) { 62 t.Helper() 63 body := `{"Username": "` + username + `", "Password": "` + password + `"}` 64 expectStatus(t, request(t, "POST", "/credentials", body), http.StatusOK) 65 } 66 67 // loginAs logs in and returns the session token. 68 func loginAs(t *testing.T, username, password string) string { 69 t.Helper() 70 body := `{"Username": "` + username + `", "Password": "` + password + `"}` 71 res := request(t, "POST", "/login", body) 72 expectStatus(t, res, http.StatusOK) 73 74 if ct := res.Header.Get("Content-Type"); ct != "application/json" { 75 t.Errorf("Content-Type = %q, want application/json", ct) 76 } 77 var out LoginResponse 78 if err := json.NewDecoder(res.Body).Decode(&out); err != nil { 79 t.Fatalf("decoding login response: %v", err) 80 } 81 return out.Token.String() 82 } 83 84 func TestLoginLogoutFlow(t *testing.T) { 85 createCredentials(t, "ana", "segredo") 86 token := loginAs(t, "ana", "segredo") 87 88 res := request(t, "GET", "/"+token, "") 89 expectStatus(t, res, http.StatusOK) 90 var out AuthenticatedResponse 91 if err := json.NewDecoder(res.Body).Decode(&out); err != nil { 92 t.Fatalf("decoding GET /{uuid} response: %v", err) 93 } 94 if out.Username != "ana" { 95 t.Errorf("GET /{uuid}: Username = %q, want %q", out.Username, "ana") 96 } 97 98 expectStatus(t, request(t, "POST", "/logout/"+token, ""), http.StatusOK) 99 expectStatus(t, request(t, "GET", "/"+token, ""), http.StatusUnauthorized) 100 } 101 102 func TestEachLoginOpensItsOwnSession(t *testing.T) { 103 createCredentials(t, "bia", "segredo") 104 first := loginAs(t, "bia", "segredo") 105 second := loginAs(t, "bia", "segredo") 106 if first == second { 107 t.Fatal("two logins returned the same token") 108 } 109 110 expectStatus(t, request(t, "POST", "/logout/"+first, ""), http.StatusOK) 111 expectStatus(t, request(t, "GET", "/"+second, ""), http.StatusOK) 112 } 113 114 func TestLoginWithWrongPassword(t *testing.T) { 115 createCredentials(t, "caio", "certa") 116 res := request(t, "POST", "/login", `{"Username": "caio", "Password": "errada"}`) 117 expectStatus(t, res, http.StatusUnauthorized) 118 } 119 120 func TestLoginWithUnknownUser(t *testing.T) { 121 res := request(t, "POST", "/login", `{"Username": "ninguem", "Password": "x"}`) 122 expectStatus(t, res, http.StatusUnauthorized) 123 } 124 125 func TestInvalidJSON(t *testing.T) { 126 for _, path := range []string{"/login", "/credentials"} { 127 expectStatus(t, request(t, "POST", path, "{"), http.StatusBadRequest) 128 } 129 } 130 131 func TestDuplicateCredentials(t *testing.T) { 132 createCredentials(t, "duda", "a") 133 res := request(t, "POST", "/credentials", `{"Username": "duda", "Password": "b"}`) 134 expectStatus(t, res, http.StatusInternalServerError) 135 136 // The original password must still work. 137 loginAs(t, "duda", "a") 138 } 139 140 func TestUnknownTokenIsUnauthorized(t *testing.T) { 141 expectStatus(t, request(t, "GET", "/"+uuid.New().String(), ""), http.StatusUnauthorized) 142 } 143 144 func TestMalformedToken(t *testing.T) { 145 expectStatus(t, request(t, "GET", "/nao-e-uuid", ""), http.StatusBadRequest) 146 expectStatus(t, request(t, "POST", "/logout/nao-e-uuid", ""), http.StatusBadRequest) 147 } 148 149 func TestWrongMethod(t *testing.T) { 150 // GET /login is not here: it matches GET /{uuid} and answers 400. 151 expectStatus(t, request(t, "DELETE", "/login", ""), http.StatusMethodNotAllowed) 152 expectStatus(t, request(t, "PUT", "/credentials", ""), http.StatusMethodNotAllowed) 153 }