fix(auth): scope notification providers and delivery to the real user (#3027)
Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/db"
|
||||
gateways "github.com/kandev/kandev/internal/gateway/websocket"
|
||||
notificationservice "github.com/kandev/kandev/internal/notifications/service"
|
||||
officesqlite "github.com/kandev/kandev/internal/office/repository/sqlite"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
@@ -67,6 +68,12 @@ func provideAuthService(
|
||||
// Pre-auth workspaces (owner_id='') become the admin's at setup.
|
||||
repos.Task.ClaimUnownedWorkspaces,
|
||||
}
|
||||
// Notification providers deliberately have no entry here. Unlike
|
||||
// workspaces and secrets, every provider row has always been written with
|
||||
// a concrete owner (userstore.DefaultUserID) rather than an empty one, and
|
||||
// Setup promotes that very row into the admin account, so pre-auth
|
||||
// providers already belong to the admin and there is nothing to claim.
|
||||
//
|
||||
// Pre-auth secrets (user_id='') are claimed the same way. Interface
|
||||
// assertion keeps SecretStore mocks free of the method.
|
||||
if claimer, ok := repos.Secrets.(interface {
|
||||
@@ -83,6 +90,16 @@ func provideAuthService(
|
||||
})
|
||||
}
|
||||
|
||||
// notificationAuthEnforced tells the notification service whether more than
|
||||
// one account can exist. It decides what an unresolvable notification owner
|
||||
// means: with authentication enforced the notification is dropped, because
|
||||
// falling back to the default user would deliver another user's task title and
|
||||
// session state to the administrator's webhook. A nil auth service is a build
|
||||
// with authentication unavailable, which is the single-user case.
|
||||
func notificationAuthEnforced(authSvc *auth.Service) notificationservice.AuthEnforced {
|
||||
return func() bool { return authSvc != nil && authSvc.Mode() != auth.ModeDisabled }
|
||||
}
|
||||
|
||||
// gatewayAuthPolicy assembles the WS gateway scoping hooks from the auth and
|
||||
// task services. The workspace-owner resolver caches lookups briefly: it runs
|
||||
// on every workspace-scoped broadcast.
|
||||
|
||||
@@ -28,6 +28,31 @@ import (
|
||||
userstore "github.com/kandev/kandev/internal/user/store"
|
||||
)
|
||||
|
||||
// newDisabledAuthService builds an auth service with the feature off, the
|
||||
// pre-auth single-user state.
|
||||
func newDisabledAuthService(t *testing.T) *auth.Service {
|
||||
t.Helper()
|
||||
conn, err := sqlx.Open("sqlite3", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
users, cleanup, err := userstore.Provide(conn, conn)
|
||||
if err != nil {
|
||||
t.Fatalf("user store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = cleanup() })
|
||||
st, err := authstore.New(conn, conn)
|
||||
if err != nil {
|
||||
t.Fatalf("auth store: %v", err)
|
||||
}
|
||||
svc, err := auth.NewService(context.Background(), auth.Deps{Cfg: &config.Config{}, Store: st, Users: users})
|
||||
if err != nil {
|
||||
t.Fatalf("auth service: %v", err)
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// newEnabledAuthService builds an auth service in ModeEnabled (features.auth
|
||||
// on + an admin identity exists) over an in-memory store pair — the state the
|
||||
// plugin SSO bridge requires.
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
agenthandlers "github.com/kandev/kandev/internal/agent/handlers"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
|
||||
"github.com/kandev/kandev/internal/auth"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/common/scripts"
|
||||
"github.com/kandev/kandev/internal/entityrefs"
|
||||
@@ -117,6 +118,7 @@ func provideGateway(
|
||||
githubSvc *github.Service,
|
||||
gitlabSvc *gitlab.Service,
|
||||
referenceValidator entityrefs.SubmissionValidator,
|
||||
authSvc *auth.Service,
|
||||
dataDir string,
|
||||
lspMaxConnections ...int,
|
||||
) (*gateways.Gateway, *notificationservice.Service, *notificationcontroller.Controller, *terminalservice.Service, error) {
|
||||
@@ -372,7 +374,15 @@ func provideGateway(
|
||||
gateway.Hub.Broadcast(msg)
|
||||
})
|
||||
|
||||
notificationSvc := notificationservice.NewService(notificationRepo, taskRepo, gateway.Hub, log)
|
||||
// taskRepo is a typed pointer that may be nil here, and a nil pointer in a
|
||||
// non-nil interface would defeat the service's own nil check when it
|
||||
// resolves a notification's owning workspace.
|
||||
var notificationTasks notificationservice.TaskContextReader
|
||||
if taskRepo != nil {
|
||||
notificationTasks = taskRepo
|
||||
}
|
||||
notificationSvc := notificationservice.NewService(
|
||||
notificationRepo, notificationTasks, gateway.Hub, log, notificationAuthEnforced(authSvc))
|
||||
notificationCtrl := notificationcontroller.NewController(notificationSvc)
|
||||
if eventBus != nil {
|
||||
_, err = eventBus.Subscribe(events.TurnCompleted, func(ctx context.Context, event *bus.Event) error {
|
||||
@@ -416,7 +426,8 @@ func provideGateway(
|
||||
}
|
||||
itemType, _ := data["type"].(string)
|
||||
title, _ := data["title"].(string)
|
||||
notificationSvc.HandleInboxItem(ctx, itemType, title)
|
||||
workspaceID, _ := data["workspace_id"].(string)
|
||||
notificationSvc.HandleInboxItem(ctx, workspaceID, itemType, title)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -837,6 +837,9 @@ func startGatewayAndServe(
|
||||
orchestratorSvc, lifecycleMgr, agentRegistry,
|
||||
repos.Notification, repos.Task, repos.Terminal, services.GitHub, services.GitLab,
|
||||
referenceValidator,
|
||||
// Notifications drop rather than redirect when a task's owner cannot
|
||||
// be resolved while authentication is enforced.
|
||||
services.Auth,
|
||||
cfg.ResolvedHomeDir(),
|
||||
cfg.Limits.LSPMaxConnections,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package backendapp
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/auth"
|
||||
"github.com/kandev/kandev/internal/common/config"
|
||||
)
|
||||
|
||||
// TestNotificationAuthEnforcedIsDisabledWithoutAnAuthService pins the
|
||||
// single-user case: no auth service means one account, so an unresolvable
|
||||
// notification owner may still fall back to the default user.
|
||||
func TestNotificationAuthEnforcedIsDisabledWithoutAnAuthService(t *testing.T) {
|
||||
if notificationAuthEnforced(nil)() {
|
||||
t.Fatal("a nil auth service must report authentication as not enforced")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotificationAuthEnforcedFollowsAnEnabledAuthService is the guard that
|
||||
// matters: while authentication is enforced, an unresolvable owner must make
|
||||
// the notification service drop the notification rather than redirect another
|
||||
// user's task title to the default administrator's webhook.
|
||||
func TestNotificationAuthEnforcedFollowsAnEnabledAuthService(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
cfg.Features.Auth = true
|
||||
cfg.Auth.SessionTTLHours = 720
|
||||
svc := newEnabledAuthService(t, cfg)
|
||||
|
||||
if svc.Mode() != auth.ModeEnabled {
|
||||
t.Fatalf("mode = %s, want enabled", svc.Mode())
|
||||
}
|
||||
if !notificationAuthEnforced(svc)() {
|
||||
t.Fatal("an enabled auth service must report authentication as enforced")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotificationAuthEnforcedFollowsADisabledAuthService keeps single-user
|
||||
// installs byte-identical: with the feature off, notifications still fall back
|
||||
// to the pre-auth default user.
|
||||
func TestNotificationAuthEnforcedFollowsADisabledAuthService(t *testing.T) {
|
||||
svc := newDisabledAuthService(t)
|
||||
|
||||
if svc.Mode() != auth.ModeDisabled {
|
||||
t.Fatalf("mode = %s, want disabled", svc.Mode())
|
||||
}
|
||||
if notificationAuthEnforced(svc)() {
|
||||
t.Fatal("a disabled auth service must report authentication as not enforced")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProvideGatewayTakesTheAuthService fails if the auth service is dropped
|
||||
// from the signature, which would leave the notification service without any
|
||||
// way to know that more than one account exists.
|
||||
func TestProvideGatewayTakesTheAuthService(t *testing.T) {
|
||||
signature := reflect.TypeOf(provideGateway)
|
||||
want := reflect.TypeOf((*auth.Service)(nil))
|
||||
for index := range signature.NumIn() {
|
||||
if signature.In(index) == want {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("provideGateway does not accept an *auth.Service")
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/kandev/kandev/internal/auth/authn"
|
||||
"github.com/kandev/kandev/internal/notifications/dto"
|
||||
"github.com/kandev/kandev/internal/notifications/models"
|
||||
"github.com/kandev/kandev/internal/notifications/service"
|
||||
@@ -18,8 +19,20 @@ func NewController(svc *service.Service) *Controller {
|
||||
return &Controller{service: svc}
|
||||
}
|
||||
|
||||
// callerUserID resolves the user whose providers this request may touch: the
|
||||
// authenticated identity when there is one, otherwise the pre-auth default
|
||||
// user. A synthetic identity means authentication is disabled, so it maps to
|
||||
// the same default row single-user installs have always used.
|
||||
func callerUserID(ctx context.Context) string {
|
||||
identity, ok := authn.IdentityFromContext(ctx)
|
||||
if !ok || identity.Synthetic || identity.UserID == "" {
|
||||
return userstore.DefaultUserID
|
||||
}
|
||||
return identity.UserID
|
||||
}
|
||||
|
||||
func (c *Controller) ListProviders(ctx context.Context) (dto.NotificationProvidersResponse, error) {
|
||||
userID := userstore.DefaultUserID
|
||||
userID := callerUserID(ctx)
|
||||
providers, subscriptions, err := c.service.ListProviders(ctx, userID)
|
||||
if err != nil {
|
||||
return dto.NotificationProvidersResponse{}, err
|
||||
@@ -37,7 +50,7 @@ func (c *Controller) ListProviders(ctx context.Context) (dto.NotificationProvide
|
||||
}
|
||||
|
||||
func (c *Controller) CreateProvider(ctx context.Context, req dto.UpsertProviderRequest) (dto.NotificationProviderDTO, error) {
|
||||
userID := userstore.DefaultUserID
|
||||
userID := callerUserID(ctx)
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if name == "" {
|
||||
name = defaultNameForType(req.Type)
|
||||
@@ -72,11 +85,11 @@ func (c *Controller) UpdateProvider(ctx context.Context, providerID string, req
|
||||
Config: req.Config,
|
||||
Events: req.Events,
|
||||
}
|
||||
provider, err := c.service.UpdateProvider(ctx, providerID, updates)
|
||||
userID := callerUserID(ctx)
|
||||
provider, err := c.service.UpdateProvider(ctx, userID, providerID, updates)
|
||||
if err != nil {
|
||||
return dto.NotificationProviderDTO{}, err
|
||||
}
|
||||
userID := userstore.DefaultUserID
|
||||
_, subscriptions, err := c.service.ListProviders(ctx, userID)
|
||||
if err != nil {
|
||||
return dto.NotificationProviderDTO{}, err
|
||||
@@ -85,11 +98,11 @@ func (c *Controller) UpdateProvider(ctx context.Context, providerID string, req
|
||||
}
|
||||
|
||||
func (c *Controller) DeleteProvider(ctx context.Context, providerID string) error {
|
||||
return c.service.DeleteProvider(ctx, providerID)
|
||||
return c.service.DeleteProvider(ctx, callerUserID(ctx), providerID)
|
||||
}
|
||||
|
||||
func (c *Controller) TestProvider(ctx context.Context, providerID string) error {
|
||||
return c.service.TestProvider(ctx, providerID)
|
||||
return c.service.TestProvider(ctx, callerUserID(ctx), providerID)
|
||||
}
|
||||
|
||||
func defaultNameForType(providerType string) string {
|
||||
|
||||
@@ -40,7 +40,7 @@ func testCreateProviderEvents(t *testing.T, request dto.UpsertProviderRequest, w
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
repo := &controllerRepository{}
|
||||
controller := NewController(service.NewService(repo, nil, nil, log))
|
||||
controller := NewController(service.NewService(repo, nil, nil, log, nil))
|
||||
provider, err := controller.CreateProvider(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("create provider: %v", err)
|
||||
@@ -77,13 +77,16 @@ func (r *controllerRepository) CreateProvider(_ context.Context, provider *model
|
||||
}
|
||||
|
||||
func (r *controllerRepository) UpdateProvider(context.Context, *models.Provider) error { return nil }
|
||||
func (r *controllerRepository) GetProvider(_ context.Context, id string) (*models.Provider, error) {
|
||||
func (r *controllerRepository) GetProvider(_ context.Context, _, id string) (*models.Provider, error) {
|
||||
return r.providers[id], nil
|
||||
}
|
||||
func (r *controllerRepository) ListProvidersByUser(context.Context, string) ([]*models.Provider, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (r *controllerRepository) DeleteProvider(context.Context, string) error { return nil }
|
||||
func (r *controllerRepository) ListProviderUserIDs(context.Context) ([]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (r *controllerRepository) DeleteProvider(context.Context, string, string) error { return nil }
|
||||
func (r *controllerRepository) ListSubscriptionsByProvider(context.Context, string) ([]*models.Subscription, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -65,6 +65,12 @@ func (h *Handlers) httpUpdateProvider(c *gin.Context) {
|
||||
}
|
||||
resp, err := h.controller.UpdateProvider(c.Request.Context(), providerID, body)
|
||||
if err != nil {
|
||||
// A provider owned by another user reaches here as ErrProviderNotFound,
|
||||
// so it is answered exactly like an ID that does not exist.
|
||||
if errors.Is(err, service.ErrProviderNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "provider not found"})
|
||||
return
|
||||
}
|
||||
h.logger.Error("failed to update notification provider", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -89,6 +95,10 @@ func (h *Handlers) httpTestProvider(c *gin.Context) {
|
||||
func (h *Handlers) httpDeleteProvider(c *gin.Context) {
|
||||
providerID := c.Param("id")
|
||||
if err := h.controller.DeleteProvider(c.Request.Context(), providerID); err != nil {
|
||||
if errors.Is(err, service.ErrProviderNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "provider not found"})
|
||||
return
|
||||
}
|
||||
h.logger.Error("failed to delete notification provider", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete notification provider"})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/auth/authn"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/db"
|
||||
"github.com/kandev/kandev/internal/notifications/controller"
|
||||
"github.com/kandev/kandev/internal/notifications/dto"
|
||||
"github.com/kandev/kandev/internal/notifications/service"
|
||||
notificationstore "github.com/kandev/kandev/internal/notifications/store"
|
||||
userstore "github.com/kandev/kandev/internal/user/store"
|
||||
)
|
||||
|
||||
// testUserHeader names the user a request authenticates as. The middleware
|
||||
// below stands in for auth/httpmw so these tests exercise the real handler,
|
||||
// controller, service and SQLite store together.
|
||||
const testUserHeader = "X-Test-User"
|
||||
|
||||
func newProviderAPI(t *testing.T) *gin.Engine {
|
||||
t.Helper()
|
||||
// Keep the auto-provisioned system provider out: SystemProvider.Available()
|
||||
// is true on desktop platforms and would vary the seeded provider count.
|
||||
t.Setenv("KANDEV_DESKTOP_NATIVE_NOTIFICATIONS", "true")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
conn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "notifications.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open SQLite database: %v", err)
|
||||
}
|
||||
database := sqlx.NewDb(conn, "sqlite3")
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
repo, cleanup, err := notificationstore.Provide(context.Background(), database, database)
|
||||
if err != nil {
|
||||
t.Fatalf("create notification store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = cleanup() })
|
||||
|
||||
log, err := logger.NewFromZap(zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
if userID := c.GetHeader(testUserHeader); userID != "" {
|
||||
authn.SetOnGin(c, authn.Identity{UserID: userID, Role: authn.RoleMember})
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
RegisterRoutes(router, controller.NewController(service.NewService(repo, nil, nil, log, nil)), log)
|
||||
return router
|
||||
}
|
||||
|
||||
func callAs(t *testing.T, router *gin.Engine, userID, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reader *bytes.Reader
|
||||
if body == "" {
|
||||
reader = bytes.NewReader(nil)
|
||||
} else {
|
||||
reader = bytes.NewReader([]byte(body))
|
||||
}
|
||||
request := httptest.NewRequest(method, path, reader)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if userID != "" {
|
||||
request.Header.Set(testUserHeader, userID)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func createProviderAs(t *testing.T, router *gin.Engine, userID, name, webhook string) dto.NotificationProviderDTO {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(dto.UpsertProviderRequest{
|
||||
Name: name,
|
||||
Type: "apprise",
|
||||
Config: map[string]interface{}{"urls": webhook},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("encode create request: %v", err)
|
||||
}
|
||||
response := callAs(t, router, userID, http.MethodPost, "/api/v1/notification-providers", string(body))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("create provider as %s = %d: %s", userID, response.Code, response.Body.String())
|
||||
}
|
||||
var created dto.NotificationProviderDTO
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("decode created provider: %v", err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
func listProviderNamesAs(t *testing.T, router *gin.Engine, userID string) []string {
|
||||
t.Helper()
|
||||
response := callAs(t, router, userID, http.MethodGet, "/api/v1/notification-providers", "")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("list providers as %s = %d: %s", userID, response.Code, response.Body.String())
|
||||
}
|
||||
var listed dto.NotificationProvidersResponse
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &listed); err != nil {
|
||||
t.Fatalf("decode provider list: %v", err)
|
||||
}
|
||||
names := make([]string, 0, len(listed.Providers))
|
||||
for _, provider := range listed.Providers {
|
||||
names = append(names, provider.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func contains(values []string, target string) bool {
|
||||
for _, value := range values {
|
||||
if value == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestProviderListShowsEachUserOnlyTheirOwnProviders(t *testing.T) {
|
||||
router := newProviderAPI(t)
|
||||
createProviderAs(t, router, "user-a", "a-webhook", "slack://user-a-token")
|
||||
createProviderAs(t, router, "user-b", "b-webhook", "slack://user-b-token")
|
||||
|
||||
forA := listProviderNamesAs(t, router, "user-a")
|
||||
forB := listProviderNamesAs(t, router, "user-b")
|
||||
|
||||
if !contains(forA, "a-webhook") || contains(forA, "b-webhook") {
|
||||
t.Fatalf("user-a sees %#v, want only their own webhook", forA)
|
||||
}
|
||||
if !contains(forB, "b-webhook") || contains(forB, "a-webhook") {
|
||||
t.Fatalf("user-b sees %#v, want only their own webhook", forB)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForeignProviderIsIndistinguishableFromAMissingOne(t *testing.T) {
|
||||
router := newProviderAPI(t)
|
||||
owned := createProviderAs(t, router, "user-a", "a-webhook", "slack://user-a-token")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name, method, suffix, body string
|
||||
}{
|
||||
{"update", http.MethodPatch, "", `{"name":"stolen"}`},
|
||||
{"delete", http.MethodDelete, "", ""},
|
||||
{"test", http.MethodPost, "/test", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
foreign := callAs(t, router, "user-b", tc.method, "/api/v1/notification-providers/"+owned.ID+tc.suffix, tc.body)
|
||||
missing := callAs(t, router, "user-b", tc.method, "/api/v1/notification-providers/no-such-provider"+tc.suffix, tc.body)
|
||||
|
||||
if foreign.Code != http.StatusNotFound {
|
||||
t.Fatalf("%s on a foreign provider = %d: %s", tc.name, foreign.Code, foreign.Body.String())
|
||||
}
|
||||
if foreign.Code != missing.Code || foreign.Body.String() != missing.Body.String() {
|
||||
t.Fatalf("%s foreign response (%d %s) differs from missing (%d %s)",
|
||||
tc.name, foreign.Code, foreign.Body.String(), missing.Code, missing.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// No mutation may have escaped: the owner still sees the original row.
|
||||
if names := listProviderNamesAs(t, router, "user-a"); !contains(names, "a-webhook") || contains(names, "stolen") {
|
||||
t.Fatalf("user-a providers = %#v, want the untouched a-webhook", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerCanStillUpdateAndDeleteTheirOwnProvider(t *testing.T) {
|
||||
router := newProviderAPI(t)
|
||||
owned := createProviderAs(t, router, "user-a", "a-webhook", "slack://user-a-token")
|
||||
|
||||
updated := callAs(t, router, "user-a", http.MethodPatch, "/api/v1/notification-providers/"+owned.ID, `{"name":"renamed"}`)
|
||||
if updated.Code != http.StatusOK {
|
||||
t.Fatalf("owner update = %d: %s", updated.Code, updated.Body.String())
|
||||
}
|
||||
if names := listProviderNamesAs(t, router, "user-a"); !contains(names, "renamed") {
|
||||
t.Fatalf("user-a providers = %#v, want the renamed provider", names)
|
||||
}
|
||||
|
||||
deleted := callAs(t, router, "user-a", http.MethodDelete, "/api/v1/notification-providers/"+owned.ID, "")
|
||||
if deleted.Code != http.StatusOK {
|
||||
t.Fatalf("owner delete = %d: %s", deleted.Code, deleted.Body.String())
|
||||
}
|
||||
if names := listProviderNamesAs(t, router, "user-a"); contains(names, "renamed") {
|
||||
t.Fatalf("user-a providers = %#v, want the provider gone", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestsWithoutAnIdentityUseTheDefaultUser(t *testing.T) {
|
||||
router := newProviderAPI(t)
|
||||
createProviderAs(t, router, "", "unauthenticated-webhook", "slack://single-user")
|
||||
|
||||
// With authentication disabled the row lands on the same default user
|
||||
// single-user installs have always used.
|
||||
if names := listProviderNamesAs(t, router, userstore.DefaultUserID); !contains(names, "unauthenticated-webhook") {
|
||||
t.Fatalf("default user providers = %#v, want the row created without an identity", names)
|
||||
}
|
||||
if names := listProviderNamesAs(t, router, ""); !contains(names, "unauthenticated-webhook") {
|
||||
t.Fatalf("unauthenticated list = %#v, want the same rows", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyntheticIdentityIsTreatedAsTheDefaultUser(t *testing.T) {
|
||||
router := newProviderAPI(t)
|
||||
createProviderAs(t, router, userstore.DefaultUserID, "single-user-webhook", "slack://single-user")
|
||||
|
||||
// auth/httpmw injects a synthetic admin while authentication is disabled;
|
||||
// it must resolve to the default row, not to its own user ID.
|
||||
ctx := authn.WithIdentity(context.Background(), authn.Identity{
|
||||
UserID: "synthetic-admin", Role: authn.RoleAdmin, Synthetic: true,
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/notification-providers", nil).WithContext(ctx)
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
|
||||
var listed dto.NotificationProvidersResponse
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &listed); err != nil {
|
||||
t.Fatalf("decode provider list: %v", err)
|
||||
}
|
||||
names := make([]string, 0, len(listed.Providers))
|
||||
for _, provider := range listed.Providers {
|
||||
names = append(names, provider.Name)
|
||||
}
|
||||
if !contains(names, "single-user-webhook") {
|
||||
t.Fatalf("synthetic identity sees %#v, want the default user's rows", names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/notifications/models"
|
||||
taskmodels "github.com/kandev/kandev/internal/task/models"
|
||||
userstore "github.com/kandev/kandev/internal/user/store"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// brokenTasks fails the lookups the recipient resolution depends on, standing
|
||||
// in for a deleted task, a workspace-deletion race, or a transient database
|
||||
// error.
|
||||
type brokenTasks struct {
|
||||
task *taskmodels.Task
|
||||
taskErr error
|
||||
workspace *taskmodels.Workspace
|
||||
workspaceErr error
|
||||
}
|
||||
|
||||
func (b brokenTasks) GetTask(context.Context, string) (*taskmodels.Task, error) {
|
||||
return b.task, b.taskErr
|
||||
}
|
||||
|
||||
func (b brokenTasks) GetWorkspace(context.Context, string) (*taskmodels.Workspace, error) {
|
||||
return b.workspace, b.workspaceErr
|
||||
}
|
||||
|
||||
// seedAdminAndMember gives the default administrator a provider alongside a
|
||||
// regular member's. A recipient resolution that falls open lands on the
|
||||
// administrator, so this is the account the assertions watch.
|
||||
func seedAdminAndMember(repo *multiUserRepository) {
|
||||
repo.seedProvider(userstore.DefaultUserID, "slack://admin", EventTaskSessionClarificationAsked, EventOfficeInboxItem)
|
||||
repo.seedProvider("user-a", "slack://user-a", EventTaskSessionClarificationAsked, EventOfficeInboxItem)
|
||||
}
|
||||
|
||||
func TestUnresolvableOwnerDeliversNothingUnderEnforcedAuth(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
tasks TaskContextReader
|
||||
}{
|
||||
{"workspace lookup fails", brokenTasks{
|
||||
task: &taskmodels.Task{ID: "task-1", WorkspaceID: "workspace-1"},
|
||||
workspaceErr: errors.New("database unavailable"),
|
||||
}},
|
||||
{"workspace vanished", brokenTasks{
|
||||
task: &taskmodels.Task{ID: "task-1", WorkspaceID: "workspace-1"},
|
||||
}},
|
||||
{"task lookup fails", brokenTasks{taskErr: errors.New("database unavailable")}},
|
||||
{"task vanished", brokenTasks{}},
|
||||
{"task carries no workspace", brokenTasks{task: &taskmodels.Task{ID: "task-1"}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
seedAdminAndMember(repo)
|
||||
svc, capture := newOwnershipTestService(t, repo, tc.tasks, true)
|
||||
|
||||
svc.HandleClarificationRequested(context.Background(), "task-1", "session-1", "pending-1")
|
||||
|
||||
if len(capture.messages) != 0 {
|
||||
t.Fatalf("delivered %#v, want nothing: an unresolvable owner must not fall back to the administrator", webhooksOf(capture.messages))
|
||||
}
|
||||
if len(repo.deliveries) != 0 {
|
||||
t.Fatalf("recorded deliveries %#v, want none", repo.deliveries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationWithoutATaskIsDroppedUnderEnforcedAuth(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
seedAdminAndMember(repo)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-a", ownerID: "user-a"}, true)
|
||||
|
||||
// An event whose payload carried no task_id names no workspace, so there
|
||||
// is no owner to deliver it to.
|
||||
svc.HandleClarificationRequested(context.Background(), "", "session-1", "pending-1")
|
||||
|
||||
if len(capture.messages) != 0 {
|
||||
t.Fatalf("delivered %#v, want nothing", webhooksOf(capture.messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxItemWithoutAWorkspaceIsDroppedUnderEnforcedAuth(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
seedAdminAndMember(repo)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-a", ownerID: "user-a"}, true)
|
||||
|
||||
svc.HandleInboxItem(context.Background(), "", "approval", "Deploy to production")
|
||||
|
||||
if len(capture.messages) != 0 {
|
||||
t.Fatalf("delivered %#v, want nothing", webhooksOf(capture.messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnownedWorkspaceStillResolvesToTheDefaultUser(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
seedAdminAndMember(repo)
|
||||
// The workspace loads successfully and is explicitly unowned: a pre-auth
|
||||
// row the setup wizard has not claimed yet, not a failed lookup.
|
||||
svc, capture := newOwnershipTestService(t, repo, brokenTasks{
|
||||
task: &taskmodels.Task{ID: "task-1", WorkspaceID: "workspace-1"},
|
||||
workspace: &taskmodels.Workspace{ID: "workspace-1"},
|
||||
}, true)
|
||||
|
||||
svc.HandleClarificationRequested(context.Background(), "task-1", "session-1", "pending-1")
|
||||
|
||||
got := webhooksOf(capture.messages)
|
||||
if len(got) != 1 || got[0] != "slack://admin" {
|
||||
t.Fatalf("delivered to %#v, want the default user's provider", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnresolvableOwnerStillFallsBackWhenAuthIsDisabled(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
seedAdminAndMember(repo)
|
||||
// Same failure as the enforced case above, but with one account on the
|
||||
// instance there is nobody else it could wrongly reach.
|
||||
svc, capture := newOwnershipTestService(t, repo, brokenTasks{
|
||||
taskErr: errors.New("database unavailable"),
|
||||
}, false)
|
||||
|
||||
svc.HandleClarificationRequested(context.Background(), "task-1", "session-1", "pending-1")
|
||||
|
||||
got := webhooksOf(capture.messages)
|
||||
if len(got) != 1 || got[0] != "slack://admin" {
|
||||
t.Fatalf("delivered to %#v, want the single-user default to be preserved", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilAuthEnforcementBehavesAsAuthDisabled(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
seedAdminAndMember(repo)
|
||||
t.Setenv(desktopNativeNotificationsEnv, "true")
|
||||
log, err := logger.NewFromZap(zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
// A nil predicate is the pre-auth single-user install.
|
||||
svc := NewService(repo, brokenTasks{taskErr: errors.New("database unavailable")}, nil, log, nil)
|
||||
capture := &captureProvider{}
|
||||
svc.providers[models.ProviderTypeLocal] = capture
|
||||
|
||||
svc.HandleClarificationRequested(context.Background(), "task-1", "session-1", "pending-1")
|
||||
|
||||
if got := webhooksOf(capture.messages); len(got) != 1 || got[0] != "slack://admin" {
|
||||
t.Fatalf("delivered to %#v, want the single-user default", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestNotificationIsAddressedToTheCaller(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
owned := repo.seedProvider("user-a", "slack://user-a", EventTaskSessionClarificationAsked)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-a", ownerID: "user-a"}, true)
|
||||
|
||||
if err := svc.TestProvider(context.Background(), "user-a", owned.ID); err != nil {
|
||||
t.Fatalf("test provider: %v", err)
|
||||
}
|
||||
if len(capture.messages) != 1 {
|
||||
t.Fatalf("messages = %#v, want one test notification", capture.messages)
|
||||
}
|
||||
// The local provider broadcasts to Message.UserID; an empty one never
|
||||
// reaches the tab that asked for the test.
|
||||
if capture.messages[0].UserID != "user-a" {
|
||||
t.Fatalf("test notification addressed to %q, want user-a", capture.messages[0].UserID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/notifications/models"
|
||||
"github.com/kandev/kandev/internal/notifications/providers"
|
||||
notificationstore "github.com/kandev/kandev/internal/notifications/store"
|
||||
taskmodels "github.com/kandev/kandev/internal/task/models"
|
||||
userstore "github.com/kandev/kandev/internal/user/store"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// multiUserRepository is a store double that honors provider ownership, so a
|
||||
// test can observe a leak instead of having the double paper over it.
|
||||
type multiUserRepository struct {
|
||||
mu sync.Mutex
|
||||
providers []*models.Provider
|
||||
subscriptions map[string][]string
|
||||
deliveries []*models.Delivery
|
||||
}
|
||||
|
||||
func newMultiUserRepository() *multiUserRepository {
|
||||
return &multiUserRepository{subscriptions: map[string][]string{}}
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) CreateProvider(_ context.Context, provider *models.Provider) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
provider.ID = uuid.New().String()
|
||||
r.providers = append(r.providers, provider)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) UpdateProvider(_ context.Context, provider *models.Provider) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for index, existing := range r.providers {
|
||||
if existing.ID == provider.ID && existing.UserID == provider.UserID {
|
||||
r.providers[index] = provider
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return notificationstore.ErrProviderNotFound
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) GetProvider(_ context.Context, userID, id string) (*models.Provider, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, provider := range r.providers {
|
||||
if provider.ID == id && provider.UserID == userID {
|
||||
return provider, nil
|
||||
}
|
||||
}
|
||||
return nil, notificationstore.ErrProviderNotFound
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) ListProvidersByUser(_ context.Context, userID string) ([]*models.Provider, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
owned := make([]*models.Provider, 0, len(r.providers))
|
||||
for _, provider := range r.providers {
|
||||
if provider.UserID == userID {
|
||||
owned = append(owned, provider)
|
||||
}
|
||||
}
|
||||
return owned, nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) ListProviderUserIDs(context.Context) ([]string, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
seen := map[string]bool{}
|
||||
owners := make([]string, 0, len(r.providers))
|
||||
for _, provider := range r.providers {
|
||||
if !seen[provider.UserID] {
|
||||
seen[provider.UserID] = true
|
||||
owners = append(owners, provider.UserID)
|
||||
}
|
||||
}
|
||||
return owners, nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) DeleteProvider(_ context.Context, userID, id string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for index, provider := range r.providers {
|
||||
if provider.ID == id && provider.UserID == userID {
|
||||
r.providers = append(r.providers[:index], r.providers[index+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return notificationstore.ErrProviderNotFound
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) ListSubscriptionsByProvider(_ context.Context, providerID string) ([]*models.Subscription, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
subs := make([]*models.Subscription, 0, len(r.subscriptions[providerID]))
|
||||
for _, eventType := range r.subscriptions[providerID] {
|
||||
subs = append(subs, &models.Subscription{ProviderID: providerID, EventType: eventType, Enabled: true})
|
||||
}
|
||||
return subs, nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) ReplaceSubscriptions(_ context.Context, providerID, _ string, events []string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.subscriptions[providerID] = append([]string(nil), events...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) InsertDelivery(_ context.Context, delivery *models.Delivery) (bool, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, existing := range r.deliveries {
|
||||
if existing.ProviderID == delivery.ProviderID && existing.EventType == delivery.EventType && existing.OccurrenceID == delivery.OccurrenceID {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
r.deliveries = append(r.deliveries, delivery)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) DeleteDelivery(context.Context, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *multiUserRepository) Close() error { return nil }
|
||||
|
||||
// seedProvider stores an enabled provider whose config carries a webhook URL
|
||||
// unique to its owner, so a captured message names the account it leaked to.
|
||||
func (r *multiUserRepository) seedProvider(userID, webhook string, events ...string) *models.Provider {
|
||||
provider := &models.Provider{
|
||||
UserID: userID,
|
||||
Name: webhook,
|
||||
Type: models.ProviderTypeLocal,
|
||||
Config: map[string]interface{}{"urls": webhook},
|
||||
Enabled: true,
|
||||
}
|
||||
_ = r.CreateProvider(context.Background(), provider)
|
||||
_ = r.ReplaceSubscriptions(context.Background(), provider.ID, userID, events)
|
||||
return provider
|
||||
}
|
||||
|
||||
// ownedWorkspaceTasks resolves every task into one workspace with one owner.
|
||||
type ownedWorkspaceTasks struct {
|
||||
workspaceID string
|
||||
ownerID string
|
||||
}
|
||||
|
||||
func (t ownedWorkspaceTasks) GetTask(_ context.Context, id string) (*taskmodels.Task, error) {
|
||||
return &taskmodels.Task{ID: id, WorkspaceID: t.workspaceID}, nil
|
||||
}
|
||||
|
||||
func (t ownedWorkspaceTasks) GetWorkspace(_ context.Context, id string) (*taskmodels.Workspace, error) {
|
||||
if id != t.workspaceID {
|
||||
return nil, errors.New("workspace not found")
|
||||
}
|
||||
return &taskmodels.Workspace{ID: id, OwnerID: t.ownerID}, nil
|
||||
}
|
||||
|
||||
func newOwnershipTestService(t *testing.T, repo notificationstore.Repository, tasks TaskContextReader, authEnforced bool) (*Service, *captureProvider) {
|
||||
t.Helper()
|
||||
// Keep the auto-provisioned system provider out so assertions count only
|
||||
// the providers the test seeded; SystemProvider.Available() is true on
|
||||
// desktop platforms and would add an extra delivery.
|
||||
t.Setenv(desktopNativeNotificationsEnv, "true")
|
||||
log, err := logger.NewFromZap(zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
svc := NewService(repo, tasks, nil, log, func() bool { return authEnforced })
|
||||
capture := &captureProvider{}
|
||||
svc.providers[models.ProviderTypeLocal] = capture
|
||||
return svc, capture
|
||||
}
|
||||
|
||||
// webhooksOf lists the provider config each captured message was sent with,
|
||||
// which is the value that would reach an external service.
|
||||
func webhooksOf(messages []providers.Message) []string {
|
||||
urls := make([]string, 0, len(messages))
|
||||
for _, message := range messages {
|
||||
url, _ := message.Config["urls"].(string)
|
||||
urls = append(urls, url)
|
||||
}
|
||||
return urls
|
||||
}
|
||||
|
||||
func TestTaskNotificationReachesOnlyTheOwningWorkspacesUser(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
repo.seedProvider("user-a", "slack://user-a", EventTaskSessionTurnFinished)
|
||||
repo.seedProvider("user-b", "slack://user-b", EventTaskSessionTurnFinished)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-a", ownerID: "user-a"}, true)
|
||||
|
||||
svc.HandleTaskTurnFinished(context.Background(), "task-in-workspace-a", "session-1", "turn-1")
|
||||
|
||||
got := webhooksOf(capture.messages)
|
||||
if len(got) != 1 || got[0] != "slack://user-a" {
|
||||
t.Fatalf("delivered to %#v, want only slack://user-a", got)
|
||||
}
|
||||
if len(repo.deliveries) != 1 || repo.deliveries[0].UserID != "user-a" {
|
||||
t.Fatalf("delivery rows = %#v, want a single row owned by user-a", repo.deliveries)
|
||||
}
|
||||
for _, message := range capture.messages {
|
||||
if message.UserID != "user-a" {
|
||||
t.Fatalf("message routed to %q, want user-a", message.UserID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClarificationNotificationDoesNotReachAnotherUsersWebhook(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
repo.seedProvider("user-a", "slack://user-a", EventTaskSessionClarificationAsked)
|
||||
repo.seedProvider("user-b", "slack://user-b", EventTaskSessionClarificationAsked)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-b", ownerID: "user-b"}, true)
|
||||
|
||||
svc.HandleClarificationRequested(context.Background(), "task-in-workspace-b", "session-9", "pending-1")
|
||||
|
||||
got := webhooksOf(capture.messages)
|
||||
if len(got) != 1 || got[0] != "slack://user-b" {
|
||||
t.Fatalf("delivered to %#v, want only slack://user-b", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfficeInboxItemFollowsItsWorkspaceOwner(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
repo.seedProvider("user-a", "slack://user-a", EventOfficeInboxItem)
|
||||
repo.seedProvider("user-b", "slack://user-b", EventOfficeInboxItem)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-b", ownerID: "user-b"}, true)
|
||||
|
||||
svc.HandleInboxItem(context.Background(), "workspace-b", "approval", "Deploy to production")
|
||||
|
||||
got := webhooksOf(capture.messages)
|
||||
if len(got) != 1 || got[0] != "slack://user-b" {
|
||||
t.Fatalf("inbox item delivered to %#v, want only slack://user-b", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecondUserGetsTheirOwnSeededDefaultProviders(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
svc, _ := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-b", ownerID: "user-b"}, true)
|
||||
|
||||
// user-b has never opened notification settings; a task event in their
|
||||
// workspace must still provision their own defaults rather than reuse
|
||||
// somebody else's.
|
||||
svc.HandleClarificationRequested(context.Background(), "task-in-workspace-b", "session-1", "pending-1")
|
||||
|
||||
owned, err := repo.ListProvidersByUser(context.Background(), "user-b")
|
||||
if err != nil {
|
||||
t.Fatalf("list user-b providers: %v", err)
|
||||
}
|
||||
if len(owned) != 1 || owned[0].Type != models.ProviderTypeLocal {
|
||||
t.Fatalf("user-b providers = %#v, want one seeded local provider", owned)
|
||||
}
|
||||
if defaultOwned, _ := repo.ListProvidersByUser(context.Background(), userstore.DefaultUserID); len(defaultOwned) != 0 {
|
||||
t.Fatalf("default user gained providers = %#v, want none", defaultOwned)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceWideUpdateNoticeReachesEveryProviderOwner(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
repo.seedProvider("user-a", "slack://user-a", EventSystemUpdateAvailable)
|
||||
repo.seedProvider("user-b", "slack://user-b", EventSystemUpdateAvailable)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-a", ownerID: "user-a"}, true)
|
||||
|
||||
svc.HandleUpdateAvailable(context.Background(), "v9.9.9", "https://example.test/releases/v9.9.9")
|
||||
|
||||
got := webhooksOf(capture.messages)
|
||||
if len(got) != 2 || got[0] != "slack://user-a" || got[1] != "slack://user-b" {
|
||||
t.Fatalf("update notice delivered to %#v, want both owners", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleUserInstallKeepsDeliveringToTheDefaultUser(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
// Authentication disabled: workspaces are still unowned (owner_id='').
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-1", ownerID: ""}, false)
|
||||
|
||||
// The seeded default provider subscribes to clarifications, not turns.
|
||||
svc.HandleClarificationRequested(context.Background(), "task-1", "session-1", "pending-1")
|
||||
|
||||
owned, err := repo.ListProvidersByUser(context.Background(), userstore.DefaultUserID)
|
||||
if err != nil {
|
||||
t.Fatalf("list default providers: %v", err)
|
||||
}
|
||||
if len(owned) != 1 {
|
||||
t.Fatalf("default user providers = %#v, want the single seeded default", owned)
|
||||
}
|
||||
if len(capture.messages) != 1 || capture.messages[0].UserID != userstore.DefaultUserID {
|
||||
t.Fatalf("messages = %#v, want one addressed to the default user", capture.messages)
|
||||
}
|
||||
if len(repo.deliveries) != 1 || repo.deliveries[0].UserID != userstore.DefaultUserID {
|
||||
t.Fatalf("delivery rows = %#v, want one owned by the default user", repo.deliveries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceRefusesToTouchAnotherUsersProvider(t *testing.T) {
|
||||
repo := newMultiUserRepository()
|
||||
owned := repo.seedProvider("user-a", "slack://user-a", EventTaskSessionTurnFinished)
|
||||
svc, capture := newOwnershipTestService(t, repo, ownedWorkspaceTasks{workspaceID: "workspace-a", ownerID: "user-a"}, true)
|
||||
|
||||
stolen := "stolen"
|
||||
if _, err := svc.UpdateProvider(context.Background(), "user-b", owned.ID, ProviderUpdate{Name: &stolen}); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("foreign update error = %v, want ErrProviderNotFound", err)
|
||||
}
|
||||
if err := svc.TestProvider(context.Background(), "user-b", owned.ID); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("foreign test error = %v, want ErrProviderNotFound", err)
|
||||
}
|
||||
if err := svc.DeleteProvider(context.Background(), "user-b", owned.ID); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("foreign delete error = %v, want ErrProviderNotFound", err)
|
||||
}
|
||||
|
||||
missingErr := svc.TestProvider(context.Background(), "user-b", "no-such-provider")
|
||||
foreignErr := svc.TestProvider(context.Background(), "user-b", owned.ID)
|
||||
if missingErr.Error() != foreignErr.Error() {
|
||||
t.Fatalf("foreign error %q differs from missing error %q", foreignErr, missingErr)
|
||||
}
|
||||
if len(capture.messages) != 0 {
|
||||
t.Fatalf("foreign test fired %#v, want no notification", capture.messages)
|
||||
}
|
||||
after, err := repo.GetProvider(context.Background(), "user-a", owned.ID)
|
||||
if err != nil || after.Name != "slack://user-a" {
|
||||
t.Fatalf("provider mutated by a foreign caller: %#v (%v)", after, err)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -28,23 +27,42 @@ const (
|
||||
desktopNativeNotificationsEnv = "KANDEV_DESKTOP_NATIVE_NOTIFICATIONS"
|
||||
)
|
||||
|
||||
var ErrProviderNotFound = errors.New("notification provider not found")
|
||||
// ErrProviderNotFound is the store sentinel, re-exported so HTTP handlers can
|
||||
// keep mapping it to 404 without importing the store package. A provider owned
|
||||
// by another user surfaces as this error too, so a 404 never reveals that
|
||||
// somebody else's provider exists.
|
||||
var ErrProviderNotFound = notificationstore.ErrProviderNotFound
|
||||
|
||||
// taskGetter is the minimal repository interface needed by the notification service.
|
||||
type taskGetter interface {
|
||||
// TaskContextReader resolves the workspace a notified task belongs to and that
|
||||
// workspace's owner. Notification recipients are derived from it: a task event
|
||||
// belongs to whoever owns the workspace it happened in, never to a constant.
|
||||
type TaskContextReader interface {
|
||||
GetTask(ctx context.Context, id string) (*taskmodels.Task, error)
|
||||
GetWorkspace(ctx context.Context, id string) (*taskmodels.Workspace, error)
|
||||
}
|
||||
|
||||
// AuthEnforced reports whether authentication is currently enforced. It is a
|
||||
// predicate rather than a snapshot because the mode flips at runtime when the
|
||||
// setup wizard completes. A nil AuthEnforced means "not enforced": the
|
||||
// single-user install that predates authentication.
|
||||
type AuthEnforced func() bool
|
||||
|
||||
type Service struct {
|
||||
defaultProvidersMu sync.Mutex
|
||||
repo notificationstore.Repository
|
||||
taskRepo taskGetter
|
||||
taskRepo TaskContextReader
|
||||
hub *gatewayws.Hub
|
||||
logger *logger.Logger
|
||||
providers map[models.ProviderType]providers.Provider
|
||||
authEnforced AuthEnforced
|
||||
}
|
||||
|
||||
func NewService(repo notificationstore.Repository, taskRepo taskGetter, hub *gatewayws.Hub, log *logger.Logger) *Service {
|
||||
// NewService builds the notification service. authEnforced decides what
|
||||
// happens when a notification's owner cannot be resolved: with authentication
|
||||
// enforced the notification is dropped, otherwise it falls back to the single
|
||||
// pre-auth user. It is a constructor parameter rather than a setter so no call
|
||||
// site can silently leave the fail-closed behavior unwired.
|
||||
func NewService(repo notificationstore.Repository, taskRepo TaskContextReader, hub *gatewayws.Hub, log *logger.Logger, authEnforced AuthEnforced) *Service {
|
||||
providerMap := map[models.ProviderType]providers.Provider{
|
||||
models.ProviderTypeLocal: providers.NewLocalProvider(hub),
|
||||
models.ProviderTypeApprise: providers.NewAppriseProvider(),
|
||||
@@ -53,11 +71,12 @@ func NewService(repo notificationstore.Repository, taskRepo taskGetter, hub *gat
|
||||
providerMap[models.ProviderTypeSystem] = providers.NewSystemProvider()
|
||||
}
|
||||
return &Service{
|
||||
repo: repo,
|
||||
taskRepo: taskRepo,
|
||||
hub: hub,
|
||||
logger: log.WithFields(zap.String("component", "notifications-service")),
|
||||
providers: providerMap,
|
||||
repo: repo,
|
||||
taskRepo: taskRepo,
|
||||
hub: hub,
|
||||
logger: log.WithFields(zap.String("component", "notifications-service")),
|
||||
providers: providerMap,
|
||||
authEnforced: authEnforced,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +143,12 @@ func (s *Service) CreateProvider(ctx context.Context, userID, name string, provi
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateProvider(ctx context.Context, providerID string, updates ProviderUpdate) (*models.Provider, error) {
|
||||
provider, err := s.repo.GetProvider(ctx, providerID)
|
||||
// UpdateProvider mutates a provider the caller owns. A provider ID belonging
|
||||
// to another user resolves to ErrProviderNotFound before any write happens.
|
||||
func (s *Service) UpdateProvider(ctx context.Context, userID, providerID string, updates ProviderUpdate) (*models.Provider, error) {
|
||||
provider, err := s.ownedProvider(ctx, userID, providerID)
|
||||
if err != nil {
|
||||
return nil, ErrProviderNotFound
|
||||
return nil, err
|
||||
}
|
||||
if updates.Name != nil {
|
||||
provider.Name = strings.TrimSpace(*updates.Name)
|
||||
@@ -158,8 +179,22 @@ func (s *Service) UpdateProvider(ctx context.Context, providerID string, updates
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteProvider(ctx context.Context, providerID string) error {
|
||||
return s.repo.DeleteProvider(ctx, providerID)
|
||||
// DeleteProvider removes a provider the caller owns.
|
||||
func (s *Service) DeleteProvider(ctx context.Context, userID, providerID string) error {
|
||||
return s.repo.DeleteProvider(ctx, userID, providerID)
|
||||
}
|
||||
|
||||
// ownedProvider reads a provider scoped to userID, normalizing a store double
|
||||
// that reports a miss as (nil, nil) into ErrProviderNotFound.
|
||||
func (s *Service) ownedProvider(ctx context.Context, userID, providerID string) (*models.Provider, error) {
|
||||
provider, err := s.repo.GetProvider(ctx, userID, providerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if provider == nil {
|
||||
return nil, ErrProviderNotFound
|
||||
}
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
type ProviderUpdate struct {
|
||||
@@ -192,29 +227,45 @@ func (s *Service) handleSemanticOccurrence(ctx context.Context, taskID, sessionI
|
||||
if occurrenceID == "" {
|
||||
return
|
||||
}
|
||||
userID := userstore.DefaultUserID
|
||||
recipients, ok := s.recipients(ctx, taskID, eventType)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
title, body := s.buildSemanticMessage(ctx, taskID, eventType, payload)
|
||||
message := notificationPayload{
|
||||
TaskID: taskID,
|
||||
TaskSessionID: sessionID,
|
||||
OccurrenceID: occurrenceID,
|
||||
EventType: eventType,
|
||||
Title: title,
|
||||
Body: body,
|
||||
Payload: payload,
|
||||
}
|
||||
for _, userID := range recipients {
|
||||
s.deliverOccurrence(ctx, userID, message)
|
||||
}
|
||||
}
|
||||
|
||||
// deliverOccurrence fans one occurrence out over a single recipient's own
|
||||
// providers. Every provider it can reach belongs to userID, so a webhook only
|
||||
// ever receives events from workspaces its owner can see.
|
||||
func (s *Service) deliverOccurrence(ctx context.Context, userID string, message notificationPayload) {
|
||||
providers, subscriptions, err := s.ListProviders(ctx, userID)
|
||||
if err != nil {
|
||||
s.logger.Error("failed to load notification providers", zap.Error(err))
|
||||
return
|
||||
}
|
||||
title, body := s.buildSemanticMessage(ctx, taskID, eventType, payload)
|
||||
for _, provider := range providers {
|
||||
if !provider.Enabled {
|
||||
if !provider.Enabled || !containsEvent(subscriptions[provider.ID], message.EventType) {
|
||||
continue
|
||||
}
|
||||
events := subscriptions[provider.ID]
|
||||
if !containsEvent(events, eventType) {
|
||||
continue
|
||||
}
|
||||
delivery := &models.Delivery{
|
||||
inserted, err := s.repo.InsertDelivery(ctx, &models.Delivery{
|
||||
UserID: userID,
|
||||
ProviderID: provider.ID,
|
||||
EventType: eventType,
|
||||
TaskSessionID: sessionID,
|
||||
OccurrenceID: occurrenceID,
|
||||
}
|
||||
inserted, err := s.repo.InsertDelivery(ctx, delivery)
|
||||
EventType: message.EventType,
|
||||
TaskSessionID: message.TaskSessionID,
|
||||
OccurrenceID: message.OccurrenceID,
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Error("failed to record notification delivery", zap.Error(err))
|
||||
continue
|
||||
@@ -222,24 +273,110 @@ func (s *Service) handleSemanticOccurrence(ctx context.Context, taskID, sessionI
|
||||
if !inserted {
|
||||
continue
|
||||
}
|
||||
if err := s.dispatchProvider(ctx, provider, notificationPayload{
|
||||
TaskID: taskID,
|
||||
TaskSessionID: sessionID,
|
||||
OccurrenceID: occurrenceID,
|
||||
EventType: eventType,
|
||||
Title: title,
|
||||
Body: body,
|
||||
Payload: payload,
|
||||
}); err != nil {
|
||||
if err := s.dispatchProvider(ctx, userID, provider, message); err != nil {
|
||||
s.logger.Warn("notification delivery failed", zap.String("provider_id", provider.ID), zap.Error(err))
|
||||
_ = s.repo.DeleteDelivery(ctx, provider.ID, eventType, occurrenceID)
|
||||
_ = s.repo.DeleteDelivery(ctx, provider.ID, message.EventType, message.OccurrenceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HandleInboxItem sends notifications for a new office inbox item.
|
||||
func (s *Service) HandleInboxItem(ctx context.Context, itemType, title string) {
|
||||
userID := userstore.DefaultUserID
|
||||
// recipients resolves who a notification belongs to, reporting false when it
|
||||
// must not be delivered at all. A task event belongs to the single owner of
|
||||
// the workspace it happened in; resolving it to a constant is what pushed one
|
||||
// user's task titles into another user's webhook. An instance-wide event (a
|
||||
// new release) has no owning workspace, so it fans out to every user that owns
|
||||
// providers instead of landing on one of them.
|
||||
func (s *Service) recipients(ctx context.Context, taskID, eventType string) ([]string, bool) {
|
||||
if eventType == EventSystemUpdateAvailable {
|
||||
return s.providerOwners(ctx)
|
||||
}
|
||||
owner, ok := s.workspaceOwnerForTask(ctx, taskID)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return []string{owner}, true
|
||||
}
|
||||
|
||||
// workspaceOwnerForTask resolves the owner of the workspace a task lives in.
|
||||
//
|
||||
// A failed lookup is NOT the default user. Under enforced authentication that
|
||||
// substitution would hand the task title and session state to the default
|
||||
// administrator's webhook and WebSocket connections, which is the very
|
||||
// cross-user leak this scoping exists to close, just behind a narrower trigger
|
||||
// (a deleted task, a workspace-deletion race, a transient database error).
|
||||
// Unresolvable ownership therefore drops the notification; see unresolvedOwner
|
||||
// for the one case that still falls back.
|
||||
func (s *Service) workspaceOwnerForTask(ctx context.Context, taskID string) (string, bool) {
|
||||
if taskID == "" || s.taskRepo == nil {
|
||||
return s.unresolvedOwner("notification names no resolvable task", zap.String("task_id", taskID))
|
||||
}
|
||||
task, err := s.taskRepo.GetTask(ctx, taskID)
|
||||
if err != nil || task == nil {
|
||||
return s.unresolvedOwner("failed to resolve the task a notification belongs to",
|
||||
zap.String("task_id", taskID), zap.Error(err))
|
||||
}
|
||||
return s.workspaceOwner(ctx, task.WorkspaceID)
|
||||
}
|
||||
|
||||
func (s *Service) workspaceOwner(ctx context.Context, workspaceID string) (string, bool) {
|
||||
if workspaceID == "" || s.taskRepo == nil {
|
||||
return s.unresolvedOwner("notification names no resolvable workspace",
|
||||
zap.String("workspace_id", workspaceID))
|
||||
}
|
||||
workspace, err := s.taskRepo.GetWorkspace(ctx, workspaceID)
|
||||
if err != nil || workspace == nil {
|
||||
return s.unresolvedOwner("failed to resolve the workspace a notification belongs to",
|
||||
zap.String("workspace_id", workspaceID), zap.Error(err))
|
||||
}
|
||||
if workspace.OwnerID == "" {
|
||||
// A workspace that loaded successfully and is explicitly unowned is a
|
||||
// pre-auth row the setup wizard has not claimed yet. That wizard
|
||||
// promotes the default-user row into the admin account, so the row
|
||||
// already belongs to whoever will own it. This is a known owner, not
|
||||
// a failed lookup.
|
||||
return userstore.DefaultUserID, true
|
||||
}
|
||||
return workspace.OwnerID, true
|
||||
}
|
||||
|
||||
// unresolvedOwner decides what an unresolvable owner means. With
|
||||
// authentication enforced there is more than one account that could wrongly
|
||||
// receive the notification, so it is dropped. Otherwise the instance has
|
||||
// exactly one user and the pre-auth default keeps single-user behavior
|
||||
// byte-identical.
|
||||
func (s *Service) unresolvedOwner(reason string, fields ...zap.Field) (string, bool) {
|
||||
if s.authEnforced == nil || !s.authEnforced() {
|
||||
return userstore.DefaultUserID, true
|
||||
}
|
||||
s.logger.Warn(reason+"; dropping it rather than delivering to another account", fields...)
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (s *Service) providerOwners(ctx context.Context) ([]string, bool) {
|
||||
owners, err := s.repo.ListProviderUserIDs(ctx)
|
||||
if err != nil {
|
||||
s.logger.Error("failed to resolve notification recipients", zap.Error(err))
|
||||
owner, ok := s.unresolvedOwner("failed to list notification provider owners")
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return []string{owner}, true
|
||||
}
|
||||
if len(owners) == 0 {
|
||||
return []string{userstore.DefaultUserID}, true
|
||||
}
|
||||
return owners, true
|
||||
}
|
||||
|
||||
// HandleInboxItem sends notifications for a new office inbox item. The item's
|
||||
// workspace names the recipient. An item carrying no workspace context has no
|
||||
// resolvable owner, so under enforced authentication it is dropped rather than
|
||||
// delivered to whichever account the fallback would pick.
|
||||
func (s *Service) HandleInboxItem(ctx context.Context, workspaceID, itemType, title string) {
|
||||
userID, ok := s.workspaceOwner(ctx, workspaceID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
providers, subscriptions, err := s.ListProviders(ctx, userID)
|
||||
if err != nil {
|
||||
s.logger.Error("failed to load notification providers for inbox item", zap.Error(err))
|
||||
@@ -258,14 +395,14 @@ func (s *Service) HandleInboxItem(ctx context.Context, itemType, title string) {
|
||||
if !containsEvent(events, EventOfficeInboxItem) {
|
||||
continue
|
||||
}
|
||||
if err := s.dispatchGenericNotification(ctx, provider, EventOfficeInboxItem, notifTitle, body); err != nil {
|
||||
if err := s.dispatchGenericNotification(ctx, userID, provider, EventOfficeInboxItem, notifTitle, body); err != nil {
|
||||
s.logger.Warn("inbox item notification delivery failed",
|
||||
zap.String("provider_id", provider.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) dispatchGenericNotification(ctx context.Context, provider *models.Provider, eventType, title, body string) error {
|
||||
func (s *Service) dispatchGenericNotification(ctx context.Context, userID string, provider *models.Provider, eventType, title, body string) error {
|
||||
adapter := s.providers[provider.Type]
|
||||
if adapter == nil {
|
||||
return fmt.Errorf("unknown provider type: %s", provider.Type)
|
||||
@@ -274,7 +411,7 @@ func (s *Service) dispatchGenericNotification(ctx context.Context, provider *mod
|
||||
EventType: eventType,
|
||||
Title: title,
|
||||
Body: body,
|
||||
UserID: userstore.DefaultUserID,
|
||||
UserID: userID,
|
||||
Config: provider.Config,
|
||||
})
|
||||
}
|
||||
@@ -289,7 +426,10 @@ type notificationPayload struct {
|
||||
Payload map[string]string
|
||||
}
|
||||
|
||||
func (s *Service) dispatchProvider(ctx context.Context, provider *models.Provider, payload notificationPayload) error {
|
||||
// dispatchProvider hands the message to the adapter. Message.UserID is the
|
||||
// resolved recipient rather than a constant: the local provider broadcasts it
|
||||
// over that user's WebSocket connections.
|
||||
func (s *Service) dispatchProvider(ctx context.Context, userID string, provider *models.Provider, payload notificationPayload) error {
|
||||
adapter := s.providers[provider.Type]
|
||||
if adapter == nil {
|
||||
return fmt.Errorf("unknown provider type: %s", provider.Type)
|
||||
@@ -302,7 +442,7 @@ func (s *Service) dispatchProvider(ctx context.Context, provider *models.Provide
|
||||
TaskID: payload.TaskID,
|
||||
TaskSessionID: payload.TaskSessionID,
|
||||
OccurrenceID: payload.OccurrenceID,
|
||||
UserID: userstore.DefaultUserID,
|
||||
UserID: userID,
|
||||
Config: provider.Config,
|
||||
})
|
||||
}
|
||||
@@ -413,10 +553,11 @@ func (s *Service) ensureSystemProvider(ctx context.Context, userID string) error
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) TestProvider(ctx context.Context, providerID string) error {
|
||||
provider, err := s.repo.GetProvider(ctx, providerID)
|
||||
// TestProvider fires a test notification through a provider the caller owns.
|
||||
func (s *Service) TestProvider(ctx context.Context, userID, providerID string) error {
|
||||
provider, err := s.ownedProvider(ctx, userID, providerID)
|
||||
if err != nil {
|
||||
return ErrProviderNotFound
|
||||
return err
|
||||
}
|
||||
adapter := s.providers[provider.Type]
|
||||
if adapter == nil {
|
||||
@@ -426,7 +567,11 @@ func (s *Service) TestProvider(ctx context.Context, providerID string) error {
|
||||
EventType: EventTaskSessionClarificationAsked,
|
||||
Title: "Test notification",
|
||||
Body: "If you can read this, notifications are working.",
|
||||
Config: provider.Config,
|
||||
// The local provider broadcasts to this user's connections, so an
|
||||
// unaddressed test notification never reaches the tab that asked
|
||||
// for it.
|
||||
UserID: userID,
|
||||
Config: provider.Config,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
gatewayws "github.com/kandev/kandev/internal/gateway/websocket"
|
||||
"github.com/kandev/kandev/internal/notifications/models"
|
||||
"github.com/kandev/kandev/internal/notifications/providers"
|
||||
notificationstore "github.com/kandev/kandev/internal/notifications/store"
|
||||
taskmodels "github.com/kandev/kandev/internal/task/models"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -29,22 +30,37 @@ func (r *notificationTestRepository) CreateProvider(_ context.Context, provider
|
||||
func (r *notificationTestRepository) UpdateProvider(context.Context, *models.Provider) error {
|
||||
return nil
|
||||
}
|
||||
func (r *notificationTestRepository) GetProvider(_ context.Context, id string) (*models.Provider, error) {
|
||||
func (r *notificationTestRepository) GetProvider(_ context.Context, userID, id string) (*models.Provider, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, provider := range r.providers {
|
||||
if provider.ID == id {
|
||||
if provider.ID == id && provider.UserID == userID {
|
||||
return provider, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
return nil, notificationstore.ErrProviderNotFound
|
||||
}
|
||||
func (r *notificationTestRepository) ListProvidersByUser(context.Context, string) ([]*models.Provider, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]*models.Provider(nil), r.providers...), nil
|
||||
}
|
||||
func (r *notificationTestRepository) DeleteProvider(context.Context, string) error { return nil }
|
||||
func (r *notificationTestRepository) ListProviderUserIDs(context.Context) ([]string, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
seen := map[string]bool{}
|
||||
owners := make([]string, 0, len(r.providers))
|
||||
for _, provider := range r.providers {
|
||||
if !seen[provider.UserID] {
|
||||
seen[provider.UserID] = true
|
||||
owners = append(owners, provider.UserID)
|
||||
}
|
||||
}
|
||||
return owners, nil
|
||||
}
|
||||
func (r *notificationTestRepository) DeleteProvider(context.Context, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (r *notificationTestRepository) ListSubscriptionsByProvider(_ context.Context, providerID string) ([]*models.Subscription, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
@@ -108,12 +124,19 @@ func (p *failOnceProvider) Send(_ context.Context, message providers.Message) er
|
||||
return nil
|
||||
}
|
||||
|
||||
type notificationTestTaskGetter struct{ task *taskmodels.Task }
|
||||
type notificationTestTaskGetter struct {
|
||||
task *taskmodels.Task
|
||||
workspace *taskmodels.Workspace
|
||||
}
|
||||
|
||||
func (g notificationTestTaskGetter) GetTask(context.Context, string) (*taskmodels.Task, error) {
|
||||
return g.task, nil
|
||||
}
|
||||
|
||||
func (g notificationTestTaskGetter) GetWorkspace(context.Context, string) (*taskmodels.Workspace, error) {
|
||||
return g.workspace, nil
|
||||
}
|
||||
|
||||
func TestNewServiceSuppressesSystemProviderForDesktopOwnedLaunch(t *testing.T) {
|
||||
t.Setenv("KANDEV_DESKTOP_NATIVE_NOTIFICATIONS", "true")
|
||||
log, err := logger.NewFromZap(zap.NewNop())
|
||||
@@ -121,7 +144,7 @@ func TestNewServiceSuppressesSystemProviderForDesktopOwnedLaunch(t *testing.T) {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
|
||||
svc := NewService(nil, nil, nil, log)
|
||||
svc := NewService(nil, nil, nil, log, nil)
|
||||
|
||||
if _, exists := svc.providers[models.ProviderTypeSystem]; exists {
|
||||
t.Fatal("system notification provider must be suppressed for a desktop-owned launch")
|
||||
@@ -138,7 +161,7 @@ func TestNewServiceRetainsSystemProviderForNonDesktopLaunch(t *testing.T) {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
|
||||
svc := NewService(nil, nil, nil, log)
|
||||
svc := NewService(nil, nil, nil, log, nil)
|
||||
|
||||
if _, exists := svc.providers[models.ProviderTypeSystem]; !exists {
|
||||
t.Fatal("system notification provider must remain enabled outside the desktop-owned launch")
|
||||
@@ -163,7 +186,7 @@ func TestSemanticOccurrencesUseEventSpecificCopyAndOccurrenceIdempotency(t *test
|
||||
},
|
||||
},
|
||||
}
|
||||
service := NewService(repo, notificationTestTaskGetter{task: &taskmodels.Task{Title: "Fix delivery"}}, nil, log)
|
||||
service := NewService(repo, notificationTestTaskGetter{task: &taskmodels.Task{Title: "Fix delivery"}}, nil, log, nil)
|
||||
capture := &captureProvider{}
|
||||
service.providers[models.ProviderTypeLocal] = capture
|
||||
|
||||
@@ -191,7 +214,7 @@ func TestUpdateAvailabilityIsAvailableEvent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
service := NewService(¬ificationTestRepository{}, nil, nil, log)
|
||||
service := NewService(¬ificationTestRepository{}, nil, nil, log, nil)
|
||||
if !containsEvent(service.AvailableEvents(), "system.update_available") {
|
||||
t.Fatalf("available events = %#v, want system.update_available", service.AvailableEvents())
|
||||
}
|
||||
@@ -203,7 +226,7 @@ func TestFreshLocalProviderSubscribesToUpdateAvailability(t *testing.T) {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
repo := ¬ificationTestRepository{subscriptions: make(map[string][]*models.Subscription)}
|
||||
service := NewService(repo, nil, nil, log)
|
||||
service := NewService(repo, nil, nil, log, nil)
|
||||
if _, _, err := service.ListProviders(context.Background(), "user-1"); err != nil {
|
||||
t.Fatalf("list providers: %v", err)
|
||||
}
|
||||
@@ -220,7 +243,7 @@ func TestConcurrentProviderInitializationCreatesSingletonDefaultsAndClaimsOneUpd
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
repo := ¬ificationTestRepository{subscriptions: make(map[string][]*models.Subscription)}
|
||||
service := NewService(repo, nil, nil, log)
|
||||
service := NewService(repo, nil, nil, log, nil)
|
||||
local, system := &captureProvider{}, &captureProvider{}
|
||||
service.providers[models.ProviderTypeLocal] = local
|
||||
service.providers[models.ProviderTypeSystem] = system
|
||||
@@ -282,7 +305,7 @@ func TestUpdateAvailabilityRoutesProviderScopedOccurrenceWithReleasePayload(t *t
|
||||
"system": {{ProviderID: "system", EventType: EventSystemUpdateAvailable, Enabled: true}},
|
||||
},
|
||||
}
|
||||
service := NewService(repo, nil, nil, log)
|
||||
service := NewService(repo, nil, nil, log, nil)
|
||||
local, apprise, system := &captureProvider{}, &captureProvider{}, &captureProvider{}
|
||||
service.providers[models.ProviderTypeLocal] = local
|
||||
service.providers[models.ProviderTypeApprise] = apprise
|
||||
@@ -320,7 +343,7 @@ func TestNoEligibleLocalUpdateSubscriberReleasesOccurrenceClaimForReplay(t *test
|
||||
"local": {{ProviderID: "local", EventType: EventSystemUpdateAvailable, Enabled: true}},
|
||||
},
|
||||
}
|
||||
service := NewService(repo, nil, gatewayws.NewHub(nil, log), log)
|
||||
service := NewService(repo, nil, gatewayws.NewHub(nil, log), log, nil)
|
||||
|
||||
service.HandleUpdateAvailable(context.Background(), "v1.2.3", "https://example.test/releases/v1.2.3")
|
||||
if len(repo.deliveries) != 0 {
|
||||
@@ -346,7 +369,7 @@ func TestFailedSemanticDeliveryReleasesOnlyItsOccurrenceClaim(t *testing.T) {
|
||||
"provider-1": {{ProviderID: "provider-1", EventType: EventTaskSessionTurnFinished, Enabled: true}},
|
||||
},
|
||||
}
|
||||
service := NewService(repo, nil, nil, log)
|
||||
service := NewService(repo, nil, nil, log, nil)
|
||||
provider := &failOnceProvider{}
|
||||
service.providers[models.ProviderTypeLocal] = provider
|
||||
|
||||
@@ -367,12 +390,12 @@ func TestProviderSendsClarificationAction(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("create logger: %v", err)
|
||||
}
|
||||
provider := &models.Provider{ID: "provider-1", Type: models.ProviderTypeLocal}
|
||||
service := NewService(¬ificationTestRepository{providers: []*models.Provider{provider}}, nil, nil, log)
|
||||
provider := &models.Provider{ID: "provider-1", UserID: "user-1", Type: models.ProviderTypeLocal}
|
||||
service := NewService(¬ificationTestRepository{providers: []*models.Provider{provider}}, nil, nil, log, nil)
|
||||
capture := &captureProvider{}
|
||||
service.providers[models.ProviderTypeLocal] = capture
|
||||
|
||||
if err := service.TestProvider(context.Background(), provider.ID); err != nil {
|
||||
if err := service.TestProvider(context.Background(), "user-1", provider.ID); err != nil {
|
||||
t.Fatalf("test provider: %v", err)
|
||||
}
|
||||
if len(capture.messages) != 1 || capture.messages[0].EventType != EventTaskSessionClarificationAsked {
|
||||
|
||||
@@ -2,16 +2,25 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/kandev/kandev/internal/notifications/models"
|
||||
)
|
||||
|
||||
// ErrProviderNotFound reports that no provider with the requested ID is
|
||||
// visible to the requesting user. A provider owned by another user is
|
||||
// reported the same way as one that does not exist, so an ID probe cannot
|
||||
// confirm the existence of someone else's provider.
|
||||
var ErrProviderNotFound = errors.New("notification provider not found")
|
||||
|
||||
type Repository interface {
|
||||
CreateProvider(ctx context.Context, provider *models.Provider) error
|
||||
// UpdateProvider is scoped to provider.UserID.
|
||||
UpdateProvider(ctx context.Context, provider *models.Provider) error
|
||||
GetProvider(ctx context.Context, id string) (*models.Provider, error)
|
||||
GetProvider(ctx context.Context, userID, id string) (*models.Provider, error)
|
||||
ListProvidersByUser(ctx context.Context, userID string) ([]*models.Provider, error)
|
||||
DeleteProvider(ctx context.Context, id string) error
|
||||
ListProviderUserIDs(ctx context.Context) ([]string, error)
|
||||
DeleteProvider(ctx context.Context, userID, id string) error
|
||||
|
||||
ListSubscriptionsByProvider(ctx context.Context, providerID string) ([]*models.Subscription, error)
|
||||
ReplaceSubscriptions(ctx context.Context, providerID, userID string, events []string) error
|
||||
|
||||
@@ -310,6 +310,8 @@ func (r *sqliteRepository) CreateProvider(ctx context.Context, provider *models.
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateProvider writes the provider back, scoped to provider.UserID. A row
|
||||
// owned by someone else is reported as ErrProviderNotFound and left untouched.
|
||||
func (r *sqliteRepository) UpdateProvider(ctx context.Context, provider *models.Provider) error {
|
||||
provider.UpdatedAt = time.Now().UTC()
|
||||
if provider.Config == nil {
|
||||
@@ -319,21 +321,31 @@ func (r *sqliteRepository) UpdateProvider(ctx context.Context, provider *models.
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to serialize provider config: %w", err)
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
UPDATE notification_providers
|
||||
SET name = ?, type = ?, config = ?, enabled = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`), provider.Name, provider.Type, string(configJSON), dialect.BoolToInt(provider.Enabled), provider.UpdatedAt, provider.ID)
|
||||
return err
|
||||
WHERE id = ? AND user_id = ?
|
||||
`), provider.Name, provider.Type, string(configJSON), dialect.BoolToInt(provider.Enabled), provider.UpdatedAt, provider.ID, provider.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errIfNoRows(result)
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) GetProvider(ctx context.Context, id string) (*models.Provider, error) {
|
||||
// GetProvider reads one provider owned by userID. A provider ID belonging to
|
||||
// another user is reported exactly like an ID that does not exist, so probing
|
||||
// IDs reveals nothing about other users' configuration.
|
||||
func (r *sqliteRepository) GetProvider(ctx context.Context, userID, id string) (*models.Provider, error) {
|
||||
row := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
|
||||
SELECT id, user_id, name, type, config, enabled, created_at, updated_at
|
||||
FROM notification_providers
|
||||
WHERE id = ?
|
||||
`), id)
|
||||
return scanProvider(row)
|
||||
WHERE id = ? AND user_id = ?
|
||||
`), id, userID)
|
||||
provider, err := scanProvider(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrProviderNotFound
|
||||
}
|
||||
return provider, err
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) ListProvidersByUser(ctx context.Context, userID string) ([]*models.Provider, error) {
|
||||
@@ -364,9 +376,58 @@ func (r *sqliteRepository) ListProvidersByUser(ctx context.Context, userID strin
|
||||
return providers, nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteProvider(ctx context.Context, id string) error {
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM notification_providers WHERE id = ?`), id)
|
||||
return err
|
||||
// DeleteProvider removes one provider owned by userID, reporting a foreign or
|
||||
// nonexistent ID identically as ErrProviderNotFound.
|
||||
// ListProviderUserIDs returns every distinct user that owns at least one
|
||||
// provider. Instance-wide events (a new release) have no owning workspace to
|
||||
// resolve a recipient from, so they fan out across these owners instead of
|
||||
// landing on one hardcoded user.
|
||||
func (r *sqliteRepository) ListProviderUserIDs(ctx context.Context) ([]string, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, `
|
||||
SELECT DISTINCT user_id FROM notification_providers ORDER BY user_id ASC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
_ = rows.Close()
|
||||
}()
|
||||
|
||||
var userIDs []string
|
||||
for rows.Next() {
|
||||
var userID string
|
||||
if err := rows.Scan(&userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userIDs = append(userIDs, userID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return userIDs, nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteProvider(ctx context.Context, userID, id string) error {
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
DELETE FROM notification_providers WHERE id = ? AND user_id = ?
|
||||
`), id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errIfNoRows(result)
|
||||
}
|
||||
|
||||
// errIfNoRows turns a write that matched nothing into ErrProviderNotFound, so
|
||||
// an unauthorized target and a missing one are indistinguishable to the caller.
|
||||
func errIfNoRows(result sql.Result) error {
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrProviderNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) ListSubscriptionsByProvider(ctx context.Context, providerID string) ([]*models.Subscription, error) {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/notifications/models"
|
||||
)
|
||||
|
||||
// seedOwnedProvider stores one enabled provider for userID and returns it.
|
||||
func seedOwnedProvider(t *testing.T, repo *sqliteRepository, userID, name string) *models.Provider {
|
||||
t.Helper()
|
||||
provider := &models.Provider{
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
Type: models.ProviderTypeApprise,
|
||||
Config: map[string]interface{}{"urls": "slack://" + name},
|
||||
Enabled: true,
|
||||
}
|
||||
if err := repo.CreateProvider(context.Background(), provider); err != nil {
|
||||
t.Fatalf("create provider for %s: %v", userID, err)
|
||||
}
|
||||
return provider
|
||||
}
|
||||
|
||||
func newOwnershipTestRepo(t *testing.T) *sqliteRepository {
|
||||
t.Helper()
|
||||
database := openNotificationTestDB(t)
|
||||
repo, err := newSQLiteRepositoryWithDB(context.Background(), database, database)
|
||||
if err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
return repo
|
||||
}
|
||||
|
||||
func TestGetProviderIsScopedToItsOwner(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newOwnershipTestRepo(t)
|
||||
owned := seedOwnedProvider(t, repo, "user-a", "a-webhook")
|
||||
|
||||
got, err := repo.GetProvider(ctx, "user-a", owned.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("owner read: %v", err)
|
||||
}
|
||||
if got.ID != owned.ID {
|
||||
t.Fatalf("owner read = %#v, want provider %s", got, owned.ID)
|
||||
}
|
||||
|
||||
foreign, foreignErr := repo.GetProvider(ctx, "user-b", owned.ID)
|
||||
missing, missingErr := repo.GetProvider(ctx, "user-b", "does-not-exist")
|
||||
if !errors.Is(foreignErr, ErrProviderNotFound) {
|
||||
t.Fatalf("foreign read error = %v, want ErrProviderNotFound", foreignErr)
|
||||
}
|
||||
if !errors.Is(missingErr, ErrProviderNotFound) {
|
||||
t.Fatalf("missing read error = %v, want ErrProviderNotFound", missingErr)
|
||||
}
|
||||
// A guessed ID belonging to someone else must be indistinguishable from
|
||||
// an ID that does not exist at all.
|
||||
if foreignErr.Error() != missingErr.Error() || foreign != nil || missing != nil {
|
||||
t.Fatalf("foreign read (%#v, %v) differs from missing read (%#v, %v)", foreign, foreignErr, missing, missingErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateProviderRejectsAForeignOwnerWithoutMutating(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newOwnershipTestRepo(t)
|
||||
owned := seedOwnedProvider(t, repo, "user-a", "a-webhook")
|
||||
|
||||
hijack := &models.Provider{
|
||||
ID: owned.ID,
|
||||
UserID: "user-b",
|
||||
Name: "stolen",
|
||||
Type: models.ProviderTypeApprise,
|
||||
Config: map[string]interface{}{"urls": "slack://attacker"},
|
||||
Enabled: false,
|
||||
}
|
||||
if err := repo.UpdateProvider(ctx, hijack); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("foreign update error = %v, want ErrProviderNotFound", err)
|
||||
}
|
||||
|
||||
after, err := repo.GetProvider(ctx, "user-a", owned.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("reload after rejected update: %v", err)
|
||||
}
|
||||
if after.Name != "a-webhook" || !after.Enabled || after.Config["urls"] != "slack://a-webhook" {
|
||||
t.Fatalf("provider mutated by a foreign update: %#v", after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteProviderRejectsAForeignOwnerWithoutMutating(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newOwnershipTestRepo(t)
|
||||
owned := seedOwnedProvider(t, repo, "user-a", "a-webhook")
|
||||
|
||||
if err := repo.DeleteProvider(ctx, "user-b", owned.ID); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("foreign delete error = %v, want ErrProviderNotFound", err)
|
||||
}
|
||||
if _, err := repo.GetProvider(ctx, "user-a", owned.ID); err != nil {
|
||||
t.Fatalf("provider deleted by a foreign caller: %v", err)
|
||||
}
|
||||
|
||||
if err := repo.DeleteProvider(ctx, "user-b", "does-not-exist"); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("missing delete error = %v, want ErrProviderNotFound", err)
|
||||
}
|
||||
if err := repo.DeleteProvider(ctx, "user-a", owned.ID); err != nil {
|
||||
t.Fatalf("owner delete: %v", err)
|
||||
}
|
||||
if _, err := repo.GetProvider(ctx, "user-a", owned.ID); !errors.Is(err, ErrProviderNotFound) {
|
||||
t.Fatalf("owner delete left the row behind: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListProvidersByUserSeesOnlyItsOwnRows(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newOwnershipTestRepo(t)
|
||||
seedOwnedProvider(t, repo, "user-a", "a-webhook")
|
||||
seedOwnedProvider(t, repo, "user-b", "b-webhook")
|
||||
|
||||
for userID, want := range map[string]string{"user-a": "a-webhook", "user-b": "b-webhook"} {
|
||||
providers, err := repo.ListProvidersByUser(ctx, userID)
|
||||
if err != nil {
|
||||
t.Fatalf("list for %s: %v", userID, err)
|
||||
}
|
||||
if len(providers) != 1 || providers[0].Name != want {
|
||||
t.Fatalf("%s sees %#v, want only %s", userID, providers, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListProviderUserIDsReturnsEachOwnerOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newOwnershipTestRepo(t)
|
||||
seedOwnedProvider(t, repo, "user-a", "a-webhook")
|
||||
seedOwnedProvider(t, repo, "user-a", "a-second")
|
||||
seedOwnedProvider(t, repo, "user-b", "b-webhook")
|
||||
|
||||
owners, err := repo.ListProviderUserIDs(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("list provider owners: %v", err)
|
||||
}
|
||||
if len(owners) != 2 || owners[0] != "user-a" || owners[1] != "user-b" {
|
||||
t.Fatalf("provider owners = %#v, want [user-a user-b]", owners)
|
||||
}
|
||||
}
|
||||
@@ -262,7 +262,7 @@ func TestService_PollBeforeLocalSubscription_ReplaysCachedUpdateExactlyOnce(t *t
|
||||
t.Cleanup(func() { _ = closeRepo() })
|
||||
|
||||
hub := gateways.NewHub(nil, logger.Default())
|
||||
notifier := notificationservice.NewService(repo, nil, hub, logger.Default())
|
||||
notifier := notificationservice.NewService(repo, nil, hub, logger.Default(), nil)
|
||||
svc := NewService(pool, "v1.0.0", nil, logger.Default())
|
||||
svc.SetNotifier(notifier)
|
||||
fetches := 0
|
||||
|
||||
Reference in New Issue
Block a user