refactor(collab): remove live document collaboration and enforce strictly read-only sharing
MindSift CI & Docker Release / Build, Test in Container & Push (push) Successful in 1m2s

This commit is contained in:
sandrodach committed 2026-10-27 17:08:38 +01:00
1 parent aea05e868a
commit 04fa774d10
16 files changed
+179 -3556

No files matched your search

-295
View File
@@ -31,9 +31,6 @@ type Server struct {
}
func NewServer(cfg *config.Config, store *storage.Store, wsHub *ws.Hub, staticFS fs.FS) *Server {
if wsHub != nil && store != nil {
wsHub.SetDocStore(store)
}
srv := &Server{
cfg: cfg,
store: store,
@@ -70,7 +67,6 @@ func (s *Server) Router() http.Handler {
r.Get("/api/v1/ws", s.handleWebSocket)
r.Get("/api/v1/ws/spaces/{spaceId}", s.handleWebSocket)
r.Get("/api/v1/ws/lists/{listId}", s.handleWebSocket)
r.Get("/api/v1/ws/docs/{id}", s.handleDocWebSocket)
r.Get("/api/v1/events", s.handleSSE)
r.Post("/api/v1/events/rooms", s.handleSSERooms)
@@ -145,13 +141,6 @@ func (s *Server) Router() http.Handler {
r.Post("/api/v1/documents/{id}/shares", s.handleCreateDocShare)
r.Delete("/api/v1/documents/{id}/shares/{userId}", s.handleDeleteDocShare)
// Document Locks & Live-Collaboration Sessions
r.Get("/api/v1/documents/{id}/locks", s.handleGetDocLocks)
r.Post("/api/v1/documents/{id}/blocks/{blockId}/lock", s.handleLockBlock)
r.Post("/api/v1/documents/{id}/blocks/{blockId}/unlock", s.handleUnlockBlock)
r.Post("/api/v1/documents/{id}/live/start", s.handleStartLiveSession)
r.Post("/api/v1/documents/{id}/live/end", s.handleEndLiveSession)
// Shared Lists & Realtime Collaboration
r.Get("/api/v1/lists", s.handleGetAllLists)
r.Post("/api/v1/lists", s.handleCreateList)
@@ -918,18 +907,6 @@ func (s *Server) handleGetDocument(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "Dokument nicht gefunden")
return
}
if s.wsHub != nil {
if liveTitle, liveBlocks, ok := s.wsHub.GetActiveDocState(docID); ok {
if liveTitle != "" {
doc.Title = liveTitle
}
if len(liveBlocks) > 0 {
doc.Blocks = liveBlocks
doc.MarkdownCache = domain.CompileBlocksToMarkdown(liveBlocks)
doc.Content = doc.MarkdownCache
}
}
}
writeJSON(w, http.StatusOK, doc)
}
@@ -937,19 +914,6 @@ func (s *Server) handleUpdateDocument(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
if s.wsHub != nil {
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusLocked)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
"lockedBy": ls.InitiatorName,
"isLocked": true,
})
return
}
}
var req struct {
Title *string `json:"title"`
Icon *string `json:"icon"`
@@ -968,9 +932,6 @@ func (s *Server) handleUpdateDocument(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if s.wsHub != nil && (req.Title != nil || req.Blocks != nil) {
s.wsHub.SyncActiveDocRoom(docID, doc.Title, doc.Blocks)
}
if req.Title != nil || req.Icon != nil || req.FolderPath != nil || req.Blocks != nil || req.Tags != nil {
s.broadcastDocToAuthorizedUsers(docID, "DOC_UPDATED")
}
@@ -981,19 +942,6 @@ func (s *Server) handlePatchDocumentBlocks(w http.ResponseWriter, r *http.Reques
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
if s.wsHub != nil {
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusLocked)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
"lockedBy": ls.InitiatorName,
"isLocked": true,
})
return
}
}
var req domain.DocBlocksPatchRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
@@ -1005,9 +953,6 @@ func (s *Server) handlePatchDocumentBlocks(w http.ResponseWriter, r *http.Reques
writeError(w, http.StatusBadRequest, err.Error())
return
}
if s.wsHub != nil {
s.wsHub.SyncActiveDocRoom(docID, doc.Title, doc.Blocks)
}
patchEvent := domain.DocBlocksPatchEvent{
DocID: docID,
@@ -1032,9 +977,6 @@ func (s *Server) handleDeleteDocument(w http.ResponseWriter, r *http.Request) {
docID := chi.URLParam(r, "id")
authorizedUsers, _ := s.store.GetAuthorizedDocUsers(docID)
if s.wsHub != nil {
s.wsHub.CloseDocRoom(docID)
}
if err := s.store.DeleteDocument(userID, docID); err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
@@ -1090,7 +1032,6 @@ func (s *Server) handleDeleteFolder(w http.ResponseWriter, r *http.Request) {
}
for _, docID := range deletedDocIDs {
s.wsHub.ReleaseDocLock(docID, userID, true)
s.wsHub.BroadcastDocEvent(docID, "DOC_DELETED", map[string]string{"id": docID})
}
s.wsHub.BroadcastDocEvent("", "WORKSPACE_FOLDERS_UPDATED", map[string]string{"path": folderPath})
@@ -1421,202 +1362,6 @@ func (s *Server) handleGetCollaborators(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, users)
}
// --- DOCUMENT LOCKS & LIVE COLLABORATION SESSIONS ---
func (s *Server) handleGetDocLocks(w http.ResponseWriter, r *http.Request) {
docID := chi.URLParam(r, "id")
var blockLocks []domain.BlockLockInfo
var liveSession *domain.LiveSessionInfo
if s.wsHub != nil {
blockLocks = s.wsHub.GetDocBlockLocks(docID)
liveSession = s.wsHub.GetLiveSession(docID)
}
if blockLocks == nil {
blockLocks = []domain.BlockLockInfo{}
}
writeJSON(w, http.StatusOK, domain.DocLocksResponse{
DocID: docID,
BlockLocks: blockLocks,
LiveSession: liveSession,
})
}
func (s *Server) handleLockBlock(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
blockID := chi.URLParam(r, "blockId")
// If live session is active by someone else, reject
if s.wsHub != nil {
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusLocked)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
"lockedBy": ls.InitiatorName,
"isLocked": true,
})
return
}
}
user, _ := s.store.GetUserByID(userID)
userName := "Anonym"
userColor := "#3b82f6"
if user != nil {
if user.DisplayName != "" {
userName = user.DisplayName
} else {
userName = user.Username
}
}
var req struct {
UserColor string `json:"userColor"`
TTLSeconds int `json:"ttlSeconds"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
if req.UserColor != "" {
userColor = req.UserColor
}
ttl := 30 * time.Second
if req.TTLSeconds > 5 && req.TTLSeconds <= 120 {
ttl = time.Duration(req.TTLSeconds) * time.Second
}
if s.wsHub != nil {
lockInfo, ok, existing := s.wsHub.AcquireBlockLock(docID, blockID, userID, userName, userColor, ttl)
if !ok && existing != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Block ist von anderem Benutzer gesperrt",
"lockedBy": existing.UserName,
"lock": existing,
})
return
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_BLOCK_LOCKED", lockInfo, nil)
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
for _, uid := range users {
s.wsHub.BroadcastToUser(uid, "DOC_BLOCK_LOCKED", lockInfo)
}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"success": true,
"lock": lockInfo,
"docId": lockInfo.DocID,
"blockId": lockInfo.BlockID,
"userId": lockInfo.UserID,
"userName": lockInfo.UserName,
"userColor": lockInfo.UserColor,
"expiresAt": lockInfo.ExpiresAt,
})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
func (s *Server) handleUnlockBlock(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
blockID := chi.URLParam(r, "blockId")
if s.wsHub != nil {
released := s.wsHub.ReleaseBlockLock(docID, blockID, userID)
if released {
evt := map[string]string{
"docId": docID,
"blockId": blockID,
"userId": userID,
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_BLOCK_UNLOCKED", evt, nil)
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
for _, uid := range users {
s.wsHub.BroadcastToUser(uid, "DOC_BLOCK_UNLOCKED", evt)
}
}
}
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
func (s *Server) handleStartLiveSession(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
user, _ := s.store.GetUserByID(userID)
userName := "Anonym"
if user != nil {
if user.DisplayName != "" {
userName = user.DisplayName
} else {
userName = user.Username
}
}
ttl := 60 * time.Second // 1 min lease with heartbeat while active
if s.wsHub != nil {
info, ok, existing := s.wsHub.StartLiveSession(docID, userID, userName, ttl)
if !ok && existing != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Live-Sitzung bereits von anderem Benutzer aktiv",
"session": existing,
"initiator": existing.InitiatorName,
})
return
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_LIVE_STARTED", info, nil)
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
for _, uid := range users {
s.wsHub.BroadcastToUser(uid, "DOC_LIVE_STARTED", info)
}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"success": true,
"session": info,
"docId": info.DocID,
"initiatorId": info.InitiatorID,
"initiatorName": info.InitiatorName,
"startedAt": info.StartedAt,
"expiresAt": info.ExpiresAt,
})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
func (s *Server) handleEndLiveSession(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
doc, _ := s.store.GetDocumentByID(userID, docID)
isOwner := doc != nil && (doc.IsOwner || doc.Permission == "owner" || doc.UserID == userID)
if s.wsHub != nil {
if isOwner {
s.wsHub.ForceEndLiveSession(docID)
} else {
s.wsHub.EndLiveSession(docID, userID)
}
evt := map[string]string{
"docId": docID,
"userId": userID,
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_LIVE_ENDED", evt, nil)
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
for _, uid := range users {
s.wsHub.BroadcastToUser(uid, "DOC_LIVE_ENDED", evt)
}
}
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
// --- DOCUMENT REALTIME WEBSOCKET ROOM ---
func (s *Server) authenticateUserFromReq(r *http.Request) string {
token := r.URL.Query().Get("token")
if token == "" {
@@ -1643,46 +1388,6 @@ func (s *Server) authenticateUserFromReq(r *http.Request) string {
return ""
}
// GET /api/v1/ws/docs/{id}
func (s *Server) handleDocWebSocket(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Sec-Websocket-Key") != "" {
if !strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade") {
r.Header.Set("Connection", "Upgrade")
}
if !strings.Contains(strings.ToLower(r.Header.Get("Upgrade")), "websocket") {
r.Header.Set("Upgrade", "websocket")
}
}
docID := chi.URLParam(r, "id")
if docID == "" {
writeError(w, http.StatusBadRequest, "docId erforderlich")
return
}
userID := s.authenticateUserFromReq(r)
if userID == "" {
userID = auth.GetUserID(r.Context())
}
if userID == "" {
userID = "anonymous"
}
canWrite := false
if userID != "anonymous" {
doc, err := s.store.GetDocumentByID(userID, docID)
if err != nil {
writeError(w, http.StatusForbidden, "Kein Zugriff auf dieses Dokument")
return
}
canWrite = doc.IsOwner || doc.Permission == "owner" || doc.Permission == "write"
}
clientID := r.URL.Query().Get("clientId")
room := s.wsHub.GetOrCreateDocRoom(docID)
room.ServeDocWS(w, r, userID, clientID, canWrite)
}
// --- REALTIME LISTS & SHARING ---
func (s *Server) handleGetAllLists(w http.ResponseWriter, r *http.Request) {
+29 -163
View File
@@ -841,93 +841,6 @@ func TestWebhookTriageBadgeAndIngestion(t *testing.T) {
}
}
func TestDocRoomLiveStateAndDebouncedFlush(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "docroom_test.db")
store, err := storage.NewStore(dbPath)
if err != nil {
t.Fatalf("NewStore failed: %v", err)
}
defer store.Close()
cfg := &config.Config{
JWTSecret: "test-jwt-secret-key",
AllowRegistration: true,
}
hub := ws.NewHub()
srv := NewServer(cfg, store, hub, nil)
router := srv.Router()
user, err := store.CreateUser("outliner_ws@example.com", "hash", "WS Outliner User", "member")
if err != nil {
t.Fatalf("CreateUser failed: %v", err)
}
token, _ := auth.GenerateToken(cfg.JWTSecret, user.ID, user.Email, user.Role, user.TokenVersion)
doc, err := store.CreateDocument(user.ID, "", "Initial Title", "📄", "", nil, nil, false)
if err != nil {
t.Fatalf("CreateDocument failed: %v", err)
}
// 1. Mutate in-memory DocRoom before 1.5s flush fires
room := hub.GetOrCreateDocRoom(doc.ID)
newContent := "Live RAM Block #ramtag"
newLevel := 1
room.HandleEvent(ws.DocSyncEvent{
Type: "title_updated",
ClientID: "cli_1",
Title: "RAM Updated Title",
}, nil)
room.HandleEvent(ws.DocSyncEvent{
Type: "block_created",
ClientID: "cli_1",
AfterBlockID: doc.Blocks[0].ID,
Block: &domain.DocumentBlock{
ID: "blk_ram_2",
Type: "text",
Content: newContent,
Level: newLevel,
},
}, nil)
// 2. Verify GET /api/v1/documents/{id} immediately returns the un-flushed in-memory state
req := httptest.NewRequest(http.MethodGet, "/api/v1/documents/"+doc.ID, nil)
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200 OK from GET document, got %d: %s", rec.Code, rec.Body.String())
}
var liveDoc domain.Document
_ = json.Unmarshal(rec.Body.Bytes(), &liveDoc)
if liveDoc.Title != "RAM Updated Title" {
t.Fatalf("expected live RAM title 'RAM Updated Title', got '%s'", liveDoc.Title)
}
if len(liveDoc.Blocks) != 2 || liveDoc.Blocks[1].Content != newContent {
t.Fatalf("expected 2 live blocks with RAM content, got %+v", liveDoc.Blocks)
}
// 3. Flush room to SQLite and verify persistence + tag extraction + markdown_cache
room.Flush()
persistedDoc, err := store.GetDocumentByID(user.ID, doc.ID)
if err != nil {
t.Fatalf("GetDocumentByID failed: %v", err)
}
if persistedDoc.Title != "RAM Updated Title" {
t.Fatalf("expected persisted title 'RAM Updated Title', got '%s'", persistedDoc.Title)
}
if !strings.Contains(persistedDoc.MarkdownCache, " - Live RAM Block #ramtag") {
t.Fatalf("expected compiled markdown_cache to contain indented bullet, got:\n%s", persistedDoc.MarkdownCache)
}
tags, _ := store.GetWorkspaceTags(user.ID)
if len(tags) != 1 || tags[0].Tag != "ramtag" {
t.Fatalf("expected extracted #ramtag in block_tags, got %+v", tags)
}
}
func TestSSEGlobalEndpoint(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test_sse.db")
store, err := storage.NewStore(dbPath)
@@ -1295,94 +1208,54 @@ func TestTokenBlacklistingAndTokenVersionRevocation(t *testing.T) {
}
}
func TestBlockLockingAndLiveSessionGuards(t *testing.T) {
func TestDocumentSharingStrictlyReadOnly(t *testing.T) {
srv, store, _ := setupTestServer(t)
router := srv.Router()
userA, _ := store.CreateUser("user_a_lock@example.com", "hash", "User A", "member")
userA, _ := store.CreateUser("user_a_ro@example.com", "hash", "User A", "member")
tokenA, _ := auth.GenerateToken(srv.cfg.JWTSecret, userA.ID, userA.Email, userA.DisplayName, userA.TokenVersion)
userB, _ := store.CreateUser("user_b_lock@example.com", "hash", "User B", "member")
userB, _ := store.CreateUser("user_b_ro@example.com", "hash", "User B", "member")
tokenB, _ := auth.GenerateToken(srv.cfg.JWTSecret, userB.ID, userB.Email, userB.DisplayName, userB.TokenVersion)
// Create document owned by User A, shared with User B
// Create document owned by User A
blocks := []domain.DocumentBlock{
{ID: "b1", Type: "bullet", Content: "Row 1", Level: 0},
{ID: "b2", Type: "bullet", Content: "Row 2", Level: 0},
}
doc, err := store.CreateDocument(userA.ID, "", "Lock Test Doc", "📝", "", blocks, nil, false)
doc, err := store.CreateDocument(userA.ID, "", "Read Only Test Doc", "📝", "", blocks, nil, false)
if err != nil {
t.Fatalf("CreateDocument failed: %v", err)
}
_, _ = store.CreateDocShare(userA.ID, doc.ID, userB.ID, "write")
// 1. Initial locks should be empty
req := httptest.NewRequest(http.MethodGet, "/api/v1/documents/"+doc.ID+"/locks", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
// Share with User B (forced read-only)
_, err = store.CreateDocShare(userA.ID, doc.ID, userB.ID, "read")
if err != nil {
t.Fatalf("CreateDocShare failed: %v", err)
}
// 1. User B can read document
req := httptest.NewRequest(http.MethodGet, "/api/v1/documents/"+doc.ID, nil)
req.Header.Set("Authorization", "Bearer "+tokenB)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("get locks failed: %d", rec.Code)
}
var locksResp domain.DocLocksResponse
_ = json.Unmarshal(rec.Body.Bytes(), &locksResp)
if len(locksResp.BlockLocks) != 0 || locksResp.LiveSession != nil {
t.Fatalf("expected 0 locks initially, got %v", locksResp)
t.Fatalf("User B should be able to read doc, got status: %d", rec.Code)
}
// 2. User A locks block b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
req.Header.Set("Authorization", "Bearer "+tokenA)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A lock b1 failed: %d, body: %s", rec.Code, rec.Body.String())
}
// 3. User B tries to lock b1 -> must receive 409 Conflict
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
// 2. User B tries to update document via PUT -> must fail (not owner)
newTitle := "Hacked Title"
updateBody, _ := json.Marshal(map[string]interface{}{"title": newTitle})
req = httptest.NewRequest(http.MethodPut, "/api/v1/documents/"+doc.ID, bytes.NewReader(updateBody))
req.Header.Set("Authorization", "Bearer "+tokenB)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict for user B on b1, got %d", rec.Code)
if rec.Code == http.StatusOK {
t.Fatalf("expected error for User B updating document, got 200 OK")
}
// 4. User A unlocks b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/unlock", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A unlock b1 failed: %d", rec.Code)
}
// 5. User B can now lock b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
req.Header.Set("Authorization", "Bearer "+tokenB)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user B lock b1 should succeed now, got %d", rec.Code)
}
// User B unlocks b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/unlock", nil)
req.Header.Set("Authorization", "Bearer "+tokenB)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
// 6. User A starts a Live-Session on doc
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/live/start", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A start live session failed: %d, body: %s", rec.Code, rec.Body.String())
}
// 7. User B tries to patch document blocks while User A's live session is active -> must receive 423 Locked!
// 3. User B tries to patch document blocks -> must fail (not owner)
patchBody, _ := json.Marshal(domain.DocBlocksPatchRequest{
Upserted: []domain.DocumentBlock{{ID: "b2", Content: "Hacked by User B"}},
})
@@ -1391,27 +1264,20 @@ func TestBlockLockingAndLiveSessionGuards(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusLocked {
t.Fatalf("expected 423 Locked for User B while live session is active, got %d, body: %s", rec.Code, rec.Body.String())
if rec.Code == http.StatusOK {
t.Fatalf("expected error for User B patching document blocks, got 200 OK")
}
// 8. User A ends the Live-Session
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/live/end", nil)
// 4. User A (owner) can successfully update document
ownerTitle := "Owner Updated Title"
ownerBody, _ := json.Marshal(map[string]interface{}{"title": ownerTitle})
req = httptest.NewRequest(http.MethodPut, "/api/v1/documents/"+doc.ID, bytes.NewReader(ownerBody))
req.Header.Set("Authorization", "Bearer "+tokenA)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A end live session failed: %d", rec.Code)
}
// 9. User B can now edit again
req = httptest.NewRequest(http.MethodPatch, "/api/v1/documents/"+doc.ID+"/blocks", bytes.NewReader(patchBody))
req.Header.Set("Authorization", "Bearer "+tokenB)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("User B edit should succeed after live session ended, got %d, body: %s", rec.Code, rec.Body.String())
t.Fatalf("owner should be able to update document, got %d", rec.Code)
}
}