63 lines
2.0 KiB
Go
63 lines
2.0 KiB
Go
package messenger
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"golang.org/x/crypto/argon2"
|
|
"mtusi/messenger/internal/database"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestLegacyArgon2RehashOnHTTPLogin(t *testing.T) {
|
|
raw, e := os.ReadFile(os.Getenv("DATABASE_TEST_URL_FILE"))
|
|
if e != nil {
|
|
t.Skip("real PostgreSQL required")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
db, e := database.Open(ctx, strings.TrimSpace(string(raw)))
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
defer db.Close()
|
|
salt := []byte("synthetic-salt16")
|
|
password := "Synthetic-old-password-123"
|
|
hash := argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32)
|
|
legacy := "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash)
|
|
if !verifyPassword(password, legacy) || !needsRehash(legacy) {
|
|
t.Fatal("legacy verification or upgrade missing")
|
|
}
|
|
username := "rehash_" + strings.ReplaceAll(uuid(), "-", "")[:16]
|
|
id := uuid()
|
|
_, e = db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,'Synthetic rehash',$3)", id, username, legacy)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
server := httptest.NewServer(New(db, nil, make([]byte, 32), 3600, nil))
|
|
defer server.Close()
|
|
req, _ := http.NewRequest("POST", server.URL+"/api/v1/auth/sessions", nil)
|
|
req.SetBasicAuth(username, password)
|
|
res, e := server.Client().Do(req)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
res.Body.Close()
|
|
if res.StatusCode != 201 {
|
|
t.Fatalf("login status %d", res.StatusCode)
|
|
}
|
|
var updated string
|
|
if db.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1", id).Scan(&updated) != nil || needsRehash(updated) || !verifyPassword(password, updated) {
|
|
t.Fatal("successful login did not safely upgrade stored hash")
|
|
}
|
|
for _, bad := range []string{"$argon2id$v=19$m=4294967295,t=999,p=2$AA$AA", "$argon2id$v=19$m=0,t=0,p=0$AA$AA"} {
|
|
if verifyPassword(password, bad) {
|
|
t.Fatal("unbounded PHC accepted")
|
|
}
|
|
}
|
|
}
|