veza/veza-backend-api/internal/handlers/room_handler.go

674 lines
23 KiB
Go
Raw Normal View History

2025-12-03 19:29:37 +00:00
package handlers
import (
"context"
"errors"
2025-12-03 19:29:37 +00:00
"net/http"
"strconv"
apperrors "veza-backend-api/internal/errors"
2025-12-03 19:29:37 +00:00
"veza-backend-api/internal/services"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.uber.org/zap"
)
// RoomServiceInterface defines the interface for room service operations
type RoomServiceInterface interface {
CreateRoom(ctx context.Context, userID uuid.UUID, req services.CreateRoomRequest) (*services.RoomResponse, error)
GetUserRooms(ctx context.Context, userID uuid.UUID) ([]*services.RoomResponse, error)
GetRoom(ctx context.Context, roomID uuid.UUID) (*services.RoomResponse, error)
fix(v0.12.6.1): remediate 2 CRITICAL + 10 HIGH + 1 MEDIUM pentest findings Security fixes implemented: CRITICAL: - CRIT-001: IDOR on chat rooms — added IsRoomMember check before returning room data or message history (returns 404, not 403) - CRIT-002: play_count/like_count exposed publicly — changed JSON tags to "-" so they are never serialized in API responses HIGH: - HIGH-001: TOCTOU race on marketplace downloads — transaction + SELECT FOR UPDATE on GetDownloadURL - HIGH-002: HS256 in production docker-compose — replaced JWT_SECRET with JWT_PRIVATE_KEY_PATH / JWT_PUBLIC_KEY_PATH (RS256) - HIGH-003: context.Background() bypass in user repository — full context propagation from handlers → services → repository (29 files) - HIGH-004: Race condition on promo codes — SELECT FOR UPDATE - HIGH-005: Race condition on exclusive licenses — SELECT FOR UPDATE - HIGH-006: Rate limiter IP spoofing — SetTrustedProxies(nil) default - HIGH-007: RGPD hard delete incomplete — added cleanup for sessions, settings, follows, notifications, audit_logs anonymization - HIGH-008: RTMP callback auth weak — fail-closed when unconfigured, header-only (no query param), constant-time compare - HIGH-009: Co-listening host hijack — UpdateHostState now takes *Conn and verifies IsHost before processing - HIGH-010: Moderator self-strike — added issuedBy != userID check MEDIUM: - MEDIUM-001: Recovery codes used math/rand — replaced with crypto/rand - MEDIUM-005: Stream token forgeable — resolved by HIGH-002 (RS256) Updated REMEDIATION_MATRIX: 14 findings marked ✅ CORRIGÉ. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 04:40:53 +00:00
IsRoomMember(ctx context.Context, roomID uuid.UUID, userID uuid.UUID) (bool, error)
UpdateRoom(ctx context.Context, roomID uuid.UUID, userID uuid.UUID, req services.UpdateRoomRequest) (*services.RoomResponse, error) // BE-API-012: Update room method
AddMember(ctx context.Context, roomID, userID uuid.UUID) error
RemoveMember(ctx context.Context, roomID, userID uuid.UUID) error // BE-API-011: Remove member method
GetRoomHistory(ctx context.Context, roomID uuid.UUID, limit, offset int) ([]services.ChatMessageResponse, error)
GetRoomHistoryWithCursor(ctx context.Context, roomID uuid.UUID, limit int, cursor string) (*services.RoomHistoryWithCursorResult, error) // v0.931: cursor pagination
2026-03-05 22:03:43 +00:00
DeleteRoom(ctx context.Context, roomID uuid.UUID, userID uuid.UUID) error // BE-API-010: Delete room method
2026-03-06 17:52:08 +00:00
GetRoomMembers(ctx context.Context, roomID uuid.UUID, requestUserID uuid.UUID) (*services.RoomMembersResponse, error) // v0.9.6 @mention, v0.9.7 roles
CreateInvitation(ctx context.Context, roomID uuid.UUID, inviterID uuid.UUID) (*services.RoomInvitationResponse, error) // v0.9.7
JoinByToken(ctx context.Context, token uuid.UUID, userID uuid.UUID) (uuid.UUID, error) // v0.9.7
KickMember(ctx context.Context, roomID uuid.UUID, targetUserID uuid.UUID, requestUserID uuid.UUID) error // v0.9.7
2026-03-06 17:58:37 +00:00
UpdateMemberRole(ctx context.Context, roomID, targetUserID, requestUserID uuid.UUID, newRole string) error // v0.9.7
}
2025-12-03 19:29:37 +00:00
// RoomHandler gère les opérations sur les rooms (conversations)
type RoomHandler struct {
roomService RoomServiceInterface
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
logger *zap.Logger
commonHandler *CommonHandler
2025-12-03 19:29:37 +00:00
}
// NewRoomHandler crée une nouvelle instance de RoomHandler
func NewRoomHandler(roomService RoomServiceInterface, logger *zap.Logger) *RoomHandler {
2025-12-03 19:29:37 +00:00
return &RoomHandler{
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
roomService: roomService,
logger: logger,
commonHandler: NewCommonHandler(logger),
2025-12-03 19:29:37 +00:00
}
}
// CreateRoom gère la création d'une nouvelle room
// POST /api/v1/conversations
func (h *RoomHandler) CreateRoom(c *gin.Context) {
// Récupérer l'ID utilisateur du contexte
userIDInterface, exists := c.Get("user_id")
if !exists {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewUnauthorizedError("User not authenticated"))
2025-12-03 19:29:37 +00:00
return
}
// Convertir userID en uuid.UUID
userID, ok := userIDInterface.(uuid.UUID)
if !ok {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalError("Invalid user ID type in context"))
2025-12-03 19:29:37 +00:00
return
}
// Parser la requête
var req services.CreateRoomRequest
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
RespondWithAppError(c, appErr)
2025-12-03 19:29:37 +00:00
return
}
// Valider le type de room si non spécifié
if req.Type == "" {
req.Type = "public"
}
// Créer la room
room, err := h.roomService.CreateRoom(c.Request.Context(), userID, req)
if err != nil {
h.logger.Error("failed to create room",
zap.Error(err),
zap.String("user_id", userID.String()),
zap.String("room_name", req.Name))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to create conversation", err))
2025-12-03 19:29:37 +00:00
return
}
h.logger.Info("room created successfully",
zap.String("room_id", room.ID.String()),
zap.String("user_id", userID.String()),
zap.String("room_name", req.Name))
RespondSuccess(c, http.StatusCreated, room)
2025-12-03 19:29:37 +00:00
}
// GetUserRooms récupère toutes les rooms d'un utilisateur
// GET /api/v1/conversations
func (h *RoomHandler) GetUserRooms(c *gin.Context) {
// Récupérer l'ID utilisateur du contexte
userIDInterface, exists := c.Get("user_id")
if !exists {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewUnauthorizedError("User not authenticated"))
2025-12-03 19:29:37 +00:00
return
}
// Convertir userID en uuid.UUID
userID, ok := userIDInterface.(uuid.UUID)
if !ok {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalError("Invalid user ID type in context"))
2025-12-03 19:29:37 +00:00
return
}
// Récupérer les rooms
rooms, err := h.roomService.GetUserRooms(c.Request.Context(), userID)
if err != nil {
h.logger.Error("failed to get user rooms",
zap.Error(err),
zap.String("user_id", userID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to fetch conversations", err))
2025-12-03 19:29:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, gin.H{
2025-12-03 19:29:37 +00:00
"conversations": rooms,
"total": len(rooms),
})
}
// GetRoom récupère une room par son ID
// GET /api/v1/conversations/:id
fix(v0.12.6.1): remediate 2 CRITICAL + 10 HIGH + 1 MEDIUM pentest findings Security fixes implemented: CRITICAL: - CRIT-001: IDOR on chat rooms — added IsRoomMember check before returning room data or message history (returns 404, not 403) - CRIT-002: play_count/like_count exposed publicly — changed JSON tags to "-" so they are never serialized in API responses HIGH: - HIGH-001: TOCTOU race on marketplace downloads — transaction + SELECT FOR UPDATE on GetDownloadURL - HIGH-002: HS256 in production docker-compose — replaced JWT_SECRET with JWT_PRIVATE_KEY_PATH / JWT_PUBLIC_KEY_PATH (RS256) - HIGH-003: context.Background() bypass in user repository — full context propagation from handlers → services → repository (29 files) - HIGH-004: Race condition on promo codes — SELECT FOR UPDATE - HIGH-005: Race condition on exclusive licenses — SELECT FOR UPDATE - HIGH-006: Rate limiter IP spoofing — SetTrustedProxies(nil) default - HIGH-007: RGPD hard delete incomplete — added cleanup for sessions, settings, follows, notifications, audit_logs anonymization - HIGH-008: RTMP callback auth weak — fail-closed when unconfigured, header-only (no query param), constant-time compare - HIGH-009: Co-listening host hijack — UpdateHostState now takes *Conn and verifies IsHost before processing - HIGH-010: Moderator self-strike — added issuedBy != userID check MEDIUM: - MEDIUM-001: Recovery codes used math/rand — replaced with crypto/rand - MEDIUM-005: Stream token forgeable — resolved by HIGH-002 (RS256) Updated REMEDIATION_MATRIX: 14 findings marked ✅ CORRIGÉ. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 04:40:53 +00:00
// SECURITY(CRIT-001): Verify membership before returning room data
2025-12-03 19:29:37 +00:00
func (h *RoomHandler) GetRoom(c *gin.Context) {
// Récupérer l'ID de la room depuis l'URL
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid room ID"))
2025-12-03 19:29:37 +00:00
return
}
fix(v0.12.6.1): remediate 2 CRITICAL + 10 HIGH + 1 MEDIUM pentest findings Security fixes implemented: CRITICAL: - CRIT-001: IDOR on chat rooms — added IsRoomMember check before returning room data or message history (returns 404, not 403) - CRIT-002: play_count/like_count exposed publicly — changed JSON tags to "-" so they are never serialized in API responses HIGH: - HIGH-001: TOCTOU race on marketplace downloads — transaction + SELECT FOR UPDATE on GetDownloadURL - HIGH-002: HS256 in production docker-compose — replaced JWT_SECRET with JWT_PRIVATE_KEY_PATH / JWT_PUBLIC_KEY_PATH (RS256) - HIGH-003: context.Background() bypass in user repository — full context propagation from handlers → services → repository (29 files) - HIGH-004: Race condition on promo codes — SELECT FOR UPDATE - HIGH-005: Race condition on exclusive licenses — SELECT FOR UPDATE - HIGH-006: Rate limiter IP spoofing — SetTrustedProxies(nil) default - HIGH-007: RGPD hard delete incomplete — added cleanup for sessions, settings, follows, notifications, audit_logs anonymization - HIGH-008: RTMP callback auth weak — fail-closed when unconfigured, header-only (no query param), constant-time compare - HIGH-009: Co-listening host hijack — UpdateHostState now takes *Conn and verifies IsHost before processing - HIGH-010: Moderator self-strike — added issuedBy != userID check MEDIUM: - MEDIUM-001: Recovery codes used math/rand — replaced with crypto/rand - MEDIUM-005: Stream token forgeable — resolved by HIGH-002 (RS256) Updated REMEDIATION_MATRIX: 14 findings marked ✅ CORRIGÉ. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 04:40:53 +00:00
// SECURITY(CRIT-001): Verify the requesting user is a member of this room
userID, ok := GetUserIDUUID(c)
if !ok {
RespondWithAppError(c, apperrors.NewUnauthorizedError("authentication required"))
return
}
isMember, err := h.roomService.IsRoomMember(c.Request.Context(), roomID, userID)
if err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
h.logger.Error("failed to check room membership",
zap.Error(err),
zap.String("room_id", roomID.String()))
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to get conversation", err))
return
}
if !isMember {
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
2025-12-03 19:29:37 +00:00
// Récupérer la room
room, err := h.roomService.GetRoom(c.Request.Context(), roomID)
if err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
2025-12-03 19:29:37 +00:00
h.logger.Error("failed to get room",
zap.Error(err),
zap.String("room_id", roomID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to get conversation", err))
2025-12-03 19:29:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, room)
2025-12-03 19:29:37 +00:00
}
// UpdateRoom met à jour une room (conversation)
// PUT /api/v1/conversations/:id
// BE-API-012: Implement conversation update endpoint
func (h *RoomHandler) UpdateRoom(c *gin.Context) {
// Récupérer l'ID de la room depuis l'URL
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid room id"))
return
}
// Récupérer l'ID utilisateur du contexte
userID, ok := GetUserIDUUID(c)
if !ok {
return // Erreur déjà envoyée par GetUserIDUUID
}
// Parser la requête
var req services.UpdateRoomRequest
if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
RespondWithAppError(c, appErr)
return
}
// Mettre à jour la room
room, err := h.roomService.UpdateRoom(c.Request.Context(), roomID, userID, req)
if err != nil {
if err.Error() == "room not found" || errors.Is(err, services.ErrRoomNotFound) {
RespondWithAppError(c, apperrors.NewNotFoundError("conversation"))
return
}
if err.Error() == "forbidden: only room creator can update the room" {
RespondWithAppError(c, apperrors.NewForbiddenError("only room creator can update the room"))
return
}
h.logger.Error("failed to update room",
zap.Error(err),
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to update conversation", err))
return
}
h.logger.Info("room updated successfully",
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondSuccess(c, http.StatusOK, room)
}
2025-12-03 19:29:37 +00:00
// AddMemberRequest représente une requête pour ajouter un membre à une room
2025-12-16 18:34:08 +00:00
// MOD-P1-001: Ajout tags validate pour validation systématique
2025-12-03 19:29:37 +00:00
type AddMemberRequest struct {
2025-12-16 18:34:08 +00:00
UserID uuid.UUID `json:"user_id" binding:"required" validate:"required"` // Changed to UUID
2025-12-03 19:29:37 +00:00
}
// AddMember ajoute un membre à une room
// POST /api/v1/conversations/:id/members
func (h *RoomHandler) AddMember(c *gin.Context) {
// Récupérer l'ID de la room depuis l'URL
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid room ID"))
2025-12-03 19:29:37 +00:00
return
}
// Parser la requête
var req AddMemberRequest
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
RespondWithAppError(c, appErr)
2025-12-03 19:29:37 +00:00
return
}
// Ajouter le membre
if err := h.roomService.AddMember(c.Request.Context(), roomID, req.UserID); err != nil {
h.logger.Error("failed to add member to room",
zap.Error(err),
zap.String("room_id", roomID.String()),
zap.String("user_id", req.UserID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to add member", err))
2025-12-03 19:29:37 +00:00
return
}
h.logger.Info("member added to room",
zap.String("room_id", roomID.String()),
zap.String("user_id", req.UserID.String()))
RespondSuccess(c, http.StatusOK, gin.H{"message": "Member added successfully"})
2025-12-03 19:29:37 +00:00
}
// GetRoomHistory récupère l'historique des messages d'une room
// GET /api/v1/conversations/:id/history
// v0.931: Supports cursor-based pagination via ?cursor=xxx&limit=20. Falls back to offset when cursor not provided.
fix(v0.12.6.1): remediate 2 CRITICAL + 10 HIGH + 1 MEDIUM pentest findings Security fixes implemented: CRITICAL: - CRIT-001: IDOR on chat rooms — added IsRoomMember check before returning room data or message history (returns 404, not 403) - CRIT-002: play_count/like_count exposed publicly — changed JSON tags to "-" so they are never serialized in API responses HIGH: - HIGH-001: TOCTOU race on marketplace downloads — transaction + SELECT FOR UPDATE on GetDownloadURL - HIGH-002: HS256 in production docker-compose — replaced JWT_SECRET with JWT_PRIVATE_KEY_PATH / JWT_PUBLIC_KEY_PATH (RS256) - HIGH-003: context.Background() bypass in user repository — full context propagation from handlers → services → repository (29 files) - HIGH-004: Race condition on promo codes — SELECT FOR UPDATE - HIGH-005: Race condition on exclusive licenses — SELECT FOR UPDATE - HIGH-006: Rate limiter IP spoofing — SetTrustedProxies(nil) default - HIGH-007: RGPD hard delete incomplete — added cleanup for sessions, settings, follows, notifications, audit_logs anonymization - HIGH-008: RTMP callback auth weak — fail-closed when unconfigured, header-only (no query param), constant-time compare - HIGH-009: Co-listening host hijack — UpdateHostState now takes *Conn and verifies IsHost before processing - HIGH-010: Moderator self-strike — added issuedBy != userID check MEDIUM: - MEDIUM-001: Recovery codes used math/rand — replaced with crypto/rand - MEDIUM-005: Stream token forgeable — resolved by HIGH-002 (RS256) Updated REMEDIATION_MATRIX: 14 findings marked ✅ CORRIGÉ. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 04:40:53 +00:00
// SECURITY(CRIT-001): Verify membership before returning history
2025-12-03 19:29:37 +00:00
func (h *RoomHandler) GetRoomHistory(c *gin.Context) {
conversationIDStr := c.Param("id")
conversationID, err := uuid.Parse(conversationIDStr)
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid conversation ID"))
2025-12-03 19:29:37 +00:00
return
}
fix(v0.12.6.1): remediate 2 CRITICAL + 10 HIGH + 1 MEDIUM pentest findings Security fixes implemented: CRITICAL: - CRIT-001: IDOR on chat rooms — added IsRoomMember check before returning room data or message history (returns 404, not 403) - CRIT-002: play_count/like_count exposed publicly — changed JSON tags to "-" so they are never serialized in API responses HIGH: - HIGH-001: TOCTOU race on marketplace downloads — transaction + SELECT FOR UPDATE on GetDownloadURL - HIGH-002: HS256 in production docker-compose — replaced JWT_SECRET with JWT_PRIVATE_KEY_PATH / JWT_PUBLIC_KEY_PATH (RS256) - HIGH-003: context.Background() bypass in user repository — full context propagation from handlers → services → repository (29 files) - HIGH-004: Race condition on promo codes — SELECT FOR UPDATE - HIGH-005: Race condition on exclusive licenses — SELECT FOR UPDATE - HIGH-006: Rate limiter IP spoofing — SetTrustedProxies(nil) default - HIGH-007: RGPD hard delete incomplete — added cleanup for sessions, settings, follows, notifications, audit_logs anonymization - HIGH-008: RTMP callback auth weak — fail-closed when unconfigured, header-only (no query param), constant-time compare - HIGH-009: Co-listening host hijack — UpdateHostState now takes *Conn and verifies IsHost before processing - HIGH-010: Moderator self-strike — added issuedBy != userID check MEDIUM: - MEDIUM-001: Recovery codes used math/rand — replaced with crypto/rand - MEDIUM-005: Stream token forgeable — resolved by HIGH-002 (RS256) Updated REMEDIATION_MATRIX: 14 findings marked ✅ CORRIGÉ. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 04:40:53 +00:00
// SECURITY(CRIT-001): Verify the requesting user is a member of this room
userID, ok := GetUserIDUUID(c)
if !ok {
RespondWithAppError(c, apperrors.NewUnauthorizedError("authentication required"))
return
}
isMember, err := h.roomService.IsRoomMember(c.Request.Context(), conversationID, userID)
if err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
h.logger.Error("failed to check room membership",
zap.Error(err),
zap.String("conversation_id", conversationID.String()))
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to get conversation history", err))
return
}
if !isMember {
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
2025-12-03 19:29:37 +00:00
limit := c.DefaultQuery("limit", "50")
limitInt, err := strconv.Atoi(limit)
if err != nil || limitInt <= 0 {
limitInt = 50
}
if limitInt > 100 {
limitInt = 100
}
cursor := c.Query("cursor")
if cursor != "" {
result, err := h.roomService.GetRoomHistoryWithCursor(c.Request.Context(), conversationID, limitInt, cursor)
if err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
h.logger.Error("failed to get room history",
zap.Error(err),
zap.String("conversation_id", conversationID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to get conversation history", err))
return
}
resp := gin.H{"messages": result.Messages}
if result.NextCursor != "" {
resp["next_cursor"] = result.NextCursor
}
RespondSuccess(c, http.StatusOK, resp)
return
}
offset := c.DefaultQuery("offset", "0")
2025-12-03 19:29:37 +00:00
offsetInt, err := strconv.Atoi(offset)
if err != nil || offsetInt < 0 {
offsetInt = 0
}
messages, err := h.roomService.GetRoomHistory(c.Request.Context(), conversationID, limitInt, offsetInt)
if err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
return
}
2025-12-03 19:29:37 +00:00
h.logger.Error("failed to get room history",
zap.Error(err),
zap.String("conversation_id", conversationID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to get conversation history", err))
2025-12-03 19:29:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, gin.H{"messages": messages})
2025-12-03 19:29:37 +00:00
}
// DeleteRoom supprime une room (conversation)
// DELETE /api/v1/conversations/:id
// BE-API-010: Implement conversation delete endpoint
func (h *RoomHandler) DeleteRoom(c *gin.Context) {
// Récupérer l'ID de la room depuis l'URL
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid room id"))
return
}
// Récupérer l'ID utilisateur du contexte
userID, ok := GetUserIDUUID(c)
if !ok {
return // Erreur déjà envoyée par GetUserIDUUID
}
// Supprimer la room
if err := h.roomService.DeleteRoom(c.Request.Context(), roomID, userID); err != nil {
if err.Error() == "room not found" || errors.Is(err, services.ErrRoomNotFound) {
RespondWithAppError(c, apperrors.NewNotFoundError("conversation"))
return
}
if err.Error() == "forbidden: only room creator can delete the room" {
RespondWithAppError(c, apperrors.NewForbiddenError("only room creator can delete the room"))
return
}
h.logger.Error("failed to delete room",
zap.Error(err),
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to delete conversation", err))
return
}
h.logger.Info("room deleted successfully",
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondSuccess(c, http.StatusOK, gin.H{"message": "Conversation deleted successfully"})
}
// AddParticipant ajoute un participant à une conversation
// POST /api/v1/conversations/:id/participants
// BE-API-011: Implement conversation participants endpoints
func (h *RoomHandler) AddParticipant(c *gin.Context) {
// Récupérer l'ID de la room depuis l'URL
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid room id"))
return
}
// Parser la requête
var req AddMemberRequest
if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
RespondWithAppError(c, appErr)
return
}
// Ajouter le participant (utilise la même logique que AddMember)
if err := h.roomService.AddMember(c.Request.Context(), roomID, req.UserID); err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
RespondWithAppError(c, apperrors.NewNotFoundError("conversation"))
return
}
h.logger.Error("failed to add participant to room",
zap.Error(err),
zap.String("room_id", roomID.String()),
zap.String("user_id", req.UserID.String()))
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to add participant", err))
return
}
h.logger.Info("participant added to room",
zap.String("room_id", roomID.String()),
zap.String("user_id", req.UserID.String()))
RespondSuccess(c, http.StatusOK, gin.H{"message": "Participant added successfully"})
}
// RemoveParticipant retire un participant d'une conversation
// DELETE /api/v1/conversations/:id/participants/:userId
// BE-API-011: Implement conversation participants endpoints
func (h *RoomHandler) RemoveParticipant(c *gin.Context) {
// Récupérer l'ID de la room depuis l'URL
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid room id"))
return
}
// Récupérer l'ID de l'utilisateur depuis l'URL
userIDStr := c.Param("userId")
userID, err := uuid.Parse(userIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid user id"))
return
}
// Retirer le participant
if err := h.roomService.RemoveMember(c.Request.Context(), roomID, userID); err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
RespondWithAppError(c, apperrors.NewNotFoundError("conversation"))
return
}
h.logger.Error("failed to remove participant from room",
zap.Error(err),
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to remove participant", err))
return
}
h.logger.Info("participant removed from room",
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondSuccess(c, http.StatusOK, gin.H{"message": "Participant removed successfully"})
}
2026-03-06 09:29:30 +00:00
2026-03-06 17:52:08 +00:00
// CreateInvitation creates a room invitation (v0.9.7)
// POST /api/v1/conversations/:id/invitations
func (h *RoomHandler) CreateInvitation(c *gin.Context) {
userID, ok := GetUserIDUUID(c)
if !ok {
return
}
roomID, err := uuid.Parse(c.Param("id"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid room ID"))
2026-03-06 17:52:08 +00:00
return
}
resp, err := h.roomService.CreateInvitation(c.Request.Context(), roomID, userID)
if err != nil {
if err.Error() == "forbidden: only owner or admin can create invitations" {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewForbiddenError(err.Error()))
2026-03-06 17:52:08 +00:00
return
}
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
2026-03-06 17:52:08 +00:00
return
}
h.logger.Error("failed to create invitation", zap.Error(err), zap.String("room_id", roomID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to create invitation", err))
2026-03-06 17:52:08 +00:00
return
}
RespondSuccess(c, http.StatusCreated, resp)
}
// JoinByToken joins a room via invitation token (v0.9.7)
// GET /api/v1/conversations/join/:token
func (h *RoomHandler) JoinByToken(c *gin.Context) {
userID, ok := GetUserIDUUID(c)
if !ok {
return
}
token, err := uuid.Parse(c.Param("token"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid token"))
2026-03-06 17:52:08 +00:00
return
}
roomID, err := h.roomService.JoinByToken(c.Request.Context(), token, userID)
if err != nil {
if err.Error() == "invitation not found or expired" {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError(err.Error()))
2026-03-06 17:52:08 +00:00
return
}
h.logger.Error("failed to join via token", zap.Error(err), zap.String("token", token.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to join", err))
2026-03-06 17:52:08 +00:00
return
}
RespondSuccess(c, http.StatusOK, gin.H{"room_id": roomID})
}
// KickMember removes a member (owner/admin only) (v0.9.7)
// DELETE /api/v1/conversations/:id/members/:userId
func (h *RoomHandler) KickMember(c *gin.Context) {
requestUserID, ok := GetUserIDUUID(c)
if !ok {
return
}
roomID, err := uuid.Parse(c.Param("id"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid room ID"))
2026-03-06 17:52:08 +00:00
return
}
targetUserID, err := uuid.Parse(c.Param("userId"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid user ID"))
2026-03-06 17:52:08 +00:00
return
}
if err := h.roomService.KickMember(c.Request.Context(), roomID, targetUserID, requestUserID); err != nil {
if err.Error() == "forbidden: only owner or admin can remove members" {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewForbiddenError(err.Error()))
2026-03-06 17:52:08 +00:00
return
}
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
2026-03-06 17:52:08 +00:00
return
}
h.logger.Error("failed to kick member", zap.Error(err), zap.String("room_id", roomID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to remove member", err))
2026-03-06 17:52:08 +00:00
return
}
RespondSuccess(c, http.StatusOK, gin.H{"message": "Member removed successfully"})
}
2026-03-06 17:58:37 +00:00
// LeaveRoom allows a user to leave a conversation (self-removal) (v0.9.7)
// POST /api/v1/conversations/:id/leave
func (h *RoomHandler) LeaveRoom(c *gin.Context) {
userID, ok := GetUserIDUUID(c)
if !ok {
return
}
roomID, err := uuid.Parse(c.Param("id"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid conversation ID"))
2026-03-06 17:58:37 +00:00
return
}
if err := h.roomService.RemoveMember(c.Request.Context(), roomID, userID); err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
2026-03-06 17:58:37 +00:00
return
}
h.logger.Error("failed to leave room",
zap.Error(err),
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to leave conversation", err))
2026-03-06 17:58:37 +00:00
return
}
h.logger.Info("user left room",
zap.String("room_id", roomID.String()),
zap.String("user_id", userID.String()))
RespondSuccess(c, http.StatusOK, gin.H{"message": "Left conversation successfully"})
}
// UpdateMemberRole updates a member's role (v0.9.7). Owner only.
// PATCH /api/v1/conversations/:id/members/:userId
func (h *RoomHandler) UpdateMemberRole(c *gin.Context) {
requestUserID, ok := GetUserIDUUID(c)
if !ok {
return
}
roomID, err := uuid.Parse(c.Param("id"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid conversation ID"))
2026-03-06 17:58:37 +00:00
return
}
targetUserID, err := uuid.Parse(c.Param("userId"))
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid user ID"))
2026-03-06 17:58:37 +00:00
return
}
var req services.UpdateMemberRoleRequest
if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
RespondWithAppError(c, appErr)
return
}
if err := h.roomService.UpdateMemberRole(c.Request.Context(), roomID, targetUserID, requestUserID, req.Role); err != nil {
if err.Error() == "forbidden: only owner can change member roles" ||
err.Error() == "forbidden: cannot change owner role" ||
err.Error() == "forbidden: owner cannot change their own role" ||
err.Error() == "forbidden: cannot promote to owner via this endpoint" {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewForbiddenError(err.Error()))
2026-03-06 17:58:37 +00:00
return
}
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation or member"))
2026-03-06 17:58:37 +00:00
return
}
h.logger.Error("failed to update member role", zap.Error(err))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to update member role", err))
2026-03-06 17:58:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, gin.H{"message": "Member role updated successfully"})
}
2026-03-06 09:29:30 +00:00
// GetMembers returns room members for @mention autocomplete (v0.9.6)
// GET /api/v1/conversations/:id/members
func (h *RoomHandler) GetMembers(c *gin.Context) {
userID, ok := GetUserIDUUID(c)
if !ok {
return
}
roomIDStr := c.Param("id")
roomID, err := uuid.Parse(roomIDStr)
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Invalid room ID"))
2026-03-06 09:29:30 +00:00
return
}
2026-03-06 17:52:08 +00:00
resp, err := h.roomService.GetRoomMembers(c.Request.Context(), roomID, userID)
2026-03-06 09:29:30 +00:00
if err != nil {
if errors.Is(err, services.ErrRoomNotFound) {
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewNotFoundError("Conversation"))
2026-03-06 09:29:30 +00:00
return
}
h.logger.Error("failed to get room members", zap.Error(err), zap.String("room_id", roomID.String()))
2026-03-06 23:54:35 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Failed to get members", err))
2026-03-06 09:29:30 +00:00
return
}
2026-03-06 17:52:08 +00:00
RespondSuccess(c, http.StatusOK, resp)
2026-03-06 09:29:30 +00:00
}