commit fb89650e3502c9040df24deaf2c394d91d0777d5
parent 629ab970f9adf423bd06278924640c95decdcff7
Author: Gabriel G. de Brito <me@gboncoffee.dev.br>
Date: Sat, 21 Nov 2026 11:57:38 -0300
Add auth tests and take the database path as a flag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
4 files changed, 271 insertions(+), 9 deletions(-)
diff --git a/auth/auth_test.go b/auth/auth_test.go
@@ -0,0 +1,144 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "uuid"
+
+ "github.com/gboncoffee/siga/auth/repository"
+)
+
+// server answers requests through the real routes of the service, backed by
+// a temporary database.
+var server *httptest.Server
+
+func TestMain(m *testing.M) {
+ dir, err := os.MkdirTemp("", "siga-auth")
+ if err != nil {
+ panic(err)
+ }
+ if err := repository.Open(filepath.Join(dir, "test.db")); err != nil {
+ panic(err)
+ }
+ router()
+ server = httptest.NewServer(http.DefaultServeMux)
+
+ code := m.Run()
+
+ server.Close()
+ repository.Close()
+ os.RemoveAll(dir)
+ os.Exit(code)
+}
+
+func request(t *testing.T, method, path, body string) *http.Response {
+ t.Helper()
+ req, err := http.NewRequest(method, server.URL+path, strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ res, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { res.Body.Close() })
+ return res
+}
+
+func expectStatus(t *testing.T, res *http.Response, want int) {
+ t.Helper()
+ if res.StatusCode != want {
+ t.Fatalf("%s %s: status %d, want %d",
+ res.Request.Method, res.Request.URL.Path, res.StatusCode, want)
+ }
+}
+
+func createCredentials(t *testing.T, username, password string) {
+ t.Helper()
+ body := `{"Username": "` + username + `", "Password": "` + password + `"}`
+ expectStatus(t, request(t, "POST", "/credentials", body), http.StatusOK)
+}
+
+// loginAs logs in and returns the session token.
+func loginAs(t *testing.T, username, password string) string {
+ t.Helper()
+ body := `{"Username": "` + username + `", "Password": "` + password + `"}`
+ res := request(t, "POST", "/login", body)
+ expectStatus(t, res, http.StatusOK)
+
+ if ct := res.Header.Get("Content-Type"); ct != "application/json" {
+ t.Errorf("Content-Type = %q, want application/json", ct)
+ }
+ var out LoginResponse
+ if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
+ t.Fatalf("decoding login response: %v", err)
+ }
+ return out.Token.String()
+}
+
+func TestLoginLogoutFlow(t *testing.T) {
+ createCredentials(t, "ana", "segredo")
+ token := loginAs(t, "ana", "segredo")
+
+ expectStatus(t, request(t, "GET", "/"+token, ""), http.StatusOK)
+ expectStatus(t, request(t, "POST", "/logout/"+token, ""), http.StatusOK)
+ expectStatus(t, request(t, "GET", "/"+token, ""), http.StatusUnauthorized)
+}
+
+func TestEachLoginOpensItsOwnSession(t *testing.T) {
+ createCredentials(t, "bia", "segredo")
+ first := loginAs(t, "bia", "segredo")
+ second := loginAs(t, "bia", "segredo")
+ if first == second {
+ t.Fatal("two logins returned the same token")
+ }
+
+ expectStatus(t, request(t, "POST", "/logout/"+first, ""), http.StatusOK)
+ expectStatus(t, request(t, "GET", "/"+second, ""), http.StatusOK)
+}
+
+func TestLoginWithWrongPassword(t *testing.T) {
+ createCredentials(t, "caio", "certa")
+ res := request(t, "POST", "/login", `{"Username": "caio", "Password": "errada"}`)
+ expectStatus(t, res, http.StatusUnauthorized)
+}
+
+func TestLoginWithUnknownUser(t *testing.T) {
+ res := request(t, "POST", "/login", `{"Username": "ninguem", "Password": "x"}`)
+ expectStatus(t, res, http.StatusUnauthorized)
+}
+
+func TestInvalidJSON(t *testing.T) {
+ for _, path := range []string{"/login", "/credentials"} {
+ expectStatus(t, request(t, "POST", path, "{"), http.StatusBadRequest)
+ }
+}
+
+func TestDuplicateCredentials(t *testing.T) {
+ createCredentials(t, "duda", "a")
+ res := request(t, "POST", "/credentials", `{"Username": "duda", "Password": "b"}`)
+ expectStatus(t, res, http.StatusInternalServerError)
+
+ // The original password must still work.
+ loginAs(t, "duda", "a")
+}
+
+func TestUnknownTokenIsUnauthorized(t *testing.T) {
+ expectStatus(t, request(t, "GET", "/"+uuid.New().String(), ""), http.StatusUnauthorized)
+}
+
+func TestMalformedToken(t *testing.T) {
+ expectStatus(t, request(t, "GET", "/nao-e-uuid", ""), http.StatusBadRequest)
+ expectStatus(t, request(t, "POST", "/logout/nao-e-uuid", ""), http.StatusBadRequest)
+}
+
+func TestWrongMethod(t *testing.T) {
+ // GET /login is not here: it matches GET /{uuid} and answers 400.
+ expectStatus(t, request(t, "DELETE", "/login", ""), http.StatusMethodNotAllowed)
+ expectStatus(t, request(t, "PUT", "/credentials", ""), http.StatusMethodNotAllowed)
+}
diff --git a/auth/main.go b/auth/main.go
@@ -4,6 +4,8 @@ import (
"flag"
"log"
"net/http"
+
+ "github.com/gboncoffee/siga/auth/repository"
)
func main() {
@@ -13,8 +15,15 @@ func main() {
flag.StringVar(&port, "port", "8080", "port to listen to")
flag.StringVar(&addr, "address", "localhost", "address to listen to")
+ var dbPath string
+ flag.StringVar(&dbPath, "db", "db.db", "path of the SQLite database")
+
flag.Parse()
+ if err := repository.Open(dbPath); err != nil {
+ log.Fatal(err)
+ }
+
router()
log.Println("Listening on " + addr + ":" + port)
diff --git a/auth/repository/repository.go b/auth/repository/repository.go
@@ -3,7 +3,6 @@ package repository
import (
"crypto/sha512"
"database/sql"
- "log"
"uuid"
_ "modernc.org/sqlite"
@@ -16,27 +15,37 @@ type Credential struct {
var db *sql.DB
-func init() {
- var err error
- db, err = sql.Open("sqlite", "db.db")
+// Open opens (creating if needed) the SQLite database at path. It must be
+// called before any other function of this package.
+func Open(path string) error {
+ conn, err := sql.Open("sqlite", path)
if err != nil {
- log.Fatal(err)
+ return err
}
- _, err = db.Exec(`
+ _, err = conn.Exec(`
CREATE TABLE IF NOT EXISTS credentials (
username TEXT NOT NULL UNIQUE,
password BLOB NOT NULL CHECK (LENGTH(password) == 64)
)`)
if err != nil {
- log.Fatal(err)
+ conn.Close()
+ return err
}
- _, err = db.Exec(`
+ _, err = conn.Exec(`
CREATE TABLE IF NOT EXISTS sessions (
token BLOB CHECK (LENGTH(token) == 16)
)`)
if err != nil {
- log.Fatal(err)
+ conn.Close()
+ return err
}
+ db = conn
+ return nil
+}
+
+// Close closes the database opened by Open.
+func Close() error {
+ return db.Close()
}
func NewCredential(c Credential) error {
diff --git a/auth/repository/repository_test.go b/auth/repository/repository_test.go
@@ -0,0 +1,100 @@
+package repository
+
+import (
+ "crypto/sha512"
+ "os"
+ "path/filepath"
+ "testing"
+ "uuid"
+)
+
+func TestMain(m *testing.M) {
+ dir, err := os.MkdirTemp("", "siga-auth-repository")
+ if err != nil {
+ panic(err)
+ }
+ if err := Open(filepath.Join(dir, "test.db")); err != nil {
+ panic(err)
+ }
+ code := m.Run()
+ Close()
+ os.RemoveAll(dir)
+ os.Exit(code)
+}
+
+func TestCredentialRoundTrip(t *testing.T) {
+ c := Credential{Username: "ana", Password: sha512.Sum512([]byte("segredo"))}
+ if err := NewCredential(c); err != nil {
+ t.Fatalf("NewCredential: %v", err)
+ }
+
+ got, err := GetByUsername("ana")
+ if err != nil {
+ t.Fatalf("GetByUsername: %v", err)
+ }
+ if got != c {
+ t.Errorf("GetByUsername = %+v, want %+v", got, c)
+ }
+}
+
+func TestDuplicateUsernameIsRejected(t *testing.T) {
+ c := Credential{Username: "bia", Password: sha512.Sum512([]byte("a"))}
+ if err := NewCredential(c); err != nil {
+ t.Fatalf("first NewCredential: %v", err)
+ }
+ c.Password = sha512.Sum512([]byte("b"))
+ if err := NewCredential(c); err == nil {
+ t.Fatal("second NewCredential with the same username succeeded")
+ }
+
+ got, err := GetByUsername("bia")
+ if err != nil {
+ t.Fatalf("GetByUsername: %v", err)
+ }
+ if got.Password != sha512.Sum512([]byte("a")) {
+ t.Error("the duplicate overwrote the original password")
+ }
+}
+
+func TestGetByUnknownUsername(t *testing.T) {
+ if _, err := GetByUsername("ninguem"); err == nil {
+ t.Fatal("GetByUsername of an unknown user returned no error")
+ }
+}
+
+func TestSessionLifecycle(t *testing.T) {
+ token := uuid.New()
+ if err := SessionExists(token); err == nil {
+ t.Fatal("session exists before being created")
+ }
+
+ if err := NewSession(token); err != nil {
+ t.Fatalf("NewSession: %v", err)
+ }
+ if err := SessionExists(token); err != nil {
+ t.Fatalf("SessionExists after NewSession: %v", err)
+ }
+
+ if err := DeleteSession(token); err != nil {
+ t.Fatalf("DeleteSession: %v", err)
+ }
+ if err := SessionExists(token); err == nil {
+ t.Fatal("session still exists after DeleteSession")
+ }
+}
+
+func TestDeletingOneSessionKeepsOthers(t *testing.T) {
+ a, b := uuid.New(), uuid.New()
+ for _, token := range []uuid.UUID{a, b} {
+ if err := NewSession(token); err != nil {
+ t.Fatalf("NewSession: %v", err)
+ }
+ }
+
+ if err := DeleteSession(a); err != nil {
+ t.Fatalf("DeleteSession: %v", err)
+ }
+ if err := SessionExists(b); err != nil {
+ t.Errorf("other session was removed: %v", err)
+ }
+}