forked from mtusi2026/mtusi2026lab5
chore(migrate) moved codebase from lab4
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
// Package auth implements password hashing, Basic login, Bearer session
|
||||
// middleware and the authentication routes.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
sessions *session.Store
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store, sessions *session.Store) *Handler {
|
||||
return &Handler{store: st, sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *Handler) CreateSession(c fiber.Ctx) error {
|
||||
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
|
||||
if !ok {
|
||||
return common.NewChallenge(basicChallenge, "invalid credentials")
|
||||
}
|
||||
|
||||
user, err := h.store.GetUserByUsername(c.Context(), username)
|
||||
if err != nil {
|
||||
if common.IsCode(err, common.ErrorCodeNotFound) {
|
||||
// An unknown username returns before Argon2 runs, while a known
|
||||
// username with a wrong password runs VerifyPassword. The branches
|
||||
// therefore take different time, so username enumeration through
|
||||
// response timing is theoretically possible. The contract only
|
||||
// requires the same 401 body and challenge.
|
||||
return common.NewChallenge(basicChallenge, "invalid credentials")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
valid, err := VerifyPassword(user.PasswordHash, password)
|
||||
if err != nil || !valid {
|
||||
return common.NewChallenge(basicChallenge, "invalid credentials")
|
||||
}
|
||||
|
||||
token, expiresAt, err := h.sessions.Create(c.Context(), user.ID)
|
||||
if err != nil {
|
||||
slog.Error("create session", "err", err)
|
||||
return common.Unavailable("session store unavailable")
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).JSON(model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: common.RFCFormTime(expiresAt),
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) RevokeSession(c fiber.Ctx) error {
|
||||
token, ok := common.SessionToken(c)
|
||||
if !ok {
|
||||
return common.NewChallenge(bearerChallenge, "authentication required")
|
||||
}
|
||||
|
||||
if err := h.sessions.Revoke(c.Context(), token); err != nil {
|
||||
slog.Error("revoke session", "err", err)
|
||||
return common.Unavailable("session store unavailable")
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
func BearerAuth(sessions *session.Store) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
header := strings.TrimSpace(c.Get(fiber.HeaderAuthorization))
|
||||
scheme, token, found := strings.Cut(header, " ")
|
||||
token = strings.TrimSpace(token)
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") {
|
||||
return common.NewChallenge(bearerChallenge, "authentication required")
|
||||
}
|
||||
|
||||
userID, err := sessions.Lookup(c.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return common.NewChallenge(bearerChallenge, "session expired or revoked")
|
||||
}
|
||||
slog.Error("session lookup", "err", err)
|
||||
return common.Unavailable("session store unavailable")
|
||||
}
|
||||
|
||||
c.Locals(common.KeyUserID, userID)
|
||||
c.Locals(common.KeySessionToken, token)
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func parseBasic(header string) (string, string, bool) {
|
||||
scheme, encoded, found := strings.Cut(strings.TrimSpace(header), " ")
|
||||
if !found || !strings.EqualFold(scheme, "Basic") || encoded == "" {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
if decoded, err = base64.RawStdEncoding.DecodeString(encoded); err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 7617: split at the first colon; a colon is legal inside the password.
|
||||
username, password, found := strings.Cut(string(decoded), ":")
|
||||
if !found || username == "" || password == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory = 64 * 1024
|
||||
argonIterations = 2
|
||||
argonParallelism = 4
|
||||
argonKeyLength = 32
|
||||
argonSaltLength = 16
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
|
||||
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
|
||||
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(encoded, password string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
var memory uint32
|
||||
var iterations uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
// argon2.IDKey panics when the cost parameters are outside its supported
|
||||
// range. A corrupted row or an attacker-supplied encoding must be rejected
|
||||
// with ErrInvalidHash instead of taking the process down.
|
||||
if iterations < 1 || parallelism < 1 || memory < 8*uint32(parallelism) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(expected) == 0 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expected)))
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordRoundTripPreservesFullRange(t *testing.T) {
|
||||
passwords := []string{
|
||||
"simple-password-123",
|
||||
"colon:inside:password",
|
||||
"пароль-с-кириллицей-12",
|
||||
strings.Repeat("😀", 128),
|
||||
}
|
||||
for _, password := range passwords {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword: %v", err)
|
||||
}
|
||||
ok, err := VerifyPassword(hash, password)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("VerifyPassword rejected the correct password (ok=%v err=%v)", ok, err)
|
||||
}
|
||||
ok, err = VerifyPassword(hash, password+"x")
|
||||
if err != nil || ok {
|
||||
t.Fatalf("VerifyPassword accepted a different password (ok=%v err=%v)", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashIsSalted(t *testing.T) {
|
||||
first, err := HashPassword("same-password-123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := HashPassword("same-password-123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("two hashes of the same password are identical")
|
||||
}
|
||||
if _, err := VerifyPassword("not-a-hash", "same-password-123"); err == nil {
|
||||
t.Fatal("invalid encoded hash was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordRejectsMalformedCostAndEmptyDigest(t *testing.T) {
|
||||
malformed := []string{
|
||||
// Empty digest would make argon2 derive a zero-length key.
|
||||
"$argon2id$v=19$m=65536,t=2,p=4$c2FsdA$",
|
||||
// Zero cost parameters are outside argon2's supported range and would
|
||||
// otherwise panic inside the KDF.
|
||||
"$argon2id$v=19$m=65536,t=0,p=4$c2FsdA$YWJjZA",
|
||||
"$argon2id$v=19$m=65536,t=2,p=0$c2FsdA$YWJjZA",
|
||||
"$argon2id$v=19$m=1,t=2,p=4$c2FsdA$YWJjZA",
|
||||
}
|
||||
for _, encoded := range malformed {
|
||||
ok, err := VerifyPassword(encoded, "same-password-123")
|
||||
if err == nil || ok {
|
||||
t.Fatalf("VerifyPassword(%q) = (%v, %v), want ErrInvalidHash", encoded, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user