Реализовать лабораторную 2: PostgreSQL, Bearer-сессии и Valkey

Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход,
opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON,
keyset-пагинацию по индексу, миграции, compose-стенд и собственные
проверки уровня 3/4. Трек 5 — план запроса и восстановление.
This commit is contained in:
IvanMeln1k
2026-11-30 23:51:33 +03:00
parent 65003b6119
commit 6ea767732e
469 changed files with 204712 additions and 10 deletions
+229
View File
@@ -0,0 +1,229 @@
package api
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab2/internal/auth"
"mtusi.ru/messenger-lab2/internal/model"
"mtusi.ru/messenger-lab2/internal/session"
"mtusi.ru/messenger-lab2/internal/store"
"mtusi.ru/messenger-lab2/internal/uuid"
)
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
type healthResponse struct {
Status string `json:"status"`
}
// identity is the authenticated principal derived only from the Bearer
// session. X-User-Id is not consulted anywhere in this package.
type identity struct {
user model.User
token string
}
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
// and messages; Valkey is the source of truth for sessions. App adds request
// validation, authentication and contract mapping.
type App struct {
store *store.Store
sessions *session.Store
log *slog.Logger
ready atomic.Bool
maxBody int64
instanceID string
dummyHash string
}
// New creates the HTTP application. The dummy Argon2id hash is generated once
// so login can spend the same work for an unknown username as for a known one.
func New(repository *store.Store, sessions *session.Store, logger *slog.Logger) (*App, error) {
dummy, err := auth.Hash("dummy-password-never-used-for-login")
if err != nil {
return nil, err
}
app := &App{
store: repository,
sessions: sessions,
log: logger,
maxBody: maxBodyBytes,
instanceID: uuid.NewRandom(8),
dummyHash: dummy,
}
app.ready.Store(true)
return app, nil
}
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
// received and before http.Server.Shutdown stops accepting connections.
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
// Handler returns the fully instrumented handler.
func (a *App) Handler() http.Handler {
return a.withObservability(a)
}
// ServeHTTP routes the lab2 API. Method mismatches become 404 in the contract
// error shape because the public error enum has no method_not_allowed code.
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/health/live":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
case "/health/ready":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.readiness(w, r)
case "/api/v1/users":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createUser(w, r)
case "/api/v1/auth/sessions":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createSession(w, r)
case "/api/v1/auth/sessions/current":
if r.Method != http.MethodDelete {
a.notFound(w, r)
return
}
a.withAuth(a.logout).ServeHTTP(w, r)
case "/api/v1/users/me":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.withAuth(a.currentUser).ServeHTTP(w, r)
case "/api/v1/chats":
switch r.Method {
case http.MethodGet:
a.withAuth(a.listChats).ServeHTTP(w, r)
case http.MethodPost:
a.withAuth(a.createChat).ServeHTTP(w, r)
default:
a.notFound(w, r)
}
default:
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
// Authentication runs before resource resolution: an anonymous
// request must not learn whether a chat id exists.
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.chatRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
a.notFound(w, r)
}
}
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getChat(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "messages" {
switch r.Method {
case http.MethodGet:
a.listMessages(w, r, parts[0], actor)
case http.MethodPost:
a.createMessage(w, r, parts[0], actor)
default:
a.notFound(w, r)
}
return
}
a.notFound(w, r)
}
// withAuth resolves the Bearer session before the wrapped handler runs.
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
actor, problem := a.authenticate(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
next(w, r, actor)
}
}
// readiness reports whether the mandatory synchronous path can be served.
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
// answer, and without Valkey it cannot authenticate a single protected call.
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
if !a.ready.Load() {
a.writeError(w, r, statusUnavailable)
return
}
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
dbErr := a.store.Ping(dbCtx)
dbCancel()
if dbErr != nil {
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
a.writeError(w, r, statusUnavailable)
return
}
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
cacheErr := a.sessions.Ping(cacheCtx)
cacheCancel()
if cacheErr != nil {
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
a.writeError(w, r, statusUnavailable)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
}
// writeJSON encodes a success response. X-Request-Id is set by middleware
// before the handler runs, so even a marshal-time 500 keeps the header.
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
data, err := json.Marshal(value)
if err != nil {
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if _, err := w.Write(data); err != nil {
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
}
}
func trimPathPrefix(value, prefix string) (string, bool) {
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
return "", false
}
return value[len(prefix):], true
}
func splitPath(value string) []string {
parts := strings.Split(value, "/")
for _, part := range parts {
if part == "" {
return nil
}
}
return parts
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab2/internal/cursor"
"mtusi.ru/messenger-lab2/internal/store"
"mtusi.ru/messenger-lab2/internal/uuid"
)
type createChatRequest struct {
Title *string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
func (a *App) createChat(w http.ResponseWriter, r *http.Request, actor identity) {
var request createChatRequest
if problem := a.decodeJSON(r, &request, "title", "member_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Title == nil {
a.writeError(w, r, invalidRequest("title is required"))
return
}
if problem := validateTitle(*request.Title); problem != nil {
a.writeError(w, r, problem)
return
}
if len(request.MemberIDs) < 1 || len(request.MemberIDs) > 100 {
a.writeError(w, r, invalidRequest("member_ids must contain 1 to 100 members"))
return
}
members := make([]string, 0, len(request.MemberIDs))
seen := make(map[string]struct{}, len(request.MemberIDs))
callerIncluded := false
for _, rawID := range request.MemberIDs {
id, ok := uuid.Normalize(rawID)
if !ok {
a.writeError(w, r, invalidRequest("every member_ids entry must be a UUID"))
return
}
if _, duplicate := seen[id]; duplicate {
a.writeError(w, r, invalidRequest("member_ids must not contain duplicates"))
return
}
seen[id] = struct{}{}
members = append(members, id)
if id == actor.user.ID {
callerIncluded = true
}
}
if !callerIncluded {
a.writeError(w, r, invalidRequest("caller must be present in member_ids"))
return
}
chat, err := a.store.CreateChat(r.Context(), *request.Title, members, actor.user.ID)
switch {
case errors.Is(err, store.ErrUnknownMember):
a.writeError(w, r, invalidRequest("every member_ids entry must reference an existing user"))
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, chat)
}
func (a *App) listChats(w http.ResponseWriter, r *http.Request, actor identity) {
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeChats, "")
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this request"))
return
}
position = &decoded
}
page, err := a.store.Chats(r.Context(), actor.user.ID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}
func (a *App) getChat(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
chat, err := a.store.ChatForUser(r.Context(), chatID, actor.user.ID)
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, chat)
}
// normalizePathUUID validates a path identifier before any database access.
func normalizePathUUID(raw, field string) (string, *apiError) {
id, ok := uuid.Normalize(raw)
if !ok {
return "", invalidRequest(field + " must be a UUID")
}
return id, nil
}
+171
View File
@@ -0,0 +1,171 @@
package api
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab2/internal/uuid"
)
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
// safe human-readable message and an optional authentication challenge. The
// request id is filled from the request context at write time.
type apiError struct {
status int
code string
message string
challenge string
}
func (e *apiError) Error() string { return e.code + ": " + e.message }
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
var (
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
)
func invalidRequest(message string) *apiError {
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
}
func unauthorizedBasic() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
}
func unauthorizedBearer() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
}
type errorEnvelope struct {
Error errorBody `json:"error"`
}
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
// writeError writes a JSON error whose request_id matches X-Request-Id. The
// message never contains SQL, stack traces, credentials or object existence
// details for foreign resources.
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
requestID := requestIDFromContext(r.Context())
if requestID == "" {
requestID = w.Header().Get("X-Request-Id")
}
if requestID == "" {
requestID = uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
}
if problem.challenge != "" {
w.Header().Set("WWW-Authenticate", problem.challenge)
}
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
Code: problem.code,
Message: problem.message,
RequestID: requestID,
}})
}
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
a.writeError(w, r, statusNotFound)
}
type requestIDContextKey struct{}
func requestIDFromContext(ctx context.Context) string {
value, _ := ctx.Value(requestIDContextKey{}).(string)
return value
}
// statusWriter records the status code and byte count for logs and for the
// panic path, so a partially written response is not written twice.
type statusWriter struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (w *statusWriter) WriteHeader(code int) {
if w.wrote {
return
}
w.wrote = true
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(data []byte) (int, error) {
if !w.wrote {
w.WriteHeader(http.StatusOK)
}
written, err := w.ResponseWriter.Write(data)
w.bytes += written
return written, err
}
func (a *App) withObservability(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
requestID := uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
// Stable for the life of the process. lab2 does not require it, but it
// is the same identifier the next lab uses and it makes log correlation
// unambiguous during restart experiments.
w.Header().Set("X-Instance-Id", a.instanceID)
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
defer func() {
if recovered := recover(); recovered != nil {
a.log.Error("panic while handling request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"path", r.URL.Path,
"panic", recovered,
)
if !writer.wrote {
a.writeError(writer, r, statusInternal)
}
}
level := slog.LevelInfo
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
level = slog.LevelDebug
}
a.log.Log(r.Context(), level, "http request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"path", r.URL.Path,
"status", writer.status,
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
"bytes", writer.bytes,
)
}()
next.ServeHTTP(writer, r)
})
}
// atomicBool keeps the readiness flag readable from the signal goroutine
// without importing sync/atomic into every handler file.
type atomicBool struct{ value atomic.Bool }
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
func (b *atomicBool) Load() bool { return b.value.Load() }
+121
View File
@@ -0,0 +1,121 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab2/internal/cursor"
"mtusi.ru/messenger-lab2/internal/store"
)
type createMessageRequest struct {
Text *string `json:"text"`
}
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// Resource access is checked before the body is decoded so a foreign chat
// always looks like a missing chat, independent of the submitted payload.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
var request createMessageRequest
if problem := a.decodeJSON(r, &request, "text"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
if problem := validateMessageText(*request.Text); problem != nil {
a.writeError(w, r, problem)
return
}
message, err := a.store.CreateMessage(r.Context(), chatID, actor.user.ID, *request.Text)
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, message)
}
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// A foreign/nonexistent chat is always 404, even if the query itself is
// malformed; this avoids making object existence observable.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
return
}
position = &decoded
}
page, err := a.store.Messages(r.Context(), chatID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"errors"
"net/http"
"strings"
"unicode/utf8"
"mtusi.ru/messenger-lab2/internal/auth"
"mtusi.ru/messenger-lab2/internal/model"
"mtusi.ru/messenger-lab2/internal/session"
"mtusi.ru/messenger-lab2/internal/store"
)
// createSession is the only endpoint that accepts Basic credentials. It never
// accepts a JSON body and never reveals whether the username exists.
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
if err != nil {
a.writeError(w, r, unauthorizedBasic())
return
}
// Reject values that could never have been registered before touching the
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
if !usernameAllowed(username) || !validLoginPassword(password) {
_, _ = auth.Verify(password, a.dummyHash)
a.writeError(w, r, unauthorizedBasic())
return
}
user, passwordHash, err := a.store.UserByUsername(r.Context(), username)
switch {
case errors.Is(err, store.ErrNotFound):
// Spend the same KDF work for an unknown username so response timing
// does not disclose account existence.
_, _ = auth.Verify(password, a.dummyHash)
a.writeError(w, r, unauthorizedBasic())
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("login lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
match, err := auth.Verify(password, passwordHash)
if err != nil {
// A corrupt stored hash is an internal data problem, not a wrong
// password; do not silently lock the account out with a 401 log line.
a.log.Error("stored password hash is invalid", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !match {
a.writeError(w, r, unauthorizedBasic())
return
}
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
if err != nil {
a.log.Error("session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, session.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, model.Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: model.Time{Time: expiresAt},
User: user,
})
}
// authenticate accepts only "Authorization: Bearer <opaque token>". A Basic
// header on a business endpoint, a missing header and an X-User-Id header all
// produce the same 401 challenge.
func (a *App) authenticate(r *http.Request) (identity, *apiError) {
token, ok := bearerToken(r.Header.Get("Authorization"))
if !ok || !auth.ValidTokenShape(token) {
return identity{}, unauthorizedBearer()
}
userID, err := a.sessions.Get(r.Context(), token)
switch {
case errors.Is(err, session.ErrInvalid):
return identity{}, unauthorizedBearer()
case errors.Is(err, session.ErrUnavailable):
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusInternal
}
user, err := a.store.UserByID(r.Context(), userID)
switch {
case errors.Is(err, store.ErrNotFound):
// A session pointing at a missing user is not usable. Deleting it is
// best effort; the response is the normal 401 either way.
_ = a.sessions.Delete(r.Context(), token)
return identity{}, unauthorizedBearer()
case errors.Is(err, store.ErrUnavailable):
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusInternal
}
return identity{user: user, token: token}, nil
}
// logout revokes the current server-side session. The response has no body.
func (a *App) logout(w http.ResponseWriter, r *http.Request, actor identity) {
if err := a.sessions.Delete(r.Context(), actor.token); err != nil {
a.log.Error("logout failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, session.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
w.WriteHeader(http.StatusNoContent)
}
func bearerToken(header string) (string, bool) {
trimmed := strings.TrimSpace(header)
space := strings.IndexByte(trimmed, ' ')
if space <= 0 {
return "", false
}
if !strings.EqualFold(trimmed[:space], "Bearer") {
return "", false
}
token := trimmed[space+1:]
if token == "" || strings.ContainsAny(token, " \t") {
return "", false
}
return token, true
}
// validLoginPassword mirrors the registration policy. A login with an
// out-of-range password cannot match any stored hash and must still look like
// an ordinary 401.
func validLoginPassword(password string) bool {
if !utf8.ValidString(password) || isBlank(password) {
return false
}
count := utf8.RuneCountInString(password)
return count >= 12 && count <= 128
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab2/internal/auth"
"mtusi.ru/messenger-lab2/internal/store"
)
type createUserRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
var request createUserRequest
if problem := a.decodeJSON(r, &request, "username", "display_name", "password"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Username == nil {
a.writeError(w, r, invalidRequest("username is required"))
return
}
if request.DisplayName == nil {
a.writeError(w, r, invalidRequest("display_name is required"))
return
}
if request.Password == nil {
a.writeError(w, r, invalidRequest("password is required"))
return
}
if problem := validateUsername(*request.Username); problem != nil {
a.writeError(w, r, problem)
return
}
if problem := validateDisplayName(*request.DisplayName); problem != nil {
a.writeError(w, r, problem)
return
}
if problem := validatePassword(*request.Password); problem != nil {
a.writeError(w, r, problem)
return
}
passwordHash, err := auth.Hash(*request.Password)
if err != nil {
a.log.Error("password hashing failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
user, err := a.store.CreateUser(r.Context(), *request.Username, *request.DisplayName, passwordHash)
switch {
case errors.Is(err, store.ErrUsernameTaken):
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, user)
}
func (a *App) currentUser(w http.ResponseWriter, r *http.Request, actor identity) {
a.writeJSON(w, r, http.StatusOK, actor.user)
}
+209
View File
@@ -0,0 +1,209 @@
package api
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"unicode/utf8"
)
// decodeJSON enforces the contract's JSON rules: application/json, strict
// UTF-8, exactly one object with exactly the documented top-level keys, no
// unknown/duplicate fields and a bounded body size.
//
// encoding/json matches struct fields case-insensitively even with
// DisallowUnknownFields, so the exact key set is checked separately on the
// token stream. That also rejects Unicode case-folding aliases and duplicates.
func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError {
if raw := r.Header.Get("Content-Type"); raw != "" {
mediaType, _, err := mime.ParseMediaType(raw)
if err != nil || mediaType != "application/json" {
return statusUnsupportedMediaType
}
}
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1))
if err != nil {
return invalidRequest("could not read request body")
}
if int64(len(body)) > a.maxBody {
return statusPayloadTooLarge
}
if len(bytes.TrimSpace(body)) == 0 {
return invalidRequest("request body must not be empty")
}
if !utf8.Valid(body) {
return invalidRequest("request body must be valid UTF-8")
}
if problem := validateTopLevelKeys(body, allowedKeys); problem != nil {
return problem
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return invalidRequest("request body does not match the documented schema")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return invalidRequest("request body must contain exactly one JSON value")
}
return nil
}
func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError {
allowed := make(map[string]struct{}, len(allowedKeys))
for _, key := range allowedKeys {
allowed[key] = struct{}{}
}
decoder := json.NewDecoder(bytes.NewReader(body))
token, err := decoder.Token()
if err != nil {
return invalidRequest("request body must be valid JSON")
}
opening, ok := token.(json.Delim)
if !ok || opening != '{' {
return invalidRequest("request body must be a JSON object")
}
seen := make(map[string]struct{}, len(allowedKeys))
for decoder.More() {
token, err := decoder.Token()
if err != nil {
return invalidRequest("request body must be valid JSON")
}
key, ok := token.(string)
if !ok {
return invalidRequest("request body must contain string field names")
}
if _, duplicate := seen[key]; duplicate {
return invalidRequest("request body must not contain duplicate fields")
}
seen[key] = struct{}{}
if _, ok := allowed[key]; !ok {
return invalidRequest("request body contains an unknown field")
}
var value json.RawMessage
if err := decoder.Decode(&value); err != nil {
return invalidRequest("request body must be valid JSON")
}
}
if _, err := decoder.Token(); err != nil {
return invalidRequest("request body must be valid JSON")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return invalidRequest("request body must contain exactly one JSON value")
}
return nil
}
// pageParams parses limit/cursor. Cursor decoding happens after membership is
// verified so a foreign chat cannot be probed with a malformed cursor.
func (a *App) pageParams(r *http.Request) (int, string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, "", invalidRequest("query string is not valid")
}
limit := 50
if values, present := query["limit"]; present {
if len(values) != 1 {
return 0, "", invalidRequest("limit must be specified once")
}
parsed, err := strconv.Atoi(values[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, "", invalidRequest("limit must be an integer between 1 and 100")
}
limit = parsed
}
cursor := ""
if values, present := query["cursor"]; present {
if len(values) != 1 || values[0] == "" {
return 0, "", invalidRequest("cursor must be a non-empty string")
}
cursor = values[0]
}
return limit, cursor, nil
}
func validateUsername(value string) *apiError {
if !usernameAllowed(value) {
return invalidRequest("username must match [a-z0-9_]{3,32}")
}
return nil
}
func validateDisplayName(value string) *apiError {
if isBlank(value) {
return invalidRequest("display_name must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
return invalidRequest("display_name must contain 1 to 100 Unicode code points")
}
return nil
}
func validateTitle(value string) *apiError {
if isBlank(value) {
return invalidRequest("title must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
return invalidRequest("title must contain 1 to 100 Unicode code points")
}
return nil
}
func validateMessageText(value string) *apiError {
if isBlank(value) {
return invalidRequest("text must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 4000 {
return invalidRequest("text must contain 1 to 4000 Unicode code points")
}
return nil
}
// validatePassword implements the registration rule: 12 to 128 Unicode code
// points, not only whitespace. The exact bytes are handed to Argon2id, so
// Unicode passwords are neither truncated nor normalized by the server.
func validatePassword(value string) *apiError {
if !utf8.ValidString(value) {
return invalidRequest("password must be valid UTF-8")
}
if isBlank(value) {
return invalidRequest("password must not be blank")
}
if count := utf8.RuneCountInString(value); count < 12 || count > 128 {
return invalidRequest("password must contain 12 to 128 Unicode code points")
}
return nil
}
func isBlank(value string) bool {
return strings.TrimSpace(value) == ""
}
// usernameAllowed is a byte-wise equivalent of the contract pattern
// ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match.
func usernameAllowed(value string) bool {
if len(value) < 3 || len(value) > 32 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
continue
}
return false
}
return true
}
+203
View File
@@ -0,0 +1,203 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type sampleRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
app := decodeTestApp()
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json; charset=utf-8")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
}
if destination.Username == nil || *destination.Username != "alice" {
t.Fatalf("decoded value = %+v", destination)
}
}
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
app := decodeTestApp()
cases := []struct {
name string
body string
contentType string
status int
}{
{"empty", "", "application/json", http.StatusBadRequest},
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
request.Header.Set("Content-Type", tc.contentType)
var destination sampleRequest
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
if problem == nil {
t.Fatal("decodeJSON accepted an invalid body")
}
if problem.status != tc.status {
t.Fatalf("status = %d, want %d", problem.status, tc.status)
}
})
}
}
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
app := decodeTestApp()
body := append([]byte(`{"username":"`), 0xff, 0xfe)
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
}
}
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
app := decodeTestApp()
app.maxBody = 16
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
request.Header.Set("Content-Type", "application/json")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body = %v, want 413", problem)
}
}
func TestUsernameValidation(t *testing.T) {
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
for _, value := range valid {
if problem := validateUsername(value); problem != nil {
t.Fatalf("validateUsername(%q) = %v", value, problem)
}
}
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
for _, value := range invalid {
if problem := validateUsername(value); problem == nil {
t.Fatalf("validateUsername accepted %q", value)
}
}
}
func TestLengthValidationCountsCodePoints(t *testing.T) {
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
t.Fatalf("100 code points rejected: %v", problem)
}
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
t.Fatal("101 code points accepted")
}
if problem := validateDisplayName(" "); problem == nil {
t.Fatal("blank display_name accepted")
}
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
t.Fatalf("4000 code points rejected: %v", problem)
}
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
t.Fatal("4001 code points accepted")
}
if problem := validateMessageText(" \t\n"); problem == nil {
t.Fatal("blank message accepted")
}
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
t.Fatalf("12-character password rejected: %v", problem)
}
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
t.Fatal("11-character password accepted")
}
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
t.Fatalf("128-character password rejected: %v", problem)
}
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
t.Fatal("129-character password accepted")
}
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
t.Fatal("whitespace password accepted")
}
}
func TestPageParams(t *testing.T) {
valid := map[string][2]any{
"": {50, ""},
"?limit=1": {1, ""},
"?limit=100": {100, ""},
"?limit=7&cursor=x": {7, "x"},
}
for query, want := range valid {
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
limit, cursor, problem := decodeTestApp().pageParams(request)
if problem != nil {
t.Fatalf("pageParams(%q) = %v", query, problem)
}
if limit != want[0].(int) || cursor != want[1].(string) {
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
}
}
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
for _, query := range invalid {
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
t.Fatalf("pageParams accepted %q", query)
}
}
}
func TestBearerTokenParsing(t *testing.T) {
token := strings.Repeat("a", 43)
cases := map[string]string{
"Bearer " + token: token,
"bearer " + token: token,
"BEARER " + token: token,
}
for header, want := range cases {
got, ok := bearerToken(header)
if !ok || got != want {
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
}
}
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
if _, ok := bearerToken(header); ok {
t.Fatalf("bearerToken accepted %q", header)
}
}
}
func TestErrorEnvelopeShape(t *testing.T) {
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
data, err := json.Marshal(envelope)
if err != nil {
t.Fatal(err)
}
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
t.Fatalf("unexpected error JSON: %s", data)
}
}
+156
View File
@@ -0,0 +1,156 @@
package auth
import (
"encoding/base64"
"strings"
"testing"
)
func TestHashAndVerify(t *testing.T) {
password := "correct horse battery staple"
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash: %v", err)
}
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$") {
t.Fatalf("unexpected PHC prefix: %q", encoded)
}
match, err := Verify(password, encoded)
if err != nil || !match {
t.Fatalf("Verify(correct) = %v, %v", match, err)
}
match, err = Verify(password+"x", encoded)
if err != nil || match {
t.Fatalf("Verify(wrong) = %v, %v", match, err)
}
}
func TestHashUnicodeAndMaximumLength(t *testing.T) {
for _, password := range []string{
"pässwörd:12✓",
strings.Repeat("界", 128),
" leading and trailing spaces ",
} {
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash(%q): %v", password, err)
}
if match, err := Verify(password, encoded); err != nil || !match {
t.Fatalf("Verify(%q) = %v, %v", password, match, err)
}
}
}
func TestHashUsesRandomSalt(t *testing.T) {
first, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
second, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("two hashes of the same password are identical")
}
}
func TestVerifyRejectsMalformedHashes(t *testing.T) {
for _, encoded := range []string{
"",
"plaintext",
"$2a$10$abcdefghijklmnopqrstuv",
"$argon2id$v=19$m=19456,t=2,p=1$not-base64$hash",
"$argon2id$v=19$m=1,t=3,p=2$c2FsdHNhbHQ$aGFzaGhhc2hoYXNoaGFzaA",
"$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
} {
if _, err := Verify("password", encoded); err == nil {
t.Fatalf("Verify accepted malformed hash %q", encoded)
}
}
}
func TestParseBasic(t *testing.T) {
cases := []struct {
name string
raw string
username string
password string
ok bool
}{
{
name: "ordinary",
raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{
name: "password contains colon and UTF-8",
raw: "bAsIc " + base64.StdEncoding.EncodeToString([]byte("alice:pässwörd:with:colons")),
username: "alice",
password: "pässwörd:with:colons",
ok: true,
},
{
name: "unpadded base64",
raw: "Basic " + base64.RawStdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{name: "no scheme", raw: "alice:secret"},
{name: "wrong scheme", raw: "Bearer abc"},
{name: "no space", raw: "Basic" + base64.StdEncoding.EncodeToString([]byte("alice:secret"))},
{name: "bad base64", raw: "Basic !!!"},
{name: "no separator", raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice"))},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
username, password, err := ParseBasic(tc.raw)
if !tc.ok {
if err == nil {
t.Fatalf("ParseBasic accepted %q", tc.raw)
}
return
}
if err != nil {
t.Fatalf("ParseBasic: %v", err)
}
if username != tc.username || password != tc.password {
t.Fatalf("got %q/%q, want %q/%q", username, password, tc.username, tc.password)
}
})
}
}
func TestTokenProperties(t *testing.T) {
first, err := NewToken()
if err != nil {
t.Fatal(err)
}
second, err := NewToken()
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("tokens are not unique")
}
if len(first) != 43 {
t.Fatalf("token length = %d, want 43 (256 bits)", len(first))
}
if !ValidTokenShape(first) {
t.Fatal("issued token fails its own shape check")
}
if TokenHash(first) == TokenHash(second) {
t.Fatal("token hashes collide")
}
if len(TokenHash(first)) != 64 {
t.Fatalf("token hash length = %d", len(TokenHash(first)))
}
for _, bad := range []string{"", "short", "has space in it", strings.Repeat("a", 129), "abc+/="} {
if ValidTokenShape(bad) {
t.Fatalf("ValidTokenShape accepted %q", bad)
}
}
}
+90
View File
@@ -0,0 +1,90 @@
// Package auth implements the lab2 credential primitives: a library password
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
// these helpers log or serialise the secret material they receive.
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
// inside the 256 MiB API container limit. The parameters are stored in every
// PHC string, so a future change remains backward compatible.
const (
argonMemory uint32 = 19 * 1024 // KiB
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
)
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
// parameters. It is an internal error, never shown to a client.
var ErrInvalidHash = errors.New("invalid password hash")
// Hash derives an Argon2id PHC string for password. Callers must validate the
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
func Hash(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password 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
}
// Verify checks password against a PHC string in constant time and reports
// whether the encoded hash was structurally valid. A malformed hash is not a
// password mismatch and should be treated as an internal error by the caller.
func Verify(password, encoded string) (match bool, err error) {
params, salt, key, err := parse(encoded)
if err != nil {
return false, err
}
candidate := argon2.IDKey([]byte(password), salt, params.iterations, params.memory, params.parallelism, uint32(len(key)))
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
}
type params struct {
memory uint32
iterations uint32
parallelism uint8
}
func parse(encoded string) (params, []byte, []byte, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return params{}, nil, nil, ErrInvalidHash
}
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
return params{}, nil, nil, ErrInvalidHash
}
var p params
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
return params{}, nil, nil, ErrInvalidHash
}
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
return params{}, nil, nil, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 || len(salt) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
key, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(key) < 16 || len(key) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
return p, salt, key, nil
}
+102
View File
@@ -0,0 +1,102 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
)
// tokenBytes gives 256 bits of entropy, the contract minimum. The token is an
// opaque value: it is not a username, a UUID or a JWT.
const tokenBytes = 32
// NewToken returns a URL-safe opaque session token.
func NewToken() (string, error) {
raw := make([]byte, tokenBytes)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
// TokenHash is the only representation of a token that is persisted. A cache
// dump therefore does not contain bearer credentials usable against the API.
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// ValidTokenShape rejects absurd header values before hashing. The check is a
// superset of the 43-character tokens this server issues, so token rotation
// remains possible without rejecting old values early.
func ValidTokenShape(token string) bool {
if len(token) < 16 || len(token) > 128 {
return false
}
for i := 0; i < len(token); i++ {
c := token[i]
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
continue
}
return false
}
return true
}
// ErrMalformedBasic is returned for anything that is not a well-formed
// RFC 7617 Basic credential. Callers must answer with the same 401 as a
// wrong password.
var ErrMalformedBasic = errors.New("malformed basic credentials")
// ParseBasic decodes an Authorization header of the form "Basic base64(user:pass)".
// The password may contain colons and arbitrary UTF-8; only the first colon
// separates the username.
func ParseBasic(header string) (username, password string, err error) {
const scheme = "basic"
trimmed := header
if len(trimmed) < len(scheme)+1 || !equalFoldASCII(trimmed[:len(scheme)], scheme) || trimmed[len(scheme)] != ' ' {
return "", "", ErrMalformedBasic
}
encoded := trimmed[len(scheme)+1:]
if encoded == "" || len(encoded) > 1024 {
return "", "", ErrMalformedBasic
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
// Some clients omit the RFC 4648 padding. Accept the unpadded form as
// well, but never fall back to a different alphabet.
decoded, err = base64.RawStdEncoding.DecodeString(encoded)
if err != nil {
return "", "", ErrMalformedBasic
}
}
separator := -1
for i := 0; i < len(decoded); i++ {
if decoded[i] == ':' {
separator = i
break
}
}
if separator < 0 {
return "", "", ErrMalformedBasic
}
return string(decoded[:separator]), string(decoded[separator+1:]), nil
}
func equalFoldASCII(value, lower string) bool {
if len(value) != len(lower) {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
if c != lower[i] {
return false
}
}
return true
}
+229
View File
@@ -0,0 +1,229 @@
// Package config loads the explicit runtime configuration of the lab2
// messenger. The container image stays immutable: the same image is configured
// through environment variables (or files referenced by *_FILE variables for
// operators that do not want secrets in the environment).
package config
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultSessionTTL is the contract default of contracts/README.md.
DefaultSessionTTL = time.Hour
// MaxShutdownTimeout leaves headroom below the 10 second termination
// window promised by the previous lab and expected by the container
// checks, even if an operator overrides the environment variable.
MaxShutdownTimeout = 9 * time.Second
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
MaxStartupTimeout = 120 * time.Second
)
// Config is validated at startup. The process refuses to start with an
// invalid value instead of silently falling back to a different security or
// durability posture.
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
StartupTimeout time.Duration
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBConnectTimeout time.Duration
DBStatementTimeout time.Duration
QueryTimeout time.Duration
CachePoolSize int
CacheTimeout time.Duration
}
// Load reads and validates the runtime configuration.
func Load() (Config, error) {
cfg := Config{
Host: envString("APP_HOST", "0.0.0.0"),
Env: envString("APP_ENV", "lab"),
ShutdownTimeout: 8 * time.Second,
StartupTimeout: 30 * time.Second,
QueryTimeout: 3 * time.Second,
}
port, err := envInt("APP_PORT", 8080)
if err != nil {
return Config{}, fmt.Errorf("APP_PORT: %w", err)
}
if port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
}
cfg.Port = port
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
if err != nil {
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
}
cfg.LogLevel = level
if strings.TrimSpace(cfg.Host) == "" {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
databaseURL, err := secret("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
cacheURL, err := secret("CACHE_URL")
if err != nil {
return Config{}, err
}
cfg.CacheURL = cacheURL
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
if err != nil {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
}
if seconds < 1 || seconds > 30*24*60*60 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
}
cfg.SessionTTL = time.Duration(seconds) * time.Second
maxConns, err := envInt("DB_MAX_CONNS", 8)
if err != nil {
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
}
if maxConns < 1 || maxConns > 100 {
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
}
cfg.DBMaxConns = int32(maxConns)
minConns, err := envInt("DB_MIN_CONNS", 1)
if err != nil {
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
}
if minConns < 0 || minConns > maxConns {
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
}
cfg.DBMinConns = int32(minConns)
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
return Config{}, err
}
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
if err != nil {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
}
if cachePool < 1 || cachePool > 100 {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
}
cfg.CachePoolSize = cachePool
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
return Config{}, err
}
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 8, 1, 60)
if err != nil {
return Config{}, err
}
if shutdown > MaxShutdownTimeout {
shutdown = MaxShutdownTimeout
}
cfg.ShutdownTimeout = shutdown
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
if err != nil {
return Config{}, err
}
cfg.StartupTimeout = startup
return cfg, nil
}
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
// compose-style file secrets win over inherited environment values. Values are
// never echoed in error messages.
func secret(name string) (string, error) {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
}
return value, nil
}
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func envString(key, fallback string) string {
// An environment variable set to an empty string is treated as unset; this
// keeps container defaults working when compose passes "" for an optional
// setting.
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) (int, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
value, err := envInt(key, fallback)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
if value < minimum || value > maximum {
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
}
return time.Duration(value) * time.Second, nil
}
func parseLogLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "debug":
return slog.LevelDebug, nil
case "info":
return slog.LevelInfo, nil
case "warn", "warning":
return slog.LevelWarn, nil
case "error":
return slog.LevelError, nil
default:
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
}
}
+131
View File
@@ -0,0 +1,131 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
)
var allKeys = []string{
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
"CACHE_URL", "CACHE_URL_FILE",
}
func clearEnvironment(t *testing.T) {
t.Helper()
for _, key := range allKeys {
t.Setenv(key, "")
}
}
func baseEnvironment(t *testing.T) {
t.Helper()
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
}
func TestLoadDefaults(t *testing.T) {
baseEnvironment(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
t.Fatalf("unexpected defaults: %+v", cfg)
}
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
t.Fatalf("unexpected pool defaults: %+v", cfg)
}
}
func TestLoadReadsSecretsFromFiles(t *testing.T) {
clearEnvironment(t)
directory := t.TempDir()
databaseFile := filepath.Join(directory, "database_url")
cacheFile := filepath.Join(directory, "cache_url")
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DATABASE_URL_FILE", databaseFile)
t.Setenv("CACHE_URL_FILE", cacheFile)
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
}
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
}
}
func TestLoadRejectsInvalidValues(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
{"zero port", "APP_PORT", "0"},
{"bad log level", "LOG_LEVEL", "verbose"},
{"zero max conns", "DB_MAX_CONNS", "0"},
{"min above max", "DB_MIN_CONNS", "9"},
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
{"bad int", "APP_PORT", "eighty"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
baseEnvironment(t)
t.Setenv(tc.key, tc.value)
if _, err := Load(); err == nil {
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
}
})
}
}
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
clearEnvironment(t)
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
}
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing CACHE_URL")
}
}
func TestShutdownTimeoutIsClamped(t *testing.T) {
baseEnvironment(t)
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.ShutdownTimeout != MaxShutdownTimeout {
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
}
}
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
_, err := Load()
if err == nil {
t.Fatal("Load accepted a missing secret file")
}
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
t.Fatalf("error leaks path: %q", got)
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package cursor implements the opaque keyset cursor of the contract. A cursor
// carries the last item already returned; the next page asks PostgreSQL for
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
// for message history, to the chat that issued them.
package cursor
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"time"
"mtusi.ru/messenger-lab2/internal/model"
"mtusi.ru/messenger-lab2/internal/uuid"
)
const (
ScopeChats = "chats"
ScopeMessages = "messages"
version = 1
maxCursorSize = 512
)
// ErrInvalid is returned for malformed, tampered or out-of-scope cursors. The
// HTTP layer maps it to 400 invalid_request.
var ErrInvalid = errors.New("invalid cursor")
// Cursor is the decoded keyset position.
type Cursor struct {
At time.Time
ID string
ChatID string
}
// Encoding of the wire form. Time is an RFC 3339 timestamp with UTC Z and
// microsecond precision, matching PostgreSQL timestamptz. It is never used as
// an identifier on its own.
type wire struct {
Version int `json:"v"`
Scope string `json:"s"`
ChatID string `json:"c,omitempty"`
Time string `json:"t"`
ID string `json:"i"`
}
// ForChat encodes the position of the last returned chat.
func ForChat(chat model.Chat) string {
return encode(wire{Scope: ScopeChats, Time: chat.CreatedAt.UTC().Format(time.RFC3339Nano), ID: chat.ID})
}
// ForMessage encodes the position of the last returned message.
func ForMessage(message model.Message) string {
return encode(wire{
Scope: ScopeMessages,
ChatID: message.ChatID,
Time: message.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: message.ID,
})
}
// Decode validates a cursor for the expected scope. chatID is required for the
// messages scope and must be empty for the chats scope.
func Decode(raw, scope, chatID string) (Cursor, error) {
if raw == "" || len(raw) > maxCursorSize {
return Cursor{}, ErrInvalid
}
data, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil {
return Cursor{}, ErrInvalid
}
var value wire
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&value); err != nil {
return Cursor{}, ErrInvalid
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return Cursor{}, ErrInvalid
}
if value.Version != version || value.Scope != scope {
return Cursor{}, ErrInvalid
}
at, err := time.Parse(time.RFC3339Nano, value.Time)
if err != nil || at.IsZero() || at.Location() != time.UTC {
return Cursor{}, ErrInvalid
}
normalizedID, ok := uuid.Normalize(value.ID)
if !ok || normalizedID != value.ID {
return Cursor{}, ErrInvalid
}
switch scope {
case ScopeChats:
if value.ChatID != "" {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID}, nil
case ScopeMessages:
normalizedChat, ok := uuid.Normalize(value.ChatID)
if !ok || normalizedChat != value.ChatID || normalizedChat != chatID {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID, ChatID: normalizedChat}, nil
default:
return Cursor{}, ErrInvalid
}
}
func encode(value wire) string {
value.Version = version
data, err := json.Marshal(value)
if err != nil {
panic("encode cursor: " + err.Error())
}
return base64.RawURLEncoding.EncodeToString(data)
}
+97
View File
@@ -0,0 +1,97 @@
package cursor
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"time"
"mtusi.ru/messenger-lab2/internal/model"
)
func TestChatCursorRoundTrip(t *testing.T) {
at := time.Date(2026, 11, 30, 12, 34, 56, 123456000, time.UTC)
chat := model.Chat{
ID: "11111111-2222-4333-8444-555555555555",
Title: "chat",
MemberIDs: []string{"11111111-2222-4333-8444-555555555555"},
CreatedAt: model.Time{Time: at},
}
raw := ForChat(chat)
decoded, err := Decode(raw, ScopeChats, "")
if err != nil {
t.Fatalf("Decode: %v", err)
}
if !decoded.At.Equal(at) || decoded.ID != chat.ID || decoded.ChatID != "" {
t.Fatalf("decoded = %+v", decoded)
}
}
func TestMessageCursorIsBoundToChat(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
chatID := "11111111-2222-4333-8444-555555555555"
message := model.Message{
ID: "99999999-2222-4333-8444-555555555555",
ChatID: chatID,
SenderID: "11111111-2222-4333-8444-555555555555",
Text: "hello",
CreatedAt: model.Time{Time: at},
}
raw := ForMessage(message)
if _, err := Decode(raw, ScopeMessages, chatID); err != nil {
t.Fatalf("Decode(same chat): %v", err)
}
if _, err := Decode(raw, ScopeMessages, "22222222-2222-4333-8444-555555555555"); err == nil {
t.Fatal("cursor was accepted for another chat")
}
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatal("message cursor was accepted by the chats scope")
}
}
func TestDecodeRejectsTamperedCursors(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
valid := wire{
Version: version,
Scope: ScopeMessages,
ChatID: "11111111-2222-4333-8444-555555555555",
Time: at.Format(time.RFC3339Nano),
ID: "99999999-2222-4333-8444-555555555555",
}
tampered := []wire{
{Version: 2, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: ScopeChats, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "not-a-uuid", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "2026-11-30T12:00:00+03:00", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "yesterday", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: "not-a-uuid"},
}
for i, value := range tampered {
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
raw := base64.RawURLEncoding.EncodeToString(data)
if _, err := Decode(raw, ScopeMessages, valid.ChatID); err == nil {
t.Fatalf("tampered cursor %d was accepted", i)
}
}
withExtra, _ := json.Marshal(map[string]any{
"v": version, "s": ScopeMessages, "c": valid.ChatID,
"t": valid.Time, "i": valid.ID, "x": 1,
})
if _, err := Decode(base64.RawURLEncoding.EncodeToString(withExtra), ScopeMessages, valid.ChatID); err == nil {
t.Fatal("cursor with an unknown field was accepted")
}
}
func TestDecodeRejectsGarbage(t *testing.T) {
for _, raw := range []string{"", "!!!", base64.RawURLEncoding.EncodeToString([]byte("not json")), strings.Repeat("a", 600)} {
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatalf("Decode accepted %q", raw)
}
}
}
+69
View File
@@ -0,0 +1,69 @@
// Package model holds the public JSON shapes of the lab2 contract. They are
// deliberately separate from the database scan helpers so an accidental new
// column cannot silently become an API field.
package model
import "time"
// Time marshals an RFC 3339 UTC timestamp with exactly six fractional digits.
// Go's default time.Time JSON encoder trims trailing zeros, which produces
// 3-5 digit fractions that some Python 3.9 datetime parsers (used by the
// public test client) reject. A fixed microsecond precision matches
// PostgreSQL timestamptz and stays valid RFC 3339.
type Time struct{ time.Time }
const timestampLayout = "2006-01-02T15:04:05.000000Z"
// MarshalJSON implements json.Marshaler.
func (t Time) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
}
// User is the public user shape. It never contains a password hash or session
// data.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Time `json:"created_at"`
}
// Chat is the public chat shape. MemberIDs preserves the order supplied at
// creation; membership is immutable in the mandatory lab2 API.
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Time `json:"created_at"`
}
// Message is the public message shape. SenderID always comes from the server
// session, never from the request body.
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Time `json:"created_at"`
}
// ChatPage is one keyset page of accessible chats.
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// MessagePage is one keyset page of a chat history.
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// Session is the login response. Token is only ever written to the response
// body, never to logs or PostgreSQL.
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Time `json:"expires_at"`
User User `json:"user"`
}
+50
View File
@@ -0,0 +1,50 @@
package model
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestTimeMarshalUsesFixedMicroseconds(t *testing.T) {
value := Time{Time: time.Date(2026, 11, 30, 12, 0, 0, 120000000, time.UTC)}
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
got := string(data)
// .120000 would be trimmed to .12 by the default encoder; the public
// Python 3.9 client requires 3 or 6 fractional digits.
if got != `"2026-11-30T12:00:00.120000Z"` {
t.Fatalf("marshal = %s", got)
}
if !strings.HasSuffix(got, "Z\"") {
t.Fatal("timestamp does not end in Z")
}
}
func TestUserJSONHasOnlyPublicFields(t *testing.T) {
user := User{
ID: "11111111-2222-4333-8444-555555555555",
Username: "alice",
DisplayName: "Алиса",
CreatedAt: Time{Time: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)},
}
data, err := json.Marshal(user)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(data, &fields); err != nil {
t.Fatal(err)
}
if len(fields) != 4 {
t.Fatalf("user JSON has unexpected fields: %v", fields)
}
for _, forbidden := range []string{"password", "password_hash", "token", "token_hash"} {
if _, present := fields[forbidden]; present {
t.Fatalf("user JSON leaks %q", forbidden)
}
}
}
+151
View File
@@ -0,0 +1,151 @@
// Package session stores opaque server-side sessions in Valkey. The token is
// never persisted: only its SHA-256 hash is used as the cache key, so a cache
// dump does not contain credentials that can be replayed against the API.
//
// Valkey is the source of truth for sessions. It is configured with AOF
// persistence and a named volume, so valid sessions survive both the API
// process and the Valkey process restarting with volumes kept.
package session
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"mtusi.ru/messenger-lab2/internal/auth"
)
const keyPrefix = "mtusi:lab2:session:"
var (
// ErrInvalid means the token is unknown, expired or malformed.
ErrInvalid = errors.New("invalid session")
// ErrUnavailable means Valkey is not answering; the API must return a
// bounded 503 instead of trusting the bearer token.
ErrUnavailable = errors.New("session store unavailable")
)
type record struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
// Options bound every network operation and the connection pool.
type Options struct {
PoolSize int
DialTimeout time.Duration
IOTimeout time.Duration
TTL time.Duration
}
// Store is a thin, timeout-aware wrapper around go-redis.
type Store struct {
client *redis.Client
ttl time.Duration
}
// Open parses CACHE_URL (redis:// or rediss://) without echoing it in errors.
// It does not require Valkey to be reachable at startup: /health/ready and
// login report the outage as 503.
func Open(rawURL string, options Options) (*Store, error) {
parsed, err := redis.ParseURL(rawURL)
if err != nil {
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
}
if options.PoolSize <= 0 {
options.PoolSize = 8
}
if options.DialTimeout <= 0 {
options.DialTimeout = 2 * time.Second
}
if options.IOTimeout <= 0 {
options.IOTimeout = 2 * time.Second
}
if options.TTL <= 0 {
options.TTL = time.Hour
}
parsed.PoolSize = options.PoolSize
parsed.DialTimeout = options.DialTimeout
parsed.ReadTimeout = options.IOTimeout
parsed.WriteTimeout = options.IOTimeout
// One retry keeps a transient blip invisible while bounding the worst-case
// time a handler spends waiting for the cache.
parsed.MaxRetries = 1
parsed.MinRetryBackoff = 20 * time.Millisecond
parsed.MaxRetryBackoff = 100 * time.Millisecond
return &Store{client: redis.NewClient(parsed), ttl: options.TTL}, nil
}
// TTL exposes the configured session lifetime (used by tests and startup logs).
func (s *Store) TTL() time.Duration { return s.ttl }
// Create issues a new opaque token and stores the session with a TTL. The
// returned expiry is the absolute instant the client must treat as the end of
// the session; restarting a process does not extend it.
func (s *Store) Create(ctx context.Context, userID string) (token string, expiresAt time.Time, err error) {
token, err = auth.NewToken()
if err != nil {
return "", time.Time{}, fmt.Errorf("generate session token: %w", err)
}
// A whole number of microseconds keeps the value parseable by the
// Python 3.9 public client (its fromisoformat accepts 3 or 6 fractional
// digits, not Go's trimmed nanosecond form) while staying RFC 3339.
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
payload, err := json.Marshal(record{UserID: userID, ExpiresAt: expiresAt})
if err != nil {
return "", time.Time{}, fmt.Errorf("encode session: %w", err)
}
if err := s.client.Set(ctx, key(auth.TokenHash(token)), payload, s.ttl).Err(); err != nil {
return "", time.Time{}, fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return token, expiresAt, nil
}
// Get resolves a token to a user id. Unknown, expired and corrupt records are
// all ErrInvalid; a transport failure is ErrUnavailable.
func (s *Store) Get(ctx context.Context, token string) (string, error) {
raw, err := s.client.Get(ctx, key(auth.TokenHash(token))).Bytes()
if errors.Is(err, redis.Nil) {
return "", ErrInvalid
}
if err != nil {
return "", fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var value record
if err := json.Unmarshal(raw, &value); err != nil || value.UserID == "" {
return "", ErrInvalid
}
if !value.ExpiresAt.After(time.Now()) {
// TTL should already have removed the key; this also covers a clock
// adjustment or an externally imported record.
_ = s.client.Del(ctx, key(auth.TokenHash(token))).Err()
return "", ErrInvalid
}
return value.UserID, nil
}
// Delete revokes the session. Missing keys are not an error here: the caller
// has already authenticated the token, and a concurrent logout is harmless.
func (s *Store) Delete(ctx context.Context, token string) error {
if err := s.client.Del(ctx, key(auth.TokenHash(token))).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
// Ping is used by /health/ready and the startup log.
func (s *Store) Ping(ctx context.Context) error {
if err := s.client.Ping(ctx).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
// Close releases the connection pool.
func (s *Store) Close() error { return s.client.Close() }
func key(tokenHash string) string { return keyPrefix + tokenHash }
+139
View File
@@ -0,0 +1,139 @@
package store
import (
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
// concurrent API replicas that start at the same time; it is released when the
// dedicated connection is returned or the session ends.
const advisoryLockKey int64 = 0x6d74756c616232 // "mtulab2"
type migration struct {
version int
name string
checksum string
sql string
}
// Migrate applies every embedded migration exactly once and records its
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
// A changed migration file is a startup error rather than a silent divergence.
func (s *Store) Migrate(ctx context.Context) error {
conn, err := s.pool.Acquire(ctx)
if err != nil {
return s.classify(err)
}
defer conn.Release()
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
return s.classify(err)
}
defer func() {
// Use a background context: the request context may already be
// cancelled when a startup timeout fires, but the lock still has to be
// released explicitly before the connection is returned to the pool.
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
}()
if _, err := conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
name text NOT NULL,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)`); err != nil {
return s.classify(err)
}
migrations, err := loadMigrations()
if err != nil {
return err
}
for _, item := range migrations {
var existing string
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
switch {
case err == nil:
if existing != item.checksum {
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
}
continue
case !errors.Is(err, pgx.ErrNoRows):
return s.classify(err)
}
tx, err := conn.Begin(ctx)
if err != nil {
return s.classify(err)
}
if _, err := tx.Exec(ctx, item.sql); err != nil {
_ = tx.Rollback(context.Background())
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
}
if _, err := tx.Exec(ctx,
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
item.version, item.name, item.checksum,
); err != nil {
_ = tx.Rollback(context.Background())
return s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return s.classify(err)
}
}
return nil
}
func loadMigrations() ([]migration, error) {
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return nil, err
}
items := make([]migration, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
name := entry.Name()
if len(name) < 9 {
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
}
version, err := strconv.Atoi(name[:4])
if err != nil {
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
}
data, err := migrationFiles.ReadFile("migrations/" + name)
if err != nil {
return nil, err
}
sum := sha256.Sum256(data)
items = append(items, migration{
version: version,
name: strings.TrimSuffix(name[5:], ".sql"),
checksum: hex.EncodeToString(sum[:]),
sql: string(data),
})
}
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
for i := 1; i < len(items); i++ {
if items[i].version == items[i-1].version {
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
}
}
return items, nil
}
+57
View File
@@ -0,0 +1,57 @@
package store
import (
"strings"
"testing"
)
func TestLoadMigrations(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatalf("loadMigrations: %v", err)
}
if len(migrations) != 2 {
t.Fatalf("loaded %d migrations, want 2", len(migrations))
}
if migrations[0].version != 1 || migrations[1].version != 2 {
t.Fatalf("migration order = %d,%d", migrations[0].version, migrations[1].version)
}
for _, item := range migrations {
if len(item.checksum) != 64 {
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
}
if !strings.Contains(strings.ToLower(item.sql), "create ") {
t.Fatalf("migration %d has no schema statements", item.version)
}
}
// The checksum must be stable across process runs: it is what detects an
// edited migration after it has been applied.
again, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
if migrations[0].checksum != again[0].checksum || migrations[1].checksum != again[1].checksum {
t.Fatal("migration checksums are not deterministic")
}
}
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
all := migrations[0].sql + migrations[1].sql
for _, required := range []string{
"CREATE TABLE users",
"CREATE TABLE chats",
"CREATE TABLE chat_members",
"CREATE TABLE messages",
"CREATE UNIQUE INDEX users_username_key",
"messages_sender_membership_fk",
"messages_chat_created_id_idx",
} {
if !strings.Contains(all, required) {
t.Fatalf("migrations do not contain %q", required)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_format
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length
CHECK (char_length(display_name) BETWEEN 1 AND 100),
CONSTRAINT users_password_hash_present
CHECK (length(password_hash) > 0)
);
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
-- two concurrent registrations of the same username cannot both succeed.
CREATE UNIQUE INDEX users_username_key ON users (username);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_length
CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
);
-- "Chats of the current user" walks chat_members by user_id.
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 1 AND 4000),
CONSTRAINT messages_chat_fk
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
-- The sender must be a member of the chat at the database level too, not
-- only in the HTTP handler.
CONSTRAINT messages_sender_membership_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,15 @@
-- Indexes justified by the two keyset queries of the contract.
--
-- Message history:
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- The three-column index lets PostgreSQL start at the cursor position inside
-- one chat instead of scanning the whole history for every page.
CREATE INDEX messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
-- Chat list:
-- ORDER BY created_at, id LIMIT $1
-- after joining chat_members for the current user.
CREATE INDEX chats_created_id_idx
ON chats (created_at, id);
+472
View File
@@ -0,0 +1,472 @@
// Package store is the PostgreSQL repository. Every statement uses positional
// parameters; identifiers are never interpolated into SQL. The pool is
// bounded and every operation carries a context timeout.
package store
import (
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/puddle/v2"
"mtusi.ru/messenger-lab2/internal/cursor"
"mtusi.ru/messenger-lab2/internal/model"
"mtusi.ru/messenger-lab2/internal/uuid"
)
// Domain errors. The HTTP layer maps them to the contract's status codes.
var (
ErrNotFound = errors.New("object not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("unknown chat member")
ErrUnavailable = errors.New("database unavailable")
)
// Options bounds the pool and every query. Zero values fall back to safe
// defaults so the store is still testable from small programs.
type Options struct {
MaxConns int32
MinConns int32
ConnectTimeout time.Duration
StatementTimeout time.Duration
QueryTimeout time.Duration
}
// Store owns a bounded pgx pool.
type Store struct {
pool *pgxpool.Pool
queryTimeout time.Duration
}
// Open parses the DSN and creates the pool. Parse errors deliberately do not
// echo the DSN: it contains the database password.
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
}
applyDefaults(&options)
config.MaxConns = options.MaxConns
config.MinConns = options.MinConns
config.MaxConnLifetime = 30 * time.Minute
config.MaxConnIdleTime = 5 * time.Minute
config.HealthCheckPeriod = 30 * time.Second
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab2"
// A statement timeout in the server session is the last line of defence
// against a runaway query; the caller's context is the first.
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
pool, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
}
func applyDefaults(options *Options) {
if options.MaxConns <= 0 {
options.MaxConns = 8
}
if options.MinConns < 0 {
options.MinConns = 0
}
if options.MinConns > options.MaxConns {
options.MinConns = options.MaxConns
}
if options.ConnectTimeout <= 0 {
options.ConnectTimeout = 3 * time.Second
}
if options.StatementTimeout <= 0 {
options.StatementTimeout = 3 * time.Second
}
if options.QueryTimeout <= 0 {
options.QueryTimeout = 3 * time.Second
}
}
// Ping is used by /health/ready and by the startup readiness loop.
func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(ctx)
}
// Close waits for in-flight queries and closes the pool.
func (s *Store) Close() { s.pool.Close() }
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return ctx, func() {}
}
return context.WithTimeout(ctx, s.queryTimeout)
}
// classify separates a dependency outage (contract 503 unavailable) from a
// genuine application bug (500 internal_error). Only the error class is mapped;
// the original error is logged server-side and never sent to a client.
func (s *Store) classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
pgErr.Code == "57P01", // admin shutdown
pgErr.Code == "57P02", // crash shutdown
pgErr.Code == "57P03", // cannot connect now
pgErr.Code == "57014", // query cancelled (statement_timeout)
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
}
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
// CreateUser inserts a user and relies on the unique index for both ordinary
// duplicates and concurrent registrations of the same username.
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
RETURNING created_at`,
id, username, displayName, passwordHash, createdAt,
).Scan(&stored)
if err != nil {
if isUniqueViolation(err) {
return model.User{}, ErrUsernameTaken
}
return model.User{}, s.classify(err)
}
return model.User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// UserByUsername returns the public user and the Argon2id hash. The hash is
// used only by the login handler and is never serialised.
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var passwordHash string
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username,
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, "", ErrNotFound
}
return model.User{}, "", s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, passwordHash, nil
}
// UserByID resolves the identity stored in a server-side session.
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, created_at
FROM users WHERE id = $1::uuid`, id,
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, ErrNotFound
}
return model.User{}, s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, nil
}
// CreateChat inserts the chat and its membership in one transaction. A caller
// cannot observe a chat without members: either both are committed or neither.
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
var existing int
if err := tx.QueryRow(ctx, `
SELECT count(*) FROM users
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
).Scan(&existing); err != nil {
return model.Chat{}, s.classify(err)
}
if existing != len(memberIDs) {
return model.Chat{}, ErrUnknownMember
}
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
if err := tx.QueryRow(ctx, `
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
RETURNING created_at`, id, title, createdAt,
).Scan(&stored); err != nil {
return model.Chat{}, s.classify(err)
}
batch := &pgx.Batch{}
for position, memberID := range memberIDs {
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
id, memberID, position)
}
results := tx.SendBatch(ctx, batch)
for range memberIDs {
if _, err := results.Exec(); err != nil {
_ = results.Close()
if isForeignKeyViolation(err) {
return model.Chat{}, ErrUnknownMember
}
return model.Chat{}, s.classify(err)
}
}
if err := results.Close(); err != nil {
return model.Chat{}, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, s.classify(err)
}
return model.Chat{
ID: id,
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// IsChatMember is used before parsing query parameters so a foreign chat is
// always 404, independent of the submitted cursor or limit.
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var member bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
)`, chatID, userID).Scan(&member)
if err != nil {
return false, s.classify(err)
}
return member, nil
}
// ChatForUser returns a chat only when the user is a member. A missing chat and
// a foreign chat are indistinguishable to the caller.
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var chat model.Chat
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1::uuid
GROUP BY c.id`, chatID, userID,
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, ErrNotFound
}
return model.Chat{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
return chat, nil
}
const chatsPageSelect = `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
JOIN chat_members cm ON cm.chat_id = c.id`
// Chats returns one keyset page of chats visible to the user.
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := chatsPageSelect + `
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $2`
args := []any{userID, limit + 1}
if position != nil {
query = chatsPageSelect + `
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4`
args = []any{userID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.ChatPage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Chat, 0, limit)
for rows.Next() {
var chat model.Chat
var createdAt time.Time
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
return model.ChatPage{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return model.ChatPage{}, s.classify(err)
}
page := model.ChatPage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForChat(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
// CreateMessage appends a message. The composite foreign key also guarantees
// that the sender belongs to the chat at the database level.
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, text string) (model.Message, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
}
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
RETURNING created_at`,
message.ID, chatID, senderID, text, time.Now().UTC(),
).Scan(&createdAt)
if err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, ErrNotFound
}
return model.Message{}, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return message, nil
}
const messagesPageSelect = `
SELECT id::text, chat_id::text, sender_id::text, text, created_at
FROM messages
WHERE chat_id = $1::uuid`
// Messages returns one keyset page of a chat history. The caller has already
// verified membership; the query itself never loads the whole history.
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := messagesPageSelect + `
ORDER BY created_at, messages.id
LIMIT $2`
args := []any{chatID, limit + 1}
if position != nil {
query = messagesPageSelect + `
AND (created_at, messages.id) > ($2::timestamptz, $3::uuid)
ORDER BY created_at, messages.id
LIMIT $4`
args = []any{chatID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.MessagePage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Message, 0, limit)
for rows.Next() {
var message model.Message
var createdAt time.Time
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil {
return model.MessagePage{}, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return model.MessagePage{}, s.classify(err)
}
page := model.MessagePage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForMessage(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
+75
View File
@@ -0,0 +1,75 @@
// Package uuid generates and normalizes canonical lowercase UUIDs. The
// application, not PostgreSQL, assigns identifiers so every API replica and
// the database agree on the exact on-the-wire form.
package uuid
import (
"crypto/rand"
"encoding/hex"
"strings"
)
// New returns a canonical lowercase UUIDv4. A failure of crypto/rand means the
// process cannot safely create identifiers, so panicking is intentional; the
// HTTP layer turns it into a generic 500 response.
func New() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic("crypto/rand failed: " + err.Error())
}
b[6] = (b[6] & 0x0f) | 0x40 // version 4
b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant
return format(b)
}
// NewRandom returns a lowercase hex string with n random bytes. It is used for
// request ids and stable per-process instance ids, not for resource ids.
func NewRandom(n int) string {
raw := make([]byte, n)
if _, err := rand.Read(raw); err != nil {
panic("crypto/rand failed: " + err.Error())
}
return hex.EncodeToString(raw)
}
func format(b [16]byte) string {
var out [36]byte
hex.Encode(out[0:8], b[0:4])
out[8] = '-'
hex.Encode(out[9:13], b[4:6])
out[13] = '-'
hex.Encode(out[14:18], b[6:8])
out[18] = '-'
hex.Encode(out[19:23], b[8:10])
out[23] = '-'
hex.Encode(out[24:36], b[10:16])
return string(out[:])
}
// Normalize accepts only the canonical 8-4-4-4-12 hyphenated form (ASCII hex,
// case-insensitive) and returns its lowercase representation. Braces, urn:
// prefixes, SQL uuid spellings and other aliases are rejected so resource
// identifiers have exactly one wire form.
func Normalize(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
for i := 0; i < len(value); i++ {
c := value[i]
switch i {
case 8, 13, 18, 23:
if c != '-' {
return "", false
}
default:
if !isHex(c) {
return "", false
}
}
}
return strings.ToLower(value), true
}
func isHex(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
+44
View File
@@ -0,0 +1,44 @@
package uuid
import "testing"
func TestNewIsCanonicalV4(t *testing.T) {
id := New()
normalized, ok := Normalize(id)
if !ok || normalized != id {
t.Fatalf("New() returned non-canonical UUID %q", id)
}
if id[14] != '4' {
t.Fatalf("version nibble = %c, want 4", id[14])
}
if id[19] != '8' && id[19] != '9' && id[19] != 'a' && id[19] != 'b' {
t.Fatalf("variant nibble = %c, want 8/9/a/b", id[19])
}
if New() == New() {
t.Fatal("two generated UUIDs are equal")
}
}
func TestNormalize(t *testing.T) {
valid := "11111111-2222-4333-8444-555555555555"
if got, ok := Normalize(valid); !ok || got != valid {
t.Fatalf("Normalize(%q) = %q, %v", valid, got, ok)
}
upper := "AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE"
if got, ok := Normalize(upper); !ok || got != "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" {
t.Fatalf("uppercase normalization failed: %q, %v", got, ok)
}
for _, invalid := range []string{
"",
"{11111111-2222-4333-8444-555555555555}",
"urn:uuid:11111111-2222-4333-8444-555555555555",
"11111111222243338444555555555555",
"11111111-2222-4333-8444-55555555555z",
"11111111-2222-4333-8444-5555555555555",
" 1111111-2222-4333-8444-555555555555",
} {
if _, ok := Normalize(invalid); ok {
t.Fatalf("Normalize accepted %q", invalid)
}
}
}