feat(app) lab2 prepared for mr

This commit is contained in:
imadev
2026-10-23 18:55:20 +03:00
parent 1db3953226
commit f6e74247fd
57 changed files with 2367 additions and 660 deletions
+132
View File
@@ -0,0 +1,132 @@
package auth
import (
"encoding/base64"
"errors"
"strings"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
)
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
const 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}
}
// AGENT: CreateSession is the only endpoint that accepts Basic auth. It reads
// no JSON body and returns the same 401 for an unknown user and a wrong
// password, so the response does not reveal which usernames exist.
func (h *Handler) CreateSession(c fiber.Ctx) error {
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
if !ok {
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
user, err := h.store.GetUserByUsername(c.Context(), username)
if err != nil {
if common.IsCode(err, common.ErrorCodeNotFound) {
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
return common.SendAppError(c, err)
}
valid, err := VerifyPassword(user.PasswordHash, password)
if err != nil || !valid {
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
token, expiresAt, err := h.sessions.Create(c.Context(), user.ID)
if err != nil {
log.Errorf("create session: %v", err)
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
return c.Status(fiber.StatusCreated).JSON(model.Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: common.RFCFormTime(expiresAt),
User: user,
})
}
// RevokeSession deletes the current token. The middleware has already proven
// that the token exists, so a repeated DELETE is a 401, not a 204.
func (h *Handler) RevokeSession(c fiber.Ctx) error {
token, _ := c.Locals(sessionTokenLocal).(string)
if token == "" {
return common.SendChallenge(c, bearerChallenge, "authentication required")
}
if err := h.sessions.Revoke(c.Context(), token); err != nil {
log.Errorf("revoke session: %v", err)
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
return c.SendStatus(fiber.StatusNoContent)
}
const sessionTokenLocal = "sessionToken"
// BearerAuth accepts only an opaque Bearer token. X-User-Id is deliberately
// never read: with lab 2 it can neither create nor override an identity.
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.SendChallenge(c, bearerChallenge, "authentication required")
}
userID, err := sessions.Lookup(c.Context(), token)
if err != nil {
if errors.Is(err, session.ErrNotFound) {
return common.SendChallenge(c, bearerChallenge, "session expired or revoked")
}
// AGENT: A dead Redis must not degrade to "anonymous allowed".
// Protected calls get a bounded 503 instead of a 401 or a bypass.
log.Errorf("session lookup: %v", err)
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
c.Locals("userID", userID)
c.Locals(sessionTokenLocal, 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
}
+72
View File
@@ -0,0 +1,72 @@
// AGENT: Argon2id is used instead of bcrypt because the contract allows 128
// Unicode code points and bcrypt silently truncates at 72 bytes. Salt and
// parameters are stored inside the encoded hash string.
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
}
// VerifyPassword recomputes the digest with the stored parameters and compares
// in constant time.
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, &parallelism); err != nil {
return false, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, ErrInvalidHash
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, ErrInvalidHash
}
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expected)))
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
}
+46
View File
@@ -0,0 +1,46 @@
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")
}
}
+17
View File
@@ -0,0 +1,17 @@
package auth
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
func RegisterPublicRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
handler := NewHandler(st, sessions)
router.Post("/auth/sessions", handler.CreateSession)
}
func RegisterRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
handler := NewHandler(st, sessions)
router.Delete("/auth/sessions/current", handler.RevokeSession)
}