Skip to content

Modern Docker Management, Designed for Everyone

fix: scope aggregate access and isolate frontend session state (#3227)

Kyle Mendell447713a00f95
diff --git a/backend/api/handlers/activities.go b/backend/api/handlers/activities.go
index 9919155ae..40744c8b0 100644
--- a/backend/api/handlers/activities.go
+++ b/backend/api/handlers/activities.go
@@ -128,7 +128,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermActivitiesRead),
+ Middlewares: humamw.RequireAnyEnvironmentPermission(api, authz.PermActivitiesRead),
}, h.StreamAllActivities)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -322,7 +322,8 @@ func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *Stream
}
}
- h.streamAllActivitiesInternal(humaCtx.Context(), input.Limit, encoder, flush)
+ ps, _ := humamw.PermissionsFromContext(humaCtx.Context())
+ h.streamAllActivitiesInternal(humaCtx.Context(), ps, input.Limit, encoder, flush)
},
}, nil
}
@@ -330,8 +331,8 @@ func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *Stream
// streamAllActivitiesInternal multiplexes activity events for the local
// environment and every enabled remote environment over a single response so
// the browser needs one connection regardless of environment count.
-func (h *ActivityHandler) streamAllActivitiesInternal(ctx context.Context, limit int, encoder *json.Encoder, flush func()) {
- _ = agg.Run(ctx, agg.Config[activity.StreamEvent]{
+func (h *ActivityHandler) streamAllActivitiesInternal(ctx context.Context, ps *authz.PermissionSet, limit int, encoder *json.Encoder, flush func()) {
+ _ = httpx.RunAuthorizedAggregateStream(ctx, ps, authz.PermActivitiesRead, agg.Config[activity.StreamEvent]{
Encoder: encoder,
Flush: flush,
Buffer: activityStreamEventBuffer,
@@ -339,15 +340,13 @@ func (h *ActivityHandler) streamAllActivitiesInternal(ctx context.Context, limit
MakeHeartbeat: func() activity.StreamEvent {
return activity.StreamEvent{Type: "heartbeat", Timestamp: time.Now()}
},
- Producers: []agg.Producer[activity.StreamEvent]{
- func(ctx context.Context, events chan<- activity.StreamEvent) {
- h.runLocalActivityStreamProducerInternal(ctx, limit, events)
- },
- func(ctx context.Context, events chan<- activity.StreamEvent) {
- h.runRemoteActivityStreamPollersInternal(ctx, limit, events)
- },
+ },
+ func(ctx context.Context, events chan<- activity.StreamEvent) {
+ h.runLocalActivityStreamProducerInternal(ctx, limit, events)
},
- })
+ func(ctx context.Context, events chan<- activity.StreamEvent) {
+ h.runRemoteActivityStreamPollersInternal(ctx, ps, limit, events)
+ })
}
func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Context, limit int, events chan<- activity.StreamEvent) {
@@ -407,9 +406,21 @@ func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Con
// runRemoteActivityStreamPollersInternal keeps one poller goroutine per
// enabled remote environment, re-listing periodically so environments added
// or removed while the stream is open are picked up without a reconnect.
-func (h *ActivityHandler) runRemoteActivityStreamPollersInternal(ctx context.Context, limit int, events chan<- activity.StreamEvent) {
+func (h *ActivityHandler) runRemoteActivityStreamPollersInternal(ctx context.Context, ps *authz.PermissionSet, limit int, events chan<- activity.StreamEvent) {
agg.ReconcilePollersByKey(ctx,
- h.environmentService.ListRemoteEnvironments,
+ func(ctx context.Context) ([]models.Environment, error) {
+ environments, err := h.environmentService.ListRemoteEnvironments(ctx)
+ if err != nil {
+ return nil, err
+ }
+ allowed := environments[:0]
+ for _, environment := range environments {
+ if ps.Allows(authz.PermActivitiesRead, environment.ID) {
+ allowed = append(allowed, environment)
+ }
+ }
+ return allowed, nil
+ },
func(environment models.Environment) string {
return environment.ID
},
diff --git a/backend/api/handlers/activities_test.go b/backend/api/handlers/activities_test.go
index 3c4d6f288..f0244800c 100644
--- a/backend/api/handlers/activities_test.go
+++ b/backend/api/handlers/activities_test.go
@@ -18,6 +18,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/types/v2/activity"
)
@@ -113,16 +114,16 @@ func limitStreamTestDBToSingleConnInternal(t *testing.T, db *database.DB) {
sqlDB.SetMaxOpenConns(1)
}
-func createStreamTestRemoteEnvironmentInternal(t *testing.T, db *database.DB, apiURL, token string) {
+func createStreamTestRemoteEnvironmentInternal(t *testing.T, db *database.DB, environmentID, name, apiURL, token string) {
t.Helper()
now := time.Now()
require.NoError(t, db.Create(&models.Environment{
BaseModel: models.BaseModel{
- ID: "remote-1",
+ ID: environmentID,
CreatedAt: now,
UpdatedAt: &now,
},
- Name: "Remote",
+ Name: name,
ApiUrl: apiURL,
Status: string(models.EnvironmentStatusOnline),
Enabled: true,
@@ -133,7 +134,7 @@ func createStreamTestRemoteEnvironmentInternal(t *testing.T, db *database.DB, ap
// runStreamAllInternal drives streamAllActivitiesInternal through a pipe and
// returns each decoded event to onEvent until it reports done or the stream
// ends; remaining output is drained so a blocked encoder can always finish.
-func runStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *ActivityHandler, onEvent func(activity.StreamEvent) bool) {
+func runStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *ActivityHandler, ps *authz.PermissionSet, onEvent func(activity.StreamEvent) bool) {
t.Helper()
pr, pw := io.Pipe()
@@ -141,7 +142,7 @@ func runStreamAllInternal(t *testing.T, ctx context.Context, cancel context.Canc
go func() {
defer close(done)
defer func() { _ = pw.Close() }()
- handler.streamAllActivitiesInternal(ctx, 50, json.NewEncoder(pw), func() {})
+ handler.streamAllActivitiesInternal(ctx, ps, 50, json.NewEncoder(pw), func() {})
}()
scanner := bufio.NewScanner(pr)
@@ -183,7 +184,7 @@ func TestActivityHandlerStreamAllEmitsEnvironmentScopedEventsInternal(t *testing
_, _ = w.Write([]byte(`{"success":true,"data":[{"id":"remote-activity-1"}],"pagination":{"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":50}}`))
}))
defer server.Close()
- createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, token)
handler := &ActivityHandler{
activityService: activityService,
@@ -191,7 +192,7 @@ func TestActivityHandlerStreamAllEmitsEnvironmentScopedEventsInternal(t *testing
}
var localSnapshot, remoteSnapshot bool
- runStreamAllInternal(t, ctx, cancel, handler, func(event activity.StreamEvent) bool {
+ runStreamAllInternal(t, ctx, cancel, handler, authz.SudoPermissionSet(), func(event activity.StreamEvent) bool {
if event.Type == "snapshot" && event.EnvironmentID == "0" && len(event.Activities) == 1 {
require.Equal(t, local.ID, event.Activities[0].ID)
require.Equal(t, "0", event.Activities[0].SourceEnvironmentID)
@@ -234,7 +235,7 @@ func TestActivityHandlerStreamAllReusesRemoteEnvironmentAfterInitialPollInternal
_, _ = w.Write([]byte(`{"success":true,"data":[{"id":"remote-activity-1"}],"pagination":{"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":50}}`))
}))
defer server.Close()
- createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, token)
handler := &ActivityHandler{
activityService: activityService,
@@ -242,7 +243,7 @@ func TestActivityHandlerStreamAllReusesRemoteEnvironmentAfterInitialPollInternal
}
remoteSnapshotCount := 0
- runStreamAllInternal(t, ctx, cancel, handler, func(event activity.StreamEvent) bool {
+ runStreamAllInternal(t, ctx, cancel, handler, authz.SudoPermissionSet(), func(event activity.StreamEvent) bool {
if event.Type != "snapshot" || event.EnvironmentID != "remote-1" {
return false
}
@@ -287,7 +288,7 @@ func TestActivityHandlerStreamAllRemoteFailureEmitsErrorAndKeepsStreamingInterna
http.Error(w, "boom", http.StatusInternalServerError)
}))
defer server.Close()
- createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, token)
handler := &ActivityHandler{
activityService: activityService,
@@ -295,7 +296,7 @@ func TestActivityHandlerStreamAllRemoteFailureEmitsErrorAndKeepsStreamingInterna
}
var localSnapshot, remoteError bool
- runStreamAllInternal(t, ctx, cancel, handler, func(event activity.StreamEvent) bool {
+ runStreamAllInternal(t, ctx, cancel, handler, authz.SudoPermissionSet(), func(event activity.StreamEvent) bool {
if event.Type == "snapshot" && event.EnvironmentID == "0" {
localSnapshot = true
}
@@ -308,3 +309,53 @@ func TestActivityHandlerStreamAllRemoteFailureEmitsErrorAndKeepsStreamingInterna
require.True(t, localSnapshot)
require.True(t, remoteError)
}
+
+func TestActivityHandlerStreamAllFiltersUnauthorizedEnvironmentsInternal(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ limitStreamTestDBToSingleConnInternal(t, db)
+ settingsService, err := services.NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ activityService := services.NewActivityService(db)
+ _, err = activityService.StartActivity(ctx, services.StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeResourceAction})
+ require.NoError(t, err)
+
+ allowedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"allowed-activity"}],"pagination":{"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":50}}`))
+ }))
+ defer allowedServer.Close()
+
+ var deniedRequests atomic.Int64
+ deniedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ deniedRequests.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":[],"pagination":{"totalPages":1,"totalItems":0,"currentPage":1,"itemsPerPage":50}}`))
+ }))
+ defer deniedServer.Close()
+
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-allowed", "Allowed", allowedServer.URL, "allowed-token")
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-denied", "Denied", deniedServer.URL, "denied-token")
+
+ handler := &ActivityHandler{
+ activityService: activityService,
+ environmentService: services.NewEnvironmentService(db, allowedServer.Client(), nil, nil, settingsService, nil),
+ }
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("remote-allowed", authz.PermActivitiesRead)
+
+ seenEnvironments := make(map[string]struct{})
+ runStreamAllInternal(t, ctx, cancel, handler, ps, func(event activity.StreamEvent) bool {
+ if event.EnvironmentID != "" {
+ seenEnvironments[event.EnvironmentID] = struct{}{}
+ }
+ return event.Type == "snapshot" && event.EnvironmentID == "remote-allowed"
+ })
+
+ require.Contains(t, seenEnvironments, "remote-allowed")
+ require.NotContains(t, seenEnvironments, "0")
+ require.NotContains(t, seenEnvironments, "remote-denied")
+ require.Zero(t, deniedRequests.Load())
+}
diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.go
index 5892f490f..3c903c5f0 100644
--- a/backend/api/handlers/dashboard.go
+++ b/backend/api/handlers/dashboard.go
@@ -10,6 +10,7 @@ import (
"github.com/danielgtaylor/huma/v2"
humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"
@@ -79,7 +80,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),
+ Middlewares: humamw.RequireAnyEnvironmentPermission(api, authz.PermDashboardRead),
}, h.StreamAllDashboards)
}
@@ -127,7 +128,8 @@ func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *Strea
}
}
- h.streamAllDashboardsInternal(humaCtx.Context(), input.DebugAllGood, encoder, flush)
+ ps, _ := humamw.PermissionsFromContext(humaCtx.Context())
+ h.streamAllDashboardsInternal(humaCtx.Context(), ps, input.DebugAllGood, encoder, flush)
},
}, nil
}
@@ -135,8 +137,8 @@ func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *Strea
// streamAllDashboardsInternal multiplexes dashboard snapshots for the local
// environment and every enabled remote environment over a single response so
// the browser needs one connection regardless of environment count.
-func (h *DashboardHandler) streamAllDashboardsInternal(ctx context.Context, debugAllGood bool, encoder *json.Encoder, flush func()) {
- _ = agg.Run(ctx, agg.Config[dashboardtypes.StreamEvent]{
+func (h *DashboardHandler) streamAllDashboardsInternal(ctx context.Context, ps *authz.PermissionSet, debugAllGood bool, encoder *json.Encoder, flush func()) {
+ _ = httpx.RunAuthorizedAggregateStream(ctx, ps, authz.PermDashboardRead, agg.Config[dashboardtypes.StreamEvent]{
Encoder: encoder,
Flush: flush,
Buffer: dashboardStreamEventBuffer,
@@ -144,15 +146,13 @@ func (h *DashboardHandler) streamAllDashboardsInternal(ctx context.Context, debu
MakeHeartbeat: func() dashboardtypes.StreamEvent {
return dashboardtypes.StreamEvent{Type: "heartbeat", Timestamp: time.Now()}
},
- Producers: []agg.Producer[dashboardtypes.StreamEvent]{
- func(ctx context.Context, events chan<- dashboardtypes.StreamEvent) {
- h.runLocalDashboardStreamProducerInternal(ctx, debugAllGood, events)
- },
- func(ctx context.Context, events chan<- dashboardtypes.StreamEvent) {
- h.runRemoteDashboardStreamPollersInternal(ctx, debugAllGood, events)
- },
+ },
+ func(ctx context.Context, events chan<- dashboardtypes.StreamEvent) {
+ h.runLocalDashboardStreamProducerInternal(ctx, debugAllGood, events)
},
- })
+ func(ctx context.Context, events chan<- dashboardtypes.StreamEvent) {
+ h.runRemoteDashboardStreamPollersInternal(ctx, ps, debugAllGood, events)
+ })
}
// trimDashboardStreamSnapshotInternal drops the first-page container/image
@@ -222,14 +222,41 @@ func (h *DashboardHandler) runLocalDashboardStreamProducerInternal(ctx context.C
// runRemoteDashboardStreamPollersInternal keeps one poller goroutine per
// enabled remote environment, re-listing periodically so environments added
// or removed while the stream is open are picked up without a reconnect.
-func (h *DashboardHandler) runRemoteDashboardStreamPollersInternal(ctx context.Context, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
- agg.ReconcileEnvironmentPollers(ctx, h.environmentService, dashboardStreamEnvReconcileInterval, "dashboard stream",
- func(pollCtx context.Context, environmentID string) {
- h.runRemoteDashboardStreamPollerInternal(pollCtx, environmentID, debugAllGood, events)
+func (h *DashboardHandler) runRemoteDashboardStreamPollersInternal(ctx context.Context, ps *authz.PermissionSet, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
+ agg.ReconcilePollersByKey(ctx,
+ func(ctx context.Context) ([]models.Environment, error) {
+ environments, err := h.environmentService.ListRemoteEnvironments(ctx)
+ if err != nil {
+ return nil, err
+ }
+ allowed := environments[:0]
+ for _, environment := range environments {
+ if ps.Allows(authz.PermDashboardRead, environment.ID) {
+ allowed = append(allowed, environment)
+ }
+ }
+ return allowed, nil
+ },
+ func(environment models.Environment) string {
+ return environment.ID
+ },
+ dashboardStreamEnvironmentVersionInternal,
+ dashboardStreamEnvReconcileInterval,
+ "dashboard stream",
+ func(pollCtx context.Context, environment models.Environment) {
+ h.runRemoteDashboardStreamPollerInternal(pollCtx, environment, debugAllGood, events)
})
}
-func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, environmentID string, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
+func dashboardStreamEnvironmentVersionInternal(environment models.Environment) string {
+ if environment.UpdatedAt == nil {
+ return environment.ID
+ }
+ return environment.ID + ":" + environment.UpdatedAt.UTC().Format(time.RFC3339Nano)
+}
+
+func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, environment models.Environment, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
+ environmentID := environment.ID
// Tell the client this environment is covered before the first poll
// completes so it can hold skeletons instead of assuming no data exists.
if !agg.Send(ctx, events, dashboardtypes.StreamEvent{
@@ -246,12 +273,21 @@ func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Co
pollCtx, cancelPoll := context.WithTimeout(ctx, dashboardStreamRemotePollTimeout)
defer cancelPoll()
- snapshot, err := h.fetchRemoteDashboardSnapshotInternal(pollCtx, environmentID, debugAllGood)
+ currentEnvironment := environment
+ if h.environmentService != nil {
+ var ok bool
+ currentEnvironment, ok = h.environmentService.GetActiveRemoteEnvironmentSnapshot(environmentID)
+ if !ok {
+ return
+ }
+ }
+
+ snapshot, err := h.fetchRemoteDashboardSnapshotInternal(pollCtx, currentEnvironment, debugAllGood)
if err != nil && isDashboardEndpointMissingInternal(err) {
// The agent runs a version without (or with an incompatible)
// aggregate dashboard endpoint; the underlying data is still
// there, so compose the snapshot from the granular endpoints.
- snapshot, err = h.fetchLegacyDashboardSnapshotInternal(pollCtx, environmentID)
+ snapshot, err = h.fetchLegacyDashboardSnapshotInternal(pollCtx, currentEnvironment)
}
if err != nil {
if ctx.Err() != nil {
@@ -300,14 +336,14 @@ func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Co
// endpoint directly through the environment service so the raw remenv error
// survives for classification (proxyRemoteJSONInternal would translate it
// into a huma error first).
-func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, environmentID string, debugAllGood bool) (*dashboardtypes.Snapshot, error) {
+func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, environment models.Environment, debugAllGood bool) (*dashboardtypes.Snapshot, error) {
path := "/api/environments/0/dashboard"
if debugAllGood {
path += "?debugAllGood=true"
}
var out base.ApiResponse[dashboardtypes.Snapshot]
- if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &out); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, path, nil, &out); err != nil {
return nil, err
}
if !out.Success {
@@ -321,7 +357,7 @@ func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Cont
// agents have exposed for far longer than the aggregate dashboard endpoint.
// Each piece is fetched independently so a partially compatible agent still
// yields partial data; only when every piece fails is an error returned.
-func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, environmentID string) (*dashboardtypes.Snapshot, error) {
+func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, environment models.Environment) (*dashboardtypes.Snapshot, error) {
snapshot := &dashboardtypes.Snapshot{
ActionItems: dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}},
}
@@ -330,7 +366,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var containerCounts base.ApiResponse[containertypes.StatusCounts]
- if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/containers/counts", nil, &containerCounts); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/environments/0/containers/counts", nil, &containerCounts); err != nil {
errs = append(errs, err)
} else {
snapshot.Containers.Counts = containerCounts.Data
@@ -345,7 +381,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var imageCounts base.ApiResponse[imagetypes.UsageCounts]
- if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/images/counts", nil, &imageCounts); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/environments/0/images/counts", nil, &imageCounts); err != nil {
errs = append(errs, err)
} else {
snapshot.ImageUsageCounts = imageCounts.Data
@@ -353,7 +389,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var versionInfo versiontypes.Info
- if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/app-version", nil, &versionInfo); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/app-version", nil, &versionInfo); err != nil {
errs = append(errs, err)
} else {
snapshot.VersionInfo = &versionInfo
diff --git a/backend/api/handlers/dashboard_test.go b/backend/api/handlers/dashboard_test.go
index 1d2f6a270..395f0858d 100644
--- a/backend/api/handlers/dashboard_test.go
+++ b/backend/api/handlers/dashboard_test.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -15,6 +16,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"
sqlite "github.com/libtnb/sqlite"
dockercontainer "github.com/moby/moby/api/types/container"
@@ -138,7 +140,7 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {
// runDashboardStreamAllInternal drives streamAllDashboardsInternal through a
// pipe and returns each decoded event to onEvent until it reports done or the
// stream ends; remaining output is drained so a blocked encoder can finish.
-func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *DashboardHandler, onEvent func(dashboardtypes.StreamEvent) bool) {
+func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *DashboardHandler, ps *authz.PermissionSet, onEvent func(dashboardtypes.StreamEvent) bool) {
t.Helper()
pr, pw := io.Pipe()
@@ -146,7 +148,7 @@ func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel con
go func() {
defer close(done)
defer func() { _ = pw.Close() }()
- handler.streamAllDashboardsInternal(ctx, false, json.NewEncoder(pw), func() {})
+ handler.streamAllDashboardsInternal(ctx, ps, false, json.NewEncoder(pw), func() {})
}()
scanner := bufio.NewScanner(pr)
@@ -191,7 +193,7 @@ func TestDashboardHandlerStreamAllEmitsRemoteSnapshotInternal(t *testing.T) {
}}`))
}))
defer server.Close()
- createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, token)
handler := &DashboardHandler{
dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
@@ -199,7 +201,7 @@ func TestDashboardHandlerStreamAllEmitsRemoteSnapshotInternal(t *testing.T) {
}
var remoteSnapshot bool
- runDashboardStreamAllInternal(t, ctx, cancel, handler, func(event dashboardtypes.StreamEvent) bool {
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, authz.SudoPermissionSet(), func(event dashboardtypes.StreamEvent) bool {
if event.Type == "snapshot" && event.EnvironmentID == "remote-1" && event.Snapshot != nil {
require.Equal(t, 2, event.Snapshot.Containers.Counts.RunningContainers)
require.Equal(t, 3, event.Snapshot.Containers.Counts.TotalContainers)
@@ -240,7 +242,7 @@ func TestDashboardHandlerStreamAllLegacyAgentComposesSnapshotFromGranularEndpoin
}
}))
defer server.Close()
- createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, token)
handler := &DashboardHandler{
dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
@@ -248,7 +250,7 @@ func TestDashboardHandlerStreamAllLegacyAgentComposesSnapshotFromGranularEndpoin
}
var composedSnapshot bool
- runDashboardStreamAllInternal(t, ctx, cancel, handler, func(event dashboardtypes.StreamEvent) bool {
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, authz.SudoPermissionSet(), func(event dashboardtypes.StreamEvent) bool {
if event.Type == "snapshot" && event.EnvironmentID == "remote-1" && event.Snapshot != nil {
require.Equal(t, 4, event.Snapshot.Containers.Counts.RunningContainers)
require.Equal(t, 2, event.Snapshot.Containers.Counts.StoppedContainers)
@@ -282,7 +284,7 @@ func TestDashboardHandlerStreamAllLegacyAgent404EmitsIncompatibleErrorInternal(t
_, _ = w.Write([]byte(`{"success":false,"error":"API endpoint not found: ` + r.URL.Path + `"}`))
}))
defer server.Close()
- createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, token)
handler := &DashboardHandler{
dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
@@ -290,7 +292,7 @@ func TestDashboardHandlerStreamAllLegacyAgent404EmitsIncompatibleErrorInternal(t
}
var incompatibleError, localEvent bool
- runDashboardStreamAllInternal(t, ctx, cancel, handler, func(event dashboardtypes.StreamEvent) bool {
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, authz.SudoPermissionSet(), func(event dashboardtypes.StreamEvent) bool {
if event.Type == "error" && event.EnvironmentID == "remote-1" {
require.Equal(t, dashboardtypes.StreamErrorCodeAgentIncompatible, event.ErrorCode)
require.NotEmpty(t, event.Error)
@@ -307,3 +309,83 @@ func TestDashboardHandlerStreamAllLegacyAgent404EmitsIncompatibleErrorInternal(t
require.True(t, incompatibleError)
require.True(t, localEvent)
}
+
+func TestDashboardHandlerStreamAllFiltersUnauthorizedEnvironmentsInternal(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ limitStreamTestDBToSingleConnInternal(t, db)
+ settingsService, err := services.NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ allowedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":{"containers":{"counts":{"runningContainers":1,"totalContainers":1}},"images":{},"imageUsageCounts":{"totalImages":1},"actionItems":{"items":[]},"settings":{}}}`))
+ }))
+ defer allowedServer.Close()
+
+ var deniedRequests atomic.Int64
+ deniedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ deniedRequests.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":{}}`))
+ }))
+ defer deniedServer.Close()
+
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-allowed", "Allowed", allowedServer.URL, "allowed-token")
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-denied", "Denied", deniedServer.URL, "denied-token")
+
+ handler := &DashboardHandler{
+ dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
+ environmentService: services.NewEnvironmentService(db, allowedServer.Client(), nil, nil, settingsService, nil),
+ }
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("remote-allowed", authz.PermDashboardRead)
+
+ seenEnvironments := make(map[string]struct{})
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, ps, func(event dashboardtypes.StreamEvent) bool {
+ if event.EnvironmentID != "" {
+ seenEnvironments[event.EnvironmentID] = struct{}{}
+ }
+ return event.Type == "snapshot" && event.EnvironmentID == "remote-allowed"
+ })
+
+ require.Contains(t, seenEnvironments, "remote-allowed")
+ require.NotContains(t, seenEnvironments, "0")
+ require.NotContains(t, seenEnvironments, "remote-denied")
+ require.Zero(t, deniedRequests.Load())
+}
+
+func TestDashboardHandlerRemoteFetchReusesLoadedEnvironmentInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupActivityHandlerTestDBInternal(t)
+ settingsService, err := services.NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":{"containers":{},"images":{},"imageUsageCounts":{},"actionItems":{"items":[]},"settings":{}}}`))
+ }))
+ defer server.Close()
+ createStreamTestRemoteEnvironmentInternal(t, db, "remote-1", "Remote", server.URL, "remote-token")
+
+ environmentService := services.NewEnvironmentService(db, server.Client(), nil, nil, settingsService, nil)
+ environments, err := environmentService.ListRemoteEnvironments(ctx)
+ require.NoError(t, err)
+ require.Len(t, environments, 1)
+
+ var environmentQueryCount atomic.Int64
+ require.NoError(t, db.Callback().Query().After("gorm:query").Register("arcane_test_count_dashboard_environment_queries", func(tx *gorm.DB) {
+ if activityTestQueryLoadsEnvironmentIDInternal(tx, "remote-1") {
+ environmentQueryCount.Add(1)
+ }
+ }))
+
+ handler := &DashboardHandler{environmentService: environmentService}
+ for range 2 {
+ _, err := handler.fetchRemoteDashboardSnapshotInternal(ctx, environments[0], false)
+ require.NoError(t, err)
+ }
+ require.Zero(t, environmentQueryCount.Load())
+}
diff --git a/backend/api/handlers/remenv_handlers_test.go b/backend/api/handlers/remenv_handlers_test.go
index d0247127d..94db6f860 100644
--- a/backend/api/handlers/remenv_handlers_test.go
+++ b/backend/api/handlers/remenv_handlers_test.go
@@ -127,6 +127,58 @@ func TestSettingsHandler_GetPublicSettings_RemoteSuccess(t *testing.T) {
require.Equal(t, expected, output.Body)
}
+func TestSettingsHandler_GetSettings_RemoteFiltersNonAdminVisibility(t *testing.T) {
+ remoteSettings := []settingstypes.PublicSetting{
+ {Key: "dockerHost", Type: "string", Value: "unix:///var/run/docker.sock"},
+ {Key: "baseServerUrl", Type: "string", Value: "https://manager.example"},
+ {Key: "defaultShell", Type: "string", Value: "/bin/bash"},
+ {Key: "futureAdminSetting", Type: "string", Value: "hidden"},
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, "/api/environments/0/settings", r.URL.Path)
+ require.NoError(t, json.NewEncoder(w).Encode(remoteSettings))
+ }))
+ defer server.Close()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ settingsService, err := services.NewSettingsService(context.Background(), db)
+ require.NoError(t, err)
+ handler := &SettingsHandler{
+ settingsService: settingsService,
+ environmentService: setupRemoteHandlerEnvironmentServiceInternal(t, server),
+ }
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("env-remote", authz.PermSettingsRead)
+ ctx := context.WithValue(context.Background(), humamiddleware.ContextKeyUserPermissions, ps)
+
+ output, err := handler.GetSettings(ctx, &GetSettingsInput{EnvironmentID: "env-remote"})
+ require.NoError(t, err)
+ require.Equal(t, []settingstypes.PublicSetting{remoteSettings[0]}, output.Body)
+}
+
+func TestSettingsHandler_GetSettings_RemotePreservesAdminResponse(t *testing.T) {
+ remoteSettings := []settingstypes.PublicSetting{
+ {Key: "baseServerUrl", Type: "string", Value: "https://manager.example"},
+ {Key: "futureAdminSetting", Type: "string", Value: "visible-to-admin"},
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ require.NoError(t, json.NewEncoder(w).Encode(remoteSettings))
+ }))
+ defer server.Close()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ settingsService, err := services.NewSettingsService(context.Background(), db)
+ require.NoError(t, err)
+ handler := &SettingsHandler{
+ settingsService: settingsService,
+ environmentService: setupRemoteHandlerEnvironmentServiceInternal(t, server),
+ }
+
+ output, err := handler.GetSettings(adminTestContextInternal(), &GetSettingsInput{EnvironmentID: "env-remote"})
+ require.NoError(t, err)
+ require.Equal(t, remoteSettings, output.Body)
+}
+
func TestTemplateHandler_GetGlobalVariables_RemoteSuccess(t *testing.T) {
expected := base.ApiResponse[[]env.Variable]{
Success: true,
diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.go
index d378d61e1..8871bea25 100644
--- a/backend/api/handlers/settings.go
+++ b/backend/api/handlers/settings.go
@@ -292,6 +292,10 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
ps, _ := humamw.PermissionsFromContext(ctx)
isAdmin := ps.IsGlobalAdmin()
+ visibility := models.SettingVisibilityNonAdmin
+ if isAdmin {
+ visibility = models.SettingVisibilityAll
+ }
if input.EnvironmentID != "0" {
if h.environmentService == nil {
@@ -301,13 +305,22 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
if err != nil {
return nil, err
}
+ if !isAdmin {
+ allowedKeys := make(map[string]struct{})
+ for _, setting := range h.settingsService.ListSettings(visibility) {
+ allowedKeys[setting.Key] = struct{}{}
+ }
+ filtered := make([]settings.PublicSetting, 0, len(*settingsDto))
+ for _, setting := range *settingsDto {
+ if _, ok := allowedKeys[setting.Key]; ok {
+ filtered = append(filtered, setting)
+ }
+ }
+ settingsDto = &filtered
+ }
return &GetSettingsOutput{Body: *settingsDto}, nil
}
- visibility := models.SettingVisibilityNonAdmin
- if isAdmin {
- visibility = models.SettingVisibilityAll
- }
settingsList := h.settingsService.ListSettings(visibility)
var settingsDto []settings.PublicSetting
diff --git a/backend/api/middleware/role.go b/backend/api/middleware/role.go
index a0ccb3a3f..8a6aeca09 100644
--- a/backend/api/middleware/role.go
+++ b/backend/api/middleware/role.go
@@ -60,6 +60,23 @@ func RequirePermission(api huma.API, perm string) huma.Middlewares {
}}
}
+// RequireAnyEnvironmentPermission protects aggregate operations that span
+// environments but do not carry an environment ID in their path. The caller
+// must hold perm globally or for at least one environment; handlers remain
+// responsible for filtering aggregate output to the exact allowed scopes.
+func RequireAnyEnvironmentPermission(api huma.API, perm string) huma.Middlewares {
+ return huma.Middlewares{func(ctx huma.Context, next func(huma.Context)) {
+ ps, _ := PermissionsFromContext(ctx.Context())
+ if !ps.AllowsAny(perm) {
+ if err := huma.WriteErr(api, ctx, http.StatusForbidden, "permission denied: "+perm); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to write 403 response", "error", err)
+ }
+ return
+ }
+ next(ctx)
+ }}
+}
+
// RequireGlobalAdmin returns a per-operation Huma middleware that rejects any
// caller who is not a global admin (or sudo). Used for operations that are
// intentionally not exposed as delegated permissions — role creation/edits,
diff --git a/backend/api/middleware/role_test.go b/backend/api/middleware/role_test.go
index b2c697a17..8b18d9e6d 100644
--- a/backend/api/middleware/role_test.go
+++ b/backend/api/middleware/role_test.go
@@ -144,3 +144,58 @@ func TestRequirePermission_SudoCallerAllowed(t *testing.T) {
require.Equal(t, http.StatusNoContent, rec.Code)
require.True(t, handlerRan)
}
+
+func TestRequireAnyEnvironmentPermission(t *testing.T) {
+ tests := []struct {
+ name string
+ permission *authz.PermissionSet
+ wantStatus int
+ wantRan bool
+ }{
+ {name: "missing", permission: authz.NewPermissionSet(), wantStatus: http.StatusForbidden},
+ {name: "other permission", permission: func() *authz.PermissionSet {
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("env-1", authz.PermContainersList)
+ return ps
+ }(), wantStatus: http.StatusForbidden},
+ {name: "environment permission", permission: func() *authz.PermissionSet {
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("env-1", authz.PermActivitiesRead)
+ return ps
+ }(), wantStatus: http.StatusNoContent, wantRan: true},
+ {name: "global permission", permission: func() *authz.PermissionSet {
+ ps := authz.NewPermissionSet()
+ ps.AddGlobal(authz.PermActivitiesRead)
+ return ps
+ }(), wantStatus: http.StatusNoContent, wantRan: true},
+ {name: "sudo", permission: authz.SudoPermissionSet(), wantStatus: http.StatusNoContent, wantRan: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ router := echo.New()
+ api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, tt.permission)))
+ })
+
+ handlerRan := false
+ huma.Register(api, huma.Operation{
+ OperationID: "aggregate-permission-" + tt.name,
+ Method: http.MethodGet,
+ Path: "/activities/stream",
+ Middlewares: RequireAnyEnvironmentPermission(api, authz.PermActivitiesRead),
+ }, func(_ context.Context, _ *struct{}) (*struct{}, error) {
+ handlerRan = true
+ return &struct{}{}, nil
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/activities/stream", nil)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, tt.wantStatus, rec.Code)
+ require.Equal(t, tt.wantRan, handlerRan)
+ })
+ }
+}
diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.go
index 7bf43bb90..6258bf331 100644
--- a/backend/pkg/authz/access_policy.go
+++ b/backend/pkg/authz/access_policy.go
@@ -203,15 +203,7 @@ func allowsPermissionForScopeModeInternal(ps *PermissionSet, perm, scopeMode, se
case AccessScopeModeSelectedEnvPlusGlobal:
return ps.Allows(perm, selectedEnvID)
case AccessScopeModeAnyEffectiveScope:
- if ps.Allows(perm, "") {
- return true
- }
- for envID := range ps.PerEnv {
- if ps.Allows(perm, envID) {
- return true
- }
- }
- return false
+ return ps.AllowsAny(perm)
default:
return false
}
diff --git a/backend/pkg/authz/permission_set.go b/backend/pkg/authz/permission_set.go
index 466b60982..f839c6a38 100644
--- a/backend/pkg/authz/permission_set.go
+++ b/backend/pkg/authz/permission_set.go
@@ -38,6 +38,24 @@ func (ps *PermissionSet) Allows(perm, envID string) bool {
return false
}
+// AllowsAny reports whether the caller may perform perm in at least one
+// effective scope. Global and sudo permissions satisfy the check immediately;
+// otherwise every explicitly granted environment is considered.
+func (ps *PermissionSet) AllowsAny(perm string) bool {
+ if ps == nil {
+ return false
+ }
+ if ps.Allows(perm, "") {
+ return true
+ }
+ for envID := range ps.PerEnv {
+ if ps.Allows(perm, envID) {
+ return true
+ }
+ }
+ return false
+}
+
// IsGlobalAdmin reports whether the caller holds enough global permissions to
// be considered an administrator. True for sudo callers and for callers whose
// Global set contains every defined permission. Used by the backward-compat
diff --git a/backend/pkg/authz/permission_set_test.go b/backend/pkg/authz/permission_set_test.go
index dc7626635..37b6e085f 100644
--- a/backend/pkg/authz/permission_set_test.go
+++ b/backend/pkg/authz/permission_set_test.go
@@ -32,6 +32,41 @@ func TestPermissionSetEnvScopedDoesNotLeak(t *testing.T) {
}
}
+func TestPermissionSetAllowsAnyEffectiveScope(t *testing.T) {
+ tests := []struct {
+ name string
+ ps *PermissionSet
+ want bool
+ }{
+ {name: "nil", ps: nil, want: false},
+ {name: "empty", ps: NewPermissionSet(), want: false},
+ {name: "unrelated environment permission", ps: func() *PermissionSet {
+ ps := NewPermissionSet()
+ ps.AddEnv("env-1", PermContainersList)
+ return ps
+ }(), want: false},
+ {name: "matching environment permission", ps: func() *PermissionSet {
+ ps := NewPermissionSet()
+ ps.AddEnv("env-1", PermActivitiesRead)
+ return ps
+ }(), want: true},
+ {name: "matching global permission", ps: func() *PermissionSet {
+ ps := NewPermissionSet()
+ ps.AddGlobal(PermActivitiesRead)
+ return ps
+ }(), want: true},
+ {name: "sudo", ps: SudoPermissionSet(), want: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.ps.AllowsAny(PermActivitiesRead); got != tt.want {
+ t.Fatalf("AllowsAny() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
func TestPermissionSetIsGlobalAdminRejectsUnknownPermissions(t *testing.T) {
ps := NewPermissionSet()
perms := AllPermissions()
diff --git a/backend/pkg/utils/httpx/aggregate_stream.go b/backend/pkg/utils/httpx/aggregate_stream.go
new file mode 100644
index 000000000..fac0e48f3
--- /dev/null
+++ b/backend/pkg/utils/httpx/aggregate_stream.go
@@ -0,0 +1,29 @@
+package httpx
+
+import (
+ "context"
+
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "go.getarcane.app/streams/agg"
+)
+
+// RunAuthorizedAggregateStream selects local and remote producers from the
+// caller's effective permissions before starting an aggregate stream. Remote
+// producers must still filter individual environments with PermissionSet.Allows.
+func RunAuthorizedAggregateStream[T any](
+ ctx context.Context,
+ ps *authz.PermissionSet,
+ permission string,
+ config agg.Config[T],
+ localProducer agg.Producer[T],
+ remoteProducer agg.Producer[T],
+) error {
+ config.Producers = make([]agg.Producer[T], 0, 2)
+ if ps.Allows(permission, "0") {
+ config.Producers = append(config.Producers, localProducer)
+ }
+ if ps.AllowsAny(permission) {
+ config.Producers = append(config.Producers, remoteProducer)
+ }
+ return agg.Run(ctx, config)
+}
diff --git a/frontend/src/lib/components/activity/activity-center-trigger.svelte b/frontend/src/lib/components/activity/activity-center-trigger.svelte
index 36ab8c8be..4c48fd7cb 100644
--- a/frontend/src/lib/components/activity/activity-center-trigger.svelte
+++ b/frontend/src/lib/components/activity/activity-center-trigger.svelte
@@ -3,6 +3,8 @@
import { activityStore } from '$lib/stores/activity.store.svelte';
import { m } from '$lib/paraglide/messages';
import { cn } from '$lib/utils';
+ import userStore, { userHasPermissionInAnyEnvironment } from '$lib/stores/user-store';
+ import { fromStore } from 'svelte/store';
let {
collapsed = false,
@@ -20,6 +22,8 @@
const activeCount = $derived(activityStore.activeCount);
const isActive = $derived(activeCount > 0);
+ const currentUser = fromStore(userStore);
+ const canReadActivities = $derived(userHasPermissionInAnyEnvironment(currentUser.current, 'activities:read'));
function handleOpenInternal() {
activityStore.openCenter();
@@ -27,82 +31,84 @@
}
</script>
-{#if compact}
- <button
- type="button"
- onclick={handleOpenInternal}
- title={m.activity_center_open()}
- aria-label={m.activity_center_open()}
- class={cn(
- 'group focus-visible:ring-ring relative flex items-center transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
- collapsed
- ? 'mx-auto h-9 w-9 justify-center rounded-xl'
- : 'text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground h-8 w-full rounded-md px-2',
- className
- )}
- >
- <span
+{#if canReadActivities}
+ {#if compact}
+ <button
+ type="button"
+ onclick={handleOpenInternal}
+ title={m.activity_center_open()}
+ aria-label={m.activity_center_open()}
class={cn(
- 'grid place-items-center rounded-md transition-colors',
- collapsed ? 'size-8' : 'size-6',
- isActive
- ? 'bg-primary/15 text-primary'
- : 'bg-sidebar-accent text-sidebar-foreground/60 group-hover:text-sidebar-foreground'
+ 'group focus-visible:ring-ring relative flex items-center transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
+ collapsed
+ ? 'mx-auto h-9 w-9 justify-center rounded-xl'
+ : 'text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground h-8 w-full rounded-md px-2',
+ className
)}
>
- <ActivityIcon class={cn(collapsed ? 'size-4.5' : 'size-3.5')} aria-hidden="true" />
- </span>
- {#if !collapsed}
- <span class="ml-2 min-w-0 flex-1 truncate text-left text-xs font-medium">{m.activity_center_title()}</span>
<span
class={cn(
- 'ml-2 inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] leading-none font-semibold tabular-nums',
- isActive ? 'bg-primary text-primary-foreground' : 'bg-sidebar-accent text-sidebar-foreground/45'
+ 'grid place-items-center rounded-md transition-colors',
+ collapsed ? 'size-8' : 'size-6',
+ isActive
+ ? 'bg-primary/15 text-primary'
+ : 'bg-sidebar-accent text-sidebar-foreground/60 group-hover:text-sidebar-foreground'
)}
>
- {isActive ? (activeCount > 9 ? m.activity_count_many() : activeCount) : '0'}
+ <ActivityIcon class={cn(collapsed ? 'size-4.5' : 'size-3.5')} aria-hidden="true" />
</span>
- {:else if isActive}
- <span
- class="bg-primary text-primary-foreground ring-sidebar absolute -top-0.5 -right-0.5 flex min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-4 font-bold tabular-nums ring-2"
- >
- {activeCount > 9 ? m.activity_count_many() : activeCount}
- </span>
- {/if}
- </button>
-{:else}
- <button
- type="button"
- onclick={handleOpenInternal}
- title={m.activity_center_open()}
- aria-label={m.activity_center_open()}
- class={cn(
- 'text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring relative flex items-center gap-3 rounded-lg transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
- mobile
- ? 'w-full px-4 py-3 text-sm font-medium'
- : collapsed
- ? 'h-9 w-9 justify-center'
- : 'h-9 w-full px-3 text-sm font-medium',
- className
- )}
- >
- <span class="relative inline-flex">
- <ActivityIcon class={cn(mobile ? 'size-5' : 'size-4.5')} aria-hidden="true" />
- {#if activeCount > 0}
+ {#if !collapsed}
+ <span class="ml-2 min-w-0 flex-1 truncate text-left text-xs font-medium">{m.activity_center_title()}</span>
+ <span
+ class={cn(
+ 'ml-2 inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] leading-none font-semibold tabular-nums',
+ isActive ? 'bg-primary text-primary-foreground' : 'bg-sidebar-accent text-sidebar-foreground/45'
+ )}
+ >
+ {isActive ? (activeCount > 9 ? m.activity_count_many() : activeCount) : '0'}
+ </span>
+ {:else if isActive}
<span
- aria-live="polite"
- aria-atomic="true"
- class="bg-primary text-primary-foreground absolute -top-2 -right-2 flex min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-4 font-bold tabular-nums"
+ class="bg-primary text-primary-foreground ring-sidebar absolute -top-0.5 -right-0.5 flex min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-4 font-bold tabular-nums ring-2"
>
{activeCount > 9 ? m.activity_count_many() : activeCount}
</span>
{/if}
- </span>
- {#if !collapsed || mobile}
- <span class="min-w-0 flex-1 truncate text-left">{m.activity_center_title()}</span>
- {#if activeCount > 0}
- <span class="text-primary text-xs font-semibold tabular-nums">{m.activity_active_count({ count: activeCount })}</span>
+ </button>
+ {:else}
+ <button
+ type="button"
+ onclick={handleOpenInternal}
+ title={m.activity_center_open()}
+ aria-label={m.activity_center_open()}
+ class={cn(
+ 'text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring relative flex items-center gap-3 rounded-lg transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
+ mobile
+ ? 'w-full px-4 py-3 text-sm font-medium'
+ : collapsed
+ ? 'h-9 w-9 justify-center'
+ : 'h-9 w-full px-3 text-sm font-medium',
+ className
+ )}
+ >
+ <span class="relative inline-flex">
+ <ActivityIcon class={cn(mobile ? 'size-5' : 'size-4.5')} aria-hidden="true" />
+ {#if activeCount > 0}
+ <span
+ aria-live="polite"
+ aria-atomic="true"
+ class="bg-primary text-primary-foreground absolute -top-2 -right-2 flex min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-4 font-bold tabular-nums"
+ >
+ {activeCount > 9 ? m.activity_count_many() : activeCount}
+ </span>
+ {/if}
+ </span>
+ {#if !collapsed || mobile}
+ <span class="min-w-0 flex-1 truncate text-left">{m.activity_center_title()}</span>
+ {#if activeCount > 0}
+ <span class="text-primary text-xs font-semibold tabular-nums">{m.activity_active_count({ count: activeCount })}</span>
+ {/if}
{/if}
- {/if}
- </button>
+ </button>
+ {/if}
{/if}
diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.ts
index 832db6cf3..6edb08adf 100644
--- a/frontend/src/lib/services/auth-service.ts
+++ b/frontend/src/lib/services/auth-service.ts
@@ -4,6 +4,9 @@ import userStore from '$lib/stores/user-store';
import type { User } from '$lib/types/auth';
import type { OidcStatusInfo } from '$lib/types/settings';
import type { OidcUserInfo, LoginCredentials, LoginResponseData, AutoLoginConfig } from '$lib/types/auth';
+import type { QueryClient } from '@tanstack/svelte-query';
+import { activityStore } from '$lib/stores/activity.store.svelte';
+import { dashboardStore } from '$lib/stores/dashboard.store.svelte';
const REFRESH_TOKEN_KEY = 'arcane_refresh_token';
const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';
@@ -200,9 +203,21 @@ class AuthService extends BaseAPIService {
);
}
- logout(): void {
- this.clearTokenData();
+ resetAuthenticatedState(queryClient: QueryClient, options?: { restartMountedStores?: boolean }): void {
+ queryClient.clear();
+ const restartActivityStore = activityStore.stop({ resetState: true });
+ const restartDashboardStore = dashboardStore.stop({ resetState: true });
userStore.clearUser();
+
+ if (options?.restartMountedStores) {
+ if (restartActivityStore) void activityStore.start();
+ if (restartDashboardStore) void dashboardStore.start();
+ }
+ }
+
+ logout(queryClient: QueryClient): void {
+ this.clearTokenData();
+ this.resetAuthenticatedState(queryClient);
}
/**
diff --git a/frontend/src/lib/stores/activity.store.svelte.ts b/frontend/src/lib/stores/activity.store.svelte.ts
index 5db1248e1..f4eeb261a 100644
--- a/frontend/src/lib/stores/activity.store.svelte.ts
+++ b/frontend/src/lib/stores/activity.store.svelte.ts
@@ -17,6 +17,7 @@ import type {
ActivityStreamEvent
} from '$lib/types/activity.type';
import type { Environment } from '$lib/types/environment';
+import userStore from '$lib/stores/user-store';
const ACTIVITY_LIST_LIMIT = 50;
const ACTIVITY_DETAIL_LIMIT = 500;
@@ -69,9 +70,12 @@ function createActivityStore() {
let _filter = $state<ActivityFilter>('running');
let _open = $state(false);
let _currentEnvironmentId = $state(LOCAL_DOCKER_ENVIRONMENT_ID);
+ let sessionGeneration = 0;
const core = createEnvironmentStreamStore<ActivityEnvironmentState, ActivityStreamEvent>({
label: 'Activity',
+ includeEnvironment: (environment) => userStore.hasPermission('activities:read', environment.id),
+ subscribeEnvironmentFilter: (reconcile) => userStore.subscribe(reconcile),
createEnvironmentState(environment: Pick<Environment, 'id' | 'name'>): ActivityEnvironmentState {
return {
id: environment.id || LOCAL_DOCKER_ENVIRONMENT_ID,
@@ -267,6 +271,7 @@ function createActivityStore() {
return;
}
+ const generation = sessionGeneration;
_detailLoadingIds = { ..._detailLoadingIds, [activityId]: true };
try {
const detail = await activityService.getActivity(
@@ -274,6 +279,9 @@ function createActivityStore() {
activityEnvironmentIdInternal(activityId),
ACTIVITY_DETAIL_LIMIT
);
+ if (generation !== sessionGeneration) {
+ return;
+ }
const environmentId = sourceEnvironmentIdInternal(detail.activity);
const normalized = {
...detail,
@@ -284,12 +292,17 @@ function createActivityStore() {
delete nextErrors[activityId];
_detailErrorIds = nextErrors;
} catch (error) {
+ if (generation !== sessionGeneration) {
+ return;
+ }
console.warn('Failed to load activity detail:', error);
_detailErrorIds = { ..._detailErrorIds, [activityId]: true };
} finally {
- const next = { ..._detailLoadingIds };
- delete next[activityId];
- _detailLoadingIds = next;
+ if (generation === sessionGeneration) {
+ const next = { ..._detailLoadingIds };
+ delete next[activityId];
+ _detailLoadingIds = next;
+ }
}
}
@@ -382,7 +395,23 @@ function createActivityStore() {
return _details[activityId]?.activity ?? _activities.find((item) => item.id === activityId) ?? null;
},
start: () => core.start(),
- stop: () => core.stop(),
+ stop: (options?: { resetState?: boolean }) => {
+ const wasStarted = core.stop(options);
+ if (options?.resetState) {
+ sessionGeneration += 1;
+ _activities = [];
+ _environmentActivities = {};
+ _details = {};
+ _expandedActivityIds = {};
+ _detailLoadingIds = {};
+ _detailErrorIds = {};
+ _cancellingIds = {};
+ _filter = 'running';
+ _open = false;
+ _currentEnvironmentId = LOCAL_DOCKER_ENVIRONMENT_ID;
+ }
+ return wasStarted;
+ },
refresh: () => core.refresh(),
cancelActivity: async (activityId: string) => {
if (!activityId || _cancellingIds[activityId]) {
@@ -400,6 +429,7 @@ function createActivityStore() {
}
},
clearHistory: async (): Promise<ActivityClearHistorySummary> => {
+ const generation = sessionGeneration;
core.reconcileEnvironments();
let deleted = 0;
@@ -422,6 +452,10 @@ function createActivityStore() {
})
);
+ if (generation !== sessionGeneration) {
+ return { deleted, succeeded, failed };
+ }
+
_details = {};
_expandedActivityIds = {};
_detailLoadingIds = {};
diff --git a/frontend/src/lib/stores/dashboard.store.svelte.ts b/frontend/src/lib/stores/dashboard.store.svelte.ts
index 86f83271a..c5b945026 100644
--- a/frontend/src/lib/stores/dashboard.store.svelte.ts
+++ b/frontend/src/lib/stores/dashboard.store.svelte.ts
@@ -8,6 +8,7 @@ import {
} from '$lib/stores/environment-stream.svelte';
import type { DashboardSnapshot, DashboardStreamErrorCode, DashboardStreamEvent } from '$lib/types/shared';
import type { Environment } from '$lib/types/environment';
+import userStore from '$lib/stores/user-store';
type DashboardEnvironmentState = StreamEnvStateBase & {
snapshot: DashboardSnapshot | null;
@@ -23,6 +24,8 @@ function createDashboardStore() {
const core = createEnvironmentStreamStore<DashboardEnvironmentState, DashboardStreamEvent>({
label: 'Dashboard',
+ includeEnvironment: (environment) => userStore.hasPermission('dashboard:read', environment.id),
+ subscribeEnvironmentFilter: (reconcile) => userStore.subscribe(reconcile),
refreshOnStart: true,
clearErrorExtra: { errorCode: undefined },
createEnvironmentState(environment: Pick<Environment, 'id' | 'name'>): DashboardEnvironmentState {
@@ -103,7 +106,7 @@ function createDashboardStore() {
return Boolean(state && state.loading && !state.hasLoaded);
},
start: async (options?: { debugAllGood?: boolean }) => {
- const nextDebugAllGood = options?.debugAllGood ?? false;
+ const nextDebugAllGood = options?.debugAllGood ?? debugAllGood;
if (!browser) {
return;
}
@@ -121,9 +124,11 @@ function createDashboardStore() {
debugAllGood = nextDebugAllGood;
await core.start();
},
- stop: () => {
+ stop: (options?: { resetState?: boolean }) => {
+ const wasStarted = started;
started = false;
- core.stop({ resetStreamFailed: true });
+ core.stop({ resetState: options?.resetState, resetStreamFailed: true });
+ return wasStarted;
},
refresh: () => core.refresh(),
retryStream: () => core.retryStream()
diff --git a/frontend/src/lib/stores/environment-stream.svelte.ts b/frontend/src/lib/stores/environment-stream.svelte.ts
index cc7d4f439..bfc5e96ef 100644
--- a/frontend/src/lib/stores/environment-stream.svelte.ts
+++ b/frontend/src/lib/stores/environment-stream.svelte.ts
@@ -42,6 +42,10 @@ export interface EnvStreamCoreConfig<TState extends StreamEnvStateBase, TEvent e
/** Fully owns a per-environment REST refresh, including generation/removal guards via core helpers. */
fetchSnapshot(environmentId: string, generation: number): Promise<void>;
refreshOnStart?: boolean;
+ /** Limits aggregate stream state and REST snapshots to caller-authorized environments. */
+ includeEnvironment?(environment: Pick<Environment, 'id' | 'name'>): boolean;
+ /** Reconciles when state used by includeEnvironment changes (for example, user permissions). */
+ subscribeEnvironmentFilter?(reconcile: () => void): () => void;
/** Extra cleanup when an environment disappears (core already dropped its state). */
onEnvironmentRemoved?(environmentId: string): void;
/** Replaces the default rename handling (which just updates state.name). */
@@ -58,6 +62,7 @@ export function createEnvironmentStreamStore<TState extends StreamEnvStateBase,
let started = false;
let unsubscribeEnvironment: (() => void) | null = null;
+ let unsubscribeEnvironmentFilter: (() => void) | null = null;
// A single aggregated stream carries every environment's events; per-env
// connections would multiply requests and exhaust the browser's
// 6-per-origin HTTP/1.1 limit.
@@ -263,16 +268,13 @@ export function createEnvironmentStreamStore<TState extends StreamEnvStateBase,
// Track only enabled environments — they are the ones the aggregated
// stream serves; a disabled environment would never leave "loading".
- const available = environmentStore.available.filter((environment) => environment.enabled);
- const environments =
- available.length > 0
- ? available
- : [
- {
- id: environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID,
- name: environmentStore.selected?.name ?? 'Local'
- }
- ];
+ const included = (environment: Pick<Environment, 'id' | 'name'>) => config.includeEnvironment?.(environment) ?? true;
+ const available = environmentStore.available.filter((environment) => environment.enabled && included(environment));
+ const selectedFallback = {
+ id: environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID,
+ name: environmentStore.selected?.name ?? 'Local'
+ };
+ const environments = available.length > 0 ? available : included(selectedFallback) ? [selectedFallback] : [];
const targetIds = new Set(environments.map((environment) => environment.id || LOCAL_DOCKER_ENVIRONMENT_ID));
for (const environmentId of Object.keys(_environmentStates)) {
@@ -347,6 +349,9 @@ export function createEnvironmentStreamStore<TState extends StreamEnvStateBase,
started = true;
await environmentStore.ready;
+ if (!started) {
+ return;
+ }
config.onSelectedEnvironment?.(environmentStore.selected);
reconcileEnvironments();
const generation = nextGeneration();
@@ -358,17 +363,25 @@ export function createEnvironmentStreamStore<TState extends StreamEnvStateBase,
config.onSelectedEnvironment?.(environment);
reconcileEnvironments();
});
+ unsubscribeEnvironmentFilter = config.subscribeEnvironmentFilter?.(reconcileEnvironments) ?? null;
},
- stop(options?: { resetStreamFailed?: boolean }) {
+ stop(options?: { resetState?: boolean; resetStreamFailed?: boolean }) {
+ const wasStarted = started;
started = false;
unsubscribeEnvironment?.();
unsubscribeEnvironment = null;
+ unsubscribeEnvironmentFilter?.();
+ unsubscribeEnvironmentFilter = null;
nextGeneration();
abortStream();
reconnectAttempt = 0;
- if (options?.resetStreamFailed) {
+ if (options?.resetState) {
+ _environmentStates = {};
+ }
+ if (options?.resetState || options?.resetStreamFailed) {
_streamFailed = false;
}
+ return wasStarted;
},
retryStream() {
_streamFailed = false;
diff --git a/frontend/src/lib/stores/user-store.ts b/frontend/src/lib/stores/user-store.ts
index 3e4801566..6505e8c45 100644
--- a/frontend/src/lib/stores/user-store.ts
+++ b/frontend/src/lib/stores/user-store.ts
@@ -6,6 +6,13 @@ import { applyFontSize, FONT_SIZE_DEFAULT } from '$lib/utils/theme';
const userStore = writable<User | null>(null);
+export const userHasPermissionInAnyEnvironment = (user: User | null | undefined, perm: string): boolean => {
+ if (!user?.permissionsByEnv) return false;
+ const global = user.permissionsByEnv[GLOBAL_SCOPE] ?? [];
+ if (global.includes(SUDO_PERMISSION) || global.includes(perm)) return true;
+ return Object.values(user.permissionsByEnv).some((permissions) => permissions.includes(perm));
+};
+
const setUser = async (user: User) => {
if (user.locale) {
await setLocale(user.locale, false);
@@ -54,6 +61,11 @@ const hasAnyPermission = (perms: string[], envId?: string): boolean => {
return perms.some((p) => set.has(p));
};
+/** Returns true if the caller may perform `perm` in at least one effective environment scope. */
+const hasPermissionInAnyEnvironment = (perm: string): boolean => {
+ return userHasPermissionInAnyEnvironment(get(userStore), perm);
+};
+
/** Returns true if the caller effectively holds global administrator access. */
const isGlobalAdmin = (): boolean => {
const user = get(userStore);
@@ -71,5 +83,6 @@ export default {
permissions,
hasPermission,
hasAnyPermission,
+ hasPermissionInAnyEnvironment,
isGlobalAdmin
};
diff --git a/frontend/src/routes/(app)/+layout.svelte b/frontend/src/routes/(app)/+layout.svelte
index 340c6d006..930b6274f 100644
--- a/frontend/src/routes/(app)/+layout.svelte
+++ b/frontend/src/routes/(app)/+layout.svelte
@@ -14,6 +14,7 @@
import { navigationItems, getManagementItems, filterByPermissions, type NavigationItem } from '$lib/config/navigation-config';
import { isEditableTarget, matchesShortcutEvent } from '$lib/utils/navigation';
import { cn } from '$lib/utils';
+ import { userHasPermissionInAnyEnvironment } from '$lib/stores/user-store';
let { data, children }: LayoutProps = $props();
const versionInformation = $derived(data.versionInformation);
@@ -22,6 +23,7 @@
const permissionsManifest = $derived(data.permissionsManifest);
const permissionsManifestLoadFailed = $derived(data.permissionsManifestLoadFailed);
const swarmEnabled = $derived(data.swarmEnabled === true);
+ const canReadActivities = $derived(userHasPermissionInAnyEnvironment(user, 'activities:read'));
const isMobile = new IsMobile();
const isTablet = new IsTablet();
@@ -119,7 +121,9 @@
)
: 'h-full p-3 sm:p-5'}
>
- {@render children()}
+ {#key page.url.pathname}
+ {@render children()}
+ {/key}
</section>
</main>
@@ -128,4 +132,6 @@
{/if}
</Sidebar.Provider>
-<ActivityCenter />
+{#if canReadActivities}
+ <ActivityCenter />
+{/if}
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
index c7934cb82..c7c8acaa4 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
@@ -18,6 +18,7 @@
import { activityStore } from '$lib/stores/activity.store.svelte';
import { dashboardStore } from '$lib/stores/dashboard.store.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import userStore from '$lib/stores/user-store';
import { hasAnyPermission, hasPermission } from '$lib/utils/auth';
import type {
DashboardActionItem,
@@ -93,7 +94,13 @@
let dockerInfoByEnvironmentId = $state<Record<string, DockerInfo | undefined>>({});
let dockerInfoPromiseByEnvironmentId = $state<Record<string, Promise<DockerInfo> | undefined>>({});
- const availableEnvironments = $derived(environmentStore.available);
+ const availableEnvironments = $derived.by(() => {
+ if (!$userStore) {
+ return [];
+ }
+
+ return environmentStore.available.filter((environment) => hasPermission('dashboard:read', environment.id));
+ });
const currentEnvironmentId = $derived(environmentStore.selected?.id ?? null);
function canPruneInEnvironment(envId: string): boolean {
diff --git a/frontend/src/routes/(auth)/logout/+page.ts b/frontend/src/routes/(auth)/logout/+page.ts
index 5074f36a8..13a13c6ce 100644
--- a/frontend/src/routes/(auth)/logout/+page.ts
+++ b/frontend/src/routes/(auth)/logout/+page.ts
@@ -1,7 +1,6 @@
import { redirect } from '@sveltejs/kit';
import type { PageLoad } from './$types';
import { authService } from '$lib/services/auth-service';
-import { queryKeys } from '$lib/query/query-keys';
export const load: PageLoad = async ({ fetch, parent }) => {
const { queryClient } = await parent();
@@ -15,8 +14,7 @@ export const load: PageLoad = async ({ fetch, parent }) => {
console.error('Logout error:', error);
}
- authService.logout();
- queryClient.removeQueries({ queryKey: queryKeys.auth.all });
+ authService.logout(queryClient);
throw redirect(302, '/login');
};
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index 512cb9675..26117b580 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -18,21 +18,22 @@ import { queryKeys } from '$lib/query/query-keys';
export const ssr = false;
-export const load = async () => {
- // Tanstack Query Client
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- enabled: browser,
- staleTime: 0,
- gcTime: 60 * 1000,
- refetchOnMount: 'always',
- refetchOnWindowFocus: 'always',
- refetchOnReconnect: 'always'
- }
+const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ enabled: browser,
+ staleTime: 0,
+ gcTime: 60 * 1000,
+ refetchOnMount: 'always',
+ refetchOnWindowFocus: 'always',
+ refetchOnReconnect: 'always'
}
- });
+ }
+});
+
+let authenticatedUserId: string | null | undefined;
+export const load = async () => {
// Step 1: Check authentication first
let user = await userService.getCurrentUser().catch(() => null);
@@ -62,6 +63,12 @@ export const load = async () => {
}
}
+ const nextAuthenticatedUserId = user?.id ?? null;
+ if (authenticatedUserId !== undefined && authenticatedUserId !== nextAuthenticatedUserId) {
+ authService.resetAuthenticatedState(queryClient, { restartMountedStores: user !== null });
+ }
+ authenticatedUserId = nextAuthenticatedUserId;
+
// Step 2: Only fetch authenticated data if user is logged in
let settings = null;
let swarmEnabled = false;
@@ -105,6 +112,8 @@ export const load = async () => {
// Step 3: Update stores with fetched data (always, even if null)
if (user) {
await userStore.setUser(user);
+ } else {
+ userStore.clearUser();
}
if (settings) {
diff --git a/tests/spec/activity-center.spec.ts b/tests/spec/activity-center.spec.ts
index f2239de26..d3fa243ea 100644
--- a/tests/spec/activity-center.spec.ts
+++ b/tests/spec/activity-center.spec.ts
@@ -25,6 +25,15 @@ type MockActivity = {
updatedAt?: string;
};
+type MockUser = {
+ id: string;
+ username: string;
+ roleAssignments: never[];
+ permissionsByEnv: Record<string, string[]>;
+ isGlobalAdmin: boolean;
+ createdAt: string;
+};
+
const localEnvironment: MockEnvironment = {
id: '0',
name: 'Local',
@@ -103,6 +112,27 @@ async function mockEnvironmentList(page: Page, environments: MockEnvironment[])
});
}
+async function mockCurrentUser(page: Page, resolveUser: () => MockUser) {
+ await page.context().route(/\/api\/auth\/me$/, async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, data: resolveUser() })
+ });
+ });
+}
+
+function user(id: string, permissionsByEnv: Record<string, string[]>): MockUser {
+ return {
+ id,
+ username: id,
+ roleAssignments: [],
+ permissionsByEnv,
+ isGlobalAdmin: false,
+ createdAt: new Date().toISOString()
+ };
+}
+
function aggregatedActivityStreamBody(
activitiesByEnvironment: Record<string, MockActivity[]>,
failedEnvironmentIds: Set<string>
@@ -124,7 +154,8 @@ async function mockActivityReads(
page: Page,
activitiesByEnvironment: Record<string, MockActivity[]>,
failedEnvironmentIds = new Set<string>(),
- failedActivityStatus = 503
+ failedActivityStatus = 503,
+ readEnvironmentIds?: string[]
) {
await page.context().route(/\/api\/activities\/stream(?:\?.*)?$/, async (route: Route) => {
await route.fulfill({
@@ -143,6 +174,7 @@ async function mockActivityReads(
await route.continue();
return;
}
+ readEnvironmentIds?.push(environmentId);
if (failedEnvironmentIds.has(environmentId)) {
await route.fulfill({
@@ -266,6 +298,137 @@ function waitForActivityStream(page: Page) {
}
test.describe('Activity Center', () => {
+ test('scopes aggregate activity and dashboard work to permitted environments', async ({
+ page
+ }) => {
+ const onlineRemoteEnvironment = { ...remoteEnvironment, status: 'online' as const };
+ const scopedUser = user('scoped-stream-user', {
+ global: [],
+ '0': ['dashboard:read'],
+ 'remote-activity-test': ['activities:read']
+ });
+ const activityReads: string[] = [];
+ const dashboardRequests: string[] = [];
+ const statsSockets: string[] = [];
+
+ await preserveLocalEnvironmentSelection(page);
+ await mockCurrentUser(page, () => scopedUser);
+ await mockEnvironmentList(page, [localEnvironment, onlineRemoteEnvironment]);
+ await mockActivityReads(
+ page,
+ {
+ '0': [activity('local-activity', '0', 'Local', 'local-network', 5)],
+ 'remote-activity-test': [
+ activity('remote-activity', 'remote-activity-test', 'Remote Lab', 'remote-network', 1)
+ ]
+ },
+ new Set(),
+ 503,
+ activityReads
+ );
+ page.on('request', (request) => {
+ const pathname = new URL(request.url()).pathname;
+ if (/^\/api\/environments\/[^/]+\/dashboard$/.test(pathname)) {
+ dashboardRequests.push(pathname);
+ }
+ });
+ page.on('websocket', (socket) => statsSockets.push(new URL(socket.url()).pathname));
+
+ const activityStream = waitForActivityStream(page);
+ await page.goto('/dashboard');
+ await activityStream;
+ await expect(page.getByRole('heading', { name: 'Environment Board' })).toBeVisible();
+
+ const activityCenter = await openActivityCenter(page);
+ await activityCenter.getByRole('button', { name: 'Completed' }).click();
+ await expect(activityRow(activityCenter, 'remote-network')).toBeVisible();
+ await expect(activityRow(activityCenter, 'local-network')).toHaveCount(0);
+ await expect.poll(() => activityReads).toContain('remote-activity-test');
+ expect(activityReads).not.toContain('0');
+ await expect.poll(() => dashboardRequests).toContain('/api/environments/0/dashboard');
+ expect(dashboardRequests).not.toContain('/api/environments/remote-activity-test/dashboard');
+ expect(statsSockets).not.toContain('/api/environments/remote-activity-test/ws/system/stats');
+ });
+
+ test('does not mount the activity center without an effective read scope', async ({ page }) => {
+ const streamRequests: string[] = [];
+
+ await preserveLocalEnvironmentSelection(page);
+ await mockCurrentUser(page, () =>
+ user('dashboard-only-user', {
+ global: [],
+ '0': ['dashboard:read']
+ })
+ );
+ await mockEnvironmentList(page, [localEnvironment]);
+ page.on('request', (request) => {
+ if (new URL(request.url()).pathname === '/api/activities/stream') {
+ streamRequests.push(request.url());
+ }
+ });
+
+ await page.goto('/dashboard');
+ await expect(page.getByRole('heading', { name: 'Environment Board' })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Open activity center' })).toHaveCount(0);
+ await page.waitForTimeout(250);
+ expect(streamRequests).toHaveLength(0);
+ });
+
+ test('clears activity state when the authenticated user changes', async ({ page }) => {
+ let activeUserId = 'user-a';
+ const streamedUsers: string[] = [];
+ const permissions = { global: ['*'] };
+
+ await preserveLocalEnvironmentSelection(page);
+ await mockCurrentUser(page, () => user(activeUserId, permissions));
+ await mockEnvironmentList(page, [localEnvironment]);
+ await page.context().route(/\/api\/activities\/stream(?:\?.*)?$/, async (route) => {
+ const requestedBy = activeUserId;
+ streamedUsers.push(requestedBy);
+ const resourceName = requestedBy === 'user-a' ? 'user-a-private-activity' : 'user-b-activity';
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/x-json-stream',
+ body: aggregatedActivityStreamBody(
+ { '0': [activity(`${requestedBy}-activity`, '0', 'Local', resourceName, 1)] },
+ new Set()
+ )
+ });
+ });
+ await page.context().route(/\/api\/environments\/0\/activities(?:\?.*)?$/, async (route) => {
+ const requestedBy = activeUserId;
+ const resourceName = requestedBy === 'user-a' ? 'user-a-private-activity' : 'user-b-activity';
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(
+ paginated([activity(`${requestedBy}-activity`, '0', 'Local', resourceName, 1)])
+ )
+ });
+ });
+ await page.context().route(/\/api\/auth\/logout$/, async (route) => {
+ activeUserId = 'user-b';
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true })
+ });
+ });
+
+ await page.goto('/dashboard');
+ let activityCenter = await openActivityCenter(page);
+ await activityCenter.getByRole('button', { name: 'Completed' }).click();
+ await expect(activityRow(activityCenter, 'user-a-private-activity')).toBeVisible();
+
+ await page.goto('/logout');
+ await page.waitForURL('/dashboard');
+ await expect.poll(() => streamedUsers).toContain('user-b');
+ activityCenter = await openActivityCenter(page);
+ await activityCenter.getByRole('button', { name: 'Completed' }).click();
+ await expect(activityRow(activityCenter, 'user-b-activity')).toBeVisible();
+ await expect(activityRow(activityCenter, 'user-a-private-activity')).toHaveCount(0);
+ });
+
test('shows activity from every configured environment', async ({ page }) => {
await preserveLocalEnvironmentSelection(page);
await mockEnvironmentList(page, [localEnvironment, remoteEnvironment]);