feat: secure service connections and login

This commit is contained in:
2026-11-06 21:14:49 +03:00
parent cb51354889
commit 48918e8b19
59 changed files with 1980 additions and 316 deletions
+3 -3
View File
@@ -16,9 +16,9 @@ import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
)
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
+68 -1
View File
@@ -1,12 +1,16 @@
package httpapi
import (
"context"
"errors"
"io"
"math"
"net"
"net/http"
"strconv"
"strings"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
)
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
@@ -21,6 +25,15 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
if !ok {
return unauthorized()
}
allowed, retryAfter, err := s.loginLimiter.Allow(r.Context(), username, loginSource(r))
if err != nil {
return unavailable()
}
if !allowed {
retrySeconds := max(int64(1), int64(math.Ceil(retryAfter.Seconds())))
w.Header().Set("Retry-After", strconv.FormatInt(retrySeconds, 10))
return rateLimited()
}
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
if errors.Is(err, model.ErrNotFound) {
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
@@ -38,6 +51,9 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
if !verified {
return unauthorized()
}
if rehashErr := s.rehashPassword(r.Context(), credentials, passwordValue); rehashErr != nil {
return rehashErr
}
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
if err != nil {
return unavailable()
@@ -51,6 +67,57 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
return nil
}
func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCredentials, passwordValue string) *apiError {
needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash)
if err != nil {
return internalError()
}
if !needsRehash {
return nil
}
passwordHash, err := s.passwords.Hash(passwordValue)
if err != nil {
return internalError()
}
updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash)
if err != nil {
return unavailable()
}
if updated {
return nil
}
current, err := s.userRepository.UserByUsername(ctx, credentials.Username)
if errors.Is(err, model.ErrNotFound) {
return unauthorized()
}
if err != nil {
return unavailable()
}
verified, err := s.passwords.Verify(passwordValue, current.PasswordHash)
if err != nil {
return internalError()
}
if !verified {
return unauthorized()
}
return nil
}
func loginSource(r *http.Request) string {
forwarded := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
// Nginx appends the address it observed last, so preceding client-supplied entries are not trusted.
if address := net.ParseIP(strings.TrimSpace(forwarded[len(forwarded)-1])); address != nil {
return address.String()
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
if address := net.ParseIP(host); address != nil {
return address.String()
}
}
return "unknown"
}
func singleBasicAuth(r *http.Request) (string, string, bool) {
if len(r.Header.Values("Authorization")) != 1 {
return "", "", false
+4
View File
@@ -36,6 +36,10 @@ func unauthorized() *apiError {
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
}
func rateLimited() *apiError {
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "too many requests"}
}
func notFound() *apiError {
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
}
+4 -1
View File
@@ -9,7 +9,7 @@ import (
"time"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
@@ -32,12 +32,15 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.database.Ping(ctx); err != nil {
s.logger.ErrorContext(ctx, "readiness dependency failed", "dependency", "postgres", "error", err)
return unavailable()
}
if err := s.sessions.Ping(ctx); err != nil {
s.logger.ErrorContext(ctx, "readiness dependency failed", "dependency", "valkey", "error", err)
return unavailable()
}
if err := s.objects.Ping(ctx); err != nil {
s.logger.ErrorContext(ctx, "readiness dependency failed", "dependency", "s3", "error", err)
return unavailable()
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
@@ -4,14 +4,15 @@ import (
"context"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
)
type UserRepository interface {
CreateUser(context.Context, string, string, string) (model.User, error)
UserByID(context.Context, string) (model.User, error)
UserByUsername(context.Context, string) (model.UserCredentials, error)
UpdatePasswordHash(context.Context, string, string, string) (bool, error)
}
type ChatRepository interface {
@@ -45,5 +46,10 @@ type SessionStore interface {
type PasswordService interface {
Hash(string) (string, error)
Verify(string, string) (bool, error)
NeedsRehash(string) (bool, error)
DummyHash() string
}
type LoginLimiter interface {
Allow(context.Context, string, string) (bool, time.Duration, error)
}
+1 -1
View File
@@ -1,7 +1,7 @@
package httpapi
import (
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"github.com/google/uuid"
)
-3
View File
@@ -14,9 +14,6 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
handler = s.live
case "/health/ready":
handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users":
handler = s.users
case "/api/v1/users/me":
+38 -12
View File
@@ -15,20 +15,21 @@ import (
semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
"go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
)
type Dependencies struct {
Users UserRepository
Chats ChatRepository
Messages MessageRepository
Attachments AttachmentService
Sessions SessionStore
Passwords PasswordService
Database HealthChecker
Objects HealthChecker
Meter metric.Meter
Metrics http.Handler
Users UserRepository
Chats ChatRepository
Messages MessageRepository
Attachments AttachmentService
Sessions SessionStore
Passwords PasswordService
LoginLimiter LoginLimiter
Database HealthChecker
Objects HealthChecker
Meter metric.Meter
Metrics http.Handler
}
type Config struct {
@@ -46,6 +47,7 @@ type Server struct {
attachments AttachmentService
sessions SessionStore
passwords PasswordService
loginLimiter LoginLimiter
database HealthChecker
objects HealthChecker
sessionTTL time.Duration
@@ -77,7 +79,8 @@ func NewServer(
userRepository: dependencies.Users, chatRepository: dependencies.Chats,
messageRepository: dependencies.Messages,
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
passwords: dependencies.Passwords, loginLimiter: dependencies.LoginLimiter,
database: dependencies.Database, objects: dependencies.Objects,
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort,
metrics: newMetrics(dependencies.Meter, dependencies.Metrics),
@@ -94,6 +97,29 @@ func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve)
}
func (s *Server) HealthHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/health/live", func(w http.ResponseWriter, r *http.Request) {
s.serveHealth(w, r, s.live)
})
mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
s.serveHealth(w, r, s.readiness)
})
return mux
}
func (s *Server) MetricsHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/metrics", s.metrics.handler)
return mux
}
func (s *Server) serveHealth(w http.ResponseWriter, r *http.Request, handler requestHandler) {
if err := handler(w, r); err != nil {
writeError(w, "", err)
}
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
tracer := otel.Tracer("messenger-api/http")
+141 -16
View File
@@ -14,8 +14,8 @@ import (
"github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
)
var errDependency = errors.New("dependency unavailable")
@@ -34,14 +34,15 @@ func (s *MessengerSuite) SetupTest() {
}
type messengerStoreStub struct {
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
updatePasswordHash func(context.Context, string, string, string) (bool, error)
}
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
@@ -54,6 +55,12 @@ func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
return s.credentials, s.credentialsErr
}
func (s messengerStoreStub) UpdatePasswordHash(ctx context.Context, userID, previousHash, passwordHash string) (bool, error) {
if s.updatePasswordHash == nil {
return false, nil
}
return s.updatePasswordHash(ctx, userID, previousHash, passwordHash)
}
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
return model.Chat{}, nil
}
@@ -109,15 +116,37 @@ func (s sessionStub) UserID(context.Context, string) (string, error) { return s.
func (sessionStub) Delete(context.Context, string) error { return nil }
type passwordsStub struct {
verified bool
err error
verified bool
err error
hash string
hashErr error
needsRehash bool
needsRehashErr error
}
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
func (passwordsStub) DummyHash() string { return "hash" }
func (s passwordsStub) Hash(string) (string, error) {
if s.hash == "" {
return "hash", s.hashErr
}
return s.hash, s.hashErr
}
func (passwordsStub) DummyHash() string { return "hash" }
func (s passwordsStub) Verify(string, string) (bool, error) {
return s.verified, s.err
}
func (s passwordsStub) NeedsRehash(string) (bool, error) {
return s.needsRehash, s.needsRehashErr
}
type loginLimiterStub struct {
allowed bool
retryAfter time.Duration
err error
}
func (s loginLimiterStub) Allow(context.Context, string, string) (bool, time.Duration, error) {
return s.allowed, s.retryAfter, s.err
}
func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
t := s.T()
@@ -135,7 +164,7 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{})
response := serveRequest(server, http.MethodGet, "/health/ready", "")
response := serveHealthRequest(server, http.MethodGet, "/health/ready")
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
@@ -143,6 +172,29 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
}
}
func (s *MessengerSuite) TestHealthHandlerDoesNotExposeBusinessAPI() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveHealthRequest(server, http.MethodGet, "/api/v1/users/me")
s.Equal(http.StatusNotFound, response.Code)
}
func (s *MessengerSuite) TestMetricsHandlerOnlyExposesMetrics() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
server.metrics.handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
metrics := httptest.NewRecorder()
server.MetricsHandler().ServeHTTP(metrics, httptest.NewRequest(http.MethodGet, "/metrics", nil))
s.Equal(http.StatusNoContent, metrics.Code)
for _, path := range []string{"/health/ready", "/api/v1/users/me"} {
response := httptest.NewRecorder()
server.MetricsHandler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
s.Equal(http.StatusNotFound, response.Code, path)
}
s.Equal(http.StatusNotFound, serveRequest(server, http.MethodGet, "/metrics", "").Code)
}
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
t := s.T()
tests := []struct {
@@ -187,6 +239,48 @@ func (s *MessengerSuite) TestAuthenticationChallenges() {
}
}
func (s *MessengerSuite) TestSessionCreationReturnsRateLimitWithRetryAfter() {
server := s.serverWithLoginLimiter(
messengerStoreStub{}, sessionStub{}, passwordsStub{},
loginLimiterStub{retryAfter: 1500 * time.Millisecond},
)
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("student", "T3st-password-123")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
s.Equal(http.StatusTooManyRequests, response.Code)
s.Equal("2", response.Header().Get("Retry-After"))
s.Contains(response.Body.String(), `"code":"rate_limited"`)
}
func (s *MessengerSuite) TestSessionCreationRehashesPasswordWithCompareAndSwap() {
var updated []string
store := messengerStoreStub{
credentials: model.UserCredentials{User: model.User{ID: "user-id"}, PasswordHash: "old-hash"},
updatePasswordHash: func(_ context.Context, userID, previousHash, passwordHash string) (bool, error) {
updated = []string{userID, previousHash, passwordHash}
return true, nil
},
}
server := s.newTestServer(store, sessionStub{}, passwordsStub{
verified: true, needsRehash: true, hash: "new-hash",
})
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("student", "T3st-password-123")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
s.Equal(http.StatusCreated, response.Code)
s.Equal([]string{"user-id", "old-hash", "new-hash"}, updated)
}
func (s *MessengerSuite) TestLoginSourceUsesAddressAppendedByIngress() {
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.Header.Set("X-Forwarded-For", "203.0.113.9, 198.51.100.7")
s.Equal("198.51.100.7", loginSource(request))
}
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveRequest(
@@ -357,10 +451,34 @@ func (s *MessengerSuite) server(
passwords PasswordService,
objects objectStoreStub,
attachments AttachmentService,
) *Server {
return s.serverWithDependencies(
store, sessions, passwords, loginLimiterStub{allowed: true}, objects, attachments,
)
}
func (s *MessengerSuite) serverWithLoginLimiter(
store messengerStoreStub,
sessions SessionStore,
passwords PasswordService,
limiter LoginLimiter,
) *Server {
return s.serverWithDependencies(
store, sessions, passwords, limiter, objectStoreStub{}, attachmentServiceStub{},
)
}
func (s *MessengerSuite) serverWithDependencies(
store messengerStoreStub,
sessions SessionStore,
passwords PasswordService,
limiter LoginLimiter,
objects objectStoreStub,
attachments AttachmentService,
) *Server {
return NewServer(s.logger, Dependencies{
Users: store, Chats: store, Messages: store, Attachments: attachments,
Sessions: sessions, Passwords: passwords, Database: store, Objects: objects,
Sessions: sessions, Passwords: passwords, LoginLimiter: limiter, Database: store, Objects: objects,
}, Config{
SessionTTL: time.Hour, IdempotencyTTL: 24 * time.Hour, RequestTTL: time.Second,
InstanceID: "test-instance", SwaggerPort: "8081",
@@ -376,3 +494,10 @@ func serveRequest(server *Server, method, path, body string) *httptest.ResponseR
server.Handler().ServeHTTP(response, request)
return response
}
func serveHealthRequest(server *Server, method, path string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, nil)
response := httptest.NewRecorder()
server.HealthHandler().ServeHTTP(response, request)
return response
}