Files
vikunja/pkg/notifications/database.go
T
kolaenteandkolaente 0638200ac0 fix(notifications): check project access when reading notifications
Notification rows outlived access. A subscription survives a project being
unshared, so every notification already written for a revoked user stayed
readable — comment bodies, task titles, project names, deletion notices. The
read paths filtered on notifiable_id alone, with no permission check anywhere.
#3325 stopped the sender writing new ones; this is the other half.

The project a notification is about is persisted on the row when it is written
and the read paths filter on it in SQL, so LIMIT, OFFSET and total are all
computed on the filtered set. Notification types declare their project through
a capability interface in pkg/notifications, the same way they already declare
SubjectID, ThreadID and ToTitle — which is what lets the package below
pkg/models stay ignorant of what a project is.

project_id 0 means account-scoped and always visible, a positive value is
checked against the projects the caller can read, and -1 marks a project-scoped
row whose project could not be determined, so it is visible to nobody. Filtering
reuses the existing accessibleProjectIDsSubquery, so the page query and the
count cannot drift apart. A migration backfills existing rows from their stored
payloads, resolving through soft-deleted tasks so task.deleted rows still land
on their project.

Covers every read path: the v1 and v2 list endpoints, mark-as-read (which
echoes the payload back), the Atom feed, and the websocket push — the last of
which is load-bearing, since a row is still written for a revoked subscriber.
Deliberately no instance-admin bypass: notifications are always the caller's
own, and being an admin says nothing about whether they should still read a
comment out of a project they were removed from.
2026-07-29 07:58:17 +00:00

163 lines
6.3 KiB
Go

// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-present Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package notifications
import (
"errors"
"time"
"code.vikunja.io/api/pkg/events"
"code.vikunja.io/api/pkg/log"
"xorm.io/builder"
"xorm.io/xorm"
)
// DatabaseNotification represents a notification that was saved to the database
type DatabaseNotification struct {
// The unique, numeric id of this notification.
ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"notificationid" readOnly:"true" doc:"The unique, numeric id of this notification."`
// The ID of the notifiable this notification is associated with.
NotifiableID int64 `xorm:"bigint not null" json:"-"`
// The actual content of the notification.
Notification interface{} `xorm:"json not null" json:"notification" readOnly:"true" doc:"The notification payload. Shape depends on the notification's name."`
// The name of the notification
Name string `xorm:"varchar(250) index not null" json:"name" readOnly:"true" doc:"The name identifying the kind of notification."`
// The thing the notification is about. Used to check if a notification for this thing already happened or not.
SubjectID int64 `xorm:"bigint null" json:"-"`
// 0 is account-scoped and always visible, > 0 needs read access to that
// project, ProjectIDUnresolved (-1) is visible to nobody.
ProjectID int64 `xorm:"bigint index not null default 0" json:"-"`
// When this notification is marked as read, this will be updated with the current timestamp.
ReadAt time.Time `xorm:"datetime null" json:"read_at" readOnly:"true" doc:"When the notification was marked read; zero value while unread. Set via the read flag, not written directly."`
// A timestamp when this notification was created. You cannot change this value.
Created time.Time `xorm:"created not null" json:"created" readOnly:"true" doc:"A timestamp when this notification was created. You cannot change this value."`
// Carried in memory so AfterInsert can queue the mail only after the row
// is committed. Unexported, so neither xorm nor json touch them.
notification Notification
notifiable Notifiable
}
// AfterInsert is called by XORM after the row is inserted. For transactional
// sessions this runs during Commit(), guaranteeing the row is persisted before
// the event fires and the mail is queued. A rolled-back transaction therefore
// sends no mail, which keeps event-handler retries from duplicating it (#2971).
func (d *DatabaseNotification) AfterInsert() {
if err := events.Dispatch(&NotificationCreatedEvent{
NotificationID: d.ID,
UserID: d.NotifiableID,
}); err != nil {
log.Errorf("Failed to dispatch notification created event for notification %d: %v", d.ID, err)
}
if d.notification == nil || d.notifiable == nil {
return
}
if err := notifyMail(d.notifiable, d.notification); err != nil {
log.Errorf("Failed to send mail for notification %d: %v", d.ID, err)
}
}
// TableName resolves to a better table name for notifications
func (d *DatabaseNotification) TableName() string {
return "notifications"
}
// GetNotificationsForUser returns all notifications for a user. It is possible to limit the amount of notifications
// to return with the limit and start parameters.
// We're not passing a user object in directly because every other package imports this one so we'd get import cycles.
//
// projectFilter is built by models and applied inside the query, so limit/start
// and total all describe the rows the caller may read.
func GetNotificationsForUser(s *xorm.Session, notifiableID int64, projectFilter builder.Cond, limit, start int) (notifications []*DatabaseNotification, resultCount int, total int64, err error) {
if projectFilter == nil {
return nil, 0, 0, errors.New("notifications cannot be read without a project filter")
}
cond := builder.And(builder.Eq{"notifiable_id": notifiableID}, projectFilter)
err = s.
Where(cond).
Limit(limit, start).
OrderBy("id DESC").
Find(&notifications)
if err != nil {
return nil, 0, 0, err
}
total, err = s.
Where(cond).
Count(&DatabaseNotification{})
return notifications, len(notifications), total, err
}
// GetNotificationByID returns a single notification by its ID.
func GetNotificationByID(s *xorm.Session, id int64) (*DatabaseNotification, error) {
n := &DatabaseNotification{}
has, err := s.ID(id).Get(n)
if err != nil {
return nil, err
}
if !has {
return nil, nil
}
return n, nil
}
func GetNotificationsForNameAndUser(s *xorm.Session, notifiableID int64, event string, subjectID int64) (notifications []*DatabaseNotification, err error) {
notifications = []*DatabaseNotification{}
err = s.Where("notifiable_id = ? AND name = ? AND subject_id = ?", notifiableID, event, subjectID).
Find(&notifications)
return
}
// CanMarkNotificationAsRead checks if a user can mark a notification as read.
func CanMarkNotificationAsRead(s *xorm.Session, notification *DatabaseNotification, notifiableID int64) (can bool, err error) {
can, err = s.
Where("notifiable_id = ? AND id = ?", notifiableID, notification.ID).
NoAutoCondition().
Get(notification)
return
}
// MarkNotificationAsRead marks a notification as read. It should be called only after CanMarkNotificationAsRead has
// been called.
func MarkNotificationAsRead(s *xorm.Session, notification *DatabaseNotification, read bool) (err error) {
notification.ReadAt = time.Time{}
if read {
notification.ReadAt = time.Now()
}
_, err = s.
Where("id = ?", notification.ID).
Cols("read_at").
Update(notification)
return
}
func MarkAllNotificationsAsRead(s *xorm.Session, userID int64) (err error) {
_, err = s.
Where("notifiable_id = ?", userID).
Cols("read_at").
Update(&DatabaseNotification{ReadAt: time.Now()})
return
}