forked from mtusi2026/mtusi2026lab2
This commit is contained in:
+135
-74
@@ -4,145 +4,206 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Address string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
ConnectTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
SwaggerPort string
|
||||
Address string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
MigrationTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
SwaggerPort string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
host, err := requiredEnv("APP_HOST")
|
||||
values := viper.New()
|
||||
values.AutomaticEnv()
|
||||
|
||||
host, err := requiredString(values, "APP_HOST")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
port, err := requiredPort("APP_PORT")
|
||||
port, err := requiredPort(values, "APP_PORT")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
databaseURL, err := secretFromEnv("DATABASE_URL_FILE")
|
||||
databaseURL, err := requiredString(values, "DATABASE_URL")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cacheURL, err := secretFromEnv("CACHE_URL_FILE")
|
||||
cacheURL, err := requiredString(values, "CACHE_URL")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if store, err := requiredEnv("SESSION_STORE"); err != nil {
|
||||
store, err := requiredString(values, "SESSION_STORE")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
} else if store != "valkey" {
|
||||
}
|
||||
if store != "valkey" {
|
||||
return Config{}, errors.New("SESSION_STORE must be valkey")
|
||||
}
|
||||
ttlSeconds, err := requiredPositiveInt("SESSION_TTL_SECONDS")
|
||||
|
||||
sessionTTL, err := seconds(values, "SESSION_TTL_SECONDS", 1, 86400*30)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
maxConns, err := intEnv("DB_MAX_CONNS", 10, 1, 100)
|
||||
maxConns, err := integer(values, "DB_MAX_CONNS", 1, 100)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
minConns, err := intEnv("DB_MIN_CONNS", 1, 0, maxConns)
|
||||
minConns, err := integer(values, "DB_MIN_CONNS", 0, maxConns)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
connectSeconds, err := intEnv("DEPENDENCY_TIMEOUT_SECONDS", 5, 1, 60)
|
||||
maxConnectionAge, err := seconds(values, "DB_MAX_CONNECTION_AGE_SECONDS", 1, 86400)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
swaggerPort := os.Getenv("SWAGGER_PORT")
|
||||
if swaggerPort == "" {
|
||||
swaggerPort = "8081"
|
||||
maxConnectionIdle, err := seconds(values, "DB_MAX_CONNECTION_IDLE_SECONDS", 1, 86400)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if _, err := parsePort(swaggerPort); err != nil {
|
||||
return Config{}, fmt.Errorf("SWAGGER_PORT: %w", err)
|
||||
healthCheckPeriod, err := seconds(values, "DB_HEALTH_CHECK_SECONDS", 1, 3600)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
dependencyTimeout, err := seconds(values, "DEPENDENCY_TIMEOUT_SECONDS", 1, 60)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
migrationTimeout, err := seconds(values, "MIGRATION_TIMEOUT_SECONDS", 1, 600)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
requestTimeout, err := seconds(values, "REQUEST_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
readHeaderTimeout, err := seconds(values, "HTTP_READ_HEADER_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
readTimeout, err := seconds(values, "HTTP_READ_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
writeTimeout, err := seconds(values, "HTTP_WRITE_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
idleTimeout, err := seconds(values, "HTTP_IDLE_TIMEOUT_SECONDS", 1, 3600)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
shutdownTimeout, err := seconds(values, "HTTP_SHUTDOWN_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
passwordMemory, err := integer(values, "PASSWORD_MEMORY_KIB", 8*1024, 1024*1024)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
passwordIterations, err := integer(values, "PASSWORD_ITERATIONS", 1, 20)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
passwordParallelism, err := integer(values, "PASSWORD_PARALLELISM", 1, 255)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
passwordSaltLength, err := integer(values, "PASSWORD_SALT_LENGTH", 8, 1024)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
passwordKeyLength, err := integer(values, "PASSWORD_KEY_LENGTH", 16, 1024)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
swaggerPort, err := requiredPort(values, "SWAGGER_PORT")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return Config{
|
||||
Address: net.JoinHostPort(host, port),
|
||||
DatabaseURL: databaseURL,
|
||||
CacheURL: cacheURL,
|
||||
SessionTTL: time.Duration(ttlSeconds) * time.Second,
|
||||
DBMaxConns: int32(maxConns),
|
||||
DBMinConns: int32(minConns),
|
||||
ConnectTimeout: time.Duration(connectSeconds) * time.Second,
|
||||
RequestTimeout: time.Duration(connectSeconds) * time.Second,
|
||||
SwaggerPort: swaggerPort,
|
||||
Address: net.JoinHostPort(host, port), DatabaseURL: databaseURL, CacheURL: cacheURL,
|
||||
SessionTTL: sessionTTL, DBMaxConns: int32(maxConns), DBMinConns: int32(minConns),
|
||||
DBMaxConnectionAge: maxConnectionAge, DBMaxConnectionIdle: maxConnectionIdle,
|
||||
DBHealthCheckPeriod: healthCheckPeriod, DependencyTimeout: dependencyTimeout,
|
||||
MigrationTimeout: migrationTimeout, RequestTimeout: requestTimeout,
|
||||
HTTPReadHeaderTimeout: readHeaderTimeout, HTTPReadTimeout: readTimeout,
|
||||
HTTPWriteTimeout: writeTimeout, HTTPIdleTimeout: idleTimeout,
|
||||
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
||||
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||
SwaggerPort: swaggerPort,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func requiredEnv(name string) (string, error) {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
func requiredString(values *viper.Viper, name string) (string, error) {
|
||||
value := strings.TrimSpace(values.GetString(name))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func requiredPort(name string) (string, error) {
|
||||
value, err := requiredEnv(name)
|
||||
func requiredPort(values *viper.Viper, name string) (string, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := parsePort(value); err != nil {
|
||||
if _, err := integerValue(value, 1, 65535); err != nil {
|
||||
return "", fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func parsePort(value string) (int, error) {
|
||||
port, err := strconv.Atoi(value)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return 0, errors.New("must be between 1 and 65535")
|
||||
}
|
||||
return port, nil
|
||||
}
|
||||
|
||||
func requiredPositiveInt(name string) (int, error) {
|
||||
value, err := requiredEnv(name)
|
||||
func seconds(values *viper.Viper, name string, minimum, maximum int) (time.Duration, error) {
|
||||
value, err := integer(values, name, minimum, maximum)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed <= 0 {
|
||||
return 0, fmt.Errorf("%s must be a positive integer", name)
|
||||
return time.Duration(value) * time.Second, nil
|
||||
}
|
||||
|
||||
func integer(values *viper.Viper, name string, minimum, maximum int) (int, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
parsed, err := integerValue(value, minimum, maximum)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func intEnv(name string, fallback, minimum, maximum int) (int, error) {
|
||||
value := os.Getenv(name)
|
||||
if value == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
func integerValue(value string, minimum, maximum int) (int, error) {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed < minimum || parsed > maximum {
|
||||
return 0, fmt.Errorf("%s must be between %d and %d", name, minimum, maximum)
|
||||
return 0, fmt.Errorf("must be between %d and %d", minimum, maximum)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func secretFromEnv(name string) (string, error) {
|
||||
path, err := requiredEnv(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", name, err)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s points to an empty file", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -10,6 +11,18 @@ import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/migrations"
|
||||
)
|
||||
|
||||
var (
|
||||
errURLRequired = errors.New("database URL is required")
|
||||
errMinConnections = errors.New("minimum database connections must not be negative")
|
||||
errMaxConnections = errors.New("maximum database connections must be positive")
|
||||
errConnectionRange = errors.New("minimum database connections exceed maximum")
|
||||
errMaxConnectionAge = errors.New("maximum database connection age must be positive")
|
||||
errMaxConnectionIdle = errors.New("maximum database connection idle time must be positive")
|
||||
errHealthCheckPeriod = errors.New("database health check period must be positive")
|
||||
errConnectionTimeout = errors.New("database connection timeout must be positive")
|
||||
errMigrationTimeout = errors.New("database migration timeout must be positive")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
MinConnections int32
|
||||
@@ -58,23 +71,23 @@ func Open(ctx context.Context, config Config) (*pgxpool.Pool, error) {
|
||||
func validateConfig(config Config) error {
|
||||
switch {
|
||||
case config.URL == "":
|
||||
return fmt.Errorf("database URL is required")
|
||||
return errURLRequired
|
||||
case config.MinConnections < 0:
|
||||
return fmt.Errorf("minimum database connections must not be negative")
|
||||
return errMinConnections
|
||||
case config.MaxConnections < 1:
|
||||
return fmt.Errorf("maximum database connections must be positive")
|
||||
return errMaxConnections
|
||||
case config.MinConnections > config.MaxConnections:
|
||||
return fmt.Errorf("minimum database connections exceed maximum")
|
||||
return errConnectionRange
|
||||
case config.MaxConnectionAge <= 0:
|
||||
return fmt.Errorf("maximum database connection age must be positive")
|
||||
return errMaxConnectionAge
|
||||
case config.MaxConnectionIdle <= 0:
|
||||
return fmt.Errorf("maximum database connection idle time must be positive")
|
||||
return errMaxConnectionIdle
|
||||
case config.HealthCheckPeriod <= 0:
|
||||
return fmt.Errorf("database health check period must be positive")
|
||||
return errHealthCheckPeriod
|
||||
case config.ConnectTimeout <= 0:
|
||||
return fmt.Errorf("database connection timeout must be positive")
|
||||
return errConnectionTimeout
|
||||
case config.MigrationTimeout <= 0:
|
||||
return fmt.Errorf("database migration timeout must be positive")
|
||||
return errMigrationTimeout
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
)
|
||||
|
||||
func New() *slog.Logger {
|
||||
return slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
|
||||
)
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
return invalidRequest()
|
||||
}
|
||||
username, passwordValue, ok := singleBasicAuth(r)
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
credentials, err := s.messengerStore.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
|
||||
return nil
|
||||
}
|
||||
|
||||
func singleBasicAuth(r *http.Request) (string, string, bool) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", "", false
|
||||
}
|
||||
username, passwordValue, ok := r.BasicAuth()
|
||||
return username, passwordValue, ok && username != ""
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodDelete {
|
||||
return methodNotAllowed(w, http.MethodDelete)
|
||||
}
|
||||
_, token, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, session.ErrNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
scheme, token, found := strings.Cut(values[0], " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
userID, err := s.sessions.UserID(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.messengerStore.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
return user, token, nil
|
||||
}
|
||||
|
||||
func authenticationChallenge(r *http.Request) string {
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
return `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
return `Bearer realm="messenger"`
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package messenger
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -12,7 +11,6 @@ import (
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
@@ -34,7 +32,7 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.repository.Ping(ctx); err != nil {
|
||||
if err := s.messengerStore.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
@@ -63,7 +61,7 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
user, err := s.repository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
user, err := s.messengerStore.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, postgres.ErrConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
|
||||
}
|
||||
@@ -79,73 +77,6 @@ func validPassword(value string) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
|
||||
}
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
return invalidRequest()
|
||||
}
|
||||
username, passwordValue, ok := singleBasicAuth(r)
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
credentials, err := s.repository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
|
||||
return nil
|
||||
}
|
||||
|
||||
func singleBasicAuth(r *http.Request) (string, string, bool) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", "", false
|
||||
}
|
||||
username, passwordValue, ok := r.BasicAuth()
|
||||
return username, passwordValue, ok && username != ""
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodDelete {
|
||||
return methodNotAllowed(w, http.MethodDelete)
|
||||
}
|
||||
_, token, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, session.ErrNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
@@ -194,7 +125,7 @@ func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if _, included := members[user.ID]; !included {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.repository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
chat, err := s.messengerStore.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
return invalidRequest()
|
||||
}
|
||||
@@ -210,7 +141,7 @@ func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *a
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.repository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
items, hasNext, listErr := s.messengerStore.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
@@ -245,7 +176,7 @@ func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.repository.ChatForUser(r.Context(), chatID, user.ID)
|
||||
chat, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
@@ -280,7 +211,7 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !validText(input.Text, 4000) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, err := s.repository.CreateMessage(r.Context(), chatID, user.ID, input.Text)
|
||||
message, err := s.messengerStore.CreateMessage(r.Context(), chatID, user.ID, input.Text)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
@@ -296,7 +227,7 @@ func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.repository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
items, hasNext, listErr := s.messengerStore.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
@@ -328,30 +259,3 @@ func cursorPosition(cursor *pageCursor) *model.Position {
|
||||
}
|
||||
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
scheme, token, found := strings.Cut(values[0], " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
userID, err := s.sessions.UserID(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.repository.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
return user, token, nil
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
type MessengerStore interface {
|
||||
Ping(context.Context) error
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
UserByID(context.Context, string) (model.User, error)
|
||||
@@ -26,7 +26,7 @@ type SessionStore interface {
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type Passwords interface {
|
||||
type PasswordService interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) (bool, error)
|
||||
DummyHash() string
|
||||
@@ -9,15 +9,15 @@ import (
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
repository Repository
|
||||
sessions SessionStore
|
||||
passwords Passwords
|
||||
sessionTTL time.Duration
|
||||
requestTTL time.Duration
|
||||
logger *slog.Logger
|
||||
swaggerPort string
|
||||
metrics *metrics
|
||||
ready atomic.Bool
|
||||
messengerStore MessengerStore
|
||||
sessions SessionStore
|
||||
passwords PasswordService
|
||||
sessionTTL time.Duration
|
||||
requestTTL time.Duration
|
||||
logger *slog.Logger
|
||||
swaggerPort string
|
||||
metrics *metrics
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
@@ -30,9 +30,9 @@ func (w *statusWriter) WriteHeader(status int) {
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func NewServer(logger *slog.Logger, repository Repository, sessions SessionStore, passwords Passwords, sessionTTL, requestTTL time.Duration, swaggerPort string) *Server {
|
||||
func NewServer(logger *slog.Logger, messages MessengerStore, sessions SessionStore, passwords PasswordService, sessionTTL, requestTTL time.Duration, swaggerPort string) *Server {
|
||||
s := &Server{
|
||||
repository: repository, sessions: sessions, passwords: passwords,
|
||||
messengerStore: messages, sessions: sessions, passwords: passwords,
|
||||
sessionTTL: sessionTTL, requestTTL: requestTTL, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
|
||||
}
|
||||
s.ready.Store(true)
|
||||
@@ -80,11 +80,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
r = r.WithContext(ctx)
|
||||
if apiErr := s.route(wrapped, r); apiErr != nil {
|
||||
if apiErr.status == http.StatusUnauthorized {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
wrapped.Header().Set("WWW-Authenticate", challenge)
|
||||
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
|
||||
}
|
||||
writeError(wrapped, requestID, apiErr)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
|
||||
type repositoryStub struct {
|
||||
type messengerStoreStub struct {
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
@@ -24,29 +24,29 @@ type repositoryStub struct {
|
||||
credentialsErr error
|
||||
}
|
||||
|
||||
func (s repositoryStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (repositoryStub) CreateUser(context.Context, string, string, string) (model.User, error) {
|
||||
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (messengerStoreStub) CreateUser(context.Context, string, string, string) (model.User, error) {
|
||||
return model.User{}, nil
|
||||
}
|
||||
func (s repositoryStub) UserByID(context.Context, string) (model.User, error) {
|
||||
func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error) {
|
||||
return s.userByID, s.userByIDErr
|
||||
}
|
||||
func (s repositoryStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
||||
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
||||
return s.credentials, s.credentialsErr
|
||||
}
|
||||
func (repositoryStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
||||
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (repositoryStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
||||
func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (repositoryStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
||||
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (repositoryStub) CreateMessage(context.Context, string, string, string) (model.Message, error) {
|
||||
func (messengerStoreStub) CreateMessage(context.Context, string, string, string) (model.Message, error) {
|
||||
return model.Message{}, nil
|
||||
}
|
||||
func (repositoryStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
@@ -77,16 +77,16 @@ func (s passwordsStub) Verify(string, string) (bool, error) {
|
||||
func TestReadinessReturnsUnavailableForDependencyFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
repo repositoryStub
|
||||
store messengerStoreStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "postgres", repo: repositoryStub{pingErr: errDependency}},
|
||||
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
|
||||
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := newTestServer(tt.repo, tt.sessions, passwordsStub{})
|
||||
server := newTestServer(tt.store, tt.sessions, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
@@ -98,16 +98,16 @@ func TestReadinessReturnsUnavailableForDependencyFailure(t *testing.T) {
|
||||
func TestBusinessRequestReturnsUnavailableForDependencyFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
repo repositoryStub
|
||||
store messengerStoreStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
|
||||
{name: "postgres", repo: repositoryStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
|
||||
{name: "postgres", store: messengerStoreStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := newTestServer(tt.repo, tt.sessions, passwordsStub{})
|
||||
server := newTestServer(tt.store, tt.sessions, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -120,14 +120,14 @@ func TestBusinessRequestReturnsUnavailableForDependencyFailure(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAuthenticationChallenges(t *testing.T) {
|
||||
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
||||
server := newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
|
||||
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
repository := repositoryStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
server = newTestServer(repository, sessionStub{}, passwordsStub{verified: false})
|
||||
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
server = newTestServer(store, sessionStub{}, passwordsStub{verified: false})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("user", "wrong-password")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -138,7 +138,7 @@ func TestAuthenticationChallenges(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSessionCreationRejectsChunkedBody(t *testing.T) {
|
||||
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
||||
server := newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.ContentLength = -1
|
||||
request.SetBasicAuth("user", "password")
|
||||
@@ -150,16 +150,16 @@ func TestSessionCreationRejectsChunkedBody(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRegistrationRejectsWhitespacePassword(t *testing.T) {
|
||||
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
||||
server := newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestServer(repository Repository, sessions SessionStore, passwords Passwords) *Server {
|
||||
func newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
return NewServer(logger, repository, sessions, passwords, time.Hour, time.Second, "8081")
|
||||
return NewServer(logger, messages, sessions, passwords, time.Hour, time.Second, "8081")
|
||||
}
|
||||
|
||||
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
|
||||
+25
-22
@@ -39,35 +39,38 @@ type Position struct {
|
||||
ID string
|
||||
}
|
||||
|
||||
type userJSON struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatJSON struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func (u User) MarshalJSON() ([]byte, error) {
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
return json.Marshal(response{u.ID, u.Username, u.DisplayName, formatTime(u.CreatedAt)})
|
||||
return json.Marshal(userJSON{u.ID, u.Username, u.DisplayName, formatTime(u.CreatedAt)})
|
||||
}
|
||||
|
||||
func (c Chat) MarshalJSON() ([]byte, error) {
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
return json.Marshal(response{c.ID, c.Title, c.MemberIDs, formatTime(c.CreatedAt)})
|
||||
return json.Marshal(chatJSON{c.ID, c.Title, c.MemberIDs, formatTime(c.CreatedAt)})
|
||||
}
|
||||
|
||||
func (m Message) MarshalJSON() ([]byte, error) {
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
return json.Marshal(response{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt)})
|
||||
return json.Marshal(messageJSON{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt)})
|
||||
}
|
||||
|
||||
func FormatTime(value time.Time) string {
|
||||
|
||||
@@ -6,95 +6,128 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
MemoryKiB uint32 = 64 * 1024
|
||||
Iterations uint32 = 3
|
||||
Parallelism uint8 = 2
|
||||
SaltLength = 16
|
||||
KeyLength uint32 = 32
|
||||
var (
|
||||
ErrInvalidConfig = errors.New("invalid password configuration")
|
||||
ErrInvalidHash = errors.New("invalid password hash")
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
var dummyHash = encode(
|
||||
make([]byte, SaltLength),
|
||||
argon2.IDKey([]byte("invalid-user-password"), make([]byte, SaltLength), Iterations, MemoryKiB, Parallelism, KeyLength),
|
||||
)
|
||||
|
||||
type Hasher struct{}
|
||||
|
||||
func (Hasher) Hash(value string) (string, error) {
|
||||
return Hash(value)
|
||||
type Config struct {
|
||||
MemoryKiB uint32
|
||||
Iterations uint32
|
||||
Parallelism uint8
|
||||
SaltLength uint32
|
||||
KeyLength uint32
|
||||
}
|
||||
|
||||
func (Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
return Verify(value, encodedHash)
|
||||
type Hasher struct {
|
||||
config Config
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func (Hasher) DummyHash() string {
|
||||
return dummyHash
|
||||
func New(config Config) (*Hasher, error) {
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
salt := make([]byte, config.SaltLength)
|
||||
digest := argon2.IDKey([]byte("invalid-user-password"), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
|
||||
return &Hasher{config: config, dummyHash: encode(config, salt, digest)}, nil
|
||||
}
|
||||
|
||||
func Hash(value string) (string, error) {
|
||||
salt := make([]byte, SaltLength)
|
||||
func validateConfig(config Config) error {
|
||||
if config.MemoryKiB < 8*1024 || config.MemoryKiB > 1024*1024 ||
|
||||
config.Iterations < 1 || config.Iterations > 20 ||
|
||||
config.Parallelism < 1 ||
|
||||
config.SaltLength < 8 || config.SaltLength > 1024 ||
|
||||
config.KeyLength < 16 || config.KeyLength > 1024 {
|
||||
return ErrInvalidConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Hash(value string) (string, error) {
|
||||
salt := make([]byte, h.config.SaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
|
||||
digest := argon2.IDKey([]byte(value), salt, Iterations, MemoryKiB, Parallelism, KeyLength)
|
||||
|
||||
return encode(salt, digest), nil
|
||||
digest := argon2.IDKey([]byte(value), salt, h.config.Iterations, h.config.MemoryKiB, h.config.Parallelism, h.config.KeyLength)
|
||||
return encode(h.config, salt, digest), nil
|
||||
}
|
||||
|
||||
func encode(salt, digest []byte) string {
|
||||
func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
config, salt, digest, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
actual := argon2.IDKey([]byte(value), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func (h *Hasher) DummyHash() string {
|
||||
return h.dummyHash
|
||||
}
|
||||
|
||||
func encode(config Config, salt, digest []byte) string {
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
MemoryKiB,
|
||||
Iterations,
|
||||
Parallelism,
|
||||
config.MemoryKiB,
|
||||
config.Iterations,
|
||||
config.Parallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(digest),
|
||||
)
|
||||
}
|
||||
|
||||
func Verify(value, encodedHash string) (bool, error) {
|
||||
salt, digest, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actual := argon2.IDKey([]byte(value), salt, Iterations, MemoryKiB, Parallelism, KeyLength)
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func decode(encodedHash string) ([]byte, []byte, error) {
|
||||
func decode(encodedHash string) (Config, []byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return nil, nil, ErrInvalidHash
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return nil, nil, ErrInvalidHash
|
||||
parameters := strings.Split(parts[3], ",")
|
||||
if len(parameters) != 3 {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
if parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", MemoryKiB, Iterations, Parallelism) {
|
||||
return nil, nil, ErrInvalidHash
|
||||
memory, err := parameter(parameters[0], "m=", 32)
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
iterations, err := parameter(parameters[1], "t=", 32)
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
parallelism, err := parameter(parameters[2], "p=", 8)
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||
if err != nil || len(salt) != SaltLength {
|
||||
return nil, nil, ErrInvalidHash
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||
if err != nil || len(digest) != int(KeyLength) {
|
||||
return nil, nil, ErrInvalidHash
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
config := Config{
|
||||
MemoryKiB: uint32(memory), Iterations: uint32(iterations), Parallelism: uint8(parallelism),
|
||||
SaltLength: uint32(len(salt)), KeyLength: uint32(len(digest)),
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
return config, salt, digest, nil
|
||||
}
|
||||
|
||||
return salt, digest, nil
|
||||
func parameter(value, prefix string, bitSize int) (uint64, error) {
|
||||
if !strings.HasPrefix(value, prefix) {
|
||||
return 0, ErrInvalidHash
|
||||
}
|
||||
return strconv.ParseUint(strings.TrimPrefix(value, prefix), 10, bitSize)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,10 @@ package password
|
||||
import "testing"
|
||||
|
||||
func TestHasher(t *testing.T) {
|
||||
hasher := Hasher{}
|
||||
hasher, err := New(testConfig())
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
hash, err := hasher.Hash("T3st-password-123")
|
||||
if err != nil {
|
||||
t.Fatalf("Hash() error = %v", err)
|
||||
@@ -27,7 +30,15 @@ func TestHasher(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHash(t *testing.T) {
|
||||
if _, err := (Hasher{}).Verify("password", "invalid"); err == nil {
|
||||
hasher, err := New(testConfig())
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
if _, err := hasher.Verify("password", "invalid"); err == nil {
|
||||
t.Fatal("Verify() error = nil for malformed hash")
|
||||
}
|
||||
}
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user