Skip to content

Modern Docker Management, Designed for Everyone

fix: users with env only scopes unable to access the UI (#3081)

Kyle Mendell3da260883906
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index 1381d7627..4684cc6a2 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -10,6 +10,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "sort"
"strconv"
"strings"
"time"
@@ -220,7 +221,10 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsList),
+ // No global PermEnvironmentsList gate: this endpoint also backs the
+ // environment switcher, so any authenticated caller may list. The handler
+ // filters the result to the environments the caller can actually access.
+ // Management mutations (create/update/delete) remain global-gated below.
}, h.ListEnvironments)
huma.Register(api, huma.Operation{
@@ -419,12 +423,26 @@ func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEn
return nil, huma.Error500InternalServerError("service not available")
}
+ // The list endpoint backs both the environments management page and the
+ // environment switcher, so any authenticated caller may reach it. Global
+ // listers (sudo, global admins, or holders of the org-level
+ // environments:list permission) see every environment; environment-scoped
+ // callers see only the environments they hold at least one permission on.
+ ps, ok := humamw.PermissionsFromContext(ctx)
+ if !ok {
+ return nil, huma.Error403Forbidden("permission denied")
+ }
+ var accessibleEnvIDs []string // nil = no restriction
+ if !environmentListerSeesAllInternal(ps) {
+ accessibleEnvIDs = accessibleEnvironmentIDsInternal(ps)
+ }
+
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Type != "" {
params.Filters["type"] = input.Type
}
- envs, paginationResp, err := h.environmentService.ListEnvironmentsPaginated(ctx, params)
+ envs, paginationResp, err := h.environmentService.ListEnvironmentsPaginated(ctx, params, accessibleEnvIDs)
if err != nil {
return nil, huma.Error500InternalServerError((&common.EnvironmentListError{Err: err}).Error())
}
@@ -441,6 +459,30 @@ func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEn
}, nil
}
+// environmentListerSeesAllInternal reports whether the caller may list every
+// environment. True for sudo callers, global admins, and holders of the
+// org-level environments:list permission (Allows short-circuits on sudo and
+// treats global admins as holding every permission).
+func environmentListerSeesAllInternal(ps *authz.PermissionSet) bool {
+ return ps != nil && ps.Allows(authz.PermEnvironmentsList, "")
+}
+
+// accessibleEnvironmentIDsInternal returns the sorted set of environment IDs the
+// caller holds at least one environment-scoped permission on. A non-nil result
+// (possibly empty) restricts the environment list for non-global callers; an
+// empty result yields no environments.
+func accessibleEnvironmentIDsInternal(ps *authz.PermissionSet) []string {
+ if ps == nil {
+ return []string{}
+ }
+ ids := make([]string, 0, len(ps.PerEnv))
+ for envID := range ps.PerEnv {
+ ids = append(ids, envID)
+ }
+ sort.Strings(ids)
+ return ids
+}
+
// CreateEnvironment creates a new environment.
func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *CreateEnvironmentInput) (*CreateEnvironmentOutput, error) {
if h.environmentService == nil || h.apiKeyService == nil {
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 42ec3340f..f5e86e070 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -718,13 +718,23 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)
return &environment, nil
}
-func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams) ([]environment.Environment, pagination.Response, error) {
+func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams, accessibleEnvIDs []string) ([]environment.Environment, pagination.Response, error) {
if strings.TrimSpace(params.Filters["type"]) != "" {
- return s.listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx, params)
+ return s.listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx, params, accessibleEnvIDs)
}
var envs []models.Environment
q := s.db.WithContext(ctx).Model(&models.Environment{}).Where("hidden = ?", false)
+ // accessibleEnvIDs == nil means "no restriction". A non-nil slice limits the
+ // result to those environment IDs; an empty slice therefore matches nothing.
+ switch {
+ case accessibleEnvIDs == nil:
+ // no restriction
+ case len(accessibleEnvIDs) == 0:
+ q = q.Where("1 = 0")
+ default:
+ q = q.Where("id IN ?", accessibleEnvIDs)
+ }
if term := strings.TrimSpace(params.Search); term != "" {
searchPattern := "%" + term + "%"
@@ -750,7 +760,24 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, para
return out, paginationResp, nil
}
-func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx context.Context, params pagination.QueryParams) ([]environment.Environment, pagination.Response, error) {
+// filterEnvironmentsByIDInternal returns only the environments whose ID is in
+// allowedIDs. A non-nil but empty allowedIDs yields an empty slice. Used to
+// restrict the runtime-filtered list path to a caller's accessible environments.
+func filterEnvironmentsByIDInternal(items []environment.Environment, allowedIDs []string) []environment.Environment {
+ allowed := make(map[string]struct{}, len(allowedIDs))
+ for _, id := range allowedIDs {
+ allowed[id] = struct{}{}
+ }
+ out := make([]environment.Environment, 0, len(items))
+ for _, item := range items {
+ if _, ok := allowed[item.ID]; ok {
+ out = append(out, item)
+ }
+ }
+ return out
+}
+
+func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx context.Context, params pagination.QueryParams, accessibleEnvIDs []string) ([]environment.Environment, pagination.Response, error) {
var envs []models.Environment
if err := s.db.WithContext(ctx).
Model(&models.Environment{}).
@@ -764,6 +791,11 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal
return nil, pagination.Response{}, fmt.Errorf("failed to map environments: %w", mapErr)
}
+ // nil = no restriction; non-nil restricts to the caller's accessible envs.
+ if accessibleEnvIDs != nil {
+ items = filterEnvironmentsByIDInternal(items, accessibleEnvIDs)
+ }
+
for i := range items {
ApplyEnvironmentRuntimeState(&items[i])
}
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index 8ac88a991..9a037d8ff 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -738,7 +738,7 @@ func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T)
listedEnvironments, _, err := svc.ListEnvironmentsPaginated(ctx, pagination.QueryParams{
Params: pagination.Params{Start: 0, Limit: 20},
Filters: map[string]string{},
- })
+ }, nil)
require.NoError(t, err)
require.Len(t, listedEnvironments, 2)
for _, env := range listedEnvironments {
@@ -751,6 +751,51 @@ func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T)
require.Equal(t, "env-visible", remoteEnvironments[0].ID)
}
+func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByAccessibleEnvIDs(t *testing.T) {
+ ctx := context.Background()
+ db := setupEnvironmentServiceTestDB(t)
+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
+
+ createTestEnvironment(t, db, "0", "http://localhost:3552", nil)
+ createNamedTestEnvironmentInternal(t, db, "env-a", "Env A", "http://a.example", new("token-a"))
+ createNamedTestEnvironmentInternal(t, db, "env-b", "Env B", "http://b.example", new("token-b"))
+
+ newParams := func(typeFilter string) pagination.QueryParams {
+ filters := map[string]string{}
+ if typeFilter != "" {
+ filters["type"] = typeFilter
+ }
+ return pagination.QueryParams{
+ Params: pagination.Params{Start: 0, Limit: 20},
+ Filters: filters,
+ }
+ }
+
+ // nil = no restriction: every non-hidden environment is returned.
+ all, _, err := svc.ListEnvironmentsPaginated(ctx, newParams(""), nil)
+ require.NoError(t, err)
+ require.ElementsMatch(t, []string{"0", "env-a", "env-b"}, environmentIDsInternal(all))
+
+ // A non-nil allow-list restricts the result on the DB path.
+ scoped, _, err := svc.ListEnvironmentsPaginated(ctx, newParams(""), []string{"env-a"})
+ require.NoError(t, err)
+ require.ElementsMatch(t, []string{"env-a"}, environmentIDsInternal(scoped))
+
+ // The runtime-filter path (type filter) honors the allow-list too.
+ scopedTyped, _, err := svc.ListEnvironmentsPaginated(ctx, newParams("http"), []string{"env-a"})
+ require.NoError(t, err)
+ require.ElementsMatch(t, []string{"env-a"}, environmentIDsInternal(scopedTyped))
+
+ // An empty (non-nil) allow-list yields no environments on either path.
+ none, _, err := svc.ListEnvironmentsPaginated(ctx, newParams(""), []string{})
+ require.NoError(t, err)
+ require.Empty(t, none)
+
+ noneTyped, _, err := svc.ListEnvironmentsPaginated(ctx, newParams("http"), []string{})
+ require.NoError(t, err)
+ require.Empty(t, noneTyped)
+}
+
func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByRuntimeType(t *testing.T) {
ctx := context.Background()
db := setupEnvironmentServiceTestDB(t)
@@ -846,7 +891,7 @@ func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByRuntimeType(t *te
listedEnvironments, _, err := svc.ListEnvironmentsPaginated(ctx, pagination.QueryParams{
Params: pagination.Params{Start: 0, Limit: 20},
Filters: map[string]string{"type": tt.typeFilter},
- })
+ }, nil)
require.NoError(t, err)
require.ElementsMatch(t, tt.wantIDs, environmentIDsInternal(listedEnvironments))
})
diff --git a/backend/internal/services/role_service.go b/backend/internal/services/role_service.go
index 69e21baa9..1683c96b0 100644
--- a/backend/internal/services/role_service.go
+++ b/backend/internal/services/role_service.go
@@ -434,28 +434,28 @@ func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([
return out, nil
}
-// SetUserAssignments replaces the user's source='manual' assignments with the
-// given desired set. Source='oidc' rows are preserved (use
-// ReplaceOidcAssignments for those). Enforces the global-admin guard.
-func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {
+// replaceUserAssignmentsForSourceInternal replaces the user's assignments for a
+// single source (manual or oidc), leaving other sources untouched. References
+// are validated inside the tx so a concurrent role/env delete yields a typed
+// error (→ 400) rather than an opaque FK violation, and the global-admin guard
+// is enforced before commit. Shared by SetUserAssignments and
+// ReplaceOidcAssignments.
+func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Context, userID, source string, desired []models.UserRoleAssignment) error {
for i := range desired {
desired[i].UserID = userID
- desired[i].Source = models.RoleAssignmentSourceManual
+ desired[i].Source = source
}
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- // Validate inside the tx so a concurrent role/env delete can't race past
- // this check. Yields a typed error → 400 at the handler, rather than an
- // opaque FK violation surfacing as 500.
if err := validateAssignmentsExistInternal(tx, desired); err != nil {
return err
}
- if err := tx.Where("user_id = ? AND source = ?", userID, models.RoleAssignmentSourceManual).
+ if err := tx.Where("user_id = ? AND source = ?", userID, source).
Delete(&models.UserRoleAssignment{}).Error; err != nil {
- return fmt.Errorf("failed to clear manual assignments: %w", err)
+ return fmt.Errorf("failed to clear %s assignments: %w", source, err)
}
if len(desired) > 0 {
if err := tx.Create(&desired).Error; err != nil {
- return fmt.Errorf("failed to insert assignments: %w", err)
+ return fmt.Errorf("failed to insert %s assignments: %w", source, err)
}
}
count, err := s.countEffectiveGlobalAdminsInternal(ctx, tx, "")
@@ -474,6 +474,13 @@ func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, des
return nil
}
+// SetUserAssignments replaces the user's source='manual' assignments with the
+// given desired set. Source='oidc' rows are preserved (use
+// ReplaceOidcAssignments for those). Enforces the global-admin guard.
+func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {
+ return s.replaceUserAssignmentsForSourceInternal(ctx, userID, models.RoleAssignmentSourceManual, desired)
+}
+
// validateAssignmentsExistInternal verifies every distinct RoleID and
// EnvironmentID referenced by `desired` exists in the database. Returns the
// first missing reference wrapped in an InvalidRoleAssignmentError so the
@@ -531,36 +538,12 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssi
}
// ReplaceOidcAssignments replaces the user's source='oidc' assignments. Manual
-// assignments are untouched. Enforces the global-admin guard after the swap.
+// assignments are untouched. An OIDC mapping referencing a since-deleted role or
+// environment fails with a typed error; the caller logs and continues login so
+// the user simply receives no OIDC-derived assignments. Enforces the
+// global-admin guard after the swap.
func (s *RoleService) ReplaceOidcAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {
- for i := range desired {
- desired[i].UserID = userID
- desired[i].Source = models.RoleAssignmentSourceOidc
- }
- err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := tx.Where("user_id = ? AND source = ?", userID, models.RoleAssignmentSourceOidc).
- Delete(&models.UserRoleAssignment{}).Error; err != nil {
- return fmt.Errorf("failed to clear oidc assignments: %w", err)
- }
- if len(desired) > 0 {
- if err := tx.Create(&desired).Error; err != nil {
- return fmt.Errorf("failed to insert oidc assignments: %w", err)
- }
- }
- count, err := s.countEffectiveGlobalAdminsInternal(ctx, tx, "")
- if err != nil {
- return err
- }
- if count == 0 {
- return &common.NoGlobalAdminRemainsError{}
- }
- return nil
- })
- if err != nil {
- return err
- }
- s.userCache.Delete(userID)
- return nil
+ return s.replaceUserAssignmentsForSourceInternal(ctx, userID, models.RoleAssignmentSourceOidc, desired)
}
// CountGlobalAdminsExcludingUser returns the number of non-service users (other
diff --git a/backend/internal/services/role_service_test.go b/backend/internal/services/role_service_test.go
index d62d8b59c..ae7ee74de 100644
--- a/backend/internal/services/role_service_test.go
+++ b/backend/internal/services/role_service_test.go
@@ -103,6 +103,33 @@ func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {
require.True(t, common.IsInvalidRoleAssignmentError(err))
}
+func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {
+ ctx := context.Background()
+ userSvc, roleSvc := setupUserAndRoleServices(t)
+ user := createTestUser(t, userSvc, "oidc-user", "oidc-user")
+
+ err := roleSvc.ReplaceOidcAssignments(ctx, user.ID, []models.UserRoleAssignment{
+ {RoleID: "role_does_not_exist"},
+ })
+ require.Error(t, err)
+ require.True(t, common.IsInvalidRoleAssignmentError(err))
+}
+
+func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {
+ ctx := context.Background()
+ userSvc, roleSvc := setupUserAndRoleServices(t)
+ user := createTestUser(t, userSvc, "oidc-user-env", "oidc-user-env")
+ missingEnv := "env_does_not_exist"
+
+ // A valid role scoped to a non-existent environment must fail existence
+ // validation (mirrors SetUserAssignments) rather than attempting an insert.
+ err := roleSvc.ReplaceOidcAssignments(ctx, user.ID, []models.UserRoleAssignment{
+ {RoleID: authz.BuiltInRoleViewer, EnvironmentID: &missingEnv},
+ })
+ require.Error(t, err)
+ require.True(t, common.IsInvalidRoleAssignmentError(err))
+}
+
func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T) {
ctx := context.Background()
userSvc, roleSvc := setupUserAndRoleServices(t)
diff --git a/frontend/src/lib/stores/environment.store.svelte.ts b/frontend/src/lib/stores/environment.store.svelte.ts
index 715bf7adf..acfee9293 100644
--- a/frontend/src/lib/stores/environment.store.svelte.ts
+++ b/frontend/src/lib/stores/environment.store.svelte.ts
@@ -93,6 +93,17 @@ function createEnvironmentManagementStore() {
return _setSelectedEnvironment(firstReachable);
}
+ // Last resort: nothing is auto-selectable (e.g. an environment-scoped user
+ // whose only environment is a currently-offline remote agent). Select the
+ // first available enabled environment so a valid environment stays in scope
+ // instead of leaving it null — which would make the app fall back to local
+ // ('0'), an environment the user may have no access to. The backend already
+ // filters the list to the caller's accessible environments.
+ const firstEnabled = available.find((env) => env.enabled);
+ if (firstEnabled) {
+ return _setSelectedEnvironment(firstEnabled);
+ }
+
_assignSelectedEnvironment(null);
return null;
}
diff --git a/frontend/src/routes/(auth)/oidc/callback/+page.svelte b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
index 0f11ce1c5..d7cd80c6a 100644
--- a/frontend/src/routes/(auth)/oidc/callback/+page.svelte
+++ b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
@@ -10,6 +10,8 @@
import { settingsService } from '$lib/services/settings-service';
import { queryKeys } from '$lib/query/query-keys';
import { authService } from '$lib/services/auth-service';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { getAuthRedirectPath } from '$lib/utils/auth';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { createMutation, useQueryClient } from '@tanstack/svelte-query';
@@ -124,7 +126,23 @@
console.warn('Skipping post-login settings fetch:', err);
}
toast.success('Successfully logged in!');
- await goto(redirectTo, { replaceState: true });
+ // Navigate straight to a route the user can actually reach. Computing the
+ // reachable target here (rather than always going to /dashboard) avoids the
+ // (app) layout's auth-redirect superseding this navigation: an interrupted
+ // goto() never resolves, which would hang this callback on "Processing
+ // Login…". Environment-scoped users (no global perms) would otherwise bounce
+ // to /no-access mid-navigation. invalidateAll() above has repopulated
+ // page.data (user + permissions manifest) and the environment store.
+ const landingUser = page.data['user'] ?? user;
+ const target =
+ getAuthRedirectPath(
+ redirectTo,
+ landingUser,
+ environmentStore.selected?.id,
+ page.data['permissionsManifest'],
+ page.data['permissionsManifestLoadFailed'] ?? false
+ ) ?? redirectTo;
+ await goto(target, { replaceState: true });
},
onError: (err: unknown) => {
console.error('OIDC callback error:', err);