chore: import lab2 baseline

This commit is contained in:
2026-10-02 15:50:49 +03:00
parent 0ab3a341aa
commit b5583a813e
39 changed files with 3405 additions and 0 deletions
+113
View File
@@ -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"`
}
+60
View File
@@ -0,0 +1,60 @@
package messenger
import (
"encoding/json"
"net/http"
)
const (
errorCodeInvalidRequest = "invalid_request"
errorCodeUnauthorized = "unauthorized"
errorCodeNotFound = "not_found"
errorCodeInternal = "internal_error"
errorCodeUnsupportedMediaType = "unsupported_media_type"
errorCodePayloadTooLarge = "payload_too_large"
errorCodeUnavailable = "unavailable"
errorCodeConflict = "conflict"
)
type apiError struct {
status int
code string
message string
}
func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError {
w.Header().Set("Allow", allowed)
return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"}
}
func invalidRequest() *apiError {
return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"}
}
func unauthorized() *apiError {
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
}
func notFound() *apiError {
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
}
func internalError() *apiError {
return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"}
}
func unavailable() *apiError {
return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"}
}
func writeError(w http.ResponseWriter, requestID string, err *apiError) {
writeJSON(w, err.status, map[string]any{"error": map[string]string{
"code": err.code, "message": err.message, "request_id": requestID,
}})
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
+261
View File
@@ -0,0 +1,261 @@
package messenger
import (
"context"
"errors"
"net/http"
"regexp"
"strings"
"time"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
if !s.ready.Load() {
return unavailable()
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.messengerStore.Ping(ctx); err != nil {
return unavailable()
}
if err := s.sessions.Ping(ctx); err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
var input struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
return invalidRequest()
}
passwordHash, err := s.passwords.Hash(input.Password)
if err != nil {
return internalError()
}
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"}
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, user)
return nil
}
func validPassword(value string) bool {
length := utf8.RuneCountInString(value)
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
}
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, err := s.authenticate(r)
if err != nil {
return err
}
writeJSON(w, http.StatusOK, user)
return nil
}
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if r.Method == http.MethodGet {
return s.listChats(w, r, user)
}
var input struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
return invalidRequest()
}
members := make(map[string]struct{}, len(input.MemberIDs))
for i, memberID := range input.MemberIDs {
canonical, valid := canonicalID(memberID)
if !valid {
return invalidRequest()
}
if _, duplicate := members[canonical]; duplicate {
return invalidRequest()
}
members[canonical] = struct{}{}
input.MemberIDs[i] = canonical
}
if _, included := members[user.ID]; !included {
return invalidRequest()
}
chat, err := s.messengerStore.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
if errors.Is(err, postgres.ErrInvalidMembers) {
return invalidRequest()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, chat)
return nil
}
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
limit, cursor, err := pageParams(r, "chat", user.ID)
if err != nil {
return err
}
items, hasNext, listErr := s.messengerStore.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, postgres.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Chat{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
chat, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID)
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, chat)
return nil
}
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
if r.Method == http.MethodGet {
return s.listMessages(w, r, user, chatID)
}
var input struct {
Text string `json:"text"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Text, 4000) {
return invalidRequest()
}
message, err := s.messengerStore.CreateMessage(r.Context(), chatID, user.ID, input.Text)
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, message)
return nil
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
limit, cursor, err := pageParams(r, "message", chatID)
if err != nil {
return err
}
items, hasNext, listErr := s.messengerStore.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, postgres.ErrNotFound) {
return notFound()
}
if errors.Is(listErr, postgres.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Message{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func cursorPosition(cursor *pageCursor) *model.Position {
if cursor == nil {
return nil
}
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
}
+33
View File
@@ -0,0 +1,33 @@
package messenger
import (
"context"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
)
type MessengerStore interface {
Ping(context.Context) error
CreateUser(context.Context, string, string, string) (model.User, error)
UserByID(context.Context, string) (model.User, error)
UserByUsername(context.Context, string) (model.UserCredentials, error)
CreateChat(context.Context, string, []string, string) (model.Chat, error)
ChatForUser(context.Context, string, string) (model.Chat, error)
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
CreateMessage(context.Context, string, string, string) (model.Message, error)
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
}
type SessionStore interface {
Ping(context.Context) error
Create(context.Context, string, time.Duration) (string, time.Time, error)
UserID(context.Context, string) (string, error)
Delete(context.Context, string) error
}
type PasswordService interface {
Hash(string) (string, error)
Verify(string, string) (bool, error)
DummyHash() string
}
+75
View File
@@ -0,0 +1,75 @@
package messenger
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type metrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
handler http.Handler
}
func newMetrics() *metrics {
registry := prometheus.NewRegistry()
result := &metrics{
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_total",
Help: "Completed HTTP requests.",
}, []string{"method", "route", "status_class"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: prometheus.DefBuckets,
}, []string{"method", "route"}),
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_in_flight",
Help: "HTTP requests currently being served.",
}),
}
registry.MustRegister(
result.requests,
result.duration,
result.inFlight,
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
return result
}
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
route := routeTemplate(r.URL.Path)
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
}
func routeTemplate(path string) string {
switch path {
case "/health/live", "/health/ready", "/metrics", "/api/v1/users", "/api/v1/users/me",
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
return path
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
return "/api/v1/chats/{chat_id}/messages"
}
return "unknown"
}
+29
View File
@@ -0,0 +1,29 @@
package messenger
import (
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"github.com/google/uuid"
)
type User = model.User
type Chat = model.Chat
type Message = model.Message
func newID() (string, error) {
id, err := uuid.NewRandom()
if err != nil {
return "", err
}
return id.String(), nil
}
func canonicalID(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
id, err := uuid.Parse(value)
if err != nil {
return "", false
}
return id.String(), true
}
+116
View File
@@ -0,0 +1,116 @@
package messenger
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const maxRequestBytes = 1 << 20
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
}
return invalidRequest()
}
if !utf8.Valid(data) {
return invalidRequest()
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil || object == nil {
return invalidRequest()
}
normalized, err := json.Marshal(object)
if err != nil {
return invalidRequest()
}
decoder := json.NewDecoder(bytes.NewReader(normalized))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return invalidRequest()
}
return nil
}
func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
type pageCursor struct {
Kind string `json:"kind"`
Resource string `json:"resource"`
Time time.Time `json:"time"`
ID string `json:"id"`
}
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, invalidRequest()
}
for key := range query {
if key != "limit" && key != "cursor" {
return 0, nil, invalidRequest()
}
if len(query[key]) != 1 {
return 0, nil, invalidRequest()
}
}
limit := 50
if value, present := query["limit"]; present {
parsed, err := strconv.Atoi(value[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, nil, invalidRequest()
}
limit = parsed
}
if value, present := query["cursor"]; present {
cursor, valid := decodeCursor(value[0], kind, resource)
if !valid {
return 0, nil, invalidRequest()
}
return limit, cursor, nil
}
return limit, nil, nil
}
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
data, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return nil, false
}
var cursor pageCursor
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
return nil, false
}
if cursor.Time.IsZero() {
return nil, false
}
if _, valid := canonicalID(cursor.ID); !valid {
return nil, false
}
return &cursor, true
}
+41
View File
@@ -0,0 +1,41 @@
package messenger
import (
"net/http"
"strings"
)
type requestHandler func(http.ResponseWriter, *http.Request) *apiError
func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
var handler requestHandler
switch r.URL.Path {
case "/health/live":
handler = s.live
case "/health/ready":
handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users":
handler = s.users
case "/api/v1/users/me":
handler = s.me
case "/api/v1/auth/sessions":
handler = s.createSession
case "/api/v1/auth/sessions/current":
handler = s.revokeSession
case "/api/v1/chats":
handler = s.chats
default:
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
handler = s.chat
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
handler = s.messages
} else {
return notFound()
}
}
return handler(w, r)
}
+98
View File
@@ -0,0 +1,98 @@
package messenger
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
)
type Server struct {
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 {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func NewServer(logger *slog.Logger, messages MessengerStore, sessions SessionStore, passwords PasswordService, sessionTTL, requestTTL time.Duration, swaggerPort string) *Server {
s := &Server{
messengerStore: messages, sessions: sessions, passwords: passwords,
sessionTTL: sessionTTL, requestTTL: requestTTL, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
}
s.ready.Store(true)
return s
}
func (s *Server) SetReady(ready bool) {
s.ready.Store(ready)
}
func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve)
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
requestID, err := newID()
if err != nil {
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("X-Request-Id", requestID)
w.Header().Set("Cache-Control", "no-store")
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
started := time.Now()
s.metrics.inFlight.Inc()
defer func() {
s.metrics.inFlight.Dec()
if recovered := recover(); recovered != nil {
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
if wrapped.status == http.StatusOK {
writeError(wrapped, requestID, internalError())
}
}
s.metrics.observe(r, wrapped.status, started)
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
}()
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
wrapped.WriteHeader(http.StatusNoContent)
return
}
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
defer cancel()
r = r.WithContext(ctx)
if apiErr := s.route(wrapped, r); apiErr != nil {
if apiErr.status == http.StatusUnauthorized {
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
}
writeError(wrapped, requestID, apiErr)
}
}
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
return false
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
w.Header().Add("Vary", "Origin")
return true
}
+173
View File
@@ -0,0 +1,173 @@
package messenger
import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
)
var errDependency = errors.New("dependency unavailable")
type messengerStoreStub struct {
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr 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 messengerStoreStub) UserByID(context.Context, string) (model.User, error) {
return s.userByID, s.userByIDErr
}
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
return s.credentials, s.credentialsErr
}
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
return nil, false, nil
}
func (messengerStoreStub) CreateMessage(context.Context, string, string, string) (model.Message, error) {
return model.Message{}, nil
}
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
return nil, false, nil
}
type sessionStub struct {
pingErr error
userID string
userIDErr error
}
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
return "token", time.Now().Add(time.Hour), nil
}
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
func (sessionStub) Delete(context.Context, string) error { return nil }
type passwordsStub struct {
verified bool
err error
}
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
func (passwordsStub) DummyHash() string { return "hash" }
func (s passwordsStub) Verify(string, string) (bool, error) {
return s.verified, s.err
}
func TestReadinessReturnsUnavailableForDependencyFailure(t *testing.T) {
tests := []struct {
name string
store messengerStoreStub
sessions sessionStub
}{
{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.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)
}
})
}
}
func TestBusinessRequestReturnsUnavailableForDependencyFailure(t *testing.T) {
tests := []struct {
name string
store messengerStoreStub
sessions sessionStub
}{
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
{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.store, tt.sessions, passwordsStub{})
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", "Bearer valid-token")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
})
}
}
func TestAuthenticationChallenges(t *testing.T) {
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"))
}
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()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
}
}
func TestSessionCreationRejectsChunkedBody(t *testing.T) {
server := newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
request.ContentLength = -1
request.SetBasicAuth("user", "password")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
}
func TestRegistrationRejectsWhitespacePassword(t *testing.T) {
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(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewServer(logger, messages, sessions, passwords, time.Hour, time.Second, "8081")
}
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response
}