Files
mtusi2026lab7/student_tests/password_rehash_test.go
T
2026-11-22 23:33:11 +03:00

62 lines
1.8 KiB
Go

package student_tests
import (
"encoding/base64"
"fmt"
"net/http"
"testing"
"time"
"mtusi2026lab7/internal/security"
"golang.org/x/crypto/argon2"
)
func legacyPasswordHash(password string) string {
salt := []byte("legacy-salt-1234")
hash := argon2.IDKey([]byte(password), salt, 1, 8*1024, 1, 32)
return fmt.Sprintf(
"$argon2id$v=%d$m=8192,t=1,p=1$%s$%s",
argon2.Version,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(hash),
)
}
func TestSuccessfulLoginRehashesLegacyPassword(t *testing.T) {
testServer, repository := setupSessionTestServer(t, time.Hour)
defer testServer.Close()
user := registerSessionTestUser(t, testServer.URL, "rehash_user")
_, currentHash, err := repository.GetUserByUsername(t.Context(), user.Username)
if err != nil {
t.Fatal(err)
}
legacyHash := legacyPasswordHash(testPassword)
if err = repository.UpdatePasswordHash(t.Context(), user.ID, currentHash, legacyHash); err != nil {
t.Fatal(err)
}
response := createSessionRequest(t, testServer.URL, user.Username, testPassword)
response.Body.Close()
if response.StatusCode != http.StatusCreated {
t.Fatalf("expected successful login, got %d", response.StatusCode)
}
_, upgradedHash, err := repository.GetUserByUsername(t.Context(), user.Username)
if err != nil {
t.Fatal(err)
}
if upgradedHash == legacyHash {
t.Fatal("successful login did not replace the legacy hash")
}
matches, err := security.VerifyPassword(testPassword, upgradedHash)
if err != nil || !matches {
t.Fatalf("upgraded hash does not verify: matches=%v err=%v", matches, err)
}
needsRehash, err := security.NeedsPasswordRehash(upgradedHash)
if err != nil || needsRehash {
t.Fatalf("upgraded hash still needs rehash: needs=%v err=%v", needsRehash, err)
}
}