Files
dizi a8edaf058d
CI / verify (pull_request) Successful in 14m53s
chore: finalize lab7 security verification
2026-11-06 22:00:42 +03:00

179 lines
5.0 KiB
Go

package httpapi
import (
"context"
"errors"
"io"
"math"
"net"
"net/http"
"strconv"
"strings"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
)
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()
}
allowed, retryAfter, err := s.loginLimiter.Allow(r.Context(), username, loginSource(r))
if err != nil {
return unavailable()
}
if !allowed {
retrySeconds := max(int64(1), int64(math.Ceil(retryAfter.Seconds())))
w.Header().Set("Retry-After", strconv.FormatInt(retrySeconds, 10))
return rateLimited()
}
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
if errors.Is(err, model.ErrNotFound) {
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
return passwordOperationError(verifyErr)
}
return unauthorized()
}
if err != nil {
return unavailable()
}
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
if err != nil {
return passwordOperationError(err)
}
if !verified {
return unauthorized()
}
if rehashErr := s.rehashPassword(r.Context(), credentials, passwordValue); rehashErr != nil {
return rehashErr
}
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 (s *Server) rehashPassword(ctx context.Context, credentials model.UserCredentials, passwordValue string) *apiError {
needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash)
if err != nil {
return passwordOperationError(err)
}
if !needsRehash {
return nil
}
passwordHash, err := s.passwords.Hash(passwordValue)
if err != nil {
return passwordOperationError(err)
}
updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash)
if err != nil {
return unavailable()
}
if updated {
return nil
}
current, err := s.userRepository.UserByUsername(ctx, credentials.Username)
if errors.Is(err, model.ErrNotFound) {
return unauthorized()
}
if err != nil {
return unavailable()
}
verified, err := s.passwords.Verify(passwordValue, current.PasswordHash)
if err != nil {
return passwordOperationError(err)
}
if !verified {
return unauthorized()
}
return nil
}
func loginSource(r *http.Request) string {
forwarded := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
// Nginx appends the address it observed last, so preceding client-supplied entries are not trusted.
if address := net.ParseIP(strings.TrimSpace(forwarded[len(forwarded)-1])); address != nil {
return address.String()
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
if address := net.ParseIP(host); address != nil {
return address.String()
}
}
return "unknown"
}
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, model.ErrSessionNotFound) {
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, model.ErrSessionNotFound) || errors.Is(err, model.ErrInvalidToken) {
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
user, err := s.userRepository.UserByID(r.Context(), userID)
if errors.Is(err, model.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"`
}