diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index b83e3792a..4b58737c3 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -94,11 +94,20 @@ body: description: We only provide support for current versions of Portainer as per the lifecycle policy linked above. If you are on an older version of Portainer we recommend [updating first](https://docs.portainer.io/start/upgrade) in case your bug has already been fixed. multiple: false options: + - '2.31.3' + - '2.31.2' + - '2.31.1' + - '2.31.0' + - '2.30.1' + - '2.30.0' - '2.29.2' - '2.29.1' - '2.29.0' - '2.28.1' - '2.28.0' + - '2.27.9' + - '2.27.8' + - '2.27.7' - '2.27.6' - '2.27.5' - '2.27.4' diff --git a/api/cli/cli.go b/api/cli/cli.go index f6035f298..0722c0b2e 100644 --- a/api/cli/cli.go +++ b/api/cli/cli.go @@ -61,6 +61,8 @@ func CLIFlags() *portainer.CLIFlags { LogMode: kingpin.Flag("log-mode", "Set the logging output mode").Default("PRETTY").Enum("NOCOLOR", "PRETTY", "JSON"), KubectlShellImage: kingpin.Flag("kubectl-shell-image", "Kubectl shell image").Envar(portainer.KubectlShellImageEnvVar).Default(portainer.DefaultKubectlShellImage).String(), PullLimitCheckDisabled: kingpin.Flag("pull-limit-check-disabled", "Pull limit check").Envar(portainer.PullLimitCheckDisabledEnvVar).Default(defaultPullLimitCheckDisabled).Bool(), + TrustedOrigins: kingpin.Flag("trusted-origins", "List of trusted origins for CSRF protection. Separate multiple origins with a comma.").Envar(portainer.TrustedOriginsEnvVar).String(), + CSP: kingpin.Flag("csp", "Content Security Policy (CSP) header").Envar(portainer.CSPEnvVar).Default("true").Bool(), } } diff --git a/api/cmd/portainer/main.go b/api/cmd/portainer/main.go index 6261efbd9..30493a3da 100644 --- a/api/cmd/portainer/main.go +++ b/api/cmd/portainer/main.go @@ -52,6 +52,7 @@ import ( "github.com/portainer/portainer/pkg/libhelm" libhelmtypes "github.com/portainer/portainer/pkg/libhelm/types" "github.com/portainer/portainer/pkg/libstack/compose" + "github.com/portainer/portainer/pkg/validate" "github.com/gofrs/uuid" "github.com/rs/zerolog/log" @@ -330,6 +331,18 @@ func buildServer(flags *portainer.CLIFlags) portainer.Server { featureflags.Parse(*flags.FeatureFlags, portainer.SupportedFeatureFlags) } + trustedOrigins := []string{} + if *flags.TrustedOrigins != "" { + // validate if the trusted origins are valid urls + for _, origin := range strings.Split(*flags.TrustedOrigins, ",") { + if !validate.IsTrustedOrigin(origin) { + log.Fatal().Str("trusted_origin", origin).Msg("invalid url for trusted origin. Please check the trusted origins flag.") + } + + trustedOrigins = append(trustedOrigins, origin) + } + } + fileService := initFileService(*flags.Data) encryptionKey := loadEncryptionSecretKey(*flags.SecretKeyName) if encryptionKey == nil { @@ -370,7 +383,8 @@ func buildServer(flags *portainer.CLIFlags) portainer.Server { gitService := git.NewService(shutdownCtx) - openAMTService := openamt.NewService() + // Setting insecureSkipVerify to true to preserve the old behaviour. + openAMTService := openamt.NewService(true) cryptoService := &crypto.Service{} @@ -545,6 +559,7 @@ func buildServer(flags *portainer.CLIFlags) portainer.Server { Status: applicationStatus, BindAddress: *flags.Addr, BindAddressHTTPS: *flags.AddrHTTPS, + CSP: *flags.CSP, HTTPEnabled: sslDBSettings.HTTPEnabled, AssetsPath: *flags.Assets, DataStore: dataStore, @@ -578,6 +593,7 @@ func buildServer(flags *portainer.CLIFlags) portainer.Server { PendingActionsService: pendingActionsService, PlatformService: platformService, PullLimitCheckDisabled: *flags.PullLimitCheckDisabled, + TrustedOrigins: trustedOrigins, } } diff --git a/api/database/boltdb/db.go b/api/database/boltdb/db.go index a0db7f4e0..32a1b55c3 100644 --- a/api/database/boltdb/db.go +++ b/api/database/boltdb/db.go @@ -138,6 +138,8 @@ func (connection *DbConnection) Open() error { db, err := bolt.Open(databasePath, 0600, &bolt.Options{ Timeout: 1 * time.Second, InitialMmapSize: connection.InitialMmapSize, + FreelistType: bolt.FreelistMapType, + NoFreelistSync: true, }) if err != nil { return err diff --git a/api/dataservices/base.go b/api/dataservices/base.go index 04af70b02..18839b60f 100644 --- a/api/dataservices/base.go +++ b/api/dataservices/base.go @@ -10,7 +10,7 @@ type BaseCRUD[T any, I constraints.Integer] interface { Create(element *T) error Read(ID I) (*T, error) Exists(ID I) (bool, error) - ReadAll() ([]T, error) + ReadAll(predicates ...func(T) bool) ([]T, error) Update(ID I, element *T) error Delete(ID I) error } @@ -56,12 +56,13 @@ func (service BaseDataService[T, I]) Exists(ID I) (bool, error) { return exists, err } -func (service BaseDataService[T, I]) ReadAll() ([]T, error) { +// ReadAll retrieves all the elements that satisfy all the provided predicates. +func (service BaseDataService[T, I]) ReadAll(predicates ...func(T) bool) ([]T, error) { var collection = make([]T, 0) return collection, service.Connection.ViewTx(func(tx portainer.Transaction) error { var err error - collection, err = service.Tx(tx).ReadAll() + collection, err = service.Tx(tx).ReadAll(predicates...) return err }) diff --git a/api/dataservices/base_test.go b/api/dataservices/base_test.go new file mode 100644 index 000000000..e97a09963 --- /dev/null +++ b/api/dataservices/base_test.go @@ -0,0 +1,92 @@ +package dataservices + +import ( + "strconv" + "testing" + + portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/slicesx" + + "github.com/stretchr/testify/require" +) + +type testObject struct { + ID int + Value int +} + +type mockConnection struct { + store map[int]testObject + + portainer.Connection +} + +func (m mockConnection) UpdateObject(bucket string, key []byte, value interface{}) error { + obj := value.(*testObject) + + m.store[obj.ID] = *obj + + return nil +} + +func (m mockConnection) GetAll(bucketName string, obj any, appendFn func(o any) (any, error)) error { + for _, v := range m.store { + if _, err := appendFn(&v); err != nil { + return err + } + } + + return nil +} + +func (m mockConnection) UpdateTx(fn func(portainer.Transaction) error) error { + return fn(m) +} + +func (m mockConnection) ViewTx(fn func(portainer.Transaction) error) error { + return fn(m) +} + +func (m mockConnection) ConvertToKey(v int) []byte { + return []byte(strconv.Itoa(v)) +} + +func TestReadAll(t *testing.T) { + service := BaseDataService[testObject, int]{ + Bucket: "testBucket", + Connection: mockConnection{store: make(map[int]testObject)}, + } + + data := []testObject{ + {ID: 1, Value: 1}, + {ID: 2, Value: 2}, + {ID: 3, Value: 3}, + {ID: 4, Value: 4}, + {ID: 5, Value: 5}, + } + + for _, item := range data { + err := service.Update(item.ID, &item) + require.NoError(t, err) + } + + // ReadAll without predicates + result, err := service.ReadAll() + require.NoError(t, err) + + expected := append([]testObject{}, data...) + + require.ElementsMatch(t, expected, result) + + // ReadAll with predicates + hasLowID := func(obj testObject) bool { return obj.ID < 3 } + isEven := func(obj testObject) bool { return obj.Value%2 == 0 } + + result, err = service.ReadAll(hasLowID, isEven) + require.NoError(t, err) + + expected = slicesx.Filter(expected, hasLowID) + expected = slicesx.Filter(expected, isEven) + + require.ElementsMatch(t, expected, result) +} diff --git a/api/dataservices/base_tx.go b/api/dataservices/base_tx.go index d9915b64c..5d7e7eee0 100644 --- a/api/dataservices/base_tx.go +++ b/api/dataservices/base_tx.go @@ -34,13 +34,32 @@ func (service BaseDataServiceTx[T, I]) Exists(ID I) (bool, error) { return service.Tx.KeyExists(service.Bucket, identifier) } -func (service BaseDataServiceTx[T, I]) ReadAll() ([]T, error) { +// ReadAll retrieves all the elements that satisfy all the provided predicates. +func (service BaseDataServiceTx[T, I]) ReadAll(predicates ...func(T) bool) ([]T, error) { var collection = make([]T, 0) + if len(predicates) == 0 { + return collection, service.Tx.GetAll( + service.Bucket, + new(T), + AppendFn(&collection), + ) + } + + filterFn := func(element T) bool { + for _, p := range predicates { + if !p(element) { + return false + } + } + + return true + } + return collection, service.Tx.GetAll( service.Bucket, new(T), - AppendFn(&collection), + FilterFn(&collection, filterFn), ) } diff --git a/api/dataservices/edgestackstatus/edgestackstatus.go b/api/dataservices/edgestackstatus/edgestackstatus.go new file mode 100644 index 000000000..7d063ba49 --- /dev/null +++ b/api/dataservices/edgestackstatus/edgestackstatus.go @@ -0,0 +1,89 @@ +package edgestackstatus + +import ( + portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/dataservices" +) + +var _ dataservices.EdgeStackStatusService = &Service{} + +const BucketName = "edge_stack_status" + +type Service struct { + conn portainer.Connection +} + +func (service *Service) BucketName() string { + return BucketName +} + +func NewService(connection portainer.Connection) (*Service, error) { + if err := connection.SetServiceName(BucketName); err != nil { + return nil, err + } + + return &Service{conn: connection}, nil +} + +func (s *Service) Tx(tx portainer.Transaction) ServiceTx { + return ServiceTx{ + service: s, + tx: tx, + } +} + +func (s *Service) Create(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID, status *portainer.EdgeStackStatusForEnv) error { + return s.conn.UpdateTx(func(tx portainer.Transaction) error { + return s.Tx(tx).Create(edgeStackID, endpointID, status) + }) +} + +func (s *Service) Read(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) (*portainer.EdgeStackStatusForEnv, error) { + var element *portainer.EdgeStackStatusForEnv + + return element, s.conn.ViewTx(func(tx portainer.Transaction) error { + var err error + element, err = s.Tx(tx).Read(edgeStackID, endpointID) + + return err + }) +} + +func (s *Service) ReadAll(edgeStackID portainer.EdgeStackID) ([]portainer.EdgeStackStatusForEnv, error) { + var collection = make([]portainer.EdgeStackStatusForEnv, 0) + + return collection, s.conn.ViewTx(func(tx portainer.Transaction) error { + var err error + collection, err = s.Tx(tx).ReadAll(edgeStackID) + + return err + }) +} + +func (s *Service) Update(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID, status *portainer.EdgeStackStatusForEnv) error { + return s.conn.UpdateTx(func(tx portainer.Transaction) error { + return s.Tx(tx).Update(edgeStackID, endpointID, status) + }) +} + +func (s *Service) Delete(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) error { + return s.conn.UpdateTx(func(tx portainer.Transaction) error { + return s.Tx(tx).Delete(edgeStackID, endpointID) + }) +} + +func (s *Service) DeleteAll(edgeStackID portainer.EdgeStackID) error { + return s.conn.UpdateTx(func(tx portainer.Transaction) error { + return s.Tx(tx).DeleteAll(edgeStackID) + }) +} + +func (s *Service) Clear(edgeStackID portainer.EdgeStackID, relatedEnvironmentsIDs []portainer.EndpointID) error { + return s.conn.UpdateTx(func(tx portainer.Transaction) error { + return s.Tx(tx).Clear(edgeStackID, relatedEnvironmentsIDs) + }) +} + +func (s *Service) key(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) []byte { + return append(s.conn.ConvertToKey(int(edgeStackID)), s.conn.ConvertToKey(int(endpointID))...) +} diff --git a/api/dataservices/edgestackstatus/tx.go b/api/dataservices/edgestackstatus/tx.go new file mode 100644 index 000000000..b0dc14856 --- /dev/null +++ b/api/dataservices/edgestackstatus/tx.go @@ -0,0 +1,95 @@ +package edgestackstatus + +import ( + "fmt" + + portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/dataservices" +) + +var _ dataservices.EdgeStackStatusService = &Service{} + +type ServiceTx struct { + service *Service + tx portainer.Transaction +} + +func (service ServiceTx) Create(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID, status *portainer.EdgeStackStatusForEnv) error { + identifier := service.service.key(edgeStackID, endpointID) + return service.tx.CreateObjectWithStringId(BucketName, identifier, status) +} + +func (s ServiceTx) Read(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) (*portainer.EdgeStackStatusForEnv, error) { + var status portainer.EdgeStackStatusForEnv + identifier := s.service.key(edgeStackID, endpointID) + + if err := s.tx.GetObject(BucketName, identifier, &status); err != nil { + return nil, err + } + + return &status, nil +} + +func (s ServiceTx) ReadAll(edgeStackID portainer.EdgeStackID) ([]portainer.EdgeStackStatusForEnv, error) { + keyPrefix := s.service.conn.ConvertToKey(int(edgeStackID)) + + statuses := make([]portainer.EdgeStackStatusForEnv, 0) + + if err := s.tx.GetAllWithKeyPrefix(BucketName, keyPrefix, &portainer.EdgeStackStatusForEnv{}, dataservices.AppendFn(&statuses)); err != nil { + return nil, fmt.Errorf("unable to retrieve EdgeStackStatus for EdgeStack %d: %w", edgeStackID, err) + } + + return statuses, nil +} + +func (s ServiceTx) Update(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID, status *portainer.EdgeStackStatusForEnv) error { + identifier := s.service.key(edgeStackID, endpointID) + return s.tx.UpdateObject(BucketName, identifier, status) +} + +func (s ServiceTx) Delete(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) error { + identifier := s.service.key(edgeStackID, endpointID) + return s.tx.DeleteObject(BucketName, identifier) +} + +func (s ServiceTx) DeleteAll(edgeStackID portainer.EdgeStackID) error { + keyPrefix := s.service.conn.ConvertToKey(int(edgeStackID)) + + statuses := make([]portainer.EdgeStackStatusForEnv, 0) + + if err := s.tx.GetAllWithKeyPrefix(BucketName, keyPrefix, &portainer.EdgeStackStatusForEnv{}, dataservices.AppendFn(&statuses)); err != nil { + return fmt.Errorf("unable to retrieve EdgeStackStatus for EdgeStack %d: %w", edgeStackID, err) + } + + for _, status := range statuses { + if err := s.tx.DeleteObject(BucketName, s.service.key(edgeStackID, status.EndpointID)); err != nil { + return fmt.Errorf("unable to delete EdgeStackStatus for EdgeStack %d and Endpoint %d: %w", edgeStackID, status.EndpointID, err) + } + } + + return nil +} + +func (s ServiceTx) Clear(edgeStackID portainer.EdgeStackID, relatedEnvironmentsIDs []portainer.EndpointID) error { + for _, envID := range relatedEnvironmentsIDs { + existingStatus, err := s.Read(edgeStackID, envID) + if err != nil && !dataservices.IsErrObjectNotFound(err) { + return fmt.Errorf("unable to retrieve status for environment %d: %w", envID, err) + } + + var deploymentInfo portainer.StackDeploymentInfo + if existingStatus != nil { + deploymentInfo = existingStatus.DeploymentInfo + } + + if err := s.Update(edgeStackID, envID, &portainer.EdgeStackStatusForEnv{ + EndpointID: envID, + Status: []portainer.EdgeStackDeploymentStatus{}, + DeploymentInfo: deploymentInfo, + }); err != nil { + return err + } + } + + return nil +} diff --git a/api/dataservices/endpointrelation/endpointrelation.go b/api/dataservices/endpointrelation/endpointrelation.go index a81c258b9..556a046bb 100644 --- a/api/dataservices/endpointrelation/endpointrelation.go +++ b/api/dataservices/endpointrelation/endpointrelation.go @@ -112,13 +112,13 @@ func (service *Service) UpdateEndpointRelation(endpointID portainer.EndpointID, } func (service *Service) AddEndpointRelationsForEdgeStack(endpointIDs []portainer.EndpointID, edgeStackID portainer.EdgeStackID) error { - return service.connection.ViewTx(func(tx portainer.Transaction) error { + return service.connection.UpdateTx(func(tx portainer.Transaction) error { return service.Tx(tx).AddEndpointRelationsForEdgeStack(endpointIDs, edgeStackID) }) } func (service *Service) RemoveEndpointRelationsForEdgeStack(endpointIDs []portainer.EndpointID, edgeStackID portainer.EdgeStackID) error { - return service.connection.ViewTx(func(tx portainer.Transaction) error { + return service.connection.UpdateTx(func(tx portainer.Transaction) error { return service.Tx(tx).RemoveEndpointRelationsForEdgeStack(endpointIDs, edgeStackID) }) } diff --git a/api/dataservices/interface.go b/api/dataservices/interface.go index 8ba55531c..d330d4959 100644 --- a/api/dataservices/interface.go +++ b/api/dataservices/interface.go @@ -12,6 +12,7 @@ type ( EdgeGroup() EdgeGroupService EdgeJob() EdgeJobService EdgeStack() EdgeStackService + EdgeStackStatus() EdgeStackStatusService Endpoint() EndpointService EndpointGroup() EndpointGroupService EndpointRelation() EndpointRelationService @@ -39,8 +40,8 @@ type ( Open() (newStore bool, err error) Init() error Close() error - UpdateTx(func(DataStoreTx) error) error - ViewTx(func(DataStoreTx) error) error + UpdateTx(func(tx DataStoreTx) error) error + ViewTx(func(tx DataStoreTx) error) error MigrateData() error Rollback(force bool) error CheckCurrentEdition() error @@ -89,6 +90,16 @@ type ( BucketName() string } + EdgeStackStatusService interface { + Create(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID, status *portainer.EdgeStackStatusForEnv) error + Read(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) (*portainer.EdgeStackStatusForEnv, error) + ReadAll(edgeStackID portainer.EdgeStackID) ([]portainer.EdgeStackStatusForEnv, error) + Update(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID, status *portainer.EdgeStackStatusForEnv) error + Delete(edgeStackID portainer.EdgeStackID, endpointID portainer.EndpointID) error + DeleteAll(edgeStackID portainer.EdgeStackID) error + Clear(edgeStackID portainer.EdgeStackID, relatedEnvironmentsIDs []portainer.EndpointID) error + } + // EndpointService represents a service for managing environment(endpoint) data EndpointService interface { Endpoint(ID portainer.EndpointID) (*portainer.Endpoint, error) diff --git a/api/dataservices/snapshot/snapshot.go b/api/dataservices/snapshot/snapshot.go index 155077677..c0066317d 100644 --- a/api/dataservices/snapshot/snapshot.go +++ b/api/dataservices/snapshot/snapshot.go @@ -51,3 +51,20 @@ func (service *Service) ReadWithoutSnapshotRaw(ID portainer.EndpointID) (*portai return snapshot, err } + +func (service *Service) ReadRawMessage(ID portainer.EndpointID) (*portainer.SnapshotRawMessage, error) { + var snapshot *portainer.SnapshotRawMessage + + err := service.Connection.ViewTx(func(tx portainer.Transaction) error { + var err error + snapshot, err = service.Tx(tx).ReadRawMessage(ID) + + return err + }) + + return snapshot, err +} + +func (service *Service) CreateRawMessage(snapshot *portainer.SnapshotRawMessage) error { + return service.Connection.CreateObjectWithId(BucketName, int(snapshot.EndpointID), snapshot) +} diff --git a/api/dataservices/snapshot/tx.go b/api/dataservices/snapshot/tx.go index 8a8dcc1c2..45d1df9fc 100644 --- a/api/dataservices/snapshot/tx.go +++ b/api/dataservices/snapshot/tx.go @@ -35,3 +35,19 @@ func (service ServiceTx) ReadWithoutSnapshotRaw(ID portainer.EndpointID) (*porta return &snapshot.Snapshot, nil } + +func (service ServiceTx) ReadRawMessage(ID portainer.EndpointID) (*portainer.SnapshotRawMessage, error) { + var snapshot = portainer.SnapshotRawMessage{} + + identifier := service.Connection.ConvertToKey(int(ID)) + + if err := service.Tx.GetObject(service.Bucket, identifier, &snapshot); err != nil { + return nil, err + } + + return &snapshot, nil +} + +func (service ServiceTx) CreateRawMessage(snapshot *portainer.SnapshotRawMessage) error { + return service.Tx.CreateObjectWithId(BucketName, int(snapshot.EndpointID), snapshot) +} diff --git a/api/datastore/migrate_data.go b/api/datastore/migrate_data.go index 8047274d1..409936db8 100644 --- a/api/datastore/migrate_data.go +++ b/api/datastore/migrate_data.go @@ -40,13 +40,11 @@ func (store *Store) MigrateData() error { } // before we alter anything in the DB, create a backup - _, err = store.Backup("") - if err != nil { + if _, err := store.Backup(""); err != nil { return errors.Wrap(err, "while backing up database") } - err = store.FailSafeMigrate(migrator, version) - if err != nil { + if err := store.FailSafeMigrate(migrator, version); err != nil { err = errors.Wrap(err, "failed to migrate database") log.Warn().Err(err).Msg("migration failed, restoring database to previous version") @@ -85,6 +83,7 @@ func (store *Store) newMigratorParameters(version *models.Version, flags *portai DockerhubService: store.DockerHubService, AuthorizationService: authorization.NewService(store), EdgeStackService: store.EdgeStackService, + EdgeStackStatusService: store.EdgeStackStatusService, EdgeJobService: store.EdgeJobService, TunnelServerService: store.TunnelServerService, PendingActionsService: store.PendingActionsService, @@ -140,8 +139,7 @@ func (store *Store) connectionRollback(force bool) error { } } - err := store.Restore() - if err != nil { + if err := store.Restore(); err != nil { return err } diff --git a/api/datastore/migrator/migrate_2_31_0.go b/api/datastore/migrator/migrate_2_31_0.go new file mode 100644 index 000000000..7afea9802 --- /dev/null +++ b/api/datastore/migrator/migrate_2_31_0.go @@ -0,0 +1,31 @@ +package migrator + +import portainer "github.com/portainer/portainer/api" + +func (m *Migrator) migrateEdgeStacksStatuses_2_31_0() error { + edgeStacks, err := m.edgeStackService.EdgeStacks() + if err != nil { + return err + } + + for _, edgeStack := range edgeStacks { + for envID, status := range edgeStack.Status { + if err := m.edgeStackStatusService.Create(edgeStack.ID, envID, &portainer.EdgeStackStatusForEnv{ + EndpointID: envID, + Status: status.Status, + DeploymentInfo: status.DeploymentInfo, + ReadyRePullImage: status.ReadyRePullImage, + }); err != nil { + return err + } + } + + edgeStack.Status = nil + + if err := m.edgeStackService.UpdateEdgeStack(edgeStack.ID, &edgeStack); err != nil { + return err + } + } + + return nil +} diff --git a/api/datastore/migrator/migrate_2_32_0.go b/api/datastore/migrator/migrate_2_32_0.go new file mode 100644 index 000000000..c32a63cad --- /dev/null +++ b/api/datastore/migrator/migrate_2_32_0.go @@ -0,0 +1,33 @@ +package migrator + +import ( + "github.com/pkg/errors" + portainer "github.com/portainer/portainer/api" + perrors "github.com/portainer/portainer/api/dataservices/errors" + "github.com/portainer/portainer/api/internal/endpointutils" +) + +func (m *Migrator) addEndpointRelationForEdgeAgents_2_32_0() error { + endpoints, err := m.endpointService.Endpoints() + if err != nil { + return err + } + + for _, endpoint := range endpoints { + if endpointutils.IsEdgeEndpoint(&endpoint) { + _, err := m.endpointRelationService.EndpointRelation(endpoint.ID) + if err != nil && errors.Is(err, perrors.ErrObjectNotFound) { + relation := &portainer.EndpointRelation{ + EndpointID: endpoint.ID, + EdgeStacks: make(map[portainer.EdgeStackID]bool), + } + + if err := m.endpointRelationService.Create(relation); err != nil { + return err + } + } + } + } + + return nil +} diff --git a/api/datastore/migrator/migrator.go b/api/datastore/migrator/migrator.go index dc92006ad..4c2a50e59 100644 --- a/api/datastore/migrator/migrator.go +++ b/api/datastore/migrator/migrator.go @@ -3,12 +3,12 @@ package migrator import ( "errors" - "github.com/Masterminds/semver" portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/database/models" "github.com/portainer/portainer/api/dataservices/dockerhub" "github.com/portainer/portainer/api/dataservices/edgejob" "github.com/portainer/portainer/api/dataservices/edgestack" + "github.com/portainer/portainer/api/dataservices/edgestackstatus" "github.com/portainer/portainer/api/dataservices/endpoint" "github.com/portainer/portainer/api/dataservices/endpointgroup" "github.com/portainer/portainer/api/dataservices/endpointrelation" @@ -27,6 +27,8 @@ import ( "github.com/portainer/portainer/api/dataservices/user" "github.com/portainer/portainer/api/dataservices/version" "github.com/portainer/portainer/api/internal/authorization" + + "github.com/Masterminds/semver" "github.com/rs/zerolog/log" ) @@ -56,6 +58,7 @@ type ( authorizationService *authorization.Service dockerhubService *dockerhub.Service edgeStackService *edgestack.Service + edgeStackStatusService *edgestackstatus.Service edgeJobService *edgejob.Service TunnelServerService *tunnelserver.Service pendingActionsService *pendingactions.Service @@ -84,6 +87,7 @@ type ( AuthorizationService *authorization.Service DockerhubService *dockerhub.Service EdgeStackService *edgestack.Service + EdgeStackStatusService *edgestackstatus.Service EdgeJobService *edgejob.Service TunnelServerService *tunnelserver.Service PendingActionsService *pendingactions.Service @@ -114,6 +118,7 @@ func NewMigrator(parameters *MigratorParameters) *Migrator { authorizationService: parameters.AuthorizationService, dockerhubService: parameters.DockerhubService, edgeStackService: parameters.EdgeStackService, + edgeStackStatusService: parameters.EdgeStackStatusService, edgeJobService: parameters.EdgeJobService, TunnelServerService: parameters.TunnelServerService, pendingActionsService: parameters.PendingActionsService, @@ -242,6 +247,10 @@ func (m *Migrator) initMigrations() { m.migratePendingActionsDataForDB130, ) + m.addMigrations("2.31.0", m.migrateEdgeStacksStatuses_2_31_0) + + m.addMigrations("2.32.0", m.addEndpointRelationForEdgeAgents_2_32_0) + // Add new migrations above... // One function per migration, each versions migration funcs in the same file. } diff --git a/api/datastore/services.go b/api/datastore/services.go index b5363afe9..b0570fa67 100644 --- a/api/datastore/services.go +++ b/api/datastore/services.go @@ -13,6 +13,7 @@ import ( "github.com/portainer/portainer/api/dataservices/edgegroup" "github.com/portainer/portainer/api/dataservices/edgejob" "github.com/portainer/portainer/api/dataservices/edgestack" + "github.com/portainer/portainer/api/dataservices/edgestackstatus" "github.com/portainer/portainer/api/dataservices/endpoint" "github.com/portainer/portainer/api/dataservices/endpointgroup" "github.com/portainer/portainer/api/dataservices/endpointrelation" @@ -39,6 +40,8 @@ import ( "github.com/segmentio/encoding/json" ) +var _ dataservices.DataStore = &Store{} + // Store defines the implementation of portainer.DataStore using // BoltDB as the storage system. type Store struct { @@ -51,6 +54,7 @@ type Store struct { EdgeGroupService *edgegroup.Service EdgeJobService *edgejob.Service EdgeStackService *edgestack.Service + EdgeStackStatusService *edgestackstatus.Service EndpointGroupService *endpointgroup.Service EndpointService *endpoint.Service EndpointRelationService *endpointrelation.Service @@ -109,6 +113,12 @@ func (store *Store) initServices() error { store.EdgeStackService = edgeStackService endpointRelationService.RegisterUpdateStackFunction(edgeStackService.UpdateEdgeStackFunc, edgeStackService.UpdateEdgeStackFuncTx) + edgeStackStatusService, err := edgestackstatus.NewService(store.connection) + if err != nil { + return err + } + store.EdgeStackStatusService = edgeStackStatusService + edgeGroupService, err := edgegroup.NewService(store.connection) if err != nil { return err @@ -269,6 +279,10 @@ func (store *Store) EdgeStack() dataservices.EdgeStackService { return store.EdgeStackService } +func (store *Store) EdgeStackStatus() dataservices.EdgeStackStatusService { + return store.EdgeStackStatusService +} + // Environment(Endpoint) gives access to the Environment(Endpoint) data management layer func (store *Store) Endpoint() dataservices.EndpointService { return store.EndpointService diff --git a/api/datastore/services_tx.go b/api/datastore/services_tx.go index ddedf20cc..cf9f868f4 100644 --- a/api/datastore/services_tx.go +++ b/api/datastore/services_tx.go @@ -32,6 +32,10 @@ func (tx *StoreTx) EdgeStack() dataservices.EdgeStackService { return tx.store.EdgeStackService.Tx(tx.tx) } +func (tx *StoreTx) EdgeStackStatus() dataservices.EdgeStackStatusService { + return tx.store.EdgeStackStatusService.Tx(tx.tx) +} + func (tx *StoreTx) Endpoint() dataservices.EndpointService { return tx.store.EndpointService.Tx(tx.tx) } diff --git a/api/datastore/test_data/output_24_to_latest.json b/api/datastore/test_data/output_24_to_latest.json index b0078c326..5e8b0eefa 100644 --- a/api/datastore/test_data/output_24_to_latest.json +++ b/api/datastore/test_data/output_24_to_latest.json @@ -8,6 +8,7 @@ } ], "edge_stack": null, + "edge_stack_status": null, "edgegroups": null, "edgejobs": null, "endpoint_groups": [ @@ -120,6 +121,10 @@ "Ecr": { "Region": "" }, + "Github": { + "OrganisationName": "", + "UseOrganisation": false + }, "Gitlab": { "InstanceURL": "", "ProjectId": 0, @@ -610,7 +615,7 @@ "RequiredPasswordLength": 12 }, "KubeconfigExpiry": "0", - "KubectlShellImage": "portainer/kubectl-shell:2.30.0", + "KubectlShellImage": "portainer/kubectl-shell:2.32.0", "LDAPSettings": { "AnonymousMode": true, "AutoCreateUsers": true, @@ -678,14 +683,11 @@ "Images": null, "Info": { "Architecture": "", - "BridgeNfIp6tables": false, - "BridgeNfIptables": false, "CDISpecDirs": null, "CPUSet": false, "CPUShares": false, "CgroupDriver": "", "ContainerdCommit": { - "Expected": "", "ID": "" }, "Containers": 0, @@ -709,7 +711,6 @@ "IndexServerAddress": "", "InitBinary": "", "InitCommit": { - "Expected": "", "ID": "" }, "Isolation": "", @@ -738,7 +739,6 @@ }, "RegistryConfig": null, "RuncCommit": { - "Expected": "", "ID": "" }, "Runtimes": null, @@ -780,6 +780,7 @@ "ImageCount": 9, "IsPodman": false, "NodeCount": 0, + "PerformanceMetrics": null, "RunningContainerCount": 5, "ServiceCount": 0, "StackCount": 2, @@ -943,7 +944,7 @@ } ], "version": { - "VERSION": "{\"SchemaVersion\":\"2.30.0\",\"MigratorCount\":0,\"Edition\":1,\"InstanceID\":\"463d5c47-0ea5-4aca-85b1-405ceefee254\"}" + "VERSION": "{\"SchemaVersion\":\"2.32.0\",\"MigratorCount\":1,\"Edition\":1,\"InstanceID\":\"463d5c47-0ea5-4aca-85b1-405ceefee254\"}" }, "webhooks": null } \ No newline at end of file diff --git a/api/hostmanagement/openamt/openamt.go b/api/hostmanagement/openamt/openamt.go index b27b78878..5843c1bdb 100644 --- a/api/hostmanagement/openamt/openamt.go +++ b/api/hostmanagement/openamt/openamt.go @@ -32,9 +32,9 @@ type Service struct { } // NewService initializes a new service. -func NewService() *Service { +func NewService(insecureSkipVerify bool) *Service { tlsConfig := crypto.CreateTLSConfiguration() - tlsConfig.InsecureSkipVerify = true + tlsConfig.InsecureSkipVerify = insecureSkipVerify return &Service{ httpsClient: &http.Client{ diff --git a/api/http/csrf/csrf.go b/api/http/csrf/csrf.go index 857d72c8b..6205c9290 100644 --- a/api/http/csrf/csrf.go +++ b/api/http/csrf/csrf.go @@ -2,6 +2,7 @@ package csrf import ( "crypto/rand" + "errors" "fmt" "net/http" "os" @@ -9,7 +10,8 @@ import ( "github.com/portainer/portainer/api/http/security" httperror "github.com/portainer/portainer/pkg/libhttp/error" - gorillacsrf "github.com/gorilla/csrf" + gcsrf "github.com/gorilla/csrf" + "github.com/rs/zerolog/log" "github.com/urfave/negroni" ) @@ -19,7 +21,7 @@ func SkipCSRFToken(w http.ResponseWriter) { w.Header().Set(csrfSkipHeader, "1") } -func WithProtect(handler http.Handler) (http.Handler, error) { +func WithProtect(handler http.Handler, trustedOrigins []string) (http.Handler, error) { // IsDockerDesktopExtension is used to check if we should skip csrf checks in the request bouncer (ShouldSkipCSRFCheck) // DOCKER_EXTENSION is set to '1' in build/docker-extension/docker-compose.yml isDockerDesktopExtension := false @@ -34,10 +36,12 @@ func WithProtect(handler http.Handler) (http.Handler, error) { return nil, fmt.Errorf("failed to generate CSRF token: %w", err) } - handler = gorillacsrf.Protect( + handler = gcsrf.Protect( token, - gorillacsrf.Path("/"), - gorillacsrf.Secure(false), + gcsrf.Path("/"), + gcsrf.Secure(false), + gcsrf.TrustedOrigins(trustedOrigins), + gcsrf.ErrorHandler(withErrorHandler(trustedOrigins)), )(handler) return withSkipCSRF(handler, isDockerDesktopExtension), nil @@ -55,7 +59,7 @@ func withSendCSRFToken(handler http.Handler) http.Handler { } if statusCode := sw.Status(); statusCode >= 200 && statusCode < 300 { - sw.Header().Set("X-CSRF-Token", gorillacsrf.Token(r)) + sw.Header().Set("X-CSRF-Token", gcsrf.Token(r)) } }) @@ -73,9 +77,33 @@ func withSkipCSRF(handler http.Handler, isDockerDesktopExtension bool) http.Hand } if skip { - r = gorillacsrf.UnsafeSkipCheck(r) + r = gcsrf.UnsafeSkipCheck(r) } handler.ServeHTTP(w, r) }) } + +func withErrorHandler(trustedOrigins []string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + err := gcsrf.FailureReason(r) + + if errors.Is(err, gcsrf.ErrBadOrigin) || errors.Is(err, gcsrf.ErrBadReferer) || errors.Is(err, gcsrf.ErrNoReferer) { + log.Error().Err(err). + Str("request_url", r.URL.String()). + Str("host", r.Host). + Str("x_forwarded_proto", r.Header.Get("X-Forwarded-Proto")). + Str("forwarded", r.Header.Get("Forwarded")). + Str("origin", r.Header.Get("Origin")). + Str("referer", r.Header.Get("Referer")). + Strs("trusted_origins", trustedOrigins). + Msg("Failed to validate Origin or Referer") + } + + http.Error( + w, + http.StatusText(http.StatusForbidden)+" - "+err.Error(), + http.StatusForbidden, + ) + }) +} diff --git a/api/http/handler/auth/authenticate.go b/api/http/handler/auth/authenticate.go index 989949daa..4df31c92c 100644 --- a/api/http/handler/auth/authenticate.go +++ b/api/http/handler/auth/authenticate.go @@ -2,6 +2,7 @@ package auth import ( "net/http" + "strconv" "strings" portainer "github.com/portainer/portainer/api" @@ -82,6 +83,11 @@ func (handler *Handler) authenticate(rw http.ResponseWriter, r *http.Request) *h } } + // Clear any existing user caches + if user != nil { + handler.KubernetesClientFactory.ClearUserClientCache(strconv.Itoa(int(user.ID))) + } + if user != nil && isUserInitialAdmin(user) || settings.AuthenticationMethod == portainer.AuthenticationInternal { return handler.authenticateInternal(rw, user, payload.Password) } diff --git a/api/http/handler/auth/handler.go b/api/http/handler/auth/handler.go index 3b7210fbf..035ceabf8 100644 --- a/api/http/handler/auth/handler.go +++ b/api/http/handler/auth/handler.go @@ -8,6 +8,7 @@ import ( "github.com/portainer/portainer/api/http/proxy" "github.com/portainer/portainer/api/http/proxy/factory/kubernetes" "github.com/portainer/portainer/api/http/security" + "github.com/portainer/portainer/api/kubernetes/cli" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/gorilla/mux" @@ -23,16 +24,18 @@ type Handler struct { OAuthService portainer.OAuthService ProxyManager *proxy.Manager KubernetesTokenCacheManager *kubernetes.TokenCacheManager + KubernetesClientFactory *cli.ClientFactory passwordStrengthChecker security.PasswordStrengthChecker bouncer security.BouncerService } // NewHandler creates a handler to manage authentication operations. -func NewHandler(bouncer security.BouncerService, rateLimiter *security.RateLimiter, passwordStrengthChecker security.PasswordStrengthChecker) *Handler { +func NewHandler(bouncer security.BouncerService, rateLimiter *security.RateLimiter, passwordStrengthChecker security.PasswordStrengthChecker, kubernetesClientFactory *cli.ClientFactory) *Handler { h := &Handler{ Router: mux.NewRouter(), passwordStrengthChecker: passwordStrengthChecker, bouncer: bouncer, + KubernetesClientFactory: kubernetesClientFactory, } h.Handle("/auth/oauth/validate", diff --git a/api/http/handler/auth/logout.go b/api/http/handler/auth/logout.go index 977fafa69..73288565d 100644 --- a/api/http/handler/auth/logout.go +++ b/api/http/handler/auth/logout.go @@ -2,6 +2,7 @@ package auth import ( "net/http" + "strconv" "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/logoutcontext" @@ -23,6 +24,7 @@ func (handler *Handler) logout(w http.ResponseWriter, r *http.Request) *httperro if tokenData != nil { handler.KubernetesTokenCacheManager.RemoveUserFromCache(tokenData.ID) + handler.KubernetesClientFactory.ClearUserClientCache(strconv.Itoa(int(tokenData.ID))) logoutcontext.Cancel(tokenData.Token) } diff --git a/api/http/handler/customtemplates/customtemplate_list.go b/api/http/handler/customtemplates/customtemplate_list.go index 581b219ae..c96d61523 100644 --- a/api/http/handler/customtemplates/customtemplate_list.go +++ b/api/http/handler/customtemplates/customtemplate_list.go @@ -71,7 +71,7 @@ func (handler *Handler) customTemplateList(w http.ResponseWriter, r *http.Reques customTemplates = filterByType(customTemplates, templateTypes) if edge != nil { - customTemplates = slicesx.Filter(customTemplates, func(customTemplate portainer.CustomTemplate) bool { + customTemplates = slicesx.FilterInPlace(customTemplates, func(customTemplate portainer.CustomTemplate) bool { return customTemplate.EdgeTemplate == *edge }) } diff --git a/api/http/handler/docker/dashboard.go b/api/http/handler/docker/dashboard.go index ad0399569..97d40e069 100644 --- a/api/http/handler/docker/dashboard.go +++ b/api/http/handler/docker/dashboard.go @@ -6,6 +6,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/image" + "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/volume" portainer "github.com/portainer/portainer/api" @@ -116,12 +117,12 @@ func (h *Handler) dashboard(w http.ResponseWriter, r *http.Request) *httperror.H return err } - networks, err := cli.NetworkList(r.Context(), types.NetworkListOptions{}) + networks, err := cli.NetworkList(r.Context(), network.ListOptions{}) if err != nil { return httperror.InternalServerError("Unable to retrieve Docker networks", err) } - networks, err = utils.FilterByResourceControl(tx, networks, portainer.NetworkResourceControl, context, func(c types.NetworkResource) string { + networks, err = utils.FilterByResourceControl(tx, networks, portainer.NetworkResourceControl, context, func(c network.Summary) string { return c.Name }) if err != nil { diff --git a/api/http/handler/edgegroups/edgegroup_update.go b/api/http/handler/edgegroups/edgegroup_update.go index 7831b634e..a51ae33d4 100644 --- a/api/http/handler/edgegroups/edgegroup_update.go +++ b/api/http/handler/edgegroups/edgegroup_update.go @@ -163,7 +163,7 @@ func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request) func (handler *Handler) updateEndpointStacks(tx dataservices.DataStoreTx, endpoint *portainer.Endpoint, edgeGroups []portainer.EdgeGroup, edgeStacks []portainer.EdgeStack) error { relation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) - if err != nil && !handler.DataStore.IsErrObjectNotFound(err) { + if err != nil { return err } @@ -179,12 +179,6 @@ func (handler *Handler) updateEndpointStacks(tx dataservices.DataStoreTx, endpoi edgeStackSet[edgeStackID] = true } - if relation == nil { - relation = &portainer.EndpointRelation{ - EndpointID: endpoint.ID, - EdgeStacks: make(map[portainer.EdgeStackID]bool), - } - } relation.EdgeStacks = edgeStackSet return tx.EndpointRelation().UpdateEndpointRelation(endpoint.ID, relation) diff --git a/api/http/handler/edgestacks/edgestack_create_file.go b/api/http/handler/edgestacks/edgestack_create_file.go index 555418835..a0bc2995f 100644 --- a/api/http/handler/edgestacks/edgestack_create_file.go +++ b/api/http/handler/edgestacks/edgestack_create_file.go @@ -101,8 +101,7 @@ func (payload *edgeStackFromFileUploadPayload) Validate(r *http.Request) error { // @router /edge_stacks/create/file [post] func (handler *Handler) createEdgeStackFromFileUpload(r *http.Request, tx dataservices.DataStoreTx, dryrun bool) (*portainer.EdgeStack, error) { payload := &edgeStackFromFileUploadPayload{} - err := payload.Validate(r) - if err != nil { + if err := payload.Validate(r); err != nil { return nil, err } diff --git a/api/http/handler/edgestacks/edgestack_create_git.go b/api/http/handler/edgestacks/edgestack_create_git.go index 2da816481..d20e5b5c2 100644 --- a/api/http/handler/edgestacks/edgestack_create_git.go +++ b/api/http/handler/edgestacks/edgestack_create_git.go @@ -103,8 +103,7 @@ func (payload *edgeStackFromGitRepositoryPayload) Validate(r *http.Request) erro // @router /edge_stacks/create/repository [post] func (handler *Handler) createEdgeStackFromGitRepository(r *http.Request, tx dataservices.DataStoreTx, dryrun bool, userID portainer.UserID) (*portainer.EdgeStack, error) { var payload edgeStackFromGitRepositoryPayload - err := request.DecodeAndValidateJSONPayload(r, &payload) - if err != nil { + if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return nil, err } @@ -137,11 +136,9 @@ func (handler *Handler) createEdgeStackFromGitRepository(r *http.Request, tx dat } func (handler *Handler) storeManifestFromGitRepository(tx dataservices.DataStoreTx, stackFolder string, relatedEndpointIds []portainer.EndpointID, deploymentType portainer.EdgeStackDeploymentType, currentUserID portainer.UserID, repositoryConfig gittypes.RepoConfig) (composePath, manifestPath, projectPath string, err error) { - hasWrongType, err := hasWrongEnvironmentType(tx.Endpoint(), relatedEndpointIds, deploymentType) - if err != nil { + if hasWrongType, err := hasWrongEnvironmentType(tx.Endpoint(), relatedEndpointIds, deploymentType); err != nil { return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err) - } - if hasWrongType { + } else if hasWrongType { return "", "", "", errors.New("edge stack with config do not match the environment type") } @@ -153,8 +150,7 @@ func (handler *Handler) storeManifestFromGitRepository(tx dataservices.DataStore repositoryPassword = repositoryConfig.Authentication.Password } - err = handler.GitService.CloneRepository(projectPath, repositoryConfig.URL, repositoryConfig.ReferenceName, repositoryUsername, repositoryPassword, repositoryConfig.TLSSkipVerify) - if err != nil { + if err := handler.GitService.CloneRepository(projectPath, repositoryConfig.URL, repositoryConfig.ReferenceName, repositoryUsername, repositoryPassword, repositoryConfig.TLSSkipVerify); err != nil { return "", "", "", err } diff --git a/api/http/handler/edgestacks/edgestack_create_string.go b/api/http/handler/edgestacks/edgestack_create_string.go index 556633fae..5e3fb57b8 100644 --- a/api/http/handler/edgestacks/edgestack_create_string.go +++ b/api/http/handler/edgestacks/edgestack_create_string.go @@ -76,8 +76,7 @@ func (payload *edgeStackFromStringPayload) Validate(r *http.Request) error { // @router /edge_stacks/create/string [post] func (handler *Handler) createEdgeStackFromFileContent(r *http.Request, tx dataservices.DataStoreTx, dryrun bool) (*portainer.EdgeStack, error) { var payload edgeStackFromStringPayload - err := request.DecodeAndValidateJSONPayload(r, &payload) - if err != nil { + if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return nil, err } @@ -96,11 +95,9 @@ func (handler *Handler) createEdgeStackFromFileContent(r *http.Request, tx datas } func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolder string, deploymentType portainer.EdgeStackDeploymentType, relatedEndpointIds []portainer.EndpointID, fileContent []byte) (composePath, manifestPath, projectPath string, err error) { - hasWrongType, err := hasWrongEnvironmentType(tx.Endpoint(), relatedEndpointIds, deploymentType) - if err != nil { + if hasWrongType, err := hasWrongEnvironmentType(tx.Endpoint(), relatedEndpointIds, deploymentType); err != nil { return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err) - } - if hasWrongType { + } else if hasWrongType { return "", "", "", errors.New("edge stack with config do not match the environment type") } @@ -124,7 +121,6 @@ func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolde } return "", manifestPath, projectPath, nil - } errMessage := fmt.Sprintf("invalid deployment type: %d", deploymentType) diff --git a/api/http/handler/edgestacks/edgestack_create_test.go b/api/http/handler/edgestacks/edgestack_create_test.go index 32158d300..486cc09d0 100644 --- a/api/http/handler/edgestacks/edgestack_create_test.go +++ b/api/http/handler/edgestacks/edgestack_create_test.go @@ -8,6 +8,7 @@ import ( "testing" portainer "github.com/portainer/portainer/api" + "github.com/stretchr/testify/require" "github.com/segmentio/encoding/json" ) @@ -28,9 +29,7 @@ func TestCreateAndInspect(t *testing.T) { } err := handler.DataStore.EdgeGroup().Create(&edgeGroup) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) endpointRelation := portainer.EndpointRelation{ EndpointID: endpoint.ID, @@ -38,9 +37,7 @@ func TestCreateAndInspect(t *testing.T) { } err = handler.DataStore.EndpointRelation().Create(&endpointRelation) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) payload := edgeStackFromStringPayload{ Name: "test-stack", @@ -50,16 +47,14 @@ func TestCreateAndInspect(t *testing.T) { } jsonPayload, err := json.Marshal(payload) - if err != nil { - t.Fatal("JSON marshal error:", err) - } + require.NoError(t, err) + r := bytes.NewBuffer(jsonPayload) // Create EdgeStack req, err := http.NewRequest(http.MethodPost, "/edge_stacks/create/string", r) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) + req.Header.Add("x-api-key", rawAPIKey) rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) @@ -70,15 +65,11 @@ func TestCreateAndInspect(t *testing.T) { data := portainer.EdgeStack{} err = json.NewDecoder(rec.Body).Decode(&data) - if err != nil { - t.Fatal("error decoding response:", err) - } + require.NoError(t, err) // Inspect req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("/edge_stacks/%d", data.ID), nil) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec = httptest.NewRecorder() @@ -90,9 +81,7 @@ func TestCreateAndInspect(t *testing.T) { data = portainer.EdgeStack{} err = json.NewDecoder(rec.Body).Decode(&data) - if err != nil { - t.Fatal("error decoding response:", err) - } + require.NoError(t, err) if payload.Name != data.Name { t.Fatalf("expected EdgeStack Name %s, found %s", payload.Name, data.Name) diff --git a/api/http/handler/edgestacks/edgestack_delete.go b/api/http/handler/edgestacks/edgestack_delete.go index 3d71f2bce..0e6307684 100644 --- a/api/http/handler/edgestacks/edgestack_delete.go +++ b/api/http/handler/edgestacks/edgestack_delete.go @@ -30,10 +30,9 @@ func (handler *Handler) edgeStackDelete(w http.ResponseWriter, r *http.Request) return httperror.BadRequest("Invalid edge stack identifier route variable", err) } - err = handler.DataStore.UpdateTx(func(tx dataservices.DataStoreTx) error { + if err := handler.DataStore.UpdateTx(func(tx dataservices.DataStoreTx) error { return handler.deleteEdgeStack(tx, portainer.EdgeStackID(edgeStackID)) - }) - if err != nil { + }); err != nil { var httpErr *httperror.HandlerError if errors.As(err, &httpErr) { return httpErr diff --git a/api/http/handler/edgestacks/edgestack_delete_test.go b/api/http/handler/edgestacks/edgestack_delete_test.go index ef25ae45c..ca334c7ce 100644 --- a/api/http/handler/edgestacks/edgestack_delete_test.go +++ b/api/http/handler/edgestacks/edgestack_delete_test.go @@ -8,9 +8,10 @@ import ( "testing" portainer "github.com/portainer/portainer/api" - "github.com/stretchr/testify/assert" "github.com/segmentio/encoding/json" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Delete @@ -23,9 +24,7 @@ func TestDeleteAndInspect(t *testing.T) { // Inspect req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), nil) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec := httptest.NewRecorder() @@ -37,9 +36,7 @@ func TestDeleteAndInspect(t *testing.T) { data := portainer.EdgeStack{} err = json.NewDecoder(rec.Body).Decode(&data) - if err != nil { - t.Fatal("error decoding response:", err) - } + require.NoError(t, err) if data.ID != edgeStack.ID { t.Fatalf("expected EdgeStackID %d, found %d", int(edgeStack.ID), data.ID) @@ -47,9 +44,7 @@ func TestDeleteAndInspect(t *testing.T) { // Delete req, err = http.NewRequest(http.MethodDelete, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), nil) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec = httptest.NewRecorder() @@ -61,9 +56,7 @@ func TestDeleteAndInspect(t *testing.T) { // Inspect req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), nil) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec = httptest.NewRecorder() @@ -117,15 +110,12 @@ func TestDeleteEdgeStack_RemoveProjectFolder(t *testing.T) { } var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(payload); err != nil { - t.Fatal("error encoding payload:", err) - } + err := json.NewEncoder(&buf).Encode(payload) + require.NoError(t, err) // Create req, err := http.NewRequest(http.MethodPost, "/edge_stacks/create/string", &buf) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec := httptest.NewRecorder() @@ -138,9 +128,8 @@ func TestDeleteEdgeStack_RemoveProjectFolder(t *testing.T) { assert.DirExists(t, handler.FileService.GetEdgeStackProjectPath("1")) // Delete - if req, err = http.NewRequest(http.MethodDelete, "/edge_stacks/1", nil); err != nil { - t.Fatal("request error:", err) - } + req, err = http.NewRequest(http.MethodDelete, "/edge_stacks/1", nil) + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec = httptest.NewRecorder() diff --git a/api/http/handler/edgestacks/edgestack_inspect.go b/api/http/handler/edgestacks/edgestack_inspect.go index 06c118835..2936f320e 100644 --- a/api/http/handler/edgestacks/edgestack_inspect.go +++ b/api/http/handler/edgestacks/edgestack_inspect.go @@ -4,6 +4,7 @@ import ( "net/http" portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/dataservices" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" "github.com/portainer/portainer/pkg/libhttp/response" @@ -33,5 +34,35 @@ func (handler *Handler) edgeStackInspect(w http.ResponseWriter, r *http.Request) return handlerDBErr(err, "Unable to find an edge stack with the specified identifier inside the database") } + if err := fillEdgeStackStatus(handler.DataStore, edgeStack); err != nil { + return handlerDBErr(err, "Unable to retrieve edge stack status from the database") + } + return response.JSON(w, edgeStack) } + +func fillEdgeStackStatus(tx dataservices.DataStoreTx, edgeStack *portainer.EdgeStack) error { + status, err := tx.EdgeStackStatus().ReadAll(edgeStack.ID) + if err != nil { + return err + } + + edgeStack.Status = make(map[portainer.EndpointID]portainer.EdgeStackStatus, len(status)) + + emptyStatus := make([]portainer.EdgeStackDeploymentStatus, 0) + + for _, s := range status { + if s.Status == nil { + s.Status = emptyStatus + } + + edgeStack.Status[s.EndpointID] = portainer.EdgeStackStatus{ + Status: s.Status, + EndpointID: s.EndpointID, + DeploymentInfo: s.DeploymentInfo, + ReadyRePullImage: s.ReadyRePullImage, + } + } + + return nil +} diff --git a/api/http/handler/edgestacks/edgestack_list.go b/api/http/handler/edgestacks/edgestack_list.go index 26fd7da05..1ea991c4b 100644 --- a/api/http/handler/edgestacks/edgestack_list.go +++ b/api/http/handler/edgestacks/edgestack_list.go @@ -3,10 +3,39 @@ package edgestacks import ( "net/http" + portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/dataservices" + "github.com/portainer/portainer/api/slicesx" httperror "github.com/portainer/portainer/pkg/libhttp/error" + "github.com/portainer/portainer/pkg/libhttp/request" "github.com/portainer/portainer/pkg/libhttp/response" ) +type aggregatedStatusesMap map[portainer.EdgeStackStatusType]int + +type SummarizedStatus string + +const ( + sumStatusUnavailable SummarizedStatus = "Unavailable" + sumStatusDeploying SummarizedStatus = "Deploying" + sumStatusFailed SummarizedStatus = "Failed" + sumStatusPaused SummarizedStatus = "Paused" + sumStatusPartiallyRunning SummarizedStatus = "PartiallyRunning" + sumStatusCompleted SummarizedStatus = "Completed" + sumStatusRunning SummarizedStatus = "Running" +) + +type edgeStackStatusSummary struct { + AggregatedStatus aggregatedStatusesMap + Status SummarizedStatus + Reason string +} + +type edgeStackListResponseItem struct { + portainer.EdgeStack + StatusSummary edgeStackStatusSummary +} + // @id EdgeStackList // @summary Fetches the list of EdgeStacks // @description **Access policy**: administrator @@ -14,16 +43,122 @@ import ( // @security ApiKeyAuth // @security jwt // @produce json +// @param summarizeStatuses query boolean false "will summarize the statuses" // @success 200 {array} portainer.EdgeStack // @failure 500 // @failure 400 // @failure 503 "Edge compute features are disabled" // @router /edge_stacks [get] func (handler *Handler) edgeStackList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { + summarizeStatuses, _ := request.RetrieveBooleanQueryParameter(r, "summarizeStatuses", true) + edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks() if err != nil { return httperror.InternalServerError("Unable to retrieve edge stacks from the database", err) } - return response.JSON(w, edgeStacks) + res := make([]edgeStackListResponseItem, len(edgeStacks)) + + for i := range edgeStacks { + res[i].EdgeStack = edgeStacks[i] + + if summarizeStatuses { + if err := fillStatusSummary(handler.DataStore, &res[i]); err != nil { + return handlerDBErr(err, "Unable to retrieve edge stack status from the database") + } + } else if err := fillEdgeStackStatus(handler.DataStore, &res[i].EdgeStack); err != nil { + return handlerDBErr(err, "Unable to retrieve edge stack status from the database") + } + } + + return response.JSON(w, res) +} + +func fillStatusSummary(tx dataservices.DataStoreTx, edgeStack *edgeStackListResponseItem) error { + statuses, err := tx.EdgeStackStatus().ReadAll(edgeStack.ID) + if err != nil { + return err + } + + aggregated := make(aggregatedStatusesMap) + + for _, envStatus := range statuses { + for _, status := range envStatus.Status { + aggregated[status.Type]++ + } + } + + status, reason := SummarizeStatuses(statuses, edgeStack.NumDeployments) + + edgeStack.StatusSummary = edgeStackStatusSummary{ + AggregatedStatus: aggregated, + Status: status, + Reason: reason, + } + + edgeStack.Status = map[portainer.EndpointID]portainer.EdgeStackStatus{} + + return nil +} + +func SummarizeStatuses(statuses []portainer.EdgeStackStatusForEnv, numDeployments int) (SummarizedStatus, string) { + if numDeployments == 0 { + return sumStatusUnavailable, "Your edge stack is currently unavailable due to the absence of an available environment in your edge group" + } + + allStatuses := slicesx.FlatMap(statuses, func(x portainer.EdgeStackStatusForEnv) []portainer.EdgeStackDeploymentStatus { + return x.Status + }) + + lastStatuses := slicesx.Map( + slicesx.Filter( + statuses, + func(s portainer.EdgeStackStatusForEnv) bool { + return len(s.Status) > 0 + }, + ), + func(x portainer.EdgeStackStatusForEnv) portainer.EdgeStackDeploymentStatus { + return x.Status[len(x.Status)-1] + }, + ) + + if len(lastStatuses) == 0 { + return sumStatusDeploying, "" + } + + if allFailed := slicesx.Every(lastStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { + return s.Type == portainer.EdgeStackStatusError + }); allFailed { + return sumStatusFailed, "" + } + + if hasPaused := slicesx.Some(allStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { + return s.Type == portainer.EdgeStackStatusPausedDeploying + }); hasPaused { + return sumStatusPaused, "" + } + + if len(lastStatuses) < numDeployments { + return sumStatusDeploying, "" + } + + hasDeploying := slicesx.Some(lastStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { return s.Type == portainer.EdgeStackStatusDeploying }) + hasRunning := slicesx.Some(lastStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { return s.Type == portainer.EdgeStackStatusRunning }) + hasFailed := slicesx.Some(lastStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { return s.Type == portainer.EdgeStackStatusError }) + + if hasRunning && hasFailed && !hasDeploying { + return sumStatusPartiallyRunning, "" + } + + if allCompleted := slicesx.Every(lastStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { return s.Type == portainer.EdgeStackStatusCompleted }); allCompleted { + return sumStatusCompleted, "" + } + + if allRunning := slicesx.Every(lastStatuses, func(s portainer.EdgeStackDeploymentStatus) bool { + return s.Type == portainer.EdgeStackStatusRunning + }); allRunning { + return sumStatusRunning, "" + } + + return sumStatusDeploying, "" } diff --git a/api/http/handler/edgestacks/edgestack_status_update.go b/api/http/handler/edgestacks/edgestack_status_update.go index fef5a6927..0ff6a9eff 100644 --- a/api/http/handler/edgestacks/edgestack_status_update.go +++ b/api/http/handler/edgestacks/edgestack_status_update.go @@ -9,11 +9,10 @@ import ( "time" portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/dataservices" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" "github.com/portainer/portainer/pkg/libhttp/response" - - "github.com/rs/zerolog/log" ) type updateStatusPayload struct { @@ -78,12 +77,25 @@ func (handler *Handler) edgeStackStatusUpdate(w http.ResponseWriter, r *http.Req return httperror.Forbidden("Permission denied to access environment", fmt.Errorf("unauthorized edge endpoint operation: %w. Environment name: %s", err, endpoint.Name)) } - updateFn := func(stack *portainer.EdgeStack) (*portainer.EdgeStack, error) { - return handler.updateEdgeStackStatus(stack, stack.ID, payload) - } + var stack *portainer.EdgeStack - stack, err := handler.stackCoordinator.UpdateStatus(r, portainer.EdgeStackID(stackID), updateFn) - if err != nil { + if err := handler.DataStore.UpdateTx(func(tx dataservices.DataStoreTx) error { + var err error + stack, err = tx.EdgeStack().EdgeStack(portainer.EdgeStackID(stackID)) + if err != nil { + if dataservices.IsErrObjectNotFound(err) { + return nil + } + + return httperror.InternalServerError("Unable to retrieve Edge stack from the database", err) + } + + if err := handler.updateEdgeStackStatus(tx, stack, stack.ID, payload); err != nil { + return httperror.InternalServerError("Unable to update Edge stack status", err) + } + + return nil + }); err != nil { var httpErr *httperror.HandlerError if errors.As(err, &httpErr) { return httpErr @@ -96,43 +108,36 @@ func (handler *Handler) edgeStackStatusUpdate(w http.ResponseWriter, r *http.Req return nil } + if err := fillEdgeStackStatus(handler.DataStore, stack); err != nil { + return handlerDBErr(err, "Unable to retrieve edge stack status from the database") + } + return response.JSON(w, stack) } -func (handler *Handler) updateEdgeStackStatus(stack *portainer.EdgeStack, stackID portainer.EdgeStackID, payload updateStatusPayload) (*portainer.EdgeStack, error) { +func (handler *Handler) updateEdgeStackStatus(tx dataservices.DataStoreTx, stack *portainer.EdgeStack, stackID portainer.EdgeStackID, payload updateStatusPayload) error { if payload.Version > 0 && payload.Version < stack.Version { - return stack, nil + return nil } status := *payload.Status - log.Debug(). - Int("stackID", int(stackID)). - Int("status", int(status)). - Msg("Updating stack status") - deploymentStatus := portainer.EdgeStackDeploymentStatus{ Type: status, Error: payload.Error, Time: payload.Time, } - updateEnvStatus(payload.EndpointID, stack, deploymentStatus) - - return stack, nil -} - -func updateEnvStatus(environmentId portainer.EndpointID, stack *portainer.EdgeStack, deploymentStatus portainer.EdgeStackDeploymentStatus) { if deploymentStatus.Type == portainer.EdgeStackStatusRemoved { - delete(stack.Status, environmentId) - - return + return tx.EdgeStackStatus().Delete(stackID, payload.EndpointID) } - environmentStatus, ok := stack.Status[environmentId] - if !ok { - environmentStatus = portainer.EdgeStackStatus{ - EndpointID: environmentId, + environmentStatus, err := tx.EdgeStackStatus().Read(stackID, payload.EndpointID) + if err != nil && !tx.IsErrObjectNotFound(err) { + return err + } else if tx.IsErrObjectNotFound(err) { + environmentStatus = &portainer.EdgeStackStatusForEnv{ + EndpointID: payload.EndpointID, Status: []portainer.EdgeStackDeploymentStatus{}, } } @@ -143,5 +148,5 @@ func updateEnvStatus(environmentId portainer.EndpointID, stack *portainer.EdgeSt environmentStatus.Status = append(environmentStatus.Status, deploymentStatus) } - stack.Status[environmentId] = environmentStatus + return tx.EdgeStackStatus().Update(stackID, payload.EndpointID, environmentStatus) } diff --git a/api/http/handler/edgestacks/edgestack_status_update_coordinator.go b/api/http/handler/edgestacks/edgestack_status_update_coordinator.go deleted file mode 100644 index 885b4c6da..000000000 --- a/api/http/handler/edgestacks/edgestack_status_update_coordinator.go +++ /dev/null @@ -1,155 +0,0 @@ -package edgestacks - -import ( - "errors" - "fmt" - "net/http" - - portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/dataservices" - - "github.com/rs/zerolog/log" -) - -type statusRequest struct { - respCh chan statusResponse - stackID portainer.EdgeStackID - updateFn statusUpdateFn -} - -type statusResponse struct { - Stack *portainer.EdgeStack - Error error -} - -type statusUpdateFn func(*portainer.EdgeStack) (*portainer.EdgeStack, error) - -type EdgeStackStatusUpdateCoordinator struct { - updateCh chan statusRequest - dataStore dataservices.DataStore -} - -var errAnotherStackUpdateInProgress = errors.New("another stack update is in progress") - -func NewEdgeStackStatusUpdateCoordinator(dataStore dataservices.DataStore) *EdgeStackStatusUpdateCoordinator { - return &EdgeStackStatusUpdateCoordinator{ - updateCh: make(chan statusRequest), - dataStore: dataStore, - } -} - -func (c *EdgeStackStatusUpdateCoordinator) Start() { - for { - c.loop() - } -} - -func (c *EdgeStackStatusUpdateCoordinator) loop() { - u := <-c.updateCh - - respChs := []chan statusResponse{u.respCh} - - var stack *portainer.EdgeStack - - err := c.dataStore.UpdateTx(func(tx dataservices.DataStoreTx) error { - // 1. Load the edge stack - var err error - - stack, err = loadEdgeStack(tx, u.stackID) - if err != nil { - return err - } - - // Return early when the agent tries to update the status on a deleted stack - if stack == nil { - return nil - } - - // 2. Mutate the edge stack opportunistically until there are no more pending updates - for { - stack, err = u.updateFn(stack) - if err != nil { - return err - } - - if m, ok := c.getNextUpdate(stack.ID); ok { - u = m - } else { - break - } - - respChs = append(respChs, u.respCh) - } - - // 3. Save the changes back to the database - if err := tx.EdgeStack().UpdateEdgeStack(stack.ID, stack); err != nil { - return handlerDBErr(fmt.Errorf("unable to update Edge stack: %w.", err), "Unable to persist the stack changes inside the database") - } - - return nil - }) - - // 4. Send back the responses - for _, ch := range respChs { - ch <- statusResponse{Stack: stack, Error: err} - } -} - -func loadEdgeStack(tx dataservices.DataStoreTx, stackID portainer.EdgeStackID) (*portainer.EdgeStack, error) { - stack, err := tx.EdgeStack().EdgeStack(stackID) - if err != nil { - if dataservices.IsErrObjectNotFound(err) { - // Skip the error when the agent tries to update the status on a deleted stack - log.Debug(). - Err(err). - Int("stackID", int(stackID)). - Msg("Unable to find a stack inside the database, skipping error") - - return nil, nil - } - - return nil, fmt.Errorf("unable to retrieve Edge stack from the database: %w.", err) - } - - return stack, nil -} - -func (c *EdgeStackStatusUpdateCoordinator) getNextUpdate(stackID portainer.EdgeStackID) (statusRequest, bool) { - for { - select { - case u := <-c.updateCh: - // Discard the update and let the agent retry - if u.stackID != stackID { - u.respCh <- statusResponse{Error: errAnotherStackUpdateInProgress} - - continue - } - - return u, true - - default: - return statusRequest{}, false - } - } -} - -func (c *EdgeStackStatusUpdateCoordinator) UpdateStatus(r *http.Request, stackID portainer.EdgeStackID, updateFn statusUpdateFn) (*portainer.EdgeStack, error) { - respCh := make(chan statusResponse) - defer close(respCh) - - msg := statusRequest{ - respCh: respCh, - stackID: stackID, - updateFn: updateFn, - } - - select { - case c.updateCh <- msg: - r := <-respCh - - return r.Stack, r.Error - - case <-r.Context().Done(): - return nil, r.Context().Err() - } -} diff --git a/api/http/handler/edgestacks/edgestack_status_update_test.go b/api/http/handler/edgestacks/edgestack_status_update_test.go index 50a0863d4..4d94368fe 100644 --- a/api/http/handler/edgestacks/edgestack_status_update_test.go +++ b/api/http/handler/edgestacks/edgestack_status_update_test.go @@ -10,6 +10,7 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/segmentio/encoding/json" + "github.com/stretchr/testify/require" ) // Update Status @@ -28,15 +29,11 @@ func TestUpdateStatusAndInspect(t *testing.T) { } jsonPayload, err := json.Marshal(payload) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) r := bytes.NewBuffer(jsonPayload) req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("/edge_stacks/%d/status", edgeStack.ID), r) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Set(portainer.PortainerAgentEdgeIDHeader, endpoint.EdgeID) rec := httptest.NewRecorder() @@ -48,9 +45,7 @@ func TestUpdateStatusAndInspect(t *testing.T) { // Get updated edge stack req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), nil) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec = httptest.NewRecorder() @@ -62,14 +57,10 @@ func TestUpdateStatusAndInspect(t *testing.T) { updatedStack := portainer.EdgeStack{} err = json.NewDecoder(rec.Body).Decode(&updatedStack) - if err != nil { - t.Fatal("error decoding response:", err) - } + require.NoError(t, err) endpointStatus, ok := updatedStack.Status[payload.EndpointID] - if !ok { - t.Fatal("Missing status") - } + require.True(t, ok) lastStatus := endpointStatus.Status[len(endpointStatus.Status)-1] @@ -84,8 +75,8 @@ func TestUpdateStatusAndInspect(t *testing.T) { if endpointStatus.EndpointID != payload.EndpointID { t.Fatalf("expected EndpointID %d, found %d", payload.EndpointID, endpointStatus.EndpointID) } - } + func TestUpdateStatusWithInvalidPayload(t *testing.T) { handler, _ := setupHandler(t) @@ -136,15 +127,11 @@ func TestUpdateStatusWithInvalidPayload(t *testing.T) { for _, tc := range cases { t.Run(tc.Name, func(t *testing.T) { jsonPayload, err := json.Marshal(tc.Payload) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) r := bytes.NewBuffer(jsonPayload) req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("/edge_stacks/%d/status", edgeStack.ID), r) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Set(portainer.PortainerAgentEdgeIDHeader, endpoint.EdgeID) rec := httptest.NewRecorder() diff --git a/api/http/handler/edgestacks/edgestack_test.go b/api/http/handler/edgestacks/edgestack_test.go index ce1e9b659..91600117b 100644 --- a/api/http/handler/edgestacks/edgestack_test.go +++ b/api/http/handler/edgestacks/edgestack_test.go @@ -17,6 +17,7 @@ import ( "github.com/portainer/portainer/api/jwt" "github.com/pkg/errors" + "github.com/stretchr/testify/require" ) // Helpers @@ -51,27 +52,21 @@ func setupHandler(t *testing.T) (*Handler, string) { t.Fatal(err) } - coord := NewEdgeStackStatusUpdateCoordinator(store) - go coord.Start() - handler := NewHandler( security.NewRequestBouncer(store, jwtService, apiKeyService), store, edgestacks.NewService(store), - coord, ) handler.FileService = fs settings, err := handler.DataStore.Settings().Settings() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) + settings.EnableEdgeComputeFeatures = true - if err := handler.DataStore.Settings().UpdateSettings(settings); err != nil { - t.Fatal(err) - } + err = handler.DataStore.Settings().UpdateSettings(settings) + require.NoError(t, err) handler.GitService = testhelpers.NewGitService(errors.New("Clone error"), "git-service-id") @@ -90,9 +85,8 @@ func createEndpointWithId(t *testing.T, store dataservices.DataStore, endpointID LastCheckInDate: time.Now().Unix(), } - if err := store.Endpoint().Create(&endpoint); err != nil { - t.Fatal(err) - } + err := store.Endpoint().Create(&endpoint) + require.NoError(t, err) return endpoint } @@ -113,15 +107,13 @@ func createEdgeStack(t *testing.T, store dataservices.DataStore, endpointID port PartialMatch: false, } - if err := store.EdgeGroup().Create(&edgeGroup); err != nil { - t.Fatal(err) - } + err := store.EdgeGroup().Create(&edgeGroup) + require.NoError(t, err) edgeStackID := portainer.EdgeStackID(14) edgeStack := portainer.EdgeStack{ ID: edgeStackID, Name: "test-edge-stack-" + strconv.Itoa(int(edgeStackID)), - Status: map[portainer.EndpointID]portainer.EdgeStackStatus{}, CreationDate: time.Now().Unix(), EdgeGroups: []portainer.EdgeGroupID{edgeGroup.ID}, ProjectPath: "/project/path", @@ -138,13 +130,11 @@ func createEdgeStack(t *testing.T, store dataservices.DataStore, endpointID port }, } - if err := store.EdgeStack().Create(edgeStack.ID, &edgeStack); err != nil { - t.Fatal(err) - } + err = store.EdgeStack().Create(edgeStack.ID, &edgeStack) + require.NoError(t, err) - if err := store.EndpointRelation().Create(&endpointRelation); err != nil { - t.Fatal(err) - } + err = store.EndpointRelation().Create(&endpointRelation) + require.NoError(t, err) return edgeStack } @@ -155,8 +145,8 @@ func createEdgeGroup(t *testing.T, store dataservices.DataStore) portainer.EdgeG Name: "EdgeGroup 1", } - if err := store.EdgeGroup().Create(&edgeGroup); err != nil { - t.Fatal(err) - } + err := store.EdgeGroup().Create(&edgeGroup) + require.NoError(t, err) + return edgeGroup } diff --git a/api/http/handler/edgestacks/edgestack_update.go b/api/http/handler/edgestacks/edgestack_update.go index a3d59abb8..db896d0eb 100644 --- a/api/http/handler/edgestacks/edgestack_update.go +++ b/api/http/handler/edgestacks/edgestack_update.go @@ -74,6 +74,10 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request) return httperror.InternalServerError("Unexpected error", err) } + if err := fillEdgeStackStatus(handler.DataStore, stack); err != nil { + return handlerDBErr(err, "Unable to retrieve edge stack status from the database") + } + return response.JSON(w, stack) } @@ -120,7 +124,7 @@ func (handler *Handler) updateEdgeStack(tx dataservices.DataStoreTx, stackID por stack.EdgeGroups = groupsIds if payload.UpdateVersion { - if err := handler.updateStackVersion(stack, payload.DeploymentType, []byte(payload.StackFileContent), "", relatedEndpointIds); err != nil { + if err := handler.updateStackVersion(tx, stack, payload.DeploymentType, []byte(payload.StackFileContent), "", relatedEndpointIds); err != nil { return nil, httperror.InternalServerError("Unable to update stack version", err) } } diff --git a/api/http/handler/edgestacks/edgestack_update_test.go b/api/http/handler/edgestacks/edgestack_update_test.go index 7e4a9b23c..68baa4129 100644 --- a/api/http/handler/edgestacks/edgestack_update_test.go +++ b/api/http/handler/edgestacks/edgestack_update_test.go @@ -25,9 +25,8 @@ func TestUpdateAndInspect(t *testing.T) { endpointID := portainer.EndpointID(6) newEndpoint := createEndpointWithId(t, handler.DataStore, endpointID) - if err := handler.DataStore.Endpoint().Create(&newEndpoint); err != nil { - t.Fatal(err) - } + err := handler.DataStore.Endpoint().Create(&newEndpoint) + require.NoError(t, err) endpointRelation := portainer.EndpointRelation{ EndpointID: endpointID, @@ -36,9 +35,8 @@ func TestUpdateAndInspect(t *testing.T) { }, } - if err := handler.DataStore.EndpointRelation().Create(&endpointRelation); err != nil { - t.Fatal(err) - } + err = handler.DataStore.EndpointRelation().Create(&endpointRelation) + require.NoError(t, err) newEdgeGroup := portainer.EdgeGroup{ ID: 2, @@ -49,9 +47,8 @@ func TestUpdateAndInspect(t *testing.T) { PartialMatch: false, } - if err := handler.DataStore.EdgeGroup().Create(&newEdgeGroup); err != nil { - t.Fatal(err) - } + err = handler.DataStore.EdgeGroup().Create(&newEdgeGroup) + require.NoError(t, err) payload := updateEdgeStackPayload{ StackFileContent: "update-test", @@ -61,15 +58,11 @@ func TestUpdateAndInspect(t *testing.T) { } jsonPayload, err := json.Marshal(payload) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) r := bytes.NewBuffer(jsonPayload) req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), r) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec := httptest.NewRecorder() @@ -81,9 +74,7 @@ func TestUpdateAndInspect(t *testing.T) { // Get updated edge stack req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), nil) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec = httptest.NewRecorder() @@ -94,9 +85,8 @@ func TestUpdateAndInspect(t *testing.T) { } updatedStack := portainer.EdgeStack{} - if err := json.NewDecoder(rec.Body).Decode(&updatedStack); err != nil { - t.Fatal("error decoding response:", err) - } + err = json.NewDecoder(rec.Body).Decode(&updatedStack) + require.NoError(t, err) if payload.UpdateVersion && updatedStack.Version != edgeStack.Version+1 { t.Fatalf("expected EdgeStack version %d, found %d", edgeStack.Version+1, updatedStack.Version+1) @@ -226,15 +216,11 @@ func TestUpdateWithInvalidPayload(t *testing.T) { for _, tc := range cases { t.Run(tc.Name, func(t *testing.T) { jsonPayload, err := json.Marshal(tc.Payload) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) r := bytes.NewBuffer(jsonPayload) req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("/edge_stacks/%d", edgeStack.ID), r) - if err != nil { - t.Fatal("request error:", err) - } + require.NoError(t, err) req.Header.Add("x-api-key", rawAPIKey) rec := httptest.NewRecorder() diff --git a/api/http/handler/edgestacks/handler.go b/api/http/handler/edgestacks/handler.go index 9fa90776f..78df853a6 100644 --- a/api/http/handler/edgestacks/handler.go +++ b/api/http/handler/edgestacks/handler.go @@ -22,17 +22,15 @@ type Handler struct { GitService portainer.GitService edgeStacksService *edgestackservice.Service KubernetesDeployer portainer.KubernetesDeployer - stackCoordinator *EdgeStackStatusUpdateCoordinator } // NewHandler creates a handler to manage environment(endpoint) group operations. -func NewHandler(bouncer security.BouncerService, dataStore dataservices.DataStore, edgeStacksService *edgestackservice.Service, stackCoordinator *EdgeStackStatusUpdateCoordinator) *Handler { +func NewHandler(bouncer security.BouncerService, dataStore dataservices.DataStore, edgeStacksService *edgestackservice.Service) *Handler { h := &Handler{ Router: mux.NewRouter(), requestBouncer: bouncer, DataStore: dataStore, edgeStacksService: edgeStacksService, - stackCoordinator: stackCoordinator, } h.Handle("/edge_stacks/create/{method}", diff --git a/api/http/handler/edgestacks/utils_update_stack_version.go b/api/http/handler/edgestacks/utils_update_stack_version.go index 2502a88f6..78ac5002f 100644 --- a/api/http/handler/edgestacks/utils_update_stack_version.go +++ b/api/http/handler/edgestacks/utils_update_stack_version.go @@ -5,15 +5,18 @@ import ( "strconv" portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/filesystem" - edgestackutils "github.com/portainer/portainer/api/internal/edge/edgestacks" "github.com/rs/zerolog/log" ) -func (handler *Handler) updateStackVersion(stack *portainer.EdgeStack, deploymentType portainer.EdgeStackDeploymentType, config []byte, oldGitHash string, relatedEnvironmentsIDs []portainer.EndpointID) error { - stack.Version = stack.Version + 1 - stack.Status = edgestackutils.NewStatus(stack.Status, relatedEnvironmentsIDs) +func (handler *Handler) updateStackVersion(tx dataservices.DataStoreTx, stack *portainer.EdgeStack, deploymentType portainer.EdgeStackDeploymentType, config []byte, oldGitHash string, relatedEnvironmentsIDs []portainer.EndpointID) error { + stack.Version++ + + if err := tx.EdgeStackStatus().Clear(stack.ID, relatedEnvironmentsIDs); err != nil { + return err + } return handler.storeStackFile(stack, deploymentType, config) } diff --git a/api/http/handler/endpointedge/endpointedge_status_inspect.go b/api/http/handler/endpointedge/endpointedge_status_inspect.go index 4d6368493..9bd341561 100644 --- a/api/http/handler/endpointedge/endpointedge_status_inspect.go +++ b/api/http/handler/endpointedge/endpointedge_status_inspect.go @@ -264,9 +264,6 @@ func (handler *Handler) buildSchedules(tx dataservices.DataStoreTx, endpointID p func (handler *Handler) buildEdgeStacks(tx dataservices.DataStoreTx, endpointID portainer.EndpointID) ([]stackStatusResponse, *httperror.HandlerError) { relation, err := tx.EndpointRelation().EndpointRelation(endpointID) if err != nil { - if tx.IsErrObjectNotFound(err) { - return nil, nil - } return nil, httperror.InternalServerError("Unable to retrieve relation object from the database", err) } diff --git a/api/http/handler/endpointedge/endpointedge_status_inspect_test.go b/api/http/handler/endpointedge/endpointedge_status_inspect_test.go index 8bfaa9814..ca9b12723 100644 --- a/api/http/handler/endpointedge/endpointedge_status_inspect_test.go +++ b/api/http/handler/endpointedge/endpointedge_status_inspect_test.go @@ -287,11 +287,8 @@ func TestEdgeStackStatus(t *testing.T) { edgeStackID := portainer.EdgeStackID(17) edgeStack := portainer.EdgeStack{ - ID: edgeStackID, - Name: "test-edge-stack-17", - Status: map[portainer.EndpointID]portainer.EdgeStackStatus{ - endpointID: {}, - }, + ID: edgeStackID, + Name: "test-edge-stack-17", CreationDate: time.Now().Unix(), EdgeGroups: []portainer.EdgeGroupID{1, 2}, ProjectPath: "/project/path", diff --git a/api/http/handler/endpointgroups/endpoints.go b/api/http/handler/endpointgroups/endpoints.go index b34032d9e..8b420f2a6 100644 --- a/api/http/handler/endpointgroups/endpoints.go +++ b/api/http/handler/endpointgroups/endpoints.go @@ -21,17 +21,10 @@ func (handler *Handler) updateEndpointRelations(tx dataservices.DataStoreTx, end } endpointRelation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) - if err != nil && !tx.IsErrObjectNotFound(err) { + if err != nil { return err } - if endpointRelation == nil { - endpointRelation = &portainer.EndpointRelation{ - EndpointID: endpoint.ID, - EdgeStacks: make(map[portainer.EdgeStackID]bool), - } - } - edgeGroups, err := tx.EdgeGroup().ReadAll() if err != nil { return err diff --git a/api/http/handler/endpoints/endpoint_create.go b/api/http/handler/endpoints/endpoint_create.go index 1c6415023..3cfe934bc 100644 --- a/api/http/handler/endpoints/endpoint_create.go +++ b/api/http/handler/endpoints/endpoint_create.go @@ -563,6 +563,10 @@ func (handler *Handler) saveEndpointAndUpdateAuthorizations(tx dataservices.Data return err } + if err := endpointutils.InitializeEdgeEndpointRelation(endpoint, tx); err != nil { + return err + } + for _, tagID := range endpoint.TagIDs { if err := tx.Tag().UpdateTagFunc(tagID, func(tag *portainer.Tag) { tag.Endpoints[endpoint.ID] = true diff --git a/api/http/handler/endpoints/endpoint_delete.go b/api/http/handler/endpoints/endpoint_delete.go index 4752364ec..f26b9dd13 100644 --- a/api/http/handler/endpoints/endpoint_delete.go +++ b/api/http/handler/endpoints/endpoint_delete.go @@ -214,14 +214,9 @@ func (handler *Handler) deleteEndpoint(tx dataservices.DataStoreTx, endpointID p log.Warn().Err(err).Msg("Unable to retrieve edge stacks from the database") } - for idx := range edgeStacks { - edgeStack := &edgeStacks[idx] - if _, ok := edgeStack.Status[endpoint.ID]; ok { - delete(edgeStack.Status, endpoint.ID) - - if err := tx.EdgeStack().UpdateEdgeStack(edgeStack.ID, edgeStack); err != nil { - log.Warn().Err(err).Msg("Unable to update edge stack") - } + for _, edgeStack := range edgeStacks { + if err := tx.EdgeStackStatus().Delete(edgeStack.ID, endpoint.ID); err != nil { + log.Warn().Err(err).Msg("Unable to delete edge stack status") } } diff --git a/api/http/handler/endpoints/endpoint_list.go b/api/http/handler/endpoints/endpoint_list.go index 86f1b1d3c..43b14ad6a 100644 --- a/api/http/handler/endpoints/endpoint_list.go +++ b/api/http/handler/endpoints/endpoint_list.go @@ -95,12 +95,11 @@ func (handler *Handler) endpointList(w http.ResponseWriter, r *http.Request) *ht return httperror.BadRequest("Invalid query parameters", err) } - filteredEndpoints := security.FilterEndpoints(endpoints, endpointGroups, securityContext) - - filteredEndpoints, totalAvailableEndpoints, err := handler.filterEndpointsByQuery(filteredEndpoints, query, endpointGroups, edgeGroups, settings) + filteredEndpoints, totalAvailableEndpoints, err := handler.filterEndpointsByQuery(endpoints, query, endpointGroups, edgeGroups, settings, securityContext) if err != nil { return httperror.InternalServerError("Unable to filter endpoints", err) } + filteredEndpoints = security.FilterEndpoints(filteredEndpoints, endpointGroups, securityContext) sortEnvironmentsByField(filteredEndpoints, endpointGroups, getSortKey(sortField), sortOrder == "desc") diff --git a/api/http/handler/endpoints/endpoint_registries_list.go b/api/http/handler/endpoints/endpoint_registries_list.go index e81bc34a9..5bc4a930d 100644 --- a/api/http/handler/endpoints/endpoint_registries_list.go +++ b/api/http/handler/endpoints/endpoint_registries_list.go @@ -75,7 +75,7 @@ func (handler *Handler) listRegistries(tx dataservices.DataStoreTx, r *http.Requ return nil, httperror.InternalServerError("Unable to retrieve registries from the database", err) } - registries, handleError := handler.filterRegistriesByAccess(r, registries, endpoint, user, securityContext.UserMemberships) + registries, handleError := handler.filterRegistriesByAccess(tx, r, registries, endpoint, user, securityContext.UserMemberships) if handleError != nil { return nil, handleError } @@ -87,15 +87,15 @@ func (handler *Handler) listRegistries(tx dataservices.DataStoreTx, r *http.Requ return registries, err } -func (handler *Handler) filterRegistriesByAccess(r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User, memberships []portainer.TeamMembership) ([]portainer.Registry, *httperror.HandlerError) { +func (handler *Handler) filterRegistriesByAccess(tx dataservices.DataStoreTx, r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User, memberships []portainer.TeamMembership) ([]portainer.Registry, *httperror.HandlerError) { if !endpointutils.IsKubernetesEndpoint(endpoint) { return security.FilterRegistries(registries, user, memberships, endpoint.ID), nil } - return handler.filterKubernetesEndpointRegistries(r, registries, endpoint, user, memberships) + return handler.filterKubernetesEndpointRegistries(tx, r, registries, endpoint, user, memberships) } -func (handler *Handler) filterKubernetesEndpointRegistries(r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User, memberships []portainer.TeamMembership) ([]portainer.Registry, *httperror.HandlerError) { +func (handler *Handler) filterKubernetesEndpointRegistries(tx dataservices.DataStoreTx, r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User, memberships []portainer.TeamMembership) ([]portainer.Registry, *httperror.HandlerError) { namespaceParam, _ := request.RetrieveQueryParameter(r, "namespace", true) isAdmin, err := security.IsAdmin(r) if err != nil { @@ -116,7 +116,7 @@ func (handler *Handler) filterKubernetesEndpointRegistries(r *http.Request, regi return registries, nil } - return handler.filterKubernetesRegistriesByUserRole(r, registries, endpoint, user) + return handler.filterKubernetesRegistriesByUserRole(tx, r, registries, endpoint, user) } func (handler *Handler) isNamespaceAuthorized(endpoint *portainer.Endpoint, namespace string, userId portainer.UserID, memberships []portainer.TeamMembership, isAdmin bool) (bool, error) { @@ -169,7 +169,7 @@ func registryAccessPoliciesContainsNamespace(registryAccess portainer.RegistryAc return false } -func (handler *Handler) filterKubernetesRegistriesByUserRole(r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User) ([]portainer.Registry, *httperror.HandlerError) { +func (handler *Handler) filterKubernetesRegistriesByUserRole(tx dataservices.DataStoreTx, r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User) ([]portainer.Registry, *httperror.HandlerError) { err := handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint) if errors.Is(err, security.ErrAuthorizationRequired) { return nil, httperror.Forbidden("User is not authorized", err) @@ -178,7 +178,7 @@ func (handler *Handler) filterKubernetesRegistriesByUserRole(r *http.Request, re return nil, httperror.InternalServerError("Unable to retrieve info from request context", err) } - userNamespaces, err := handler.userNamespaces(endpoint, user) + userNamespaces, err := handler.userNamespaces(tx, endpoint, user) if err != nil { return nil, httperror.InternalServerError("unable to retrieve user namespaces", err) } @@ -186,7 +186,7 @@ func (handler *Handler) filterKubernetesRegistriesByUserRole(r *http.Request, re return filterRegistriesByNamespaces(registries, endpoint.ID, userNamespaces), nil } -func (handler *Handler) userNamespaces(endpoint *portainer.Endpoint, user *portainer.User) ([]string, error) { +func (handler *Handler) userNamespaces(tx dataservices.DataStoreTx, endpoint *portainer.Endpoint, user *portainer.User) ([]string, error) { kcl, err := handler.K8sClientFactory.GetPrivilegedKubeClient(endpoint) if err != nil { return nil, err @@ -197,7 +197,7 @@ func (handler *Handler) userNamespaces(endpoint *portainer.Endpoint, user *porta return nil, err } - userMemberships, err := handler.DataStore.TeamMembership().TeamMembershipsByUserID(user.ID) + userMemberships, err := tx.TeamMembership().TeamMembershipsByUserID(user.ID) if err != nil { return nil, err } diff --git a/api/http/handler/endpoints/filter.go b/api/http/handler/endpoints/filter.go index 6dc41b0bd..7cf7b9760 100644 --- a/api/http/handler/endpoints/filter.go +++ b/api/http/handler/endpoints/filter.go @@ -11,6 +11,7 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/http/handler/edgegroups" + "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/internal/edge" "github.com/portainer/portainer/api/internal/endpointutils" "github.com/portainer/portainer/api/slicesx" @@ -140,6 +141,7 @@ func (handler *Handler) filterEndpointsByQuery( groups []portainer.EndpointGroup, edgeGroups []portainer.EdgeGroup, settings *portainer.Settings, + context *security.RestrictedRequestContext, ) ([]portainer.Endpoint, int, error) { totalAvailableEndpoints := len(filteredEndpoints) @@ -181,11 +183,16 @@ func (handler *Handler) filterEndpointsByQuery( } // filter edge environments by trusted/untrusted + // only portainer admins are allowed to see untrusted environments filteredEndpoints = filter(filteredEndpoints, func(endpoint portainer.Endpoint) bool { if !endpointutils.IsEdgeEndpoint(&endpoint) { return true } + if query.edgeDeviceUntrusted { + return !endpoint.UserTrusted && context.IsAdmin + } + return endpoint.UserTrusted == !query.edgeDeviceUntrusted }) @@ -247,19 +254,17 @@ func (handler *Handler) filterEndpointsByQuery( return filteredEndpoints, totalAvailableEndpoints, nil } -func endpointStatusInStackMatchesFilter(edgeStackStatus map[portainer.EndpointID]portainer.EdgeStackStatus, envId portainer.EndpointID, statusFilter portainer.EdgeStackStatusType) bool { - status, ok := edgeStackStatus[envId] - +func endpointStatusInStackMatchesFilter(stackStatus *portainer.EdgeStackStatusForEnv, envId portainer.EndpointID, statusFilter portainer.EdgeStackStatusType) bool { // consider that if the env has no status in the stack it is in Pending state if statusFilter == portainer.EdgeStackStatusPending { - return !ok || len(status.Status) == 0 + return stackStatus == nil || len(stackStatus.Status) == 0 } - if !ok { + if stackStatus == nil { return false } - return slices.ContainsFunc(status.Status, func(s portainer.EdgeStackDeploymentStatus) bool { + return slices.ContainsFunc(stackStatus.Status, func(s portainer.EdgeStackDeploymentStatus) bool { return s.Type == statusFilter }) } @@ -291,7 +296,14 @@ func filterEndpointsByEdgeStack(endpoints []portainer.Endpoint, edgeStackId port if statusFilter != nil { n := 0 for _, envId := range envIds { - if endpointStatusInStackMatchesFilter(stack.Status, envId, *statusFilter) { + edgeStackStatus, err := datastore.EdgeStackStatus().Read(edgeStackId, envId) + if dataservices.IsErrObjectNotFound(err) { + continue + } else if err != nil { + return nil, errors.WithMessagef(err, "Unable to retrieve edge stack status for environment %d", envId) + } + + if endpointStatusInStackMatchesFilter(edgeStackStatus, envId, *statusFilter) { envIds[n] = envId n++ } diff --git a/api/http/handler/endpoints/filter_test.go b/api/http/handler/endpoints/filter_test.go index f19d0a276..8abc76fb7 100644 --- a/api/http/handler/endpoints/filter_test.go +++ b/api/http/handler/endpoints/filter_test.go @@ -6,6 +6,7 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/datastore" + "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/internal/testhelpers" "github.com/portainer/portainer/api/slicesx" @@ -263,6 +264,7 @@ func runTest(t *testing.T, test filterTest, handler *Handler, endpoints []portai []portainer.EndpointGroup{}, []portainer.EdgeGroup{}, &portainer.Settings{}, + &security.RestrictedRequestContext{IsAdmin: true}, ) is.NoError(err) diff --git a/api/http/handler/endpoints/update_edge_relations.go b/api/http/handler/endpoints/update_edge_relations.go index 1390c9fd4..c487519f0 100644 --- a/api/http/handler/endpoints/update_edge_relations.go +++ b/api/http/handler/endpoints/update_edge_relations.go @@ -17,17 +17,7 @@ func (handler *Handler) updateEdgeRelations(tx dataservices.DataStoreTx, endpoin relation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) if err != nil { - if !tx.IsErrObjectNotFound(err) { - return errors.WithMessage(err, "Unable to retrieve environment relation inside the database") - } - - relation = &portainer.EndpointRelation{ - EndpointID: endpoint.ID, - EdgeStacks: map[portainer.EdgeStackID]bool{}, - } - if err := tx.EndpointRelation().Create(relation); err != nil { - return errors.WithMessage(err, "Unable to create environment relation inside the database") - } + return errors.WithMessage(err, "Unable to retrieve environment relation inside the database") } endpointGroup, err := tx.EndpointGroup().Read(endpoint.GroupID) diff --git a/api/http/handler/file/handler.go b/api/http/handler/file/handler.go index 66f81b64a..9e57478c8 100644 --- a/api/http/handler/file/handler.go +++ b/api/http/handler/file/handler.go @@ -17,12 +17,12 @@ type Handler struct { } // NewHandler creates a handler to serve static files. -func NewHandler(assetPublicPath string, wasInstanceDisabled func() bool) *Handler { +func NewHandler(assetPublicPath string, csp bool, wasInstanceDisabled func() bool) *Handler { h := &Handler{ Handler: security.MWSecureHeaders( gzhttp.GzipHandler(http.FileServer(http.Dir(assetPublicPath))), featureflags.IsEnabled("hsts"), - featureflags.IsEnabled("csp"), + csp, ), wasInstanceDisabled: wasInstanceDisabled, } @@ -36,6 +36,7 @@ func isHTML(acceptContent []string) bool { return true } } + return false } @@ -43,11 +44,13 @@ func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if handler.wasInstanceDisabled() { if r.RequestURI == "/" || r.RequestURI == "/index.html" { http.Redirect(w, r, "/timeout.html", http.StatusTemporaryRedirect) + return } } else { if strings.HasPrefix(r.RequestURI, "/timeout.html") { http.Redirect(w, r, "/", http.StatusTemporaryRedirect) + return } } diff --git a/api/http/handler/handler.go b/api/http/handler/handler.go index 72c7f7669..1704eb316 100644 --- a/api/http/handler/handler.go +++ b/api/http/handler/handler.go @@ -81,7 +81,7 @@ type Handler struct { } // @title PortainerCE API -// @version 2.30.0 +// @version 2.32.0 // @description.markdown api-description.md // @termsOfService diff --git a/api/http/handler/helm/helm_repo_search.go b/api/http/handler/helm/helm_repo_search.go index aab9c523d..c29423fa9 100644 --- a/api/http/handler/helm/helm_repo_search.go +++ b/api/http/handler/helm/helm_repo_search.go @@ -7,6 +7,7 @@ import ( "github.com/portainer/portainer/pkg/libhelm/options" httperror "github.com/portainer/portainer/pkg/libhttp/error" + "github.com/portainer/portainer/pkg/libhttp/request" "github.com/pkg/errors" ) @@ -17,6 +18,8 @@ import ( // @description **Access policy**: authenticated // @tags helm // @param repo query string true "Helm repository URL" +// @param chart query string false "Helm chart name" +// @param useCache query string false "If true will use cache to search" // @security ApiKeyAuth // @security jwt // @produce json @@ -32,13 +35,19 @@ func (handler *Handler) helmRepoSearch(w http.ResponseWriter, r *http.Request) * return httperror.BadRequest("Bad request", errors.New("missing `repo` query parameter")) } + chart, _ := request.RetrieveQueryParameter(r, "chart", false) + // If true will useCache to search, will always add to cache after + useCache, _ := request.RetrieveBooleanQueryParameter(r, "useCache", false) + _, err := url.ParseRequestURI(repo) if err != nil { return httperror.BadRequest("Bad request", errors.Wrap(err, fmt.Sprintf("provided URL %q is not valid", repo))) } searchOpts := options.SearchRepoOptions{ - Repo: repo, + Repo: repo, + Chart: chart, + UseCache: useCache, } result, err := handler.helmPackageManager.SearchRepo(searchOpts) diff --git a/api/http/handler/helm/helm_show.go b/api/http/handler/helm/helm_show.go index 591c57922..f139827b8 100644 --- a/api/http/handler/helm/helm_show.go +++ b/api/http/handler/helm/helm_show.go @@ -20,6 +20,7 @@ import ( // @tags helm // @param repo query string true "Helm repository URL" // @param chart query string true "Chart name" +// @param version query string true "Chart version" // @param command path string true "chart/values/readme" // @security ApiKeyAuth // @security jwt @@ -45,6 +46,11 @@ func (handler *Handler) helmShow(w http.ResponseWriter, r *http.Request) *httper return httperror.BadRequest("Bad request", errors.New("missing `chart` query parameter")) } + version, err := request.RetrieveQueryParameter(r, "version", true) + if err != nil { + return httperror.BadRequest("Bad request", errors.Wrap(err, fmt.Sprintf("provided version %q is not valid", version))) + } + cmd, err := request.RetrieveRouteVariableValue(r, "command") if err != nil { cmd = "all" @@ -55,6 +61,7 @@ func (handler *Handler) helmShow(w http.ResponseWriter, r *http.Request) *httper OutputFormat: options.ShowOutputFormat(cmd), Chart: chart, Repo: repo, + Version: version, } result, err := handler.helmPackageManager.Show(showOptions) if err != nil { diff --git a/api/http/handler/kubernetes/client.go b/api/http/handler/kubernetes/client.go index a85f2cff9..a7f2485e3 100644 --- a/api/http/handler/kubernetes/client.go +++ b/api/http/handler/kubernetes/client.go @@ -2,8 +2,10 @@ package kubernetes import ( "net/http" + "strconv" "github.com/portainer/portainer/api/http/middlewares" + "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/kubernetes/cli" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/rs/zerolog/log" @@ -25,13 +27,19 @@ func (handler *Handler) prepareKubeClient(r *http.Request) (*cli.KubeClient, *ht return nil, httperror.NotFound("Unable to find the Kubernetes endpoint associated to the request.", err) } - pcli, err := handler.KubernetesClientFactory.GetPrivilegedKubeClient(endpoint) + tokenData, err := security.RetrieveTokenData(r) + if err != nil { + log.Error().Err(err).Str("context", "prepareKubeClient").Msg("Unable to retrieve token data associated to the request.") + return nil, httperror.InternalServerError("Unable to retrieve token data associated to the request.", err) + } + + pcli, err := handler.KubernetesClientFactory.GetPrivilegedUserKubeClient(endpoint, strconv.Itoa(int(tokenData.ID))) if err != nil { log.Error().Err(err).Str("context", "prepareKubeClient").Msg("Unable to get a privileged Kubernetes client for the user.") return nil, httperror.InternalServerError("Unable to get a privileged Kubernetes client for the user.", err) } - pcli.IsKubeAdmin = cli.IsKubeAdmin - pcli.NonAdminNamespaces = cli.NonAdminNamespaces + pcli.SetIsKubeAdmin(cli.GetIsKubeAdmin()) + pcli.SetClientNonAdminNamespaces(cli.GetClientNonAdminNamespaces()) return pcli, nil } diff --git a/api/http/handler/kubernetes/cluster_role_bindings.go b/api/http/handler/kubernetes/cluster_role_bindings.go index a5050c947..83621a900 100644 --- a/api/http/handler/kubernetes/cluster_role_bindings.go +++ b/api/http/handler/kubernetes/cluster_role_bindings.go @@ -32,7 +32,7 @@ func (handler *Handler) getAllKubernetesClusterRoleBindings(w http.ResponseWrite return httperror.Forbidden("User is not authorized to fetch cluster role bindings from the Kubernetes cluster.", httpErr) } - if !cli.IsKubeAdmin { + if !cli.GetIsKubeAdmin() { log.Error().Str("context", "getAllKubernetesClusterRoleBindings").Msg("user is not authorized to fetch cluster role bindings from the Kubernetes cluster.") return httperror.Forbidden("User is not authorized to fetch cluster role bindings from the Kubernetes cluster.", nil) } diff --git a/api/http/handler/kubernetes/cluster_roles.go b/api/http/handler/kubernetes/cluster_roles.go index 3fd2ca8aa..6d5d028be 100644 --- a/api/http/handler/kubernetes/cluster_roles.go +++ b/api/http/handler/kubernetes/cluster_roles.go @@ -32,7 +32,7 @@ func (handler *Handler) getAllKubernetesClusterRoles(w http.ResponseWriter, r *h return httperror.Forbidden("User is not authorized to fetch cluster roles from the Kubernetes cluster.", httpErr) } - if !cli.IsKubeAdmin { + if !cli.GetIsKubeAdmin() { log.Error().Str("context", "getAllKubernetesClusterRoles").Msg("user is not authorized to fetch cluster roles from the Kubernetes cluster.") return httperror.Forbidden("User is not authorized to fetch cluster roles from the Kubernetes cluster.", nil) } diff --git a/api/http/handler/kubernetes/event.go b/api/http/handler/kubernetes/event.go new file mode 100644 index 000000000..25f024303 --- /dev/null +++ b/api/http/handler/kubernetes/event.go @@ -0,0 +1,102 @@ +package kubernetes + +import ( + "net/http" + + httperror "github.com/portainer/portainer/pkg/libhttp/error" + "github.com/portainer/portainer/pkg/libhttp/request" + "github.com/portainer/portainer/pkg/libhttp/response" + "github.com/rs/zerolog/log" + k8serrors "k8s.io/apimachinery/pkg/api/errors" +) + +// @id getKubernetesEventsForNamespace +// @summary Gets kubernetes events for namespace +// @description Get events by optional query param resourceId for a given namespace. +// @description **Access policy**: Authenticated user. +// @tags kubernetes +// @security ApiKeyAuth || jwt +// @produce json +// @param id path int true "Environment identifier" +// @param namespace path string true "The namespace name the events are associated to" +// @param resourceId query string false "The resource id of the involved kubernetes object" example:"e5b021b6-4bce-4c06-bd3b-6cca906797aa" +// @success 200 {object} []kubernetes.K8sEvent "Success" +// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria." +// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions." +// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions." +// @failure 500 "Server error occurred while attempting to retrieve the events within the specified namespace." +// @router /kubernetes/{id}/namespaces/{namespace}/events [get] +func (handler *Handler) getKubernetesEventsForNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { + namespace, err := request.RetrieveRouteVariableValue(r, "namespace") + if err != nil { + log.Error().Err(err).Str("context", "getKubernetesEvents").Str("namespace", namespace).Msg("Unable to retrieve namespace identifier route variable") + return httperror.BadRequest("Unable to retrieve namespace identifier route variable", err) + } + + resourceId, err := request.RetrieveQueryParameter(r, "resourceId", true) + if err != nil { + log.Error().Err(err).Str("context", "getKubernetesEvents").Msg("Unable to retrieve resourceId query parameter") + return httperror.BadRequest("Unable to retrieve resourceId query parameter", err) + } + + cli, httpErr := handler.getProxyKubeClient(r) + if httpErr != nil { + log.Error().Err(httpErr).Str("context", "getKubernetesEvents").Str("resourceId", resourceId).Msg("Unable to get a Kubernetes client for the user") + return httperror.InternalServerError("Unable to get a Kubernetes client for the user", httpErr) + } + + events, err := cli.GetEvents(namespace, resourceId) + if err != nil { + if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) { + log.Error().Err(err).Str("context", "getKubernetesEvents").Msg("Unauthorized access to the Kubernetes API") + return httperror.Forbidden("Unauthorized access to the Kubernetes API", err) + } + + log.Error().Err(err).Str("context", "getKubernetesEvents").Msg("Unable to retrieve events") + return httperror.InternalServerError("Unable to retrieve events", err) + } + + return response.JSON(w, events) +} + +// @id getAllKubernetesEvents +// @summary Gets kubernetes events +// @description Get events by query param resourceId +// @description **Access policy**: Authenticated user. +// @tags kubernetes +// @security ApiKeyAuth || jwt +// @produce json +// @param id path int true "Environment identifier" +// @param resourceId query string false "The resource id of the involved kubernetes object" example:"e5b021b6-4bce-4c06-bd3b-6cca906797aa" +// @success 200 {object} []kubernetes.K8sEvent "Success" +// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria." +// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions." +// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions." +// @failure 500 "Server error occurred while attempting to retrieve the events." +// @router /kubernetes/{id}/events [get] +func (handler *Handler) getAllKubernetesEvents(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { + resourceId, err := request.RetrieveQueryParameter(r, "resourceId", true) + if err != nil { + log.Error().Err(err).Str("context", "getKubernetesEvents").Msg("Unable to retrieve resourceId query parameter") + return httperror.BadRequest("Unable to retrieve resourceId query parameter", err) + } + + cli, httpErr := handler.getProxyKubeClient(r) + if httpErr != nil { + log.Error().Err(httpErr).Str("context", "getKubernetesEvents").Str("resourceId", resourceId).Msg("Unable to get a Kubernetes client for the user") + return httperror.InternalServerError("Unable to get a Kubernetes client for the user", httpErr) + } + + events, err := cli.GetEvents("", resourceId) + if err != nil { + if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) { + log.Error().Err(err).Str("context", "getKubernetesEvents").Msg("Unauthorized access to the Kubernetes API") + return httperror.Forbidden("Unauthorized access to the Kubernetes API", err) + } + + log.Error().Err(err).Str("context", "getKubernetesEvents").Msg("Unable to retrieve events") + return httperror.InternalServerError("Unable to retrieve events", err) + } + + return response.JSON(w, events) +} diff --git a/api/http/handler/kubernetes/event_test.go b/api/http/handler/kubernetes/event_test.go new file mode 100644 index 000000000..77f38c511 --- /dev/null +++ b/api/http/handler/kubernetes/event_test.go @@ -0,0 +1,60 @@ +package kubernetes + +import ( + "net/http" + "net/http/httptest" + "testing" + + portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/datastore" + "github.com/portainer/portainer/api/http/security" + "github.com/portainer/portainer/api/internal/authorization" + "github.com/portainer/portainer/api/internal/testhelpers" + "github.com/portainer/portainer/api/jwt" + "github.com/portainer/portainer/api/kubernetes" + kubeClient "github.com/portainer/portainer/api/kubernetes/cli" + "github.com/stretchr/testify/assert" +) + +// Currently this test just tests the HTTP Handler is setup correctly, in the future we should move the ClientFactory to a mock in order +// test the logic in event.go +func TestGetKubernetesEvents(t *testing.T) { + is := assert.New(t) + + _, store := datastore.MustNewTestStore(t, true, true) + + err := store.Endpoint().Create(&portainer.Endpoint{ + ID: 1, + Type: portainer.AgentOnKubernetesEnvironment, + }, + ) + is.NoError(err, "error creating environment") + + err = store.User().Create(&portainer.User{Username: "admin", Role: portainer.AdministratorRole}) + is.NoError(err, "error creating a user") + + jwtService, err := jwt.NewService("1h", store) + is.NoError(err, "Error initiating jwt service") + + tk, _, _ := jwtService.GenerateToken(&portainer.TokenData{ID: 1, Username: "admin", Role: portainer.AdministratorRole}) + + kubeClusterAccessService := kubernetes.NewKubeClusterAccessService("", "", "") + + cli := testhelpers.NewKubernetesClient() + factory, _ := kubeClient.NewClientFactory(nil, nil, store, "", "", "") + + authorizationService := authorization.NewService(store) + handler := NewHandler(testhelpers.NewTestRequestBouncer(), authorizationService, store, jwtService, kubeClusterAccessService, + factory, cli) + is.NotNil(handler, "Handler should not fail") + + req := httptest.NewRequest(http.MethodGet, "/kubernetes/1/events?resourceId=8", nil) + ctx := security.StoreTokenData(req, &portainer.TokenData{ID: 1, Username: "admin", Role: 1}) + req = req.WithContext(ctx) + testhelpers.AddTestSecurityCookie(req, tk) + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + is.Equal(http.StatusOK, rr.Code, "Status should be 200") +} diff --git a/api/http/handler/kubernetes/handler.go b/api/http/handler/kubernetes/handler.go index cc068e4a4..a8a5898c8 100644 --- a/api/http/handler/kubernetes/handler.go +++ b/api/http/handler/kubernetes/handler.go @@ -58,6 +58,7 @@ func NewHandler(bouncer security.BouncerService, authorizationService *authoriza endpointRouter.Handle("/configmaps/count", httperror.LoggerHandler(h.getAllKubernetesConfigMapsCount)).Methods(http.MethodGet) endpointRouter.Handle("/cron_jobs", httperror.LoggerHandler(h.getAllKubernetesCronJobs)).Methods(http.MethodGet) endpointRouter.Handle("/cron_jobs/delete", httperror.LoggerHandler(h.deleteKubernetesCronJobs)).Methods(http.MethodPost) + endpointRouter.Handle("/events", httperror.LoggerHandler(h.getAllKubernetesEvents)).Methods(http.MethodGet) endpointRouter.Handle("/jobs", httperror.LoggerHandler(h.getAllKubernetesJobs)).Methods(http.MethodGet) endpointRouter.Handle("/jobs/delete", httperror.LoggerHandler(h.deleteKubernetesJobs)).Methods(http.MethodPost) endpointRouter.Handle("/cluster_roles", httperror.LoggerHandler(h.getAllKubernetesClusterRoles)).Methods(http.MethodGet) @@ -110,6 +111,7 @@ func NewHandler(bouncer security.BouncerService, authorizationService *authoriza // to keep it simple, we've decided to leave it like this. namespaceRouter := endpointRouter.PathPrefix("/namespaces/{namespace}").Subrouter() namespaceRouter.Handle("/configmaps/{configmap}", httperror.LoggerHandler(h.getKubernetesConfigMap)).Methods(http.MethodGet) + namespaceRouter.Handle("/events", httperror.LoggerHandler(h.getKubernetesEventsForNamespace)).Methods(http.MethodGet) namespaceRouter.Handle("/system", bouncer.RestrictedAccess(httperror.LoggerHandler(h.namespacesToggleSystem))).Methods(http.MethodPut) namespaceRouter.Handle("/ingresscontrollers", httperror.LoggerHandler(h.getKubernetesIngressControllersByNamespace)).Methods(http.MethodGet) namespaceRouter.Handle("/ingresscontrollers", httperror.LoggerHandler(h.updateKubernetesIngressControllersByNamespace)).Methods(http.MethodPut) @@ -133,7 +135,7 @@ func NewHandler(bouncer security.BouncerService, authorizationService *authoriza // getProxyKubeClient gets a kubeclient for the user. It's generally what you want as it retrieves the kubeclient // from the Authorization token of the currently logged in user. The kubeclient that is not from the proxy is actually using // admin permissions. If you're unsure which one to use, use this. -func (h *Handler) getProxyKubeClient(r *http.Request) (*cli.KubeClient, *httperror.HandlerError) { +func (h *Handler) getProxyKubeClient(r *http.Request) (portainer.KubeClient, *httperror.HandlerError) { endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id") if err != nil { return nil, httperror.BadRequest(fmt.Sprintf("an error occurred during the getProxyKubeClient operation, the environment identifier route variable is invalid for /api/kubernetes/%d. Error: ", endpointID), err) @@ -144,7 +146,7 @@ func (h *Handler) getProxyKubeClient(r *http.Request) (*cli.KubeClient, *httperr return nil, httperror.Forbidden(fmt.Sprintf("an error occurred during the getProxyKubeClient operation, permission denied to access the environment /api/kubernetes/%d. Error: ", endpointID), err) } - cli, ok := h.KubernetesClientFactory.GetProxyKubeClient(strconv.Itoa(endpointID), tokenData.Token) + cli, ok := h.KubernetesClientFactory.GetProxyKubeClient(strconv.Itoa(endpointID), strconv.Itoa(int(tokenData.ID))) if !ok { return nil, httperror.InternalServerError("an error occurred during the getProxyKubeClient operation,failed to get proxy KubeClient", nil) } @@ -177,7 +179,7 @@ func (handler *Handler) kubeClientMiddleware(next http.Handler) http.Handler { } // Check if we have a kubeclient against this auth token already, otherwise generate a new one - _, ok := handler.KubernetesClientFactory.GetProxyKubeClient(strconv.Itoa(endpointID), tokenData.Token) + _, ok := handler.KubernetesClientFactory.GetProxyKubeClient(strconv.Itoa(endpointID), strconv.Itoa(int(tokenData.ID))) if ok { next.ServeHTTP(w, r) return @@ -253,7 +255,7 @@ func (handler *Handler) kubeClientMiddleware(next http.Handler) http.Handler { return } serverURL.Scheme = "https" - serverURL.Host = "localhost" + handler.KubernetesClientFactory.AddrHTTPS + serverURL.Host = "localhost" + handler.KubernetesClientFactory.GetAddrHTTPS() config.Clusters[0].Cluster.Server = serverURL.String() yaml, err := cli.GenerateYAML(config) @@ -267,7 +269,7 @@ func (handler *Handler) kubeClientMiddleware(next http.Handler) http.Handler { return } - handler.KubernetesClientFactory.SetProxyKubeClient(strconv.Itoa(int(endpoint.ID)), tokenData.Token, kubeCli) + handler.KubernetesClientFactory.SetProxyKubeClient(strconv.Itoa(int(endpoint.ID)), strconv.Itoa(int(tokenData.ID)), kubeCli) next.ServeHTTP(w, r) }) } diff --git a/api/http/handler/kubernetes/namespaces.go b/api/http/handler/kubernetes/namespaces.go index 2efde3b85..75dae9e69 100644 --- a/api/http/handler/kubernetes/namespaces.go +++ b/api/http/handler/kubernetes/namespaces.go @@ -22,6 +22,7 @@ import ( // @produce json // @param id path int true "Environment identifier" // @param withResourceQuota query boolean true "When set to true, include the resource quota information as part of the Namespace information. Default is false" +// @param withUnhealthyEvents query boolean true "When set to true, include the unhealthy events information as part of the Namespace information. Default is false" // @success 200 {array} portainer.K8sNamespaceInfo "Success" // @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria." // @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions." @@ -36,6 +37,12 @@ func (handler *Handler) getKubernetesNamespaces(w http.ResponseWriter, r *http.R return httperror.BadRequest("an error occurred during the GetKubernetesNamespaces operation, invalid query parameter withResourceQuota. Error: ", err) } + withUnhealthyEvents, err := request.RetrieveBooleanQueryParameter(r, "withUnhealthyEvents", true) + if err != nil { + log.Error().Err(err).Str("context", "GetKubernetesNamespaces").Msg("Invalid query parameter withUnhealthyEvents") + return httperror.BadRequest("an error occurred during the GetKubernetesNamespaces operation, invalid query parameter withUnhealthyEvents. Error: ", err) + } + cli, httpErr := handler.prepareKubeClient(r) if httpErr != nil { log.Error().Err(httpErr).Str("context", "GetKubernetesNamespaces").Msg("Unable to get a Kubernetes client for the user") @@ -48,6 +55,14 @@ func (handler *Handler) getKubernetesNamespaces(w http.ResponseWriter, r *http.R return httperror.InternalServerError("an error occurred during the GetKubernetesNamespaces operation, unable to retrieve namespaces from the Kubernetes cluster. Error: ", err) } + if withUnhealthyEvents { + namespaces, err = cli.CombineNamespacesWithUnhealthyEvents(namespaces) + if err != nil { + log.Error().Err(err).Str("context", "GetKubernetesNamespaces").Msg("Unable to combine namespaces with unhealthy events") + return httperror.InternalServerError("an error occurred during the GetKubernetesNamespaces operation, unable to combine namespaces with unhealthy events. Error: ", err) + } + } + if withResourceQuota { return cli.CombineNamespacesWithResourceQuotas(namespaces, w) } diff --git a/api/http/handler/motd/motd.go b/api/http/handler/motd/motd.go index dd2112c16..4117de830 100644 --- a/api/http/handler/motd/motd.go +++ b/api/http/handler/motd/motd.go @@ -7,7 +7,9 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/http/client" "github.com/portainer/portainer/pkg/libcrypto" + libclient "github.com/portainer/portainer/pkg/libhttp/client" "github.com/portainer/portainer/pkg/libhttp/response" + "github.com/rs/zerolog/log" "github.com/segmentio/encoding/json" ) @@ -37,6 +39,12 @@ type motdData struct { // @success 200 {object} motdResponse // @router /motd [get] func (handler *Handler) motd(w http.ResponseWriter, r *http.Request) { + if err := libclient.ExternalRequestDisabled(portainer.MessageOfTheDayURL); err != nil { + log.Debug().Err(err).Msg("External request disabled: MOTD") + response.JSON(w, &motdResponse{Message: ""}) + return + } + motd, err := client.Get(portainer.MessageOfTheDayURL, 0) if err != nil { response.JSON(w, &motdResponse{Message: ""}) diff --git a/api/http/handler/registries/handler.go b/api/http/handler/registries/handler.go index dee14885e..026039833 100644 --- a/api/http/handler/registries/handler.go +++ b/api/http/handler/registries/handler.go @@ -5,10 +5,10 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" + httperrors "github.com/portainer/portainer/api/http/errors" "github.com/portainer/portainer/api/http/proxy" "github.com/portainer/portainer/api/http/security" - "github.com/portainer/portainer/api/internal/endpointutils" - "github.com/portainer/portainer/api/kubernetes" + "github.com/portainer/portainer/api/internal/registryutils/access" "github.com/portainer/portainer/api/kubernetes/cli" "github.com/portainer/portainer/api/pendingactions" httperror "github.com/portainer/portainer/pkg/libhttp/error" @@ -17,6 +17,7 @@ import ( "github.com/gorilla/mux" "github.com/pkg/errors" + "github.com/rs/zerolog/log" ) func hideFields(registry *portainer.Registry, hideAccesses bool) { @@ -56,17 +57,20 @@ func newHandler(bouncer security.BouncerService) *Handler { func (handler *Handler) initRouter(bouncer accessGuard) { adminRouter := handler.NewRoute().Subrouter() adminRouter.Use(bouncer.AdminAccess) - - authenticatedRouter := handler.NewRoute().Subrouter() - authenticatedRouter.Use(bouncer.AuthenticatedAccess) - adminRouter.Handle("/registries", httperror.LoggerHandler(handler.registryList)).Methods(http.MethodGet) adminRouter.Handle("/registries", httperror.LoggerHandler(handler.registryCreate)).Methods(http.MethodPost) adminRouter.Handle("/registries/{id}", httperror.LoggerHandler(handler.registryUpdate)).Methods(http.MethodPut) adminRouter.Handle("/registries/{id}/configure", httperror.LoggerHandler(handler.registryConfigure)).Methods(http.MethodPost) adminRouter.Handle("/registries/{id}", httperror.LoggerHandler(handler.registryDelete)).Methods(http.MethodDelete) - authenticatedRouter.Handle("/registries/{id}", httperror.LoggerHandler(handler.registryInspect)).Methods(http.MethodGet) + // Use registry-specific access bouncer for inspect and repositories endpoints + registryAccessRouter := handler.NewRoute().Subrouter() + registryAccessRouter.Use(bouncer.AuthenticatedAccess, handler.RegistryAccess) + registryAccessRouter.Handle("/registries/{id}", httperror.LoggerHandler(handler.registryInspect)).Methods(http.MethodGet) + + // Keep the gitlab proxy on the regular authenticated router as it doesn't require specific registry access + authenticatedRouter := handler.NewRoute().Subrouter() + authenticatedRouter.Use(bouncer.AuthenticatedAccess) authenticatedRouter.PathPrefix("/registries/proxies/gitlab").Handler(httperror.LoggerHandler(handler.proxyRequestsToGitlabAPIWithoutRegistry)) } @@ -88,9 +92,7 @@ func (handler *Handler) registriesHaveSameURLAndCredentials(r1, r2 *portainer.Re } // this function validates that -// // 1. user has the appropriate authorizations to perform the request -// // 2. user has a direct or indirect access to the registry func (handler *Handler) userHasRegistryAccess(r *http.Request, registry *portainer.Registry) (hasAccess bool, isAdmin bool, err error) { securityContext, err := security.RetrieveRestrictedRequestContext(r) @@ -98,11 +100,6 @@ func (handler *Handler) userHasRegistryAccess(r *http.Request, registry *portain return false, false, err } - user, err := handler.DataStore.User().Read(securityContext.UserID) - if err != nil { - return false, false, err - } - // Portainer admins always have access to everything if securityContext.IsAdmin { return true, true, nil @@ -128,47 +125,68 @@ func (handler *Handler) userHasRegistryAccess(r *http.Request, registry *portain return false, false, err } - memberships, err := handler.DataStore.TeamMembership().TeamMembershipsByUserID(user.ID) + // Use the enhanced registry access utility function that includes namespace validation + _, err = access.GetAccessibleRegistry( + handler.DataStore, + handler.K8sClientFactory, + securityContext.UserID, + endpointId, + registry.ID, + ) if err != nil { - return false, false, nil + return false, false, nil // No access } - // validate access for kubernetes namespaces (leverage registry.RegistryAccesses[endpointId].Namespaces) - if endpointutils.IsKubernetesEndpoint(endpoint) { - kcl, err := handler.K8sClientFactory.GetPrivilegedKubeClient(endpoint) - if err != nil { - return false, false, errors.Wrap(err, "unable to retrieve kubernetes client to validate registry access") - } - accessPolicies, err := kcl.GetNamespaceAccessPolicies() - if err != nil { - return false, false, errors.Wrap(err, "unable to retrieve environment's namespaces policies to validate registry access") - } - - authorizedNamespaces := registry.RegistryAccesses[endpointId].Namespaces - - for _, namespace := range authorizedNamespaces { - // when the default namespace is authorized to use a registry, all users have the ability to use it - // unless the default namespace is restricted: in this case continue to search for other potential accesses authorizations - if namespace == kubernetes.DefaultNamespace && !endpoint.Kubernetes.Configuration.RestrictDefaultNamespace { - return true, false, nil - } - - namespacePolicy := accessPolicies[namespace] - if security.AuthorizedAccess(user.ID, memberships, namespacePolicy.UserAccessPolicies, namespacePolicy.TeamAccessPolicies) { - return true, false, nil - } - } - return false, false, nil - } - - // validate access for docker environments - // leverage registry.RegistryAccesses[endpointId].UserAccessPolicies (direct access) - // and registry.RegistryAccesses[endpointId].TeamAccessPolicies (indirect access via his teams) - if security.AuthorizedRegistryAccess(registry, user, memberships, endpoint.ID) { - return true, false, nil - } - - // when user has no access via their role, direct grant or indirect grant - // then they don't have access to the registry - return false, false, nil + return true, false, nil +} + +// RegistryAccess defines a security check for registry-specific API endpoints. +// Authentication is required to access these endpoints. +// The user must have direct or indirect access to the specific registry being requested. +// This bouncer validates registry access using the userHasRegistryAccess logic. +func (handler *Handler) RegistryAccess(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // First ensure the user is authenticated + tokenData, err := security.RetrieveTokenData(r) + if err != nil { + httperror.WriteError(w, http.StatusUnauthorized, "Authentication required", httperrors.ErrUnauthorized) + return + } + + // Extract registry ID from the route + registryID, err := request.RetrieveNumericRouteVariableValue(r, "id") + if err != nil { + httperror.WriteError(w, http.StatusBadRequest, "Invalid registry identifier route variable", err) + return + } + + // Get the registry from the database + registry, err := handler.DataStore.Registry().Read(portainer.RegistryID(registryID)) + if handler.DataStore.IsErrObjectNotFound(err) { + httperror.WriteError(w, http.StatusNotFound, "Unable to find a registry with the specified identifier inside the database", err) + return + } else if err != nil { + httperror.WriteError(w, http.StatusInternalServerError, "Unable to find a registry with the specified identifier inside the database", err) + return + } + + // Check if user has access to this registry + hasAccess, _, err := handler.userHasRegistryAccess(r, registry) + if err != nil { + httperror.WriteError(w, http.StatusInternalServerError, "Unable to retrieve info from request context", err) + return + } + if !hasAccess { + log.Debug(). + Int("registry_id", registryID). + Str("registry_name", registry.Name). + Int("user_id", int(tokenData.ID)). + Str("context", "RegistryAccessBouncer"). + Msg("User access denied to registry") + httperror.WriteError(w, http.StatusForbidden, "Access denied to resource", httperrors.ErrResourceAccessDenied) + return + } + + next.ServeHTTP(w, r) + }) } diff --git a/api/http/handler/registries/registry_access_test.go b/api/http/handler/registries/registry_access_test.go new file mode 100644 index 000000000..8231f4d66 --- /dev/null +++ b/api/http/handler/registries/registry_access_test.go @@ -0,0 +1,89 @@ +package registries + +import ( + "net/http" + "net/http/httptest" + "testing" + + portainer "github.com/portainer/portainer/api" + "github.com/portainer/portainer/api/datastore" + "github.com/portainer/portainer/api/http/security" + "github.com/portainer/portainer/api/internal/testhelpers" + + "github.com/gorilla/mux" + "github.com/stretchr/testify/assert" +) + +func Test_RegistryAccess_RequiresAuthentication(t *testing.T) { + _, store := datastore.MustNewTestStore(t, true, true) + registry := &portainer.Registry{ + ID: 1, + Name: "test-registry", + URL: "https://registry.test.com", + } + err := store.Registry().Create(registry) + assert.NoError(t, err) + handler := &Handler{ + DataStore: store, + } + req := httptest.NewRequest(http.MethodGet, "/registries/1", nil) + req = mux.SetURLVars(req, map[string]string{"id": "1"}) + rr := httptest.NewRecorder() + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + bouncer := handler.RegistryAccess(testHandler) + bouncer.ServeHTTP(rr, req) + assert.Equal(t, http.StatusUnauthorized, rr.Code) +} + +func Test_RegistryAccess_InvalidRegistryID(t *testing.T) { + _, store := datastore.MustNewTestStore(t, true, true) + user := &portainer.User{ID: 1, Username: "test", Role: portainer.StandardUserRole} + err := store.User().Create(user) + assert.NoError(t, err) + + handler := &Handler{ + DataStore: store, + } + req := httptest.NewRequest(http.MethodGet, "/registries/invalid", nil) + req = mux.SetURLVars(req, map[string]string{"id": "invalid"}) + tokenData := &portainer.TokenData{ID: 1, Role: portainer.StandardUserRole} + req = req.WithContext(security.StoreTokenData(req, tokenData)) + + rr := httptest.NewRecorder() + + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + bouncer := handler.RegistryAccess(testHandler) + bouncer.ServeHTTP(rr, req) + assert.Equal(t, http.StatusBadRequest, rr.Code) +} + +func Test_RegistryAccess_RegistryNotFound(t *testing.T) { + _, store := datastore.MustNewTestStore(t, true, true) + user := &portainer.User{ID: 1, Username: "test", Role: portainer.StandardUserRole} + err := store.User().Create(user) + assert.NoError(t, err) + + handler := &Handler{ + DataStore: store, + requestBouncer: testhelpers.NewTestRequestBouncer(), + } + req := httptest.NewRequest(http.MethodGet, "/registries/999", nil) + req = mux.SetURLVars(req, map[string]string{"id": "999"}) + tokenData := &portainer.TokenData{ID: 1, Role: portainer.StandardUserRole} + req = req.WithContext(security.StoreTokenData(req, tokenData)) + + rr := httptest.NewRecorder() + + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + bouncer := handler.RegistryAccess(testHandler) + bouncer.ServeHTTP(rr, req) + assert.Equal(t, http.StatusNotFound, rr.Code) +} diff --git a/api/http/handler/registries/registry_inspect.go b/api/http/handler/registries/registry_inspect.go index a1f0bd9c5..f606a953e 100644 --- a/api/http/handler/registries/registry_inspect.go +++ b/api/http/handler/registries/registry_inspect.go @@ -4,10 +4,12 @@ import ( "net/http" portainer "github.com/portainer/portainer/api" - httperrors "github.com/portainer/portainer/api/http/errors" + "github.com/portainer/portainer/api/http/security" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" "github.com/portainer/portainer/pkg/libhttp/response" + + "github.com/rs/zerolog/log" ) // @id RegistryInspect @@ -31,6 +33,11 @@ func (handler *Handler) registryInspect(w http.ResponseWriter, r *http.Request) return httperror.BadRequest("Invalid registry identifier route variable", err) } + log.Debug(). + Int("registry_id", registryID). + Str("context", "RegistryInspectHandler"). + Msg("Starting registry inspection") + registry, err := handler.DataStore.Registry().Read(portainer.RegistryID(registryID)) if handler.DataStore.IsErrObjectNotFound(err) { return httperror.NotFound("Unable to find a registry with the specified identifier inside the database", err) @@ -38,14 +45,12 @@ func (handler *Handler) registryInspect(w http.ResponseWriter, r *http.Request) return httperror.InternalServerError("Unable to find a registry with the specified identifier inside the database", err) } - hasAccess, isAdmin, err := handler.userHasRegistryAccess(r, registry) + // Check if user is admin to determine if we should hide sensitive fields + securityContext, err := security.RetrieveRestrictedRequestContext(r) if err != nil { return httperror.InternalServerError("Unable to retrieve info from request context", err) } - if !hasAccess { - return httperror.Forbidden("Access denied to resource", httperrors.ErrResourceAccessDenied) - } - hideFields(registry, !isAdmin) + hideFields(registry, !securityContext.IsAdmin) return response.JSON(w, registry) } diff --git a/api/http/handler/system/version.go b/api/http/handler/system/version.go index 9d80b88a9..52af5879c 100644 --- a/api/http/handler/system/version.go +++ b/api/http/handler/system/version.go @@ -7,6 +7,7 @@ import ( "github.com/portainer/portainer/api/http/client" "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/pkg/build" + libclient "github.com/portainer/portainer/pkg/libhttp/client" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/response" @@ -69,10 +70,14 @@ func (handler *Handler) version(w http.ResponseWriter, r *http.Request) *httperr } func GetLatestVersion() string { + if err := libclient.ExternalRequestDisabled(portainer.VersionCheckURL); err != nil { + log.Debug().Err(err).Msg("External request disabled: Version check") + return "" + } + motd, err := client.Get(portainer.VersionCheckURL, 5) if err != nil { log.Debug().Err(err).Msg("couldn't fetch latest Portainer release version") - return "" } diff --git a/api/http/handler/tags/tag_delete.go b/api/http/handler/tags/tag_delete.go index 4f8554faf..f8f1b7786 100644 --- a/api/http/handler/tags/tag_delete.go +++ b/api/http/handler/tags/tag_delete.go @@ -8,6 +8,7 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/internal/edge" + "github.com/portainer/portainer/api/internal/endpointutils" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" "github.com/portainer/portainer/pkg/libhttp/response" @@ -58,6 +59,9 @@ func deleteTag(tx dataservices.DataStoreTx, tagID portainer.TagID) error { for endpointID := range tag.Endpoints { endpoint, err := tx.Endpoint().Endpoint(endpointID) + if tx.IsErrObjectNotFound(err) { + continue + } if err != nil { return httperror.InternalServerError("Unable to retrieve environment from the database", err) } @@ -103,15 +107,10 @@ func deleteTag(tx dataservices.DataStoreTx, tagID portainer.TagID) error { return httperror.InternalServerError("Unable to retrieve edge stacks from the database", err) } - for _, endpoint := range endpoints { - if (tag.Endpoints[endpoint.ID] || tag.EndpointGroups[endpoint.GroupID]) && (endpoint.Type == portainer.EdgeAgentOnDockerEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment) { - err = updateEndpointRelations(tx, endpoint, edgeGroups, edgeStacks) - if err != nil { - return httperror.InternalServerError("Unable to update environment relations in the database", err) - } - } + edgeJobs, err := tx.EdgeJob().ReadAll() + if err != nil { + return httperror.InternalServerError("Unable to retrieve edge job configurations from the database", err) } - for _, edgeGroup := range edgeGroups { edgeGroup.TagIDs = slices.DeleteFunc(edgeGroup.TagIDs, func(t portainer.TagID) bool { return t == tagID @@ -123,6 +122,16 @@ func deleteTag(tx dataservices.DataStoreTx, tagID portainer.TagID) error { } } + for _, endpoint := range endpoints { + if (!tag.Endpoints[endpoint.ID] && !tag.EndpointGroups[endpoint.GroupID]) || !endpointutils.IsEdgeEndpoint(&endpoint) { + continue + } + + if err := updateEndpointRelations(tx, endpoint, edgeGroups, edgeStacks, edgeJobs); err != nil { + return httperror.InternalServerError("Unable to update environment relations in the database", err) + } + } + err = tx.Tag().Delete(tagID) if err != nil { return httperror.InternalServerError("Unable to remove the tag from the database", err) @@ -131,19 +140,12 @@ func deleteTag(tx dataservices.DataStoreTx, tagID portainer.TagID) error { return nil } -func updateEndpointRelations(tx dataservices.DataStoreTx, endpoint portainer.Endpoint, edgeGroups []portainer.EdgeGroup, edgeStacks []portainer.EdgeStack) error { +func updateEndpointRelations(tx dataservices.DataStoreTx, endpoint portainer.Endpoint, edgeGroups []portainer.EdgeGroup, edgeStacks []portainer.EdgeStack, edgeJobs []portainer.EdgeJob) error { endpointRelation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) - if err != nil && !tx.IsErrObjectNotFound(err) { + if err != nil { return err } - if endpointRelation == nil { - endpointRelation = &portainer.EndpointRelation{ - EndpointID: endpoint.ID, - EdgeStacks: make(map[portainer.EdgeStackID]bool), - } - } - endpointGroup, err := tx.EndpointGroup().Read(endpoint.GroupID) if err != nil { return err @@ -157,5 +159,25 @@ func updateEndpointRelations(tx dataservices.DataStoreTx, endpoint portainer.End endpointRelation.EdgeStacks = stacksSet - return tx.EndpointRelation().UpdateEndpointRelation(endpoint.ID, endpointRelation) + if err := tx.EndpointRelation().UpdateEndpointRelation(endpoint.ID, endpointRelation); err != nil { + return err + } + + for _, edgeJob := range edgeJobs { + endpoints, err := edge.GetEndpointsFromEdgeGroups(edgeJob.EdgeGroups, tx) + if err != nil { + return err + } + if slices.Contains(endpoints, endpoint.ID) { + continue + } + + delete(edgeJob.GroupLogsCollection, endpoint.ID) + + if err := tx.EdgeJob().Update(edgeJob.ID, &edgeJob); err != nil { + return err + } + } + + return nil } diff --git a/api/http/handler/tags/tag_delete_test.go b/api/http/handler/tags/tag_delete_test.go index cabf20963..ecced7c0d 100644 --- a/api/http/handler/tags/tag_delete_test.go +++ b/api/http/handler/tags/tag_delete_test.go @@ -1,6 +1,7 @@ package tags import ( + "github.com/portainer/portainer/api/dataservices" "net/http" "net/http/httptest" "strconv" @@ -8,23 +9,18 @@ import ( "testing" portainer "github.com/portainer/portainer/api" + portainerDsErrors "github.com/portainer/portainer/api/dataservices/errors" "github.com/portainer/portainer/api/datastore" "github.com/portainer/portainer/api/internal/testhelpers" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTagDeleteEdgeGroupsConcurrently(t *testing.T) { const tagsCount = 100 - _, store := datastore.MustNewTestStore(t, true, false) - - user := &portainer.User{ID: 2, Username: "admin", Role: portainer.AdministratorRole} - if err := store.User().Create(user); err != nil { - t.Fatal("could not create admin user:", err) - } - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - + handler, store := setUpHandler(t) // Create all the tags and add them to the same edge group var tagIDs []portainer.TagID @@ -84,3 +80,132 @@ func TestTagDeleteEdgeGroupsConcurrently(t *testing.T) { t.Fatal("the edge group is not consistent") } } + +func TestHandler_tagDelete(t *testing.T) { + t.Run("should delete tag and update related endpoints and edge groups", func(t *testing.T) { + handler, store := setUpHandler(t) + + tag := &portainer.Tag{ + ID: 1, + Name: "tag-1", + Endpoints: make(map[portainer.EndpointID]bool), + EndpointGroups: make(map[portainer.EndpointGroupID]bool), + } + require.NoError(t, store.Tag().Create(tag)) + + endpointGroup := &portainer.EndpointGroup{ + ID: 2, + Name: "endpoint-group-1", + TagIDs: []portainer.TagID{tag.ID}, + } + require.NoError(t, store.EndpointGroup().Create(endpointGroup)) + + endpoint1 := &portainer.Endpoint{ + ID: 1, + Name: "endpoint-1", + GroupID: endpointGroup.ID, + } + require.NoError(t, store.Endpoint().Create(endpoint1)) + + endpoint2 := &portainer.Endpoint{ + ID: 2, + Name: "endpoint-2", + TagIDs: []portainer.TagID{tag.ID}, + } + require.NoError(t, store.Endpoint().Create(endpoint2)) + + tag.Endpoints[endpoint2.ID] = true + tag.EndpointGroups[endpointGroup.ID] = true + require.NoError(t, store.Tag().Update(tag.ID, tag)) + + dynamicEdgeGroup := &portainer.EdgeGroup{ + ID: 1, + Name: "edgegroup-1", + TagIDs: []portainer.TagID{tag.ID}, + Dynamic: true, + } + require.NoError(t, store.EdgeGroup().Create(dynamicEdgeGroup)) + + staticEdgeGroup := &portainer.EdgeGroup{ + ID: 2, + Name: "edgegroup-2", + Endpoints: []portainer.EndpointID{endpoint2.ID}, + } + require.NoError(t, store.EdgeGroup().Create(staticEdgeGroup)) + + req, err := http.NewRequest(http.MethodDelete, "/tags/"+strconv.Itoa(int(tag.ID)), nil) + if err != nil { + t.Fail() + + return + } + + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + require.Equal(t, http.StatusNoContent, rec.Code) + + // Check that the tag is deleted + _, err = store.Tag().Read(tag.ID) + require.ErrorIs(t, err, portainerDsErrors.ErrObjectNotFound) + + // Check that the endpoints are updated + endpoint1, err = store.Endpoint().Endpoint(endpoint1.ID) + require.NoError(t, err) + assert.Len(t, endpoint1.TagIDs, 0, "endpoint-1 should not have any tags") + assert.Equal(t, endpoint1.GroupID, endpointGroup.ID, "endpoint-1 should still belong to the endpoint group") + + endpoint2, err = store.Endpoint().Endpoint(endpoint2.ID) + require.NoError(t, err) + assert.Len(t, endpoint2.TagIDs, 0, "endpoint-2 should not have any tags") + + // Check that the dynamic edge group is updated + dynamicEdgeGroup, err = store.EdgeGroup().Read(dynamicEdgeGroup.ID) + require.NoError(t, err) + assert.Len(t, dynamicEdgeGroup.TagIDs, 0, "dynamic edge group should not have any tags") + assert.Len(t, dynamicEdgeGroup.Endpoints, 0, "dynamic edge group should not have any endpoints") + + // Check that the static edge group is not updated + staticEdgeGroup, err = store.EdgeGroup().Read(staticEdgeGroup.ID) + require.NoError(t, err) + assert.Len(t, staticEdgeGroup.TagIDs, 0, "static edge group should not have any tags") + assert.Len(t, staticEdgeGroup.Endpoints, 1, "static edge group should have one endpoint") + assert.Equal(t, endpoint2.ID, staticEdgeGroup.Endpoints[0], "static edge group should have the endpoint-2") + }) + + // Test the tx.IsErrObjectNotFound logic when endpoint is not found during cleanup + t.Run("should continue gracefully when endpoint not found during cleanup", func(t *testing.T) { + _, store := setUpHandler(t) + // Create a tag with a reference to a non-existent endpoint + tag := &portainer.Tag{ + ID: 1, + Name: "test-tag", + Endpoints: map[portainer.EndpointID]bool{999: true}, // Non-existent endpoint + EndpointGroups: make(map[portainer.EndpointGroupID]bool), + } + + err := store.Tag().Create(tag) + if err != nil { + t.Fatal("could not create tag:", err) + } + + err = deleteTag(store, 1) + if err != nil { + t.Fatal("could not delete tag:", err) + } + }) +} + +func setUpHandler(t *testing.T) (*Handler, dataservices.DataStore) { + _, store := datastore.MustNewTestStore(t, true, false) + + user := &portainer.User{ID: 2, Username: "admin", Role: portainer.AdministratorRole} + if err := store.User().Create(user); err != nil { + t.Fatal("could not create admin user:", err) + } + + handler := NewHandler(testhelpers.NewTestRequestBouncer()) + handler.DataStore = store + + return handler, store +} diff --git a/api/http/handler/templates/utils_fetch_templates.go b/api/http/handler/templates/utils_fetch_templates.go index 6feb9edeb..fc5c97125 100644 --- a/api/http/handler/templates/utils_fetch_templates.go +++ b/api/http/handler/templates/utils_fetch_templates.go @@ -4,7 +4,9 @@ import ( "net/http" portainer "github.com/portainer/portainer/api" + libclient "github.com/portainer/portainer/pkg/libhttp/client" httperror "github.com/portainer/portainer/pkg/libhttp/error" + "github.com/rs/zerolog/log" "github.com/segmentio/encoding/json" ) @@ -24,18 +26,27 @@ func (handler *Handler) fetchTemplates() (*listResponse, *httperror.HandlerError templatesURL = portainer.DefaultTemplatesURL } + var body *listResponse + if err := libclient.ExternalRequestDisabled(templatesURL); err != nil { + if templatesURL == portainer.DefaultTemplatesURL { + log.Debug().Err(err).Msg("External request disabled: Default templates") + return body, nil + } + } + resp, err := http.Get(templatesURL) if err != nil { return nil, httperror.InternalServerError("Unable to retrieve templates via the network", err) } defer resp.Body.Close() - var body *listResponse - err = json.NewDecoder(resp.Body).Decode(&body) - if err != nil { + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { return nil, httperror.InternalServerError("Unable to parse template file", err) } + for i := range body.Templates { + body.Templates[i].ID = portainer.TemplateID(i + 1) + } return body, nil } diff --git a/api/http/handler/webhooks/webhook_create.go b/api/http/handler/webhooks/webhook_create.go index b69e93db3..d7edde333 100644 --- a/api/http/handler/webhooks/webhook_create.go +++ b/api/http/handler/webhooks/webhook_create.go @@ -80,7 +80,7 @@ func (handler *Handler) webhookCreate(w http.ResponseWriter, r *http.Request) *h return httperror.InternalServerError("Unable to retrieve user authentication token", err) } - _, err = access.GetAccessibleRegistry(handler.DataStore, tokenData.ID, endpointID, payload.RegistryID) + _, err = access.GetAccessibleRegistry(handler.DataStore, nil, tokenData.ID, endpointID, payload.RegistryID) if err != nil { return httperror.Forbidden("Permission deny to access registry", err) } diff --git a/api/http/handler/webhooks/webhook_update.go b/api/http/handler/webhooks/webhook_update.go index 7a026fcd7..94133c49a 100644 --- a/api/http/handler/webhooks/webhook_update.go +++ b/api/http/handler/webhooks/webhook_update.go @@ -69,7 +69,7 @@ func (handler *Handler) webhookUpdate(w http.ResponseWriter, r *http.Request) *h return httperror.InternalServerError("Unable to retrieve user authentication token", err) } - _, err = access.GetAccessibleRegistry(handler.DataStore, tokenData.ID, webhook.EndpointID, payload.RegistryID) + _, err = access.GetAccessibleRegistry(handler.DataStore, nil, tokenData.ID, webhook.EndpointID, payload.RegistryID) if err != nil { return httperror.Forbidden("Permission deny to access registry", err) } diff --git a/api/http/middlewares/endpoint.go b/api/http/middlewares/endpoint.go index c88731dd3..0050e4300 100644 --- a/api/http/middlewares/endpoint.go +++ b/api/http/middlewares/endpoint.go @@ -25,12 +25,12 @@ type key int const contextEndpoint key = 0 func WithEndpoint(endpointService dataservices.EndpointService, endpointIDParam string) mux.MiddlewareFunc { + if endpointIDParam == "" { + endpointIDParam = "id" + } + return func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, request *http.Request) { - if endpointIDParam == "" { - endpointIDParam = "id" - } - endpointID, err := requesthelpers.RetrieveNumericRouteVariableValue(request, endpointIDParam) if err != nil { httperror.WriteError(rw, http.StatusBadRequest, "Invalid environment identifier route variable", err) @@ -51,7 +51,6 @@ func WithEndpoint(endpointService dataservices.EndpointService, endpointIDParam ctx := context.WithValue(request.Context(), contextEndpoint, endpoint) next.ServeHTTP(rw, request.WithContext(ctx)) - }) } } diff --git a/api/http/middlewares/plaintext_http_request.go b/api/http/middlewares/plaintext_http_request.go index 668346098..e746fd819 100644 --- a/api/http/middlewares/plaintext_http_request.go +++ b/api/http/middlewares/plaintext_http_request.go @@ -3,6 +3,7 @@ package middlewares import ( "net/http" "slices" + "strings" "github.com/gorilla/csrf" ) @@ -16,6 +17,45 @@ type plainTextHTTPRequestHandler struct { next http.Handler } +// parseForwardedHeaderProto parses the Forwarded header and extracts the protocol. +// The Forwarded header format supports: +// - Single proxy: Forwarded: by=;for=;host=;proto= +// - Multiple proxies: Forwarded: for=192.0.2.43, for=198.51.100.17 +// We take the first (leftmost) entry as it represents the original client +func parseForwardedHeaderProto(forwarded string) string { + if forwarded == "" { + return "" + } + + // Parse the first part (leftmost proxy, closest to original client) + firstPart, _, _ := strings.Cut(forwarded, ",") + firstPart = strings.TrimSpace(firstPart) + + // Split by semicolon to get key-value pairs within this proxy entry + // Format: key=value;key=value;key=value + pairs := strings.Split(firstPart, ";") + for _, pair := range pairs { + // Split by equals sign to separate key and value + key, value, found := strings.Cut(pair, "=") + if !found { + continue + } + + if strings.EqualFold(strings.TrimSpace(key), "proto") { + return strings.Trim(strings.TrimSpace(value), `"'`) + } + } + + return "" +} + +// isHTTPSRequest checks if the original request was made over HTTPS +// by examining both X-Forwarded-Proto and Forwarded headers +func isHTTPSRequest(r *http.Request) bool { + return strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") || + strings.EqualFold(parseForwardedHeaderProto(r.Header.Get("Forwarded")), "https") +} + func (h *plainTextHTTPRequestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if slices.Contains(safeMethods, r.Method) { h.next.ServeHTTP(w, r) @@ -24,7 +64,7 @@ func (h *plainTextHTTPRequestHandler) ServeHTTP(w http.ResponseWriter, r *http.R req := r // If original request was HTTPS (via proxy), keep CSRF checks. - if xfproto := r.Header.Get("X-Forwarded-Proto"); xfproto != "https" { + if !isHTTPSRequest(r) { req = csrf.PlaintextHTTPRequest(r) } diff --git a/api/http/middlewares/plaintext_http_request_test.go b/api/http/middlewares/plaintext_http_request_test.go new file mode 100644 index 000000000..33912be80 --- /dev/null +++ b/api/http/middlewares/plaintext_http_request_test.go @@ -0,0 +1,173 @@ +package middlewares + +import ( + "testing" +) + +var tests = []struct { + name string + forwarded string + expected string +}{ + { + name: "empty header", + forwarded: "", + expected: "", + }, + { + name: "single proxy with proto=https", + forwarded: "proto=https", + expected: "https", + }, + { + name: "single proxy with proto=http", + forwarded: "proto=http", + expected: "http", + }, + { + name: "single proxy with multiple directives", + forwarded: "for=192.0.2.60;proto=https;by=203.0.113.43", + expected: "https", + }, + { + name: "single proxy with proto in middle", + forwarded: "for=192.0.2.60;proto=https;host=example.com", + expected: "https", + }, + { + name: "single proxy with proto at end", + forwarded: "for=192.0.2.60;host=example.com;proto=https", + expected: "https", + }, + { + name: "multiple proxies - takes first", + forwarded: "proto=https, proto=http", + expected: "https", + }, + { + name: "multiple proxies with complex format", + forwarded: "for=192.0.2.43;proto=https, for=198.51.100.17;proto=http", + expected: "https", + }, + { + name: "multiple proxies with for directive only", + forwarded: "for=192.0.2.43, for=198.51.100.17", + expected: "", + }, + { + name: "multiple proxies with proto only in second", + forwarded: "for=192.0.2.43, proto=https", + expected: "", + }, + { + name: "multiple proxies with proto only in first", + forwarded: "proto=https, for=198.51.100.17", + expected: "https", + }, + { + name: "quoted protocol value", + forwarded: "proto=\"https\"", + expected: "https", + }, + { + name: "single quoted protocol value", + forwarded: "proto='https'", + expected: "https", + }, + { + name: "mixed case protocol", + forwarded: "proto=HTTPS", + expected: "HTTPS", + }, + { + name: "no proto directive", + forwarded: "for=192.0.2.60;by=203.0.113.43", + expected: "", + }, + { + name: "empty proto value", + forwarded: "proto=", + expected: "", + }, + { + name: "whitespace around values", + forwarded: " proto = https ", + expected: "https", + }, + { + name: "whitespace around semicolons", + forwarded: "for=192.0.2.60 ; proto=https ; by=203.0.113.43", + expected: "https", + }, + { + name: "whitespace around commas", + forwarded: "proto=https , proto=http", + expected: "https", + }, + { + name: "IPv6 address in for directive", + forwarded: "for=\"[2001:db8:cafe::17]:4711\";proto=https", + expected: "https", + }, + { + name: "complex multiple proxies with IPv6", + forwarded: "for=192.0.2.43;proto=https, for=\"[2001:db8:cafe::17]\";proto=http", + expected: "https", + }, + { + name: "obfuscated identifiers", + forwarded: "for=_mdn;proto=https", + expected: "https", + }, + { + name: "unknown identifier", + forwarded: "for=unknown;proto=https", + expected: "https", + }, + { + name: "malformed key-value pair", + forwarded: "proto", + expected: "", + }, + { + name: "malformed key-value pair with equals", + forwarded: "proto=", + expected: "", + }, + { + name: "multiple equals signs", + forwarded: "proto=https=extra", + expected: "https=extra", + }, + { + name: "mixed case directive name", + forwarded: "PROTO=https", + expected: "https", + }, + { + name: "mixed case directive name with spaces", + forwarded: " Proto = https ", + expected: "https", + }, +} + +func TestParseForwardedHeaderProto(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := parseForwardedHeaderProto(tt.forwarded) + if result != tt.expected { + t.Errorf("parseForwardedHeader(%q) = %q, want %q", tt.forwarded, result, tt.expected) + } + }) + } +} + +func FuzzParseForwardedHeaderProto(f *testing.F) { + for _, t := range tests { + f.Add(t.forwarded) + } + + f.Fuzz(func(t *testing.T, forwarded string) { + parseForwardedHeaderProto(forwarded) + }) +} diff --git a/api/http/models/kubernetes/application.go b/api/http/models/kubernetes/application.go index fcb49b23d..4759d9214 100644 --- a/api/http/models/kubernetes/application.go +++ b/api/http/models/kubernetes/application.go @@ -38,14 +38,30 @@ type K8sApplication struct { Labels map[string]string `json:"Labels,omitempty"` Resource K8sApplicationResource `json:"Resource,omitempty"` HorizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler `json:"HorizontalPodAutoscaler,omitempty"` + CustomResourceMetadata CustomResourceMetadata `json:"CustomResourceMetadata,omitempty"` } type Metadata struct { Labels map[string]string `json:"labels"` } +type CustomResourceMetadata struct { + Kind string `json:"kind"` + APIVersion string `json:"apiVersion"` + Plural string `json:"plural"` +} + type Pod struct { - Status string `json:"Status"` + Name string `json:"Name"` + ContainerName string `json:"ContainerName"` + Image string `json:"Image"` + ImagePullPolicy string `json:"ImagePullPolicy"` + Status string `json:"Status"` + NodeName string `json:"NodeName"` + PodIP string `json:"PodIP"` + UID string `json:"Uid"` + Resource K8sApplicationResource `json:"Resource,omitempty"` + CreationDate time.Time `json:"CreationDate"` } type Configuration struct { @@ -72,8 +88,8 @@ type TLSInfo struct { // Existing types type K8sApplicationResource struct { - CPURequest float64 `json:"CpuRequest"` - CPULimit float64 `json:"CpuLimit"` - MemoryRequest int64 `json:"MemoryRequest"` - MemoryLimit int64 `json:"MemoryLimit"` + CPURequest float64 `json:"CpuRequest,omitempty"` + CPULimit float64 `json:"CpuLimit,omitempty"` + MemoryRequest int64 `json:"MemoryRequest,omitempty"` + MemoryLimit int64 `json:"MemoryLimit,omitempty"` } diff --git a/api/http/models/kubernetes/event.go b/api/http/models/kubernetes/event.go new file mode 100644 index 000000000..be447b554 --- /dev/null +++ b/api/http/models/kubernetes/event.go @@ -0,0 +1,25 @@ +package kubernetes + +import "time" + +type K8sEvent struct { + Type string `json:"type"` + Name string `json:"name"` + Reason string `json:"reason"` + Message string `json:"message"` + Namespace string `json:"namespace"` + EventTime time.Time `json:"eventTime"` + Kind string `json:"kind,omitempty"` + Count int32 `json:"count"` + FirstTimestamp *time.Time `json:"firstTimestamp,omitempty"` + LastTimestamp *time.Time `json:"lastTimestamp,omitempty"` + UID string `json:"uid"` + InvolvedObjectKind K8sEventInvolvedObject `json:"involvedObject"` +} + +type K8sEventInvolvedObject struct { + Kind string `json:"kind,omitempty"` + UID string `json:"uid"` + Name string `json:"name"` + Namespace string `json:"namespace"` +} diff --git a/api/http/proxy/factory/docker/access_control.go b/api/http/proxy/factory/docker/access_control.go index e945d38da..ac25a7b7a 100644 --- a/api/http/proxy/factory/docker/access_control.go +++ b/api/http/proxy/factory/docker/access_control.go @@ -35,7 +35,7 @@ type ( func getUniqueElements(items string) []string { xs := strings.Split(items, ",") xs = slicesx.Map(xs, strings.TrimSpace) - xs = slicesx.Filter(xs, func(x string) bool { return len(x) > 0 }) + xs = slicesx.FilterInPlace(xs, func(x string) bool { return len(x) > 0 }) return slicesx.Unique(xs) } diff --git a/api/http/proxy/factory/docker/networks.go b/api/http/proxy/factory/docker/networks.go index 95c96df81..cd94478d2 100644 --- a/api/http/proxy/factory/docker/networks.go +++ b/api/http/proxy/factory/docker/networks.go @@ -6,7 +6,7 @@ import ( portainer "github.com/portainer/portainer/api" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" @@ -20,7 +20,7 @@ const ( ) func getInheritedResourceControlFromNetworkLabels(dockerClient *client.Client, endpointID portainer.EndpointID, networkID string, resourceControls []portainer.ResourceControl) (*portainer.ResourceControl, error) { - network, err := dockerClient.NetworkInspect(context.Background(), networkID, types.NetworkInspectOptions{}) + network, err := dockerClient.NetworkInspect(context.Background(), networkID, network.InspectOptions{}) if err != nil { return nil, err } diff --git a/api/http/proxy/factory/docker/registry.go b/api/http/proxy/factory/docker/registry.go index ecf7935f1..7036853c7 100644 --- a/api/http/proxy/factory/docker/registry.go +++ b/api/http/proxy/factory/docker/registry.go @@ -55,12 +55,13 @@ func createRegistryAuthenticationHeader( return } - if err = registryutils.EnsureRegTokenValid(dataStore, matchingRegistry); err != nil { + if err = registryutils.PrepareRegistryCredentials(dataStore, matchingRegistry); err != nil { return } authenticationHeader.Serveraddress = matchingRegistry.URL - authenticationHeader.Username, authenticationHeader.Password, err = registryutils.GetRegEffectiveCredential(matchingRegistry) + authenticationHeader.Username = matchingRegistry.Username + authenticationHeader.Password = matchingRegistry.Password return } diff --git a/api/http/proxy/factory/github/client.go b/api/http/proxy/factory/github/client.go new file mode 100644 index 000000000..74dcfb994 --- /dev/null +++ b/api/http/proxy/factory/github/client.go @@ -0,0 +1,108 @@ +package github + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/segmentio/encoding/json" + "oras.land/oras-go/v2/registry/remote/retry" +) + +const GitHubAPIHost = "https://api.github.com" + +// Package represents a GitHub container package +type Package struct { + Name string `json:"name"` + Owner struct { + Login string `json:"login"` + } `json:"owner"` +} + +// Client represents a GitHub API client +type Client struct { + httpClient *http.Client + baseURL string +} + +// NewClient creates a new GitHub API client +func NewClient(token string) *Client { + return &Client{ + httpClient: NewHTTPClient(token), + baseURL: GitHubAPIHost, + } +} + +// GetContainerPackages fetches container packages for the configured namespace +// It's a small http client wrapper instead of using the github client because listing repositories is the only known operation that isn't directly supported by oras +func (c *Client) GetContainerPackages(ctx context.Context, useOrganisation bool, organisationName string) ([]string, error) { + // Determine the namespace (user or organisation) for the request + namespace := "user" + if useOrganisation { + namespace = "orgs/" + organisationName + } + + // Build the full URL for listing container packages + url := fmt.Sprintf("%s/%s/packages?package_type=container", c.baseURL, namespace) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to execute request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + var packages []Package + if err := json.Unmarshal(body, &packages); err != nil { + return nil, fmt.Errorf("failed to parse response: %w", err) + } + + // Extract repository names in the form "owner/name" + repositories := make([]string, len(packages)) + for i, pkg := range packages { + repositories[i] = fmt.Sprintf("%s/%s", strings.ToLower(pkg.Owner.Login), strings.ToLower(pkg.Name)) + } + + return repositories, nil +} + +// NewHTTPClient creates a new HTTP client configured for GitHub API requests +func NewHTTPClient(token string) *http.Client { + return &http.Client{ + Transport: &tokenTransport{ + token: token, + transport: retry.NewTransport(&http.Transport{}), // Use ORAS retry transport for consistent rate limiting and error handling + }, + Timeout: 1 * time.Minute, + } +} + +// tokenTransport automatically adds the Bearer token header to requests +type tokenTransport struct { + token string + transport http.RoundTripper +} + +func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if t.token != "" { + req.Header.Set("Authorization", "Bearer "+t.token) + req.Header.Set("Accept", "application/vnd.github+json") + } + return t.transport.RoundTrip(req) +} diff --git a/api/http/proxy/factory/gitlab/client.go b/api/http/proxy/factory/gitlab/client.go new file mode 100644 index 000000000..13d07e18b --- /dev/null +++ b/api/http/proxy/factory/gitlab/client.go @@ -0,0 +1,130 @@ +package gitlab + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "time" + + "github.com/segmentio/encoding/json" + "oras.land/oras-go/v2/registry/remote/retry" +) + +// Repository represents a GitLab registry repository +type Repository struct { + ID int `json:"id"` + Name string `json:"name"` + Path string `json:"path"` + ProjectID int `json:"project_id"` + Location string `json:"location"` + CreatedAt string `json:"created_at"` + Status string `json:"status"` +} + +// Client represents a GitLab API client +type Client struct { + httpClient *http.Client + baseURL string +} + +// NewClient creates a new GitLab API client +// it currently is an http client because only GetRegistryRepositoryNames is needed (oras supports other commands). +// if we need to support other commands, consider using the gitlab client library. +func NewClient(baseURL, token string) *Client { + return &Client{ + httpClient: NewHTTPClient(token), + baseURL: baseURL, + } +} + +// GetRegistryRepositoryNames fetches registry repository names for a given project. +// It's a small http client wrapper instead of using the gitlab client library because listing repositories is the only known operation that isn't directly supported by oras +func (c *Client) GetRegistryRepositoryNames(ctx context.Context, projectID int) ([]string, error) { + url := fmt.Sprintf("%s/api/v4/projects/%d/registry/repositories", c.baseURL, projectID) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to execute request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GitLab API returned status %d: %s", resp.StatusCode, resp.Status) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + var repositories []Repository + if err := json.Unmarshal(body, &repositories); err != nil { + return nil, fmt.Errorf("failed to parse response: %w", err) + } + + // Extract repository names + names := make([]string, len(repositories)) + for i, repo := range repositories { + // the full path is required for further repo operations + names[i] = repo.Path + } + + return names, nil +} + +type Transport struct { + httpTransport *http.Transport +} + +// NewTransport returns a pointer to a new instance of Transport that implements the HTTP Transport +// interface for proxying requests to the Gitlab API. +func NewTransport() *Transport { + return &Transport{ + httpTransport: &http.Transport{}, + } +} + +// RoundTrip is the implementation of the http.RoundTripper interface +func (transport *Transport) RoundTrip(request *http.Request) (*http.Response, error) { + token := request.Header.Get("Private-Token") + if token == "" { + return nil, errors.New("no gitlab token provided") + } + + r, err := http.NewRequest(request.Method, request.URL.String(), request.Body) + if err != nil { + return nil, err + } + + r.Header.Set("Private-Token", token) + return transport.httpTransport.RoundTrip(r) +} + +// NewHTTPClient creates a new HTTP client configured for GitLab API requests +func NewHTTPClient(token string) *http.Client { + return &http.Client{ + Transport: &tokenTransport{ + token: token, + transport: retry.NewTransport(&http.Transport{}), // Use ORAS retry transport for consistent rate limiting and error handling + }, + Timeout: 1 * time.Minute, + } +} + +// tokenTransport automatically adds the Private-Token header to requests +type tokenTransport struct { + token string + transport http.RoundTripper +} + +func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req.Header.Set("Private-Token", t.token) + return t.transport.RoundTrip(req) +} diff --git a/api/http/proxy/factory/gitlab/transport.go b/api/http/proxy/factory/gitlab/transport.go deleted file mode 100644 index 7e1804c45..000000000 --- a/api/http/proxy/factory/gitlab/transport.go +++ /dev/null @@ -1,34 +0,0 @@ -package gitlab - -import ( - "errors" - "net/http" -) - -type Transport struct { - httpTransport *http.Transport -} - -// NewTransport returns a pointer to a new instance of Transport that implements the HTTP Transport -// interface for proxying requests to the Gitlab API. -func NewTransport() *Transport { - return &Transport{ - httpTransport: &http.Transport{}, - } -} - -// RoundTrip is the implementation of the http.RoundTripper interface -func (transport *Transport) RoundTrip(request *http.Request) (*http.Response, error) { - token := request.Header.Get("Private-Token") - if token == "" { - return nil, errors.New("no gitlab token provided") - } - - r, err := http.NewRequest(request.Method, request.URL.String(), request.Body) - if err != nil { - return nil, err - } - - r.Header.Set("Private-Token", token) - return transport.httpTransport.RoundTrip(r) -} diff --git a/api/http/proxy/factory/kubernetes/transport.go b/api/http/proxy/factory/kubernetes/transport.go index 76e9daa68..ddab7a096 100644 --- a/api/http/proxy/factory/kubernetes/transport.go +++ b/api/http/proxy/factory/kubernetes/transport.go @@ -58,6 +58,7 @@ func (transport *baseTransport) proxyKubernetesRequest(request *http.Request) (* switch { case strings.EqualFold(requestPath, "/namespaces/portainer/configmaps/portainer-config") && (request.Method == "PUT" || request.Method == "POST"): + transport.k8sClientFactory.ClearClientCache() defer transport.tokenManager.UpdateUserServiceAccountsForEndpoint(portainer.EndpointID(endpointID)) return transport.executeKubernetesRequest(request) case strings.EqualFold(requestPath, "/namespaces"): diff --git a/api/http/proxy/factory/reverse_proxy.go b/api/http/proxy/factory/reverse_proxy.go index d583d75fe..c40e6c485 100644 --- a/api/http/proxy/factory/reverse_proxy.go +++ b/api/http/proxy/factory/reverse_proxy.go @@ -7,6 +7,21 @@ import ( "strings" ) +// Note that we discard any non-canonical headers by design +var allowedHeaders = map[string]struct{}{ + "Accept": {}, + "Accept-Encoding": {}, + "Accept-Language": {}, + "Cache-Control": {}, + "Content-Length": {}, + "Content-Type": {}, + "Private-Token": {}, + "User-Agent": {}, + "X-Portaineragent-Target": {}, + "X-Portainer-Volumename": {}, + "X-Registry-Auth": {}, +} + // newSingleHostReverseProxyWithHostHeader is based on NewSingleHostReverseProxy // from golang.org/src/net/http/httputil/reverseproxy.go and merely sets the Host // HTTP header, which NewSingleHostReverseProxy deliberately preserves. @@ -15,7 +30,6 @@ func NewSingleHostReverseProxyWithHostHeader(target *url.URL) *httputil.ReverseP } func createDirector(target *url.URL) func(*http.Request) { - sensitiveHeaders := []string{"Cookie", "X-Csrf-Token"} targetQuery := target.RawQuery return func(req *http.Request) { req.URL.Scheme = target.Scheme @@ -32,8 +46,11 @@ func createDirector(target *url.URL) func(*http.Request) { req.Header.Set("User-Agent", "") } - for _, header := range sensitiveHeaders { - delete(req.Header, header) + for k := range req.Header { + if _, ok := allowedHeaders[k]; !ok { + // We use delete here instead of req.Header.Del because we want to delete non canonical headers. + delete(req.Header, k) + } } } } diff --git a/api/http/proxy/factory/reverse_proxy_test.go b/api/http/proxy/factory/reverse_proxy_test.go index 1a3d88ba0..6f23d75ec 100644 --- a/api/http/proxy/factory/reverse_proxy_test.go +++ b/api/http/proxy/factory/reverse_proxy_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" + portainer "github.com/portainer/portainer/api" ) func Test_createDirector(t *testing.T) { @@ -23,12 +24,14 @@ func Test_createDirector(t *testing.T) { "GET", "https://agent-portainer.io/test?c=7", map[string]string{"Accept-Encoding": "gzip", "Accept": "application/json", "User-Agent": "something"}, + true, ), expectedReq: createRequest( t, "GET", "https://portainer.io/api/docker/test?a=5&b=6&c=7", map[string]string{"Accept-Encoding": "gzip", "Accept": "application/json", "User-Agent": "something"}, + true, ), }, { @@ -39,12 +42,14 @@ func Test_createDirector(t *testing.T) { "GET", "https://agent-portainer.io/test?c=7", map[string]string{"Accept-Encoding": "gzip", "Accept": "application/json"}, + true, ), expectedReq: createRequest( t, "GET", "https://portainer.io/api/docker/test?a=5&b=6&c=7", map[string]string{"Accept-Encoding": "gzip", "Accept": "application/json", "User-Agent": ""}, + true, ), }, { @@ -55,18 +60,83 @@ func Test_createDirector(t *testing.T) { "GET", "https://agent-portainer.io/test?c=7", map[string]string{ - "Accept-Encoding": "gzip", - "Accept": "application/json", - "User-Agent": "something", - "Cookie": "junk", - "X-Csrf-Token": "junk", + "Authorization": "secret", + "Proxy-Authorization": "secret", + "Cookie": "secret", + "X-Csrf-Token": "secret", + "X-Api-Key": "secret", + "Accept": "application/json", + "Accept-Encoding": "gzip", + "Accept-Language": "en-GB", + "Cache-Control": "None", + "Content-Length": "100", + "Content-Type": "application/json", + "Private-Token": "test-private-token", + "User-Agent": "test-user-agent", + "X-Portaineragent-Target": "test-agent-1", + "X-Portainer-Volumename": "test-volume-1", + "X-Registry-Auth": "test-registry-auth", }, + true, ), expectedReq: createRequest( t, "GET", "https://portainer.io/api/docker/test?a=5&b=6&c=7", - map[string]string{"Accept-Encoding": "gzip", "Accept": "application/json", "User-Agent": "something"}, + map[string]string{ + "Accept": "application/json", + "Accept-Encoding": "gzip", + "Accept-Language": "en-GB", + "Cache-Control": "None", + "Content-Length": "100", + "Content-Type": "application/json", + "Private-Token": "test-private-token", + "User-Agent": "test-user-agent", + "X-Portaineragent-Target": "test-agent-1", + "X-Portainer-Volumename": "test-volume-1", + "X-Registry-Auth": "test-registry-auth", + }, + true, + ), + }, + { + name: "Non canonical Headers", + target: createURL(t, "https://portainer.io/api/docker?a=5&b=6"), + req: createRequest( + t, + "GET", + "https://agent-portainer.io/test?c=7", + map[string]string{ + "Accept": "application/json", + "Accept-Encoding": "gzip", + "Accept-Language": "en-GB", + "Cache-Control": "None", + "Content-Length": "100", + "Content-Type": "application/json", + "Private-Token": "test-private-token", + "User-Agent": "test-user-agent", + portainer.PortainerAgentTargetHeader: "test-agent-1", + "X-Portainer-VolumeName": "test-volume-1", + "X-Registry-Auth": "test-registry-auth", + }, + false, + ), + expectedReq: createRequest( + t, + "GET", + "https://portainer.io/api/docker/test?a=5&b=6&c=7", + map[string]string{ + "Accept": "application/json", + "Accept-Encoding": "gzip", + "Accept-Language": "en-GB", + "Cache-Control": "None", + "Content-Length": "100", + "Content-Type": "application/json", + "Private-Token": "test-private-token", + "User-Agent": "test-user-agent", + "X-Registry-Auth": "test-registry-auth", + }, + true, ), }, } @@ -92,13 +162,17 @@ func createURL(t *testing.T, urlString string) *url.URL { return parsedURL } -func createRequest(t *testing.T, method, url string, headers map[string]string) *http.Request { +func createRequest(t *testing.T, method, url string, headers map[string]string, canonicalHeaders bool) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { t.Fatalf("Failed to create http request: %s", err) } else { for k, v := range headers { - req.Header.Add(k, v) + if canonicalHeaders { + req.Header.Add(k, v) + } else { + req.Header[k] = []string{v} + } } } diff --git a/api/http/security/bouncer.go b/api/http/security/bouncer.go index eb240692d..fa7360f4c 100644 --- a/api/http/security/bouncer.go +++ b/api/http/security/bouncer.go @@ -35,6 +35,7 @@ type ( JWTAuthLookup(*http.Request) (*portainer.TokenData, error) TrustedEdgeEnvironmentAccess(dataservices.DataStoreTx, *portainer.Endpoint) error RevokeJWT(string) + DisableCSP() } // RequestBouncer represents an entity that manages API request accesses @@ -72,7 +73,7 @@ func NewRequestBouncer(dataStore dataservices.DataStore, jwtService portainer.JW jwtService: jwtService, apiKeyService: apiKeyService, hsts: featureflags.IsEnabled("hsts"), - csp: featureflags.IsEnabled("csp"), + csp: true, } go b.cleanUpExpiredJWT() @@ -80,6 +81,11 @@ func NewRequestBouncer(dataStore dataservices.DataStore, jwtService portainer.JW return b } +// DisableCSP disables Content Security Policy +func (bouncer *RequestBouncer) DisableCSP() { + bouncer.csp = false +} + // PublicAccess defines a security check for public API endpoints. // No authentication is required to access these endpoints. func (bouncer *RequestBouncer) PublicAccess(h http.Handler) http.Handler { @@ -528,7 +534,7 @@ func MWSecureHeaders(next http.Handler, hsts, csp bool) http.Handler { } if csp { - w.Header().Set("Content-Security-Policy", "script-src 'self' cdn.matomo.cloud") + w.Header().Set("Content-Security-Policy", "script-src 'self' cdn.matomo.cloud; frame-ancestors 'none';") } w.Header().Set("X-Content-Type-Options", "nosniff") diff --git a/api/http/security/bouncer_test.go b/api/http/security/bouncer_test.go index 4d84dcfee..3dd42fdc5 100644 --- a/api/http/security/bouncer_test.go +++ b/api/http/security/bouncer_test.go @@ -530,3 +530,34 @@ func TestJWTRevocation(t *testing.T) { require.Equal(t, 1, revokeLen()) } + +func TestCSPHeaderDefault(t *testing.T) { + b := NewRequestBouncer(nil, nil, nil) + + srv := httptest.NewServer( + b.PublicAccess(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})), + ) + defer srv.Close() + + resp, err := http.Get(srv.URL + "/") + require.NoError(t, err) + defer resp.Body.Close() + + require.Contains(t, resp.Header, "Content-Security-Policy") +} + +func TestCSPHeaderDisabled(t *testing.T) { + b := NewRequestBouncer(nil, nil, nil) + b.DisableCSP() + + srv := httptest.NewServer( + b.PublicAccess(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})), + ) + defer srv.Close() + + resp, err := http.Get(srv.URL + "/") + require.NoError(t, err) + defer resp.Body.Close() + + require.NotContains(t, resp.Header, "Content-Security-Policy") +} diff --git a/api/http/server.go b/api/http/server.go index 183a78c04..8f073ce58 100644 --- a/api/http/server.go +++ b/api/http/server.go @@ -77,6 +77,7 @@ type Server struct { AuthorizationService *authorization.Service BindAddress string BindAddressHTTPS string + CSP bool HTTPEnabled bool AssetsPath string Status *portainer.Status @@ -113,6 +114,7 @@ type Server struct { PendingActionsService *pendingactions.PendingActionsService PlatformService platform.Service PullLimitCheckDisabled bool + TrustedOrigins []string } // Start starts the HTTP server @@ -120,13 +122,16 @@ func (server *Server) Start() error { kubernetesTokenCacheManager := server.KubernetesTokenCacheManager requestBouncer := security.NewRequestBouncer(server.DataStore, server.JWTService, server.APIKeyService) + if !server.CSP { + requestBouncer.DisableCSP() + } rateLimiter := security.NewRateLimiter(10, 1*time.Second, 1*time.Hour) offlineGate := offlinegate.NewOfflineGate() passwordStrengthChecker := security.NewPasswordStrengthChecker(server.DataStore.Settings()) - var authHandler = auth.NewHandler(requestBouncer, rateLimiter, passwordStrengthChecker) + var authHandler = auth.NewHandler(requestBouncer, rateLimiter, passwordStrengthChecker, server.KubernetesClientFactory) authHandler.DataStore = server.DataStore authHandler.CryptoService = server.CryptoService authHandler.JWTService = server.JWTService @@ -161,10 +166,7 @@ func (server *Server) Start() error { edgeJobsHandler.FileService = server.FileService edgeJobsHandler.ReverseTunnelService = server.ReverseTunnelService - edgeStackCoordinator := edgestacks.NewEdgeStackStatusUpdateCoordinator(server.DataStore) - go edgeStackCoordinator.Start() - - var edgeStacksHandler = edgestacks.NewHandler(requestBouncer, server.DataStore, server.EdgeStacksService, edgeStackCoordinator) + var edgeStacksHandler = edgestacks.NewHandler(requestBouncer, server.DataStore, server.EdgeStacksService) edgeStacksHandler.FileService = server.FileService edgeStacksHandler.GitService = server.GitService edgeStacksHandler.KubernetesDeployer = server.KubernetesDeployer @@ -202,7 +204,7 @@ func (server *Server) Start() error { var dockerHandler = dockerhandler.NewHandler(requestBouncer, server.AuthorizationService, server.DataStore, server.DockerClientFactory, containerService) - var fileHandler = file.NewHandler(filepath.Join(server.AssetsPath, "public"), adminMonitor.WasInstanceDisabled) + var fileHandler = file.NewHandler(filepath.Join(server.AssetsPath, "public"), server.CSP, adminMonitor.WasInstanceDisabled) var endpointHelmHandler = helm.NewHandler(requestBouncer, server.DataStore, server.JWTService, server.KubernetesDeployer, server.HelmPackageManager, server.KubeClusterAccessService) @@ -339,7 +341,7 @@ func (server *Server) Start() error { handler = middlewares.WithPanicLogger(middlewares.WithSlowRequestsLogger(handler)) - handler, err := csrf.WithProtect(handler) + handler, err := csrf.WithProtect(handler, server.TrustedOrigins) if err != nil { return errors.Wrap(err, "failed to create CSRF middleware") } diff --git a/api/internal/edge/edgestacks/service.go b/api/internal/edge/edgestacks/service.go index 6986a6917..c0ecb5caf 100644 --- a/api/internal/edge/edgestacks/service.go +++ b/api/internal/edge/edgestacks/service.go @@ -49,7 +49,6 @@ func (service *Service) BuildEdgeStack( DeploymentType: deploymentType, CreationDate: time.Now().Unix(), EdgeGroups: edgeGroups, - Status: make(map[portainer.EndpointID]portainer.EdgeStackStatus, 0), Version: 1, UseManifestNamespaces: useManifestNamespaces, }, nil @@ -104,6 +103,14 @@ func (service *Service) PersistEdgeStack( return nil, err } + for _, endpointID := range relatedEndpointIds { + status := &portainer.EdgeStackStatusForEnv{EndpointID: endpointID} + + if err := tx.EdgeStackStatus().Create(stack.ID, endpointID, status); err != nil { + return nil, err + } + } + if err := tx.EndpointRelation().AddEndpointRelationsForEdgeStack(relatedEndpointIds, stack.ID); err != nil { return nil, fmt.Errorf("unable to add endpoint relations: %w", err) } @@ -122,9 +129,6 @@ func (service *Service) updateEndpointRelations(tx dataservices.DataStoreTx, edg for _, endpointID := range relatedEndpointIds { relation, err := endpointRelationService.EndpointRelation(endpointID) if err != nil { - if tx.IsErrObjectNotFound(err) { - continue - } return fmt.Errorf("unable to find endpoint relation in database: %w", err) } @@ -158,5 +162,9 @@ func (service *Service) DeleteEdgeStack(tx dataservices.DataStoreTx, edgeStackID return errors.WithMessage(err, "Unable to remove the edge stack from the database") } + if err := tx.EdgeStackStatus().DeleteAll(edgeStackID); err != nil { + return errors.WithMessage(err, "unable to remove edge stack statuses from the database") + } + return nil } diff --git a/api/internal/edge/edgestacks/status.go b/api/internal/edge/edgestacks/status.go deleted file mode 100644 index 25629d958..000000000 --- a/api/internal/edge/edgestacks/status.go +++ /dev/null @@ -1,26 +0,0 @@ -package edgestacks - -import ( - portainer "github.com/portainer/portainer/api" -) - -// NewStatus returns a new status object for an Edge stack -func NewStatus(oldStatus map[portainer.EndpointID]portainer.EdgeStackStatus, relatedEnvironmentIDs []portainer.EndpointID) map[portainer.EndpointID]portainer.EdgeStackStatus { - status := map[portainer.EndpointID]portainer.EdgeStackStatus{} - - for _, environmentID := range relatedEnvironmentIDs { - newEnvStatus := portainer.EdgeStackStatus{ - Status: []portainer.EdgeStackDeploymentStatus{}, - EndpointID: environmentID, - } - - oldEnvStatus, ok := oldStatus[environmentID] - if ok { - newEnvStatus.DeploymentInfo = oldEnvStatus.DeploymentInfo - } - - status[environmentID] = newEnvStatus - } - - return status -} diff --git a/api/internal/endpointutils/endpointutils.go b/api/internal/endpointutils/endpointutils.go index 6b7eb1c2d..f596ae0d5 100644 --- a/api/internal/endpointutils/endpointutils.go +++ b/api/internal/endpointutils/endpointutils.go @@ -249,3 +249,19 @@ func getEndpointCheckinInterval(endpoint *portainer.Endpoint, settings *portaine return defaultInterval } + +func InitializeEdgeEndpointRelation(endpoint *portainer.Endpoint, tx dataservices.DataStoreTx) error { + if !IsEdgeEndpoint(endpoint) { + return nil + } + + relation := &portainer.EndpointRelation{ + EndpointID: endpoint.ID, + EdgeStacks: make(map[portainer.EdgeStackID]bool), + } + + if err := tx.EndpointRelation().Create(relation); err != nil { + return err + } + return nil +} diff --git a/api/internal/registryutils/access/access.go b/api/internal/registryutils/access/access.go index 0d14cba39..bfa5181c0 100644 --- a/api/internal/registryutils/access/access.go +++ b/api/internal/registryutils/access/access.go @@ -2,40 +2,82 @@ package access import ( "errors" + "fmt" portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/http/security" + "github.com/portainer/portainer/api/internal/endpointutils" + "github.com/portainer/portainer/api/kubernetes" + "github.com/portainer/portainer/api/kubernetes/cli" ) func hasPermission( dataStore dataservices.DataStore, + k8sClientFactory *cli.ClientFactory, userID portainer.UserID, endpointID portainer.EndpointID, registry *portainer.Registry, ) (hasPermission bool, err error) { user, err := dataStore.User().Read(userID) if err != nil { - return + return false, err } if user.Role == portainer.AdministratorRole { - return true, err + return true, nil + } + + endpoint, err := dataStore.Endpoint().Endpoint(endpointID) + if err != nil { + return false, err } teamMemberships, err := dataStore.TeamMembership().TeamMembershipsByUserID(userID) if err != nil { - return + return false, err } + // validate access for kubernetes namespaces (leverage registry.RegistryAccesses[endpointId].Namespaces) + if endpointutils.IsKubernetesEndpoint(endpoint) && k8sClientFactory != nil { + kcl, err := k8sClientFactory.GetPrivilegedKubeClient(endpoint) + if err != nil { + return false, fmt.Errorf("unable to retrieve kubernetes client to validate registry access: %w", err) + } + accessPolicies, err := kcl.GetNamespaceAccessPolicies() + if err != nil { + return false, fmt.Errorf("unable to retrieve environment's namespaces policies to validate registry access: %w", err) + } + + authorizedNamespaces := registry.RegistryAccesses[endpointID].Namespaces + + for _, namespace := range authorizedNamespaces { + // when the default namespace is authorized to use a registry, all users have the ability to use it + // unless the default namespace is restricted: in this case continue to search for other potential accesses authorizations + if namespace == kubernetes.DefaultNamespace && !endpoint.Kubernetes.Configuration.RestrictDefaultNamespace { + return true, nil + } + + namespacePolicy := accessPolicies[namespace] + if security.AuthorizedAccess(user.ID, teamMemberships, namespacePolicy.UserAccessPolicies, namespacePolicy.TeamAccessPolicies) { + return true, nil + } + } + return false, nil + } + + // validate access for docker environments + // leverage registry.RegistryAccesses[endpointId].UserAccessPolicies (direct access) + // and registry.RegistryAccesses[endpointId].TeamAccessPolicies (indirect access via his teams) hasPermission = security.AuthorizedRegistryAccess(registry, user, teamMemberships, endpointID) - return + return hasPermission, nil } // GetAccessibleRegistry get the registry if the user has permission func GetAccessibleRegistry( dataStore dataservices.DataStore, + k8sClientFactory *cli.ClientFactory, userID portainer.UserID, endpointID portainer.EndpointID, registryID portainer.RegistryID, @@ -46,7 +88,7 @@ func GetAccessibleRegistry( return } - hasPermission, err := hasPermission(dataStore, userID, endpointID, registry) + hasPermission, err := hasPermission(dataStore, k8sClientFactory, userID, endpointID, registry) if err != nil { return } diff --git a/api/internal/registryutils/ecr_reg_token.go b/api/internal/registryutils/ecr_reg_token.go index cbcceb982..6e9a754bf 100644 --- a/api/internal/registryutils/ecr_reg_token.go +++ b/api/internal/registryutils/ecr_reg_token.go @@ -62,3 +62,26 @@ func GetRegEffectiveCredential(registry *portainer.Registry) (username, password return } + +// PrepareRegistryCredentials consolidates the common pattern of ensuring valid ECR token +// and setting effective credentials on the registry when authentication is enabled. +// This function modifies the registry in-place by setting Username and Password to the effective values. +func PrepareRegistryCredentials(tx dataservices.DataStoreTx, registry *portainer.Registry) error { + if !registry.Authentication { + return nil + } + + if err := EnsureRegTokenValid(tx, registry); err != nil { + return err + } + + username, password, err := GetRegEffectiveCredential(registry) + if err != nil { + return err + } + + registry.Username = username + registry.Password = password + + return nil +} diff --git a/api/internal/testhelpers/datastore.go b/api/internal/testhelpers/datastore.go index d4a29ae09..19254f540 100644 --- a/api/internal/testhelpers/datastore.go +++ b/api/internal/testhelpers/datastore.go @@ -7,6 +7,7 @@ import ( "github.com/portainer/portainer/api/database" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/dataservices/errors" + "github.com/portainer/portainer/api/slicesx" ) var _ dataservices.DataStore = &testDatastore{} @@ -16,6 +17,7 @@ type testDatastore struct { edgeGroup dataservices.EdgeGroupService edgeJob dataservices.EdgeJobService edgeStack dataservices.EdgeStackService + edgeStackStatus dataservices.EdgeStackStatusService endpoint dataservices.EndpointService endpointGroup dataservices.EndpointGroupService endpointRelation dataservices.EndpointRelationService @@ -53,8 +55,11 @@ func (d *testDatastore) CustomTemplate() dataservices.CustomTemplateService { re func (d *testDatastore) EdgeGroup() dataservices.EdgeGroupService { return d.edgeGroup } func (d *testDatastore) EdgeJob() dataservices.EdgeJobService { return d.edgeJob } func (d *testDatastore) EdgeStack() dataservices.EdgeStackService { return d.edgeStack } -func (d *testDatastore) Endpoint() dataservices.EndpointService { return d.endpoint } -func (d *testDatastore) EndpointGroup() dataservices.EndpointGroupService { return d.endpointGroup } +func (d *testDatastore) EdgeStackStatus() dataservices.EdgeStackStatusService { + return d.edgeStackStatus +} +func (d *testDatastore) Endpoint() dataservices.EndpointService { return d.endpoint } +func (d *testDatastore) EndpointGroup() dataservices.EndpointGroupService { return d.endpointGroup } func (d *testDatastore) EndpointRelation() dataservices.EndpointRelationService { return d.endpointRelation @@ -148,8 +153,17 @@ type stubUserService struct { users []portainer.User } -func (s *stubUserService) BucketName() string { return "users" } -func (s *stubUserService) ReadAll() ([]portainer.User, error) { return s.users, nil } +func (s *stubUserService) BucketName() string { return "users" } +func (s *stubUserService) ReadAll(predicates ...func(portainer.User) bool) ([]portainer.User, error) { + filtered := s.users + + for _, p := range predicates { + filtered = slicesx.Filter(filtered, p) + } + + return filtered, nil +} + func (s *stubUserService) UsersByRole(role portainer.UserRole) ([]portainer.User, error) { return s.users, nil } @@ -167,8 +181,16 @@ type stubEdgeJobService struct { jobs []portainer.EdgeJob } -func (s *stubEdgeJobService) BucketName() string { return "edgejobs" } -func (s *stubEdgeJobService) ReadAll() ([]portainer.EdgeJob, error) { return s.jobs, nil } +func (s *stubEdgeJobService) BucketName() string { return "edgejobs" } +func (s *stubEdgeJobService) ReadAll(predicates ...func(portainer.EdgeJob) bool) ([]portainer.EdgeJob, error) { + filtered := s.jobs + + for _, p := range predicates { + filtered = slicesx.Filter(filtered, p) + } + + return filtered, nil +} // WithEdgeJobs option will instruct testDatastore to return provided jobs func WithEdgeJobs(js []portainer.EdgeJob) datastoreOption { @@ -358,8 +380,14 @@ func (s *stubStacksService) Read(ID portainer.StackID) (*portainer.Stack, error) return nil, errors.ErrObjectNotFound } -func (s *stubStacksService) ReadAll() ([]portainer.Stack, error) { - return s.stacks, nil +func (s *stubStacksService) ReadAll(predicates ...func(portainer.Stack) bool) ([]portainer.Stack, error) { + filtered := s.stacks + + for _, p := range predicates { + filtered = slicesx.Filter(filtered, p) + } + + return filtered, nil } func (s *stubStacksService) StacksByEndpointID(endpointID portainer.EndpointID) ([]portainer.Stack, error) { diff --git a/api/internal/testhelpers/kube_client.go b/api/internal/testhelpers/kube_client.go new file mode 100644 index 000000000..550e7ce92 --- /dev/null +++ b/api/internal/testhelpers/kube_client.go @@ -0,0 +1,19 @@ +package testhelpers + +import ( + portainer "github.com/portainer/portainer/api" + models "github.com/portainer/portainer/api/http/models/kubernetes" +) + +type testKubeClient struct { + portainer.KubeClient +} + +func NewKubernetesClient() portainer.KubeClient { + return &testKubeClient{} +} + +// Event +func (kcl *testKubeClient) GetEvents(namespace string, resourceId string) ([]models.K8sEvent, error) { + return nil, nil +} diff --git a/api/internal/testhelpers/request_bouncer.go b/api/internal/testhelpers/request_bouncer.go index b89154549..0586dffef 100644 --- a/api/internal/testhelpers/request_bouncer.go +++ b/api/internal/testhelpers/request_bouncer.go @@ -60,6 +60,8 @@ func (testRequestBouncer) JWTAuthLookup(r *http.Request) (*portainer.TokenData, func (testRequestBouncer) RevokeJWT(jti string) {} +func (testRequestBouncer) DisableCSP() {} + // AddTestSecurityCookie adds a security cookie to the request func AddTestSecurityCookie(r *http.Request, jwt string) { r.AddCookie(&http.Cookie{ diff --git a/api/kubernetes/cli/access.go b/api/kubernetes/cli/access.go index 73f8d50af..6f254c296 100644 --- a/api/kubernetes/cli/access.go +++ b/api/kubernetes/cli/access.go @@ -143,3 +143,23 @@ func (kcl *KubeClient) GetNonAdminNamespaces(userID int, teamIDs []int, isRestri return nonAdminNamespaces, nil } + +// GetIsKubeAdmin retrieves true if client is admin +func (client *KubeClient) GetIsKubeAdmin() bool { + return client.IsKubeAdmin +} + +// UpdateIsKubeAdmin sets whether the kube client is admin +func (client *KubeClient) SetIsKubeAdmin(isKubeAdmin bool) { + client.IsKubeAdmin = isKubeAdmin +} + +// GetClientNonAdminNamespaces retrieves non-admin namespaces +func (client *KubeClient) GetClientNonAdminNamespaces() []string { + return client.NonAdminNamespaces +} + +// UpdateClientNonAdminNamespaces sets the client non admin namespace list +func (client *KubeClient) SetClientNonAdminNamespaces(nonAdminNamespaces []string) { + client.NonAdminNamespaces = nonAdminNamespaces +} diff --git a/api/kubernetes/cli/client.go b/api/kubernetes/cli/client.go index 6d2cc437c..550ade1d3 100644 --- a/api/kubernetes/cli/client.go +++ b/api/kubernetes/cli/client.go @@ -77,9 +77,30 @@ func (factory *ClientFactory) ClearClientCache() { factory.endpointProxyClients.Flush() } +// ClearClientCache removes all cached kube clients for a userId +func (factory *ClientFactory) ClearUserClientCache(userID string) { + for key := range factory.endpointProxyClients.Items() { + if strings.HasSuffix(key, "."+userID) { + factory.endpointProxyClients.Delete(key) + } + } +} + // Remove the cached kube client so a new one can be created func (factory *ClientFactory) RemoveKubeClient(endpointID portainer.EndpointID) { factory.endpointProxyClients.Delete(strconv.Itoa(int(endpointID))) + + endpointPrefix := strconv.Itoa(int(endpointID)) + "." + + for key := range factory.endpointProxyClients.Items() { + if strings.HasPrefix(key, endpointPrefix) { + factory.endpointProxyClients.Delete(key) + } + } +} + +func (factory *ClientFactory) GetAddrHTTPS() string { + return factory.AddrHTTPS } // GetPrivilegedKubeClient checks if an existing client is already registered for the environment(endpoint) and returns it if one is found. @@ -100,6 +121,24 @@ func (factory *ClientFactory) GetPrivilegedKubeClient(endpoint *portainer.Endpoi return kcl, nil } +// GetPrivilegedUserKubeClient checks if an existing admin client is already registered for the environment(endpoint) and user and returns it if one is found. +// If no client is registered, it will create a new client, register it, and returns it. +func (factory *ClientFactory) GetPrivilegedUserKubeClient(endpoint *portainer.Endpoint, userID string) (*KubeClient, error) { + key := strconv.Itoa(int(endpoint.ID)) + ".admin." + userID + pcl, ok := factory.endpointProxyClients.Get(key) + if ok { + return pcl.(*KubeClient), nil + } + + kcl, err := factory.createCachedPrivilegedKubeClient(endpoint) + if err != nil { + return nil, err + } + + factory.endpointProxyClients.Set(key, kcl, cache.DefaultExpiration) + return kcl, nil +} + // GetProxyKubeClient retrieves a KubeClient from the cache. You should be // calling SetProxyKubeClient before first. It is normally, called the // kubernetes middleware. @@ -152,8 +191,9 @@ func (factory *ClientFactory) createCachedPrivilegedKubeClient(endpoint *portain } return &KubeClient{ - cli: cli, - instanceID: factory.instanceID, + cli: cli, + instanceID: factory.instanceID, + IsKubeAdmin: true, }, nil } diff --git a/api/kubernetes/cli/client_test.go b/api/kubernetes/cli/client_test.go new file mode 100644 index 000000000..993a966e3 --- /dev/null +++ b/api/kubernetes/cli/client_test.go @@ -0,0 +1,22 @@ +package cli + +import ( + "testing" +) + +func TestClearUserClientCache(t *testing.T) { + factory, _ := NewClientFactory(nil, nil, nil, "", "", "") + kcl := &KubeClient{} + factory.endpointProxyClients.Set("12.1", kcl, 0) + factory.endpointProxyClients.Set("12.12", kcl, 0) + factory.endpointProxyClients.Set("12", kcl, 0) + + factory.ClearUserClientCache("12") + + if len(factory.endpointProxyClients.Items()) != 2 { + t.Errorf("Incorrect clients cached after clearUserClientCache;\ngot=\n%d\nwant=\n%d", len(factory.endpointProxyClients.Items()), 2) + } + if _, ok := factory.GetProxyKubeClient("12", "12"); ok { + t.Errorf("Expected not to find client cache for user after clear") + } +} diff --git a/api/kubernetes/cli/event.go b/api/kubernetes/cli/event.go new file mode 100644 index 000000000..03472fca6 --- /dev/null +++ b/api/kubernetes/cli/event.go @@ -0,0 +1,93 @@ +package cli + +import ( + "context" + + models "github.com/portainer/portainer/api/http/models/kubernetes" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// GetEvents gets all the Events for a given namespace and resource +// If the user is a kube admin, it returns all events in the namespace +// Otherwise, it returns only the events in the non-admin namespaces +func (kcl *KubeClient) GetEvents(namespace string, resourceId string) ([]models.K8sEvent, error) { + if kcl.IsKubeAdmin { + return kcl.fetchAllEvents(namespace, resourceId) + } + + return kcl.fetchEventsForNonAdmin(namespace, resourceId) +} + +// fetchEventsForNonAdmin returns all events in the given namespace and resource +// It returns only the events in the non-admin namespaces +func (kcl *KubeClient) fetchEventsForNonAdmin(namespace string, resourceId string) ([]models.K8sEvent, error) { + if len(kcl.NonAdminNamespaces) == 0 { + return nil, nil + } + + events, err := kcl.fetchAllEvents(namespace, resourceId) + if err != nil { + return nil, err + } + + nonAdminNamespaceSet := kcl.buildNonAdminNamespacesMap() + results := make([]models.K8sEvent, 0) + for _, event := range events { + if _, ok := nonAdminNamespaceSet[event.Namespace]; ok { + results = append(results, event) + } + } + + return results, nil +} + +// fetchEventsForNonAdmin returns all events in the given namespace and resource +// It returns all events in the namespace and resource +func (kcl *KubeClient) fetchAllEvents(namespace string, resourceId string) ([]models.K8sEvent, error) { + options := metav1.ListOptions{} + if resourceId != "" { + options.FieldSelector = "involvedObject.uid=" + resourceId + } + + list, err := kcl.cli.CoreV1().Events(namespace).List(context.TODO(), options) + if err != nil { + return nil, err + } + + results := make([]models.K8sEvent, 0) + for _, event := range list.Items { + results = append(results, parseEvent(&event)) + } + + return results, nil +} + +func parseEvent(event *corev1.Event) models.K8sEvent { + result := models.K8sEvent{ + Type: event.Type, + Name: event.Name, + Message: event.Message, + Reason: event.Reason, + Namespace: event.Namespace, + EventTime: event.EventTime.UTC(), + Kind: event.Kind, + Count: event.Count, + UID: string(event.ObjectMeta.GetUID()), + InvolvedObjectKind: models.K8sEventInvolvedObject{ + Kind: event.InvolvedObject.Kind, + UID: string(event.InvolvedObject.UID), + Name: event.InvolvedObject.Name, + Namespace: event.InvolvedObject.Namespace, + }, + } + + if !event.LastTimestamp.Time.IsZero() { + result.LastTimestamp = &event.LastTimestamp.Time + } + if !event.FirstTimestamp.Time.IsZero() { + result.FirstTimestamp = &event.FirstTimestamp.Time + } + + return result +} diff --git a/api/kubernetes/cli/event_test.go b/api/kubernetes/cli/event_test.go new file mode 100644 index 000000000..926928317 --- /dev/null +++ b/api/kubernetes/cli/event_test.go @@ -0,0 +1,108 @@ +package cli + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kfake "k8s.io/client-go/kubernetes/fake" +) + +// TestGetEvents tests the GetEvents method +// It creates a fake Kubernetes client and passes it to the GetEvents method +// It then logs the fetched events and validated the data returned +func TestGetEvents(t *testing.T) { + t.Run("can get events for resource id when admin", func(t *testing.T) { + kcl := &KubeClient{ + cli: kfake.NewSimpleClientset(), + instanceID: "instance", + IsKubeAdmin: true, + } + event := corev1.Event{ + InvolvedObject: corev1.ObjectReference{UID: "resourceId"}, + Action: "something", + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "myEvent"}, + EventTime: metav1.NowMicro(), + Type: "warning", + Message: "This event has a very serious warning", + } + _, err := kcl.cli.CoreV1().Events("default").Create(context.TODO(), &event, metav1.CreateOptions{}) + if err != nil { + t.Fatalf("Failed to create Event: %v", err) + } + + events, err := kcl.GetEvents("default", "resourceId") + + if err != nil { + t.Fatalf("Failed to fetch Cron Jobs: %v", err) + } + t.Logf("Fetched Events: %v", events) + require.Equal(t, 1, len(events), "Expected to return 1 event") + assert.Equal(t, event.Message, events[0].Message, "Expected Message to be equal to event message created") + assert.Equal(t, event.Type, events[0].Type, "Expected Type to be equal to event type created") + assert.Equal(t, event.EventTime.UTC(), events[0].EventTime, "Expected EventTime to be saved as a string from event time created") + }) + t.Run("can get kubernetes events for non admin namespace when non admin", func(t *testing.T) { + kcl := &KubeClient{ + cli: kfake.NewSimpleClientset(), + instanceID: "instance", + IsKubeAdmin: false, + NonAdminNamespaces: []string{"nonAdmin"}, + } + event := corev1.Event{ + InvolvedObject: corev1.ObjectReference{UID: "resourceId"}, + Action: "something", + ObjectMeta: metav1.ObjectMeta{Namespace: "nonAdmin", Name: "myEvent"}, + EventTime: metav1.NowMicro(), + Type: "warning", + Message: "This event has a very serious warning", + } + _, err := kcl.cli.CoreV1().Events("nonAdmin").Create(context.TODO(), &event, metav1.CreateOptions{}) + if err != nil { + t.Fatalf("Failed to create Event: %v", err) + } + + events, err := kcl.GetEvents("nonAdmin", "resourceId") + + if err != nil { + t.Fatalf("Failed to fetch Cron Jobs: %v", err) + } + t.Logf("Fetched Events: %v", events) + require.Equal(t, 1, len(events), "Expected to return 1 event") + assert.Equal(t, event.Message, events[0].Message, "Expected Message to be equal to event message created") + assert.Equal(t, event.Type, events[0].Type, "Expected Type to be equal to event type created") + assert.Equal(t, event.EventTime.UTC(), events[0].EventTime, "Expected EventTime to be saved as a string from event time created") + }) + + t.Run("cannot get kubernetes events for admin namespace when non admin", func(t *testing.T) { + kcl := &KubeClient{ + cli: kfake.NewSimpleClientset(), + instanceID: "instance", + IsKubeAdmin: false, + NonAdminNamespaces: []string{"nonAdmin"}, + } + event := corev1.Event{ + InvolvedObject: corev1.ObjectReference{UID: "resourceId"}, + Action: "something", + ObjectMeta: metav1.ObjectMeta{Namespace: "admin", Name: "myEvent"}, + EventTime: metav1.NowMicro(), + Type: "warning", + Message: "This event has a very serious warning", + } + _, err := kcl.cli.CoreV1().Events("admin").Create(context.TODO(), &event, metav1.CreateOptions{}) + if err != nil { + t.Fatalf("Failed to create Event: %v", err) + } + + events, err := kcl.GetEvents("admin", "resourceId") + + if err != nil { + t.Fatalf("Failed to fetch Cron Jobs: %v", err) + } + t.Logf("Fetched Events: %v", events) + assert.Equal(t, 0, len(events), "Expected to return 0 events") + }) +} diff --git a/api/kubernetes/cli/namespace.go b/api/kubernetes/cli/namespace.go index 11307d651..560b91e75 100644 --- a/api/kubernetes/cli/namespace.go +++ b/api/kubernetes/cli/namespace.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net/http" + "sort" "strconv" "time" @@ -351,6 +352,34 @@ func (kcl *KubeClient) DeleteNamespace(namespaceName string) (*corev1.Namespace, return namespace, nil } +// CombineNamespacesWithUnhealthyEvents combines namespaces with unhealthy events across all namespaces +func (kcl *KubeClient) CombineNamespacesWithUnhealthyEvents(namespaces map[string]portainer.K8sNamespaceInfo) (map[string]portainer.K8sNamespaceInfo, error) { + allEvents, err := kcl.GetEvents("", "") + if err != nil && !k8serrors.IsNotFound(err) { + log.Error(). + Str("context", "CombineNamespacesWithUnhealthyEvents"). + Err(err). + Msg("unable to retrieve unhealthy events from the Kubernetes for an admin user") + return nil, err + } + + unhealthyEventCounts := make(map[string]int) + for _, event := range allEvents { + if event.Type == "Warning" { + unhealthyEventCounts[event.Namespace]++ + } + } + + for namespaceName, namespace := range namespaces { + if count, exists := unhealthyEventCounts[namespaceName]; exists { + namespace.UnhealthyEventCount = count + namespaces[namespaceName] = namespace + } + } + + return namespaces, nil +} + // CombineNamespacesWithResourceQuotas combines namespaces with resource quotas where matching is based on "portainer-rq-"+namespace.Name func (kcl *KubeClient) CombineNamespacesWithResourceQuotas(namespaces map[string]portainer.K8sNamespaceInfo, w http.ResponseWriter) *httperror.HandlerError { resourceQuotas, err := kcl.GetResourceQuotas("") @@ -409,5 +438,10 @@ func (kcl *KubeClient) ConvertNamespaceMapToSlice(namespaces map[string]portaine namespaceSlice = append(namespaceSlice, namespace) } + // Sort namespaces by name + sort.Slice(namespaceSlice, func(i, j int) bool { + return namespaceSlice[i].Name < namespaceSlice[j].Name + }) + return namespaceSlice } diff --git a/api/portainer.go b/api/portainer.go index 935def1f1..8172f08fa 100644 --- a/api/portainer.go +++ b/api/portainer.go @@ -4,15 +4,19 @@ import ( "context" "fmt" "io" + "net/http" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/image" + "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/system" "github.com/docker/docker/api/types/volume" gittypes "github.com/portainer/portainer/api/git/types" models "github.com/portainer/portainer/api/http/models/kubernetes" "github.com/portainer/portainer/pkg/featureflags" + httperror "github.com/portainer/portainer/pkg/libhttp/error" + "github.com/segmentio/encoding/json" "golang.org/x/oauth2" corev1 "k8s.io/api/core/v1" @@ -106,6 +110,7 @@ type ( AdminPassword *string AdminPasswordFile *string Assets *string + CSP *bool Data *string FeatureFlags *[]string EnableEdgeComputeFeatures *bool @@ -135,6 +140,7 @@ type ( LogMode *string KubectlShellImage *string PullLimitCheckDisabled *bool + TrustedOrigins *string } // CustomTemplateVariableDefinition @@ -209,26 +215,34 @@ type ( // DockerSnapshot represents a snapshot of a specific Docker environment(endpoint) at a specific time DockerSnapshot struct { - Time int64 `json:"Time"` - DockerVersion string `json:"DockerVersion"` - Swarm bool `json:"Swarm"` - TotalCPU int `json:"TotalCPU"` - TotalMemory int64 `json:"TotalMemory"` - ContainerCount int `json:"ContainerCount"` - RunningContainerCount int `json:"RunningContainerCount"` - StoppedContainerCount int `json:"StoppedContainerCount"` - HealthyContainerCount int `json:"HealthyContainerCount"` - UnhealthyContainerCount int `json:"UnhealthyContainerCount"` - VolumeCount int `json:"VolumeCount"` - ImageCount int `json:"ImageCount"` - ServiceCount int `json:"ServiceCount"` - StackCount int `json:"StackCount"` - SnapshotRaw DockerSnapshotRaw `json:"DockerSnapshotRaw"` - NodeCount int `json:"NodeCount"` - GpuUseAll bool `json:"GpuUseAll"` - GpuUseList []string `json:"GpuUseList"` - IsPodman bool `json:"IsPodman"` - DiagnosticsData *DiagnosticsData `json:"DiagnosticsData"` + Time int64 `json:"Time"` + DockerVersion string `json:"DockerVersion"` + Swarm bool `json:"Swarm"` + TotalCPU int `json:"TotalCPU"` + TotalMemory int64 `json:"TotalMemory"` + ContainerCount int `json:"ContainerCount"` + RunningContainerCount int `json:"RunningContainerCount"` + StoppedContainerCount int `json:"StoppedContainerCount"` + HealthyContainerCount int `json:"HealthyContainerCount"` + UnhealthyContainerCount int `json:"UnhealthyContainerCount"` + VolumeCount int `json:"VolumeCount"` + ImageCount int `json:"ImageCount"` + ServiceCount int `json:"ServiceCount"` + StackCount int `json:"StackCount"` + SnapshotRaw DockerSnapshotRaw `json:"DockerSnapshotRaw"` + NodeCount int `json:"NodeCount"` + GpuUseAll bool `json:"GpuUseAll"` + GpuUseList []string `json:"GpuUseList"` + IsPodman bool `json:"IsPodman"` + DiagnosticsData *DiagnosticsData `json:"DiagnosticsData"` + PerformanceMetrics *PerformanceMetrics `json:"PerformanceMetrics"` + } + + // PerformanceMetrics represents the performance metrics of a Docker, Swarm, Podman, and Kubernetes environments + PerformanceMetrics struct { + CPUUsage float64 `json:"CPUUsage,omitempty"` + MemoryUsage float64 `json:"MemoryUsage,omitempty"` + NetworkUsage float64 `json:"NetworkUsage,omitempty"` } // DockerContainerSnapshot is an extent of Docker's Container struct @@ -242,7 +256,7 @@ type ( DockerSnapshotRaw struct { Containers []DockerContainerSnapshot `json:"Containers" swaggerignore:"true"` Volumes volume.ListResponse `json:"Volumes" swaggerignore:"true"` - Networks []types.NetworkResource `json:"Networks" swaggerignore:"true"` + Networks []network.Summary `json:"Networks" swaggerignore:"true"` Images []image.Summary `json:"Images" swaggerignore:"true"` Info system.Info `json:"Info" swaggerignore:"true"` Version types.Version `json:"Version" swaggerignore:"true"` @@ -332,6 +346,15 @@ type ( UseManifestNamespaces bool } + EdgeStackStatusForEnv struct { + EndpointID EndpointID + Status []EdgeStackDeploymentStatus + // EE only feature + DeploymentInfo StackDeploymentInfo + // ReadyRePullImage is a flag to indicate whether the auto update is trigger to re-pull image + ReadyRePullImage bool `json:"ReadyRePullImage,omitempty"` + } + EdgeStackDeploymentType int // EdgeStackID represents an edge stack id @@ -580,6 +603,12 @@ type ( ProjectPath string `json:"ProjectPath"` } + // GithubRegistryData represents data required for Github registry to work + GithubRegistryData struct { + UseOrganisation bool `json:"UseOrganisation"` + OrganisationName string `json:"OrganisationName"` + } + HelmUserRepositoryID int // HelmUserRepositories stores a Helm repository URL for the given user @@ -607,15 +636,16 @@ type ( JobType int K8sNamespaceInfo struct { - Id string `json:"Id"` - Name string `json:"Name"` - Status corev1.NamespaceStatus `json:"Status"` - Annotations map[string]string `json:"Annotations"` - CreationDate string `json:"CreationDate"` - NamespaceOwner string `json:"NamespaceOwner"` - IsSystem bool `json:"IsSystem"` - IsDefault bool `json:"IsDefault"` - ResourceQuota *corev1.ResourceQuota `json:"ResourceQuota"` + Id string `json:"Id"` + Name string `json:"Name"` + Status corev1.NamespaceStatus `json:"Status"` + Annotations map[string]string `json:"Annotations"` + CreationDate string `json:"CreationDate"` + UnhealthyEventCount int `json:"UnhealthyEventCount"` + NamespaceOwner string `json:"NamespaceOwner"` + IsSystem bool `json:"IsSystem"` + IsDefault bool `json:"IsDefault"` + ResourceQuota *corev1.ResourceQuota `json:"ResourceQuota"` } K8sNodeLimits struct { @@ -647,12 +677,13 @@ type ( // KubernetesSnapshot represents a snapshot of a specific Kubernetes environment(endpoint) at a specific time KubernetesSnapshot struct { - Time int64 `json:"Time"` - KubernetesVersion string `json:"KubernetesVersion"` - NodeCount int `json:"NodeCount"` - TotalCPU int64 `json:"TotalCPU"` - TotalMemory int64 `json:"TotalMemory"` - DiagnosticsData *DiagnosticsData `json:"DiagnosticsData"` + Time int64 `json:"Time"` + KubernetesVersion string `json:"KubernetesVersion"` + NodeCount int `json:"NodeCount"` + TotalCPU int64 `json:"TotalCPU"` + TotalMemory int64 `json:"TotalMemory"` + DiagnosticsData *DiagnosticsData `json:"DiagnosticsData"` + PerformanceMetrics *PerformanceMetrics `json:"PerformanceMetrics"` } // KubernetesConfiguration represents the configuration of a Kubernetes environment(endpoint) @@ -798,6 +829,7 @@ type ( Password string `json:"Password,omitempty" example:"registry_password"` ManagementConfiguration *RegistryManagementConfiguration `json:"ManagementConfiguration"` Gitlab GitlabRegistryData `json:"Gitlab"` + Github GithubRegistryData `json:"Github"` Quay QuayRegistryData `json:"Quay"` Ecr EcrData `json:"Ecr"` RegistryAccesses RegistryAccesses `json:"RegistryAccesses"` @@ -1374,6 +1406,12 @@ type ( Kubernetes *KubernetesSnapshot `json:"Kubernetes"` } + SnapshotRawMessage struct { + EndpointID EndpointID `json:"EndpointId"` + Docker json.RawMessage `json:"Docker"` + Kubernetes json.RawMessage `json:"Kubernetes"` + } + // CLIService represents a service for managing CLI CLIService interface { ParseFlags(version string) (*CLIFlags, error) @@ -1524,56 +1562,127 @@ type ( // KubeClient represents a service used to query a Kubernetes environment(endpoint) KubeClient interface { - ServerVersion() (*version.Info, error) + // Access + GetIsKubeAdmin() bool + SetIsKubeAdmin(isKubeAdmin bool) + GetClientNonAdminNamespaces() []string + SetClientNonAdminNamespaces([]string) + NamespaceAccessPoliciesDeleteNamespace(ns string) error + UpdateNamespaceAccessPolicies(accessPolicies map[string]K8sNamespaceAccessPolicy) error + GetNamespaceAccessPolicies() (map[string]K8sNamespaceAccessPolicy, error) + GetNonAdminNamespaces(userID int, teamIDs []int, isRestrictDefaultNamespace bool) ([]string, error) - SetupUserServiceAccount(userID int, teamIDs []int, restrictDefaultNamespace bool) error - IsRBACEnabled() (bool, error) - GetPortainerUserServiceAccount(tokendata *TokenData) (*corev1.ServiceAccount, error) - GetServiceAccounts(namespace string) ([]models.K8sServiceAccount, error) - DeleteServiceAccounts(reqs models.K8sServiceAccountDeleteRequests) error - GetServiceAccountBearerToken(userID int) (string, error) - CreateUserShellPod(ctx context.Context, serviceAccountName, shellPodImage string) (*KubernetesShellPod, error) + // Applications + GetApplications(namespace, nodeName string) ([]models.K8sApplication, error) + GetApplicationsResource(namespace, node string) (models.K8sApplicationResource, error) + + // ClusterRole + GetClusterRoles() ([]models.K8sClusterRole, error) + DeleteClusterRoles(req models.K8sClusterRoleDeleteRequests) error + + // ConfigMap + GetConfigMap(namespace, configMapName string) (models.K8sConfigMap, error) + CombineConfigMapWithApplications(configMap models.K8sConfigMap) (models.K8sConfigMap, error) + + // CronJob + GetCronJobs(namespace string) ([]models.K8sCronJob, error) + DeleteCronJobs(payload models.K8sCronJobDeleteRequests) error + + // Event + GetEvents(namespace string, resourceId string) ([]models.K8sEvent, error) + + // Exec StartExecProcess(token string, useAdminToken bool, namespace, podName, containerName string, command []string, stdin io.Reader, stdout io.Writer, errChan chan error) + // ClusterRoleBinding + GetClusterRoleBindings() ([]models.K8sClusterRoleBinding, error) + DeleteClusterRoleBindings(reqs models.K8sClusterRoleBindingDeleteRequests) error + + // Dashboard + GetDashboard() (models.K8sDashboard, error) + + // Deployment HasStackName(namespace string, stackName string) (bool, error) - NamespaceAccessPoliciesDeleteNamespace(namespace string) error - CreateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) - UpdateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) - GetNamespaces() (map[string]K8sNamespaceInfo, error) - GetNamespace(string) (K8sNamespaceInfo, error) - DeleteNamespace(namespace string) (*corev1.Namespace, error) - GetConfigMaps(namespace string) ([]models.K8sConfigMap, error) - GetSecrets(namespace string) ([]models.K8sSecret, error) + + // Ingress GetIngressControllers() (models.K8sIngressControllers, error) - GetApplications(namespace, nodename string) ([]models.K8sApplication, error) - GetMetrics() (models.K8sMetrics, error) - GetStorage() ([]KubernetesStorageClassConfig, error) - CreateIngress(namespace string, info models.K8sIngressInfo, owner string) error - UpdateIngress(namespace string, info models.K8sIngressInfo) error + GetIngress(namespace, ingressName string) (models.K8sIngressInfo, error) GetIngresses(namespace string) ([]models.K8sIngressInfo, error) + CreateIngress(namespace string, info models.K8sIngressInfo, owner string) error DeleteIngresses(reqs models.K8sIngressDeleteRequests) error - CreateService(namespace string, service models.K8sServiceInfo) error - UpdateService(namespace string, service models.K8sServiceInfo) error - GetServices(namespace string) ([]models.K8sServiceInfo, error) - DeleteServices(reqs models.K8sServiceDeleteRequests) error + UpdateIngress(namespace string, info models.K8sIngressInfo) error + CombineIngressWithService(ingress models.K8sIngressInfo) (models.K8sIngressInfo, error) + CombineIngressesWithServices(ingresses []models.K8sIngressInfo) ([]models.K8sIngressInfo, error) + + // Job + GetJobs(namespace string, includeCronJobChildren bool) ([]models.K8sJob, error) + DeleteJobs(payload models.K8sJobDeleteRequests) error + + // Metrics + GetMetrics() (models.K8sMetrics, error) + + // Namespace + ToggleSystemState(namespaceName string, isSystem bool) error + UpdateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) + GetNamespace(name string) (K8sNamespaceInfo, error) + CreateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) + GetNamespaces() (map[string]K8sNamespaceInfo, error) + CombineNamespaceWithResourceQuota(namespace K8sNamespaceInfo, w http.ResponseWriter) *httperror.HandlerError + DeleteNamespace(namespaceName string) (*corev1.Namespace, error) + CombineNamespacesWithResourceQuotas(namespaces map[string]K8sNamespaceInfo, w http.ResponseWriter) *httperror.HandlerError + ConvertNamespaceMapToSlice(namespaces map[string]K8sNamespaceInfo) []K8sNamespaceInfo + + // NodeLimits GetNodesLimits() (K8sNodesLimits, error) - GetMaxResourceLimits(name string, overCommitEnabled bool, resourceOverCommitPercent int) (K8sNodeLimits, error) - GetNamespaceAccessPolicies() (map[string]K8sNamespaceAccessPolicy, error) - UpdateNamespaceAccessPolicies(accessPolicies map[string]K8sNamespaceAccessPolicy) error + GetMaxResourceLimits(skipNamespace string, overCommitEnabled bool, resourceOverCommitPercent int) (K8sNodeLimits, error) + + // Pod + CreateUserShellPod(ctx context.Context, serviceAccountName, shellPodImage string) (*KubernetesShellPod, error) + + // RBAC + IsRBACEnabled() (bool, error) + + // Registries DeleteRegistrySecret(registry RegistryID, namespace string) error CreateRegistrySecret(registry *Registry, namespace string) error IsRegistrySecret(namespace, secretName string) (bool, error) - ToggleSystemState(namespace string, isSystem bool) error - GetClusterRoles() ([]models.K8sClusterRole, error) - DeleteClusterRoles(models.K8sClusterRoleDeleteRequests) error - GetClusterRoleBindings() ([]models.K8sClusterRoleBinding, error) - DeleteClusterRoleBindings(models.K8sClusterRoleBindingDeleteRequests) error - - GetRoles(namespace string) ([]models.K8sRole, error) - DeleteRoles(models.K8sRoleDeleteRequests) error + // RoleBinding GetRoleBindings(namespace string) ([]models.K8sRoleBinding, error) - DeleteRoleBindings(models.K8sRoleBindingDeleteRequests) error + DeleteRoleBindings(reqs models.K8sRoleBindingDeleteRequests) error + + // Role + DeleteRoles(reqs models.K8sRoleDeleteRequests) error + + // Secret + GetSecrets(namespace string) ([]models.K8sSecret, error) + GetSecret(namespace string, secretName string) (models.K8sSecret, error) + CombineSecretWithApplications(secret models.K8sSecret) (models.K8sSecret, error) + + // ServiceAccount + GetServiceAccounts(namespace string) ([]models.K8sServiceAccount, error) + DeleteServiceAccounts(reqs models.K8sServiceAccountDeleteRequests) error + SetupUserServiceAccount(int, []int, bool) error + GetPortainerUserServiceAccount(tokendata *TokenData) (*corev1.ServiceAccount, error) + GetServiceAccountBearerToken(userID int) (string, error) + + // Service + GetServices(namespace string) ([]models.K8sServiceInfo, error) + CombineServicesWithApplications(services []models.K8sServiceInfo) ([]models.K8sServiceInfo, error) + CreateService(namespace string, info models.K8sServiceInfo) error + DeleteServices(reqs models.K8sServiceDeleteRequests) error + UpdateService(namespace string, info models.K8sServiceInfo) error + + // ServerVersion + ServerVersion() (*version.Info, error) + + // Storage + GetStorage() ([]KubernetesStorageClassConfig, error) + + // Volumes + GetVolumes(namespace string) ([]models.K8sVolumeInfo, error) + GetVolume(namespace, volumeName string) (*models.K8sVolumeInfo, error) + CombineVolumesWithApplications(volumes *[]models.K8sVolumeInfo) (*[]models.K8sVolumeInfo, error) } // KubernetesDeployer represents a service to deploy a manifest inside a Kubernetes environment(endpoint) @@ -1638,7 +1747,7 @@ type ( const ( // APIVersion is the version number of the Portainer API - APIVersion = "2.30.0" + APIVersion = "2.32.0" // Support annotation for the API version ("STS" for Short-Term Support or "LTS" for Long-Term Support) APIVersionSupport = "STS" // Edition is what this edition of Portainer is called @@ -1692,6 +1801,15 @@ const ( KubectlShellImageEnvVar = "KUBECTL_SHELL_IMAGE" // PullLimitCheckDisabledEnvVar is the environment variable used to disable the pull limit check PullLimitCheckDisabledEnvVar = "PULL_LIMIT_CHECK_DISABLED" + // LicenseServerBaseURL represents the base URL of the API used to validate + // an extension license. + LicenseServerBaseURL = "https://api.portainer.io" + // URL to validate licenses along with system metadata. + LicenseCheckInURL = LicenseServerBaseURL + "/licenses/checkin" + // TrustedOriginsEnvVar is the environment variable used to set the trusted origins for CSRF protection + TrustedOriginsEnvVar = "TRUSTED_ORIGINS" + // CSPEnvVar is the environment variable used to enable/disable the Content Security Policy + CSPEnvVar = "CSP" ) // List of supported features @@ -1861,6 +1979,8 @@ const ( DockerHubRegistry // EcrRegistry represents an ECR registry EcrRegistry + // Github container registry + GithubRegistry ) const ( diff --git a/api/slicesx/filter.go b/api/slicesx/filter.go new file mode 100644 index 000000000..13dc12105 --- /dev/null +++ b/api/slicesx/filter.go @@ -0,0 +1,28 @@ +package slicesx + +// Iterates over elements of collection, returning an array of all elements predicate returns truthy for. +// +// Note: Unlike `FilterInPlace`, this method returns a new array. +func Filter[T any](input []T, predicate func(T) bool) []T { + result := make([]T, 0) + for i := range input { + if predicate(input[i]) { + result = append(result, input[i]) + } + } + return result +} + +// Filter in place all elements from input that predicate returns truthy for and returns an array of the removed elements. +// +// Note: Unlike `Filter`, this method mutates input. +func FilterInPlace[T any](input []T, predicate func(T) bool) []T { + n := 0 + for _, v := range input { + if predicate(v) { + input[n] = v + n++ + } + } + return input[:n] +} diff --git a/api/slicesx/filter_test.go b/api/slicesx/filter_test.go new file mode 100644 index 000000000..36f97fa10 --- /dev/null +++ b/api/slicesx/filter_test.go @@ -0,0 +1,96 @@ +package slicesx_test + +import ( + "testing" + + "github.com/portainer/portainer/api/slicesx" +) + +func Test_Filter(t *testing.T) { + test(t, slicesx.Filter, "Filter even numbers", + []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + []int{2, 4, 6, 8}, + func(x int) bool { return x%2 == 0 }, + ) + test(t, slicesx.Filter, "Filter odd numbers", + []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + []int{1, 3, 5, 7, 9}, + func(x int) bool { return x%2 == 1 }, + ) + test(t, slicesx.Filter, "Filter strings starting with 'A'", + []string{"Apple", "Banana", "Avocado", "Grapes", "Apricot"}, + []string{"Apple", "Avocado", "Apricot"}, + func(s string) bool { return s[0] == 'A' }, + ) + test(t, slicesx.Filter, "Filter strings longer than 5 chars", + []string{"Apple", "Banana", "Avocado", "Grapes", "Apricot"}, + []string{"Banana", "Avocado", "Grapes", "Apricot"}, + func(s string) bool { return len(s) > 5 }, + ) +} + +func Test_Retain(t *testing.T) { + test(t, slicesx.FilterInPlace, "Filter even numbers", + []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + []int{2, 4, 6, 8}, + func(x int) bool { return x%2 == 0 }, + ) + test(t, slicesx.FilterInPlace, "Filter odd numbers", + []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + []int{1, 3, 5, 7, 9}, + func(x int) bool { return x%2 == 1 }, + ) + test(t, slicesx.FilterInPlace, "Filter strings starting with 'A'", + []string{"Apple", "Banana", "Avocado", "Grapes", "Apricot"}, + []string{"Apple", "Avocado", "Apricot"}, + func(s string) bool { return s[0] == 'A' }, + ) + test(t, slicesx.FilterInPlace, "Filter strings longer than 5 chars", + []string{"Apple", "Banana", "Avocado", "Grapes", "Apricot"}, + []string{"Banana", "Avocado", "Grapes", "Apricot"}, + func(s string) bool { return len(s) > 5 }, + ) +} + +func Benchmark_Filter(b *testing.B) { + n := 100000 + + source := make([]int, n) + for i := range source { + source[i] = i + } + + b.ResetTimer() + for range b.N { + e := slicesx.Filter(source, func(x int) bool { return x%2 == 0 }) + if len(e) != n/2 { + b.FailNow() + } + } +} + +func Benchmark_FilterInPlace(b *testing.B) { + n := 100000 + + source := make([]int, n) + for i := range source { + source[i] = i + } + + // Preallocate all copies before timing + // because FilterInPlace mutates the original slice + copies := make([][]int, b.N) + for i := range b.N { + buf := make([]int, len(source)) + copy(buf, source) + copies[i] = buf + } + + b.ResetTimer() + for i := range b.N { + e := slicesx.FilterInPlace(copies[i], func(x int) bool { return x%2 == 0 }) + if len(e) != n/2 { + b.FailNow() + } + } +} diff --git a/api/slicesx/flatten.go b/api/slicesx/flatten.go new file mode 100644 index 000000000..56a77f3e9 --- /dev/null +++ b/api/slicesx/flatten.go @@ -0,0 +1,7 @@ +package slicesx + +import "slices" + +func Flatten[T any](input [][]T) []T { + return slices.Concat(input...) +} diff --git a/api/slicesx/flatten_test.go b/api/slicesx/flatten_test.go new file mode 100644 index 000000000..6875c4e6b --- /dev/null +++ b/api/slicesx/flatten_test.go @@ -0,0 +1,19 @@ +package slicesx_test + +import ( + "testing" + + "github.com/portainer/portainer/api/slicesx" + "github.com/stretchr/testify/assert" +) + +func Test_Flatten(t *testing.T) { + t.Run("Flatten an array of arrays", func(t *testing.T) { + is := assert.New(t) + + source := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} + expected := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} + is.ElementsMatch(slicesx.Flatten(source), expected) + + }) +} diff --git a/api/slicesx/includes.go b/api/slicesx/includes.go new file mode 100644 index 000000000..377a54215 --- /dev/null +++ b/api/slicesx/includes.go @@ -0,0 +1,17 @@ +package slicesx + +import "slices" + +// Checks if predicate returns truthy for any element of input. Iteration is stopped once predicate returns truthy. +func Some[T any](input []T, predicate func(T) bool) bool { + return slices.ContainsFunc(input, predicate) +} + +// Checks if predicate returns truthy for all elements of input. Iteration is stopped once predicate returns falsey. +// +// Note: This method returns true for empty collections because everything is true of elements of empty collections. +// https://en.wikipedia.org/wiki/Vacuous_truth +func Every[T any](input []T, predicate func(T) bool) bool { + // if the slice doesn't contain an inverted predicate then all items follow the predicate + return !slices.ContainsFunc(input, func(t T) bool { return !predicate(t) }) +} diff --git a/api/slicesx/includes_test.go b/api/slicesx/includes_test.go new file mode 100644 index 000000000..a3f074c1c --- /dev/null +++ b/api/slicesx/includes_test.go @@ -0,0 +1,76 @@ +package slicesx_test + +import ( + "testing" + + "github.com/portainer/portainer/api/slicesx" +) + +func Test_Every(t *testing.T) { + test(t, slicesx.Every, "All start with an A (ok)", + []string{"Apple", "Avocado", "Apricot"}, + true, + func(s string) bool { return s[0] == 'A' }, + ) + test(t, slicesx.Every, "All start with an A (ko = some don't start with A)", + []string{"Apple", "Avocado", "Banana"}, + false, + func(s string) bool { return s[0] == 'A' }, + ) + test(t, slicesx.Every, "All are under 5 (ok)", + []int{1, 2, 3}, + true, + func(i int) bool { return i < 5 }, + ) + test(t, slicesx.Every, "All are under 5 (ko = some above 10)", + []int{1, 2, 10}, + false, + func(i int) bool { return i < 5 }, + ) + test(t, slicesx.Every, "All are true (ok)", + []struct{ x bool }{{x: true}, {x: true}, {x: true}}, + true, + func(s struct{ x bool }) bool { return s.x }) + test(t, slicesx.Every, "All are true (ko = some are false)", + []struct{ x bool }{{x: true}, {x: true}, {x: false}}, + false, + func(s struct{ x bool }) bool { return s.x }) + test(t, slicesx.Every, "Must be true on empty slice", + []int{}, + true, + func(i int) bool { return i%2 == 0 }, + ) +} + +func Test_Some(t *testing.T) { + test(t, slicesx.Some, "Some start with an A (ok)", + []string{"Apple", "Avocado", "Banana"}, + true, + func(s string) bool { return s[0] == 'A' }, + ) + test(t, slicesx.Some, "Some start with an A (ko = all don't start with A)", + []string{"Banana", "Cherry", "Peach"}, + false, + func(s string) bool { return s[0] == 'A' }, + ) + test(t, slicesx.Some, "Some are under 5 (ok)", + []int{1, 2, 30}, + true, + func(i int) bool { return i < 5 }, + ) + test(t, slicesx.Some, "Some are under 5 (ko = all above 5)", + []int{10, 11, 12}, + false, + func(i int) bool { return i < 5 }, + ) + test(t, slicesx.Some, "Some are true (ok)", + []struct{ x bool }{{x: true}, {x: true}, {x: false}}, + true, + func(s struct{ x bool }) bool { return s.x }, + ) + test(t, slicesx.Some, "Some are true (ko = all are false)", + []struct{ x bool }{{x: false}, {x: false}, {x: false}}, + false, + func(s struct{ x bool }) bool { return s.x }, + ) +} diff --git a/api/slicesx/map.go b/api/slicesx/map.go new file mode 100644 index 000000000..7e24bdd0d --- /dev/null +++ b/api/slicesx/map.go @@ -0,0 +1,15 @@ +package slicesx + +// Map applies the given function to each element of the slice and returns a new slice with the results +func Map[T, U any](s []T, f func(T) U) []U { + result := make([]U, len(s)) + for i, v := range s { + result[i] = f(v) + } + return result +} + +// FlatMap applies the given function to each element of the slice and returns a new slice with the flattened results +func FlatMap[T, U any](s []T, f func(T) []U) []U { + return Flatten(Map(s, f)) +} diff --git a/api/slicesx/map_test.go b/api/slicesx/map_test.go new file mode 100644 index 000000000..a2cd2256d --- /dev/null +++ b/api/slicesx/map_test.go @@ -0,0 +1,43 @@ +package slicesx_test + +import ( + "strconv" + "testing" + + "github.com/portainer/portainer/api/slicesx" +) + +func Test_Map(t *testing.T) { + test(t, slicesx.Map, "Map integers to strings", + []int{1, 2, 3, 4, 5}, + []string{"1", "2", "3", "4", "5"}, + strconv.Itoa, + ) + test(t, slicesx.Map, "Map strings to integers", + []string{"1", "2", "3", "4", "5"}, + []int{1, 2, 3, 4, 5}, + func(s string) int { + n, _ := strconv.Atoi(s) + return n + }, + ) +} + +func Test_FlatMap(t *testing.T) { + test(t, slicesx.FlatMap, "Map integers to strings and flatten", + []int{1, 2, 3, 4, 5}, + []string{"1", "1", "2", "2", "3", "3", "4", "4", "5", "5"}, + func(i int) []string { + x := strconv.Itoa(i) + return []string{x, x} + }, + ) + test(t, slicesx.FlatMap, "Map strings to integers and flatten", + []string{"1", "2", "3", "4", "5"}, + []int{1, 1, 2, 2, 3, 3, 4, 4, 5, 5}, + func(s string) []int { + n, _ := strconv.Atoi(s) + return []int{n, n} + }, + ) +} diff --git a/api/slicesx/slices_test.go b/api/slicesx/slices_test.go deleted file mode 100644 index d75f9b559..000000000 --- a/api/slicesx/slices_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package slicesx - -import ( - "strconv" - "testing" - - "github.com/stretchr/testify/assert" -) - -type filterTestCase[T any] struct { - name string - input []T - expected []T - predicate func(T) bool -} - -func TestFilter(t *testing.T) { - intTestCases := []filterTestCase[int]{ - { - name: "Filter even numbers", - input: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, - expected: []int{2, 4, 6, 8}, - - predicate: func(n int) bool { - return n%2 == 0 - }, - }, - { - name: "Filter odd numbers", - input: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, - expected: []int{1, 3, 5, 7, 9}, - - predicate: func(n int) bool { - return n%2 != 0 - }, - }, - } - - runTestCases(t, intTestCases) - - stringTestCases := []filterTestCase[string]{ - { - name: "Filter strings starting with 'A'", - input: []string{"Apple", "Banana", "Avocado", "Grapes", "Apricot"}, - expected: []string{"Apple", "Avocado", "Apricot"}, - predicate: func(s string) bool { - return s[0] == 'A' - }, - }, - { - name: "Filter strings longer than 5 characters", - input: []string{"Apple", "Banana", "Avocado", "Grapes", "Apricot"}, - expected: []string{"Banana", "Avocado", "Grapes", "Apricot"}, - predicate: func(s string) bool { - return len(s) > 5 - }, - }, - } - - runTestCases(t, stringTestCases) -} - -func runTestCases[T any](t *testing.T, testCases []filterTestCase[T]) { - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - is := assert.New(t) - result := Filter(testCase.input, testCase.predicate) - - is.Equal(len(testCase.expected), len(result)) - is.ElementsMatch(testCase.expected, result) - }) - } -} - -func TestMap(t *testing.T) { - intTestCases := []struct { - name string - input []int - expected []string - mapper func(int) string - }{ - { - name: "Map integers to strings", - input: []int{1, 2, 3, 4, 5}, - expected: []string{"1", "2", "3", "4", "5"}, - mapper: strconv.Itoa, - }, - } - - runMapTestCases(t, intTestCases) - - stringTestCases := []struct { - name string - input []string - expected []int - mapper func(string) int - }{ - { - name: "Map strings to integers", - input: []string{"1", "2", "3", "4", "5"}, - expected: []int{1, 2, 3, 4, 5}, - mapper: func(s string) int { - n, _ := strconv.Atoi(s) - return n - }, - }, - } - - runMapTestCases(t, stringTestCases) -} - -func runMapTestCases[T, U any](t *testing.T, testCases []struct { - name string - input []T - expected []U - mapper func(T) U -}) { - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - is := assert.New(t) - result := Map(testCase.input, testCase.mapper) - - is.Equal(len(testCase.expected), len(result)) - is.ElementsMatch(testCase.expected, result) - }) - } -} diff --git a/api/slicesx/slicesx_test.go b/api/slicesx/slicesx_test.go new file mode 100644 index 000000000..1bb8a76fe --- /dev/null +++ b/api/slicesx/slicesx_test.go @@ -0,0 +1,29 @@ +package slicesx_test + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" +) + +type libFunc[T, U, V any] func([]T, func(T) U) V +type predicateFunc[T, U any] func(T) U + +func test[T, U, V any](t *testing.T, libFn libFunc[T, U, V], name string, input []T, expected V, predicate predicateFunc[T, U]) { + t.Helper() + + t.Run(name, func(t *testing.T) { + is := assert.New(t) + + result := libFn(input, predicate) + + switch reflect.TypeOf(result).Kind() { + case reflect.Slice, reflect.Array: + is.Equal(expected, result) + is.ElementsMatch(expected, result) + default: + is.Equal(expected, result) + } + }) +} diff --git a/api/slicesx/slices.go b/api/slicesx/unique.go similarity index 51% rename from api/slicesx/slices.go rename to api/slicesx/unique.go index b7e0aa0ef..8659b0778 100644 --- a/api/slicesx/slices.go +++ b/api/slicesx/unique.go @@ -1,27 +1,5 @@ package slicesx -// Map applies the given function to each element of the slice and returns a new slice with the results -func Map[T, U any](s []T, f func(T) U) []U { - result := make([]U, len(s)) - for i, v := range s { - result[i] = f(v) - } - return result -} - -// Filter returns a new slice containing only the elements of the slice for which the given predicate returns true -func Filter[T any](s []T, predicate func(T) bool) []T { - n := 0 - for _, v := range s { - if predicate(v) { - s[n] = v - n++ - } - } - - return s[:n] -} - func Unique[T comparable](items []T) []T { return UniqueBy(items, func(item T) T { return item diff --git a/api/slicesx/unique_test.go b/api/slicesx/unique_test.go new file mode 100644 index 000000000..8ff967ca6 --- /dev/null +++ b/api/slicesx/unique_test.go @@ -0,0 +1,46 @@ +package slicesx_test + +import ( + "testing" + + "github.com/portainer/portainer/api/slicesx" + "github.com/stretchr/testify/assert" +) + +func Test_Unique(t *testing.T) { + is := assert.New(t) + t.Run("Should extract unique numbers", func(t *testing.T) { + + source := []int{1, 1, 2, 3, 4, 4, 5, 4, 6, 7, 8, 9, 1} + result := slicesx.Unique(source) + expected := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} + + is.ElementsMatch(result, expected) + }) + + t.Run("Should return empty array", func(t *testing.T) { + source := []int{} + result := slicesx.Unique(source) + expected := []int{} + is.ElementsMatch(result, expected) + }) +} + +func Test_UniqueBy(t *testing.T) { + is := assert.New(t) + t.Run("Should extract unique numbers by property", func(t *testing.T) { + + source := []struct{ int }{{1}, {1}, {2}, {3}, {4}, {4}, {5}, {4}, {6}, {7}, {8}, {9}, {1}} + result := slicesx.UniqueBy(source, func(item struct{ int }) int { return item.int }) + expected := []struct{ int }{{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}} + + is.ElementsMatch(result, expected) + }) + + t.Run("Should return empty array", func(t *testing.T) { + source := []int{} + result := slicesx.UniqueBy(source, func(x int) int { return x }) + expected := []int{} + is.ElementsMatch(result, expected) + }) +} diff --git a/app/assets/css/button.css b/app/assets/css/button.css index dc3f82460..547d9fdc0 100644 --- a/app/assets/css/button.css +++ b/app/assets/css/button.css @@ -24,44 +24,84 @@ fieldset[disabled] .btn { box-shadow: none; } +.btn-icon { + @apply !border-none !bg-transparent p-0; +} + .btn.btn-primary { - @apply border-blue-8 bg-blue-8 text-white; - @apply hover:border-blue-9 hover:bg-blue-9 hover:text-white; - @apply th-dark:hover:border-blue-7 th-dark:hover:bg-blue-7; + @apply border-graphite-700 bg-graphite-700 text-mist-100; + @apply hover:border-graphite-700/90 hover:bg-graphite-700/90 hover:text-mist-100; + @apply focus:border-blue-5 focus:shadow-graphite-700/80 focus:text-mist-100; + + @apply th-dark:border-mist-100 th-dark:bg-mist-100 th-dark:text-graphite-700; + @apply th-dark:hover:border-mist-100/90 th-dark:hover:bg-mist-100/90 th-dark:hover:text-graphite-700; + @apply th-dark:focus:border-blue-5 th-dark:focus:shadow-white/80 th-dark:focus:text-graphite-700; + + @apply th-highcontrast:border-mist-100 th-highcontrast:bg-mist-100 th-highcontrast:text-graphite-700; + @apply th-highcontrast:hover:border-mist-100/90 th-highcontrast:hover:bg-mist-100/90 th-highcontrast:hover:text-graphite-700; + @apply th-highcontrast:focus:border-blue-5 th-highcontrast:focus:shadow-white/80 th-highcontrast:focus:text-graphite-700; +} + +/* Sidebar background is always dark, so we need to override the primary button styles */ +.btn.btn-primary.sidebar { + @apply border-mist-100 bg-mist-100 text-graphite-700; + @apply hover:border-mist-100/90 hover:bg-mist-100/90 hover:text-graphite-700; + @apply focus:border-blue-5 focus:shadow-white/80 focus:text-graphite-700; } .btn.btn-primary:active, .btn.btn-primary.active, .open > .dropdown-toggle.btn-primary { - @apply border-blue-5 bg-blue-9; + @apply border-graphite-700/80 bg-graphite-700 text-mist-100; + @apply th-dark:border-white/80 th-dark:bg-mist-100 th-dark:text-graphite-700; + @apply th-highcontrast:border-white/80 th-highcontrast:bg-mist-100 th-highcontrast:text-graphite-700; } .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus { - @apply bg-blue-8; + @apply bg-graphite-700 text-mist-100; + @apply th-dark:bg-mist-100 th-dark:text-graphite-700; + @apply th-highcontrast:bg-mist-100 th-highcontrast:text-graphite-700; } /* Button Secondary */ .btn.btn-secondary { @apply border border-solid; - @apply border-blue-8 bg-blue-2 text-blue-9; - @apply hover:bg-blue-3; + @apply border-graphite-700 bg-mist-100 text-graphite-700; + @apply hover:border-graphite-700 hover:bg-graphite-700/10 hover:text-graphite-700; + @apply focus:border-blue-5 focus:shadow-graphite-700/20 focus:text-graphite-700; - @apply th-dark:border-blue-7 th-dark:bg-gray-10 th-dark:text-blue-3; - @apply th-dark:hover:bg-blue-11; + @apply th-dark:border-mist-100 th-dark:bg-graphite-700 th-dark:text-mist-100; + @apply th-dark:hover:border-mist-100 th-dark:hover:bg-mist-100/20 th-dark:hover:text-mist-100; + @apply th-dark:focus:border-blue-5 th-dark:focus:shadow-white/80 th-dark:focus:text-mist-100; + + @apply th-highcontrast:border-mist-100 th-highcontrast:bg-graphite-700 th-highcontrast:text-mist-100; + @apply th-highcontrast:hover:border-mist-100 th-highcontrast:hover:bg-mist-100/20 th-highcontrast:hover:text-mist-100; + @apply th-highcontrast:focus:border-blue-5 th-highcontrast:focus:shadow-white/80 th-highcontrast:focus:text-mist-100; +} + +.btn.btn-secondary:active, +.btn.btn-secondary.active, +.open > .dropdown-toggle.btn-secondary { + @apply border-graphite-700 bg-graphite-700/10 text-graphite-700; + @apply th-dark:border-mist-100 th-dark:bg-mist-100/20 th-dark:text-mist-100; + @apply th-highcontrast:border-mist-100 th-highcontrast:bg-mist-100/20 th-highcontrast:text-mist-100; } .btn.btn-danger { @apply border-error-8 bg-error-8; @apply hover:border-error-7 hover:bg-error-7 hover:text-white; + @apply focus:border-blue-5 focus:shadow-error-8/20 focus:text-white; + @apply th-dark:focus:border-blue-5 th-dark:focus:shadow-white/80 th-dark:focus:text-white; + @apply th-highcontrast:focus:border-blue-5 th-highcontrast:focus:shadow-white/80 th-highcontrast:focus:text-white; } .btn.btn-danger:active, .btn.btn-danger.active, .open > .dropdown-toggle.btn-danger { - @apply border-blue-5 bg-error-8 text-white; + @apply border-error-5 bg-error-8 text-white; } .btn.btn-dangerlight { @@ -70,6 +110,13 @@ fieldset[disabled] .btn { @apply hover:bg-error-2 th-dark:hover:bg-error-11; @apply border-error-5 th-highcontrast:border-error-7 th-dark:border-error-7; @apply border border-solid; + + @apply focus:border-blue-5 focus:shadow-error-8/20 focus:text-error-9; + @apply th-dark:focus:border-blue-5 th-dark:focus:shadow-white/80 th-dark:focus:text-white; + @apply th-highcontrast:focus:border-blue-5 th-highcontrast:focus:shadow-white/80; +} +.btn.btn-icon.btn-dangerlight { + @apply hover:text-error-11 th-dark:hover:text-error-7; } .btn.btn-success { @@ -83,15 +130,18 @@ fieldset[disabled] .btn { /* secondary-grey */ .btn.btn-default, .btn.btn-light { - @apply border-gray-5 bg-white text-gray-9; + @apply border-gray-5 bg-white text-gray-8; @apply hover:border-gray-5 hover:bg-gray-3 hover:text-gray-10; + @apply focus:border-blue-5 focus:shadow-graphite-700/20 focus:text-gray-8; /* dark mode */ @apply th-dark:border-gray-warm-7 th-dark:bg-gray-iron-10 th-dark:text-gray-warm-4; @apply th-dark:hover:border-gray-6 th-dark:hover:bg-gray-iron-9 th-dark:hover:text-gray-warm-4; + @apply th-dark:focus:border-blue-5 th-dark:focus:shadow-white/80 th-dark:focus:text-gray-warm-4; @apply th-highcontrast:border-gray-2 th-highcontrast:bg-black th-highcontrast:text-white; @apply th-highcontrast:hover:border-gray-6 th-highcontrast:hover:bg-gray-9 th-highcontrast:hover:text-gray-warm-4; + @apply th-highcontrast:focus:border-blue-5 th-highcontrast:focus:shadow-white/80 th-highcontrast:focus:text-white; } .btn.btn-light:active, @@ -112,38 +162,17 @@ fieldset[disabled] .btn { .input-group-btn .btn.active, .btn-group .btn.active { - @apply border-blue-5 bg-blue-2 text-blue-10; - @apply th-dark:border-blue-9 th-dark:bg-blue-11 th-dark:text-blue-2; + @apply border-graphite-700/80 bg-graphite-700 text-mist-100; + @apply th-dark:border-white/80 th-dark:bg-mist-100 th-dark:text-graphite-700; + @apply th-highcontrast:border-white/80 th-highcontrast:bg-mist-100 th-highcontrast:text-graphite-700; } -/* focus */ - -.btn.btn-primary:focus, -.btn.btn-secondary:focus, -.btn.btn-light:focus { - @apply border-blue-5; +.btn.btn-icon:focus { + box-shadow: none !important; } -.btn.btn-danger:focus, -.btn.btn-dangerlight:focus { - @apply border-blue-6; -} - -.btn.btn-primary:focus, -.btn.btn-secondary:focus, -.btn.btn-light:focus, -.btn.btn-danger:focus, -.btn.btn-dangerlight:focus { - --btn-focus-color: var(--ui-blue-3); - box-shadow: 0px 0px 0px 4px var(--btn-focus-color); -} - -[theme='dark'] .btn.btn-primary:focus, -[theme='dark'] .btn.btn-secondary:focus, -[theme='dark'] .btn.btn-light:focus, -[theme='dark'] .btn.btn-danger:focus, -[theme='dark'] .btn.btn-dangerlight:focus { - --btn-focus-color: var(--ui-blue-11); +.btn:focus { + box-shadow: 0px 0px 0px 2px var(--tw-shadow-color); } a.no-link, diff --git a/app/assets/css/colors.json b/app/assets/css/colors.json index 55f2922e5..94d3c2015 100644 --- a/app/assets/css/colors.json +++ b/app/assets/css/colors.json @@ -1,6 +1,31 @@ { "black": "#000000", "white": "#ffffff", + "graphite": { + "10": "#f5f5f6", + "50": "#e5e6e8", + "100": "#ced0d3", + "200": "#abafb5", + "300": "#7b8089", + "400": "#5c6066", + "500": "#484a4e", + "600": "#3a3b3f", + "700": "#2e2f33", + "800": "#222326", + "900": "#161719" + }, + "mist": { + "50": "#fcfbfa", + "100": "#f7f6f3", + "200": "#f0f0ec", + "300": "#e8e7e2", + "400": "#e2e1db", + "500": "#d9d8d2", + "600": "#ceccc4", + "700": "#bebcb4", + "800": "#a7a6a0", + "900": "#8b8983" + }, "gray": { "1": "#fcfcfd", "2": "#f9fafb", diff --git a/app/assets/css/react-datetime-picker-override.css b/app/assets/css/react-datetime-picker-override.css index acd26fb58..dbbea4766 100644 --- a/app/assets/css/react-datetime-picker-override.css +++ b/app/assets/css/react-datetime-picker-override.css @@ -12,35 +12,40 @@ /* Extending Calendar.css from react-daterange-picker__calendar */ -.react-daterange-picker__calendar .react-calendar { +.react-calendar { background: var(--bg-calendar-color); color: var(--text-main-color); + @apply th-dark:bg-gray-iron-10; } /* calendar nav buttons */ -.react-daterange-picker__calendar .react-calendar__navigation button:disabled { +.react-calendar__navigation button:disabled { background: var(--bg-calendar-color); @apply opacity-60; @apply brightness-95 th-dark:brightness-110; + @apply th-dark:bg-gray-iron-7; } -.react-daterange-picker__calendar .react-calendar__navigation button:enabled:hover, -.react-daterange-picker__calendar .react-calendar__navigation button:enabled:focus { +.react-calendar__navigation button:enabled:hover, +.react-calendar__navigation button:enabled:focus { background: var(--bg-daterangepicker-color); + @apply th-dark:bg-gray-iron-7; } /* date tile */ -.react-daterange-picker__calendar .react-calendar__tile:disabled { - background: var(--bg-calendar-color); +.react-calendar__tile:disabled { @apply opacity-60; @apply brightness-95 th-dark:brightness-110; + @apply th-dark:bg-gray-iron-7; } -.react-daterange-picker__calendar .react-calendar__tile:enabled:hover, -.react-daterange-picker__calendar .react-calendar__tile:enabled:focus { + +.react-calendar__tile:enabled:hover, +.react-calendar__tile:enabled:focus { background: var(--bg-daterangepicker-hover); + @apply th-dark:bg-gray-iron-7; } /* today's date tile */ -.react-daterange-picker__calendar .react-calendar__tile--now { +.react-calendar__tile--now { @apply th-highcontrast:text-[color:var(--bg-calendar-color)] th-dark:text-[color:var(--bg-calendar-color)]; border-radius: 0.25rem !important; } @@ -48,23 +53,27 @@ .react-daterange-picker__calendar .react-calendar__tile--now:enabled:focus { background: var(--bg-daterangepicker-hover); color: var(--text-daterangepicker-hover); + @apply th-dark:bg-gray-iron-7; } /* probably date tile in range */ -.react-daterange-picker__calendar .react-calendar__tile--hasActive { +.react-calendar__tile--hasActive { background: var(--bg-daterangepicker-end-date); color: var(--text-daterangepicker-end-date); + @apply th-dark:bg-gray-iron-7; } -.react-daterange-picker__calendar .react-calendar__tile--hasActive:enabled:hover, -.react-daterange-picker__calendar .react-calendar__tile--hasActive:enabled:focus { +.react-calendar__tile--hasActive:enabled:hover, +.react-calendar__tile--hasActive:enabled:focus { background: var(--bg-daterangepicker-hover); color: var(--text-daterangepicker-hover); + @apply th-dark:bg-gray-iron-7; } -.react-daterange-picker__calendar .react-calendar__tile--active:enabled:hover, -.react-daterange-picker__calendar .react-calendar__tile--active:enabled:focus { +.react-calendar__tile--active:enabled:hover, +.react-calendar__tile--active:enabled:focus { background: var(--bg-daterangepicker-hover); color: var(--text-daterangepicker-hover); + @apply th-dark:bg-gray-iron-7; } .react-daterange-picker__calendar @@ -75,9 +84,10 @@ } /* on range select hover */ -.react-daterange-picker__calendar .react-calendar--selectRange .react-calendar__tile--hover { +.react-calendar--selectRange .react-calendar__tile--hover { background: var(--bg-daterangepicker-in-range); color: var(--text-daterangepicker-in-range); + @apply th-dark:bg-gray-iron-7; } /* @@ -111,4 +121,5 @@ .react-calendar__tile--active.react-calendar__month-view__days__day--weekend { color: var(--text-daterangepicker-active); + @apply th-dark:bg-gray-iron-7; } diff --git a/app/assets/css/theme.css b/app/assets/css/theme.css index eb2d36882..318e0d9e4 100644 --- a/app/assets/css/theme.css +++ b/app/assets/css/theme.css @@ -3,6 +3,16 @@ --black-color: var(--ui-black); --white-color: var(--ui-white); + --graphite-600: #3a3b3f; + --graphite-700: #2e2f33; + --graphite-800: #222326; + --graphite-900: #161719; + + --mist-50: #fcfbfa; + --mist-100: #f7f6f3; + --mist-200: #f0f0ec; + --mist-300: #e8e7e2; + --grey-1: #212121; --grey-2: #181818; --grey-3: #383838; @@ -58,6 +68,8 @@ --grey-58: #ebf4f8; --grey-59: #e6e6e6; --grey-61: rgb(231, 231, 231); + --grey-62: #fdfdfd; + --grey-63: #121212; --blue-1: #219; --blue-2: #337ab7; @@ -99,17 +111,16 @@ /* Default Theme */ --bg-card-color: var(--white-color); --bg-main-color: var(--white-color); - --bg-body-color: var(--grey-9); + --bg-body-color: var(--grey-62); --bg-checkbox-border-color: var(--grey-49); - --bg-sidebar-color: var(--ui-blue-10); - --bg-sidebar-nav-color: var(--ui-blue-11); + --bg-sidebar-color: var(--graphite-700); + --bg-sidebar-nav-color: var(--graphite-600); --bg-widget-color: var(--white-color); --bg-widget-header-color: var(--grey-10); --bg-widget-table-color: var(--ui-gray-3); --bg-header-color: var(--white-color); --bg-hover-table-color: var(--grey-14); --bg-input-group-addon-color: var(--ui-gray-3); - --bg-btn-default-color: var(--ui-blue-10); --bg-blocklist-hover-color: var(--ui-blue-2); --bg-table-color: var(--white-color); --bg-md-checkbox-color: var(--grey-12); @@ -128,7 +139,8 @@ --border-pagination-color: var(--ui-white); --bg-pagination-span-color: var(--white-color); --bg-pagination-hover-color: var(--ui-blue-3); - --bg-motd-body-color: var(--grey-20); + --bg-motd-body-color: var(--mist-50); + --bg-motd-btn-color: var(--graphite-700); --bg-item-highlighted-color: var(--grey-21); --bg-item-highlighted-null-color: var(--grey-14); --bg-panel-body-color: var(--white-color); @@ -144,8 +156,6 @@ --bg-daterangepicker-in-range: var(--grey-58); --bg-daterangepicker-active: var(--blue-14); --bg-input-autofill-color: var(--bg-inputbox); - --bg-btn-default-hover-color: var(--ui-blue-9); - --bg-btn-focus: var(--grey-59); --bg-small-select-color: var(--white-color); --bg-stepper-item-active: var(--white-color); --bg-stepper-item-counter: var(--grey-61); @@ -177,7 +187,6 @@ --text-navtabs-color: var(--grey-7); --text-navtabs-hover-color: var(--grey-6); --text-nav-tab-active-color: var(--grey-25); - --text-dropdown-menu-color: var(--grey-6); --text-log-viewer-color: var(--black-color); --text-json-tree-color: var(--blue-3); @@ -189,6 +198,8 @@ --text-pagination-color: var(--grey-26); --text-pagination-span-color: var(--grey-3); --text-pagination-span-hover-color: var(--grey-3); + --text-motd-body-color: var(--black-color); + --text-motd-btn-color: var(--mist-100); --text-summary-color: var(--black-color); --text-tooltip-color: var(--white-color); --text-rzslider-color: var(--grey-36); @@ -203,6 +214,7 @@ --text-button-group-color: var(--ui-gray-9); --text-button-dangerlight-color: var(--ui-error-5); --text-stepper-active-color: var(--ui-blue-8); + --border-color: var(--grey-42); --border-widget-color: var(--grey-43); --border-sidebar-color: var(--ui-blue-9); @@ -218,7 +230,8 @@ --border-pre-color: var(--grey-43); --border-pagination-span-color: var(--ui-white); --border-pagination-hover-color: var(--ui-white); - --border-panel-color: var(--white-color); + --border-motd-body-color: var(--mist-300); + --border-panel-color: var(--mist-300); --border-input-sm-color: var(--grey-47); --border-daterangepicker-color: var(--grey-19); --border-calendar-table: var(--white-color); @@ -265,8 +278,7 @@ --text-log-viewer-color-json-red: var(--text-log-viewer-color); --text-log-viewer-color-json-blue: var(--text-log-viewer-color); - --bg-body-color: var(--grey-2); - --bg-btn-default-color: var(--grey-3); + --bg-body-color: var(--grey-63); --bg-blocklist-hover-color: var(--ui-gray-iron-10); --bg-blocklist-item-selected-color: var(--ui-gray-iron-10); --bg-card-color: var(--grey-1); @@ -274,8 +286,6 @@ --bg-code-color: var(--grey-2); --bg-dropdown-menu-color: var(--ui-gray-warm-8); --bg-main-color: var(--grey-2); - --bg-sidebar-color: var(--grey-1); - --bg-sidebar-nav-color: var(--grey-2); --bg-widget-color: var(--grey-1); --bg-widget-header-color: var(--grey-3); --bg-widget-table-color: var(--grey-3); @@ -296,7 +306,8 @@ --bg-pagination-color: var(--grey-3); --bg-pagination-span-color: var(--grey-1); --bg-pagination-hover-color: var(--grey-3); - --bg-motd-body-color: var(--grey-1); + --bg-motd-body-color: var(--graphite-800); + --bg-motd-btn-color: var(--mist-100); --bg-item-highlighted-color: var(--grey-2); --bg-item-highlighted-null-color: var(--grey-2); --bg-panel-body-color: var(--grey-1); @@ -316,8 +327,6 @@ --bg-daterangepicker-in-range: var(--ui-gray-warm-11); --bg-daterangepicker-active: var(--blue-14); --bg-input-autofill-color: var(--bg-inputbox); - --bg-btn-default-hover-color: var(--grey-4); - --bg-btn-focus: var(--grey-3); --bg-small-select-color: var(--grey-2); --bg-stepper-item-active: var(--grey-1); --bg-stepper-item-counter: var(--grey-7); @@ -348,7 +357,6 @@ --text-navtabs-color: var(--grey-8); --text-navtabs-hover-color: var(--grey-9); --text-nav-tab-active-color: var(--white-color); - --text-dropdown-menu-color: var(--white-color); --text-log-viewer-color: var(--white-color); --text-json-tree-color: var(--grey-40); @@ -360,6 +368,8 @@ --text-pagination-color: var(--white-color); --text-pagination-span-color: var(--ui-white); --text-pagination-span-hover-color: var(--ui-white); + --text-motd-body-color: var(--mist-100); + --text-motd-btn-color: var(--graphite-700); --text-summary-color: var(--white-color); --text-tooltip-color: var(--white-color); --text-rzslider-color: var(--white-color); @@ -374,6 +384,7 @@ --text-button-group-color: var(--ui-white); --text-button-dangerlight-color: var(--ui-error-7); --text-stepper-active-color: var(--ui-white); + --border-color: var(--grey-3); --border-widget-color: var(--grey-1); --border-sidebar-color: var(--ui-gray-8); @@ -391,6 +402,7 @@ --border-blocklist-item-selected-color: var(--grey-31); --border-pagination-span-color: var(--grey-1); --border-pagination-hover-color: var(--grey-3); + --border-motd-body-color: var(--graphite-800); --border-panel-color: var(--grey-2); --border-input-sm-color: var(--grey-3); --border-daterangepicker-color: var(--grey-3); @@ -450,6 +462,7 @@ --bg-panel-body-color: var(--black-color); --bg-dropdown-menu-color: var(--ui-gray-warm-8); --bg-motd-body-color: var(--black-color); + --bg-motd-btn-color: var(--white-color); --bg-blocklist-hover-color: var(--black-color); --bg-blocklist-item-selected-color: var(--black-color); --bg-input-group-addon-color: var(--grey-3); @@ -481,11 +494,8 @@ --bg-navtabs-hover-color: var(--grey-3); --bg-nav-tab-active-color: var(--ui-black); - --bg-btn-default-color: var(--black-color); --bg-input-autofill-color: var(--bg-inputbox); --bg-code-color: var(--ui-black); - --bg-btn-default-hover-color: var(--grey-4); - --bg-btn-focus: var(--black-color); --bg-small-select-color: var(--black-color); --bg-stepper-item-active: var(--black-color); --bg-stepper-item-counter: var(--grey-3); @@ -523,6 +533,8 @@ --text-daterangepicker-end-date: var(--ui-white); --text-daterangepicker-in-range: var(--white-color); --text-daterangepicker-active: var(--white-color); + --text-motd-body-color: var(--white-color); + --text-motd-btn-color: var(--black-color); --text-json-tree-color: var(--white-color); --text-json-tree-leaf-color: var(--white-color); --text-json-tree-branch-preview-color: var(--white-color); @@ -553,6 +565,7 @@ --border-input-sm-color: var(--white-color); --border-pagination-color: var(--grey-1); --border-pagination-span-color: var(--grey-1); + --border-motd-body-color: var(--white-color); --border-daterangepicker-color: var(--white-color); --border-calendar-table: var(--black-color); --border-daterangepicker: var(--black-color); diff --git a/app/assets/css/vendor-override.css b/app/assets/css/vendor-override.css index 74fa94d4e..12e0fc947 100644 --- a/app/assets/css/vendor-override.css +++ b/app/assets/css/vendor-override.css @@ -201,8 +201,18 @@ pre { background-color: var(--bg-progress-color); } -.motd-body { - background-color: var(--bg-motd-body-color) !important; +.widget-body.motd-body { + border: 1px solid var(--border-motd-body-color); + color: var(--text-motd-body-color); + background: var(--bg-motd-body-color) url(../images/purple-gradient.svg) top right / 40% no-repeat; +} + +.widget-body.motd-body .btn.btn-link, +.widget-body.motd-body .btn.btn-link:hover { + padding: 0 5px 0 4px; + border-radius: 4px; + background-color: var(--bg-motd-btn-color); + color: var(--text-motd-btn-color); } .panel-body { @@ -408,14 +418,10 @@ input:-webkit-autofill { } .sidebar.tippy-box[data-placement^='right'] > .tippy-arrow:before { - border-right: 8px solid var(--ui-blue-9); + border-right: 8px solid var(--graphite-600); border-width: 6px 8px 6px 0; } -[theme='dark'] .sidebar.tippy-box[data-placement^='right'] > .tippy-arrow:before { - border-right: 8px solid var(--ui-gray-true-9); -} - [theme='highcontrast'] .sidebar.tippy-box[data-placement^='right'] > .tippy-arrow:before { border-right: 8px solid var(--ui-white); } diff --git a/app/assets/ico/android-chrome-192x192.png b/app/assets/ico/android-chrome-192x192.png index 8f31e405a..236db0e2b 100644 Binary files a/app/assets/ico/android-chrome-192x192.png and b/app/assets/ico/android-chrome-192x192.png differ diff --git a/app/assets/ico/android-chrome-256x256.png b/app/assets/ico/android-chrome-256x256.png index cc95d0044..52848e019 100644 Binary files a/app/assets/ico/android-chrome-256x256.png and b/app/assets/ico/android-chrome-256x256.png differ diff --git a/app/assets/ico/apple-touch-icon.png b/app/assets/ico/apple-touch-icon.png index aeea31ce8..f05e9c161 100644 Binary files a/app/assets/ico/apple-touch-icon.png and b/app/assets/ico/apple-touch-icon.png differ diff --git a/app/assets/ico/favicon-16x16.png b/app/assets/ico/favicon-16x16.png index f7a26b564..8c60e5d9f 100644 Binary files a/app/assets/ico/favicon-16x16.png and b/app/assets/ico/favicon-16x16.png differ diff --git a/app/assets/ico/favicon-32x32.png b/app/assets/ico/favicon-32x32.png index d1ccc9cea..8735718a2 100644 Binary files a/app/assets/ico/favicon-32x32.png and b/app/assets/ico/favicon-32x32.png differ diff --git a/app/assets/ico/favicon.ico b/app/assets/ico/favicon.ico index 28ed661f9..066969400 100644 Binary files a/app/assets/ico/favicon.ico and b/app/assets/ico/favicon.ico differ diff --git a/app/assets/ico/logomark.svg b/app/assets/ico/logomark.svg index b7679d482..140c1b494 100644 --- a/app/assets/ico/logomark.svg +++ b/app/assets/ico/logomark.svg @@ -1,35 +1,12 @@ - - - - - - - - - - - - - - - - - + + + + + - - - - - - - - - - - - - - + + + diff --git a/app/assets/ico/mstile-150x150.png b/app/assets/ico/mstile-150x150.png index 5e7eb6873..f48374538 100644 Binary files a/app/assets/ico/mstile-150x150.png and b/app/assets/ico/mstile-150x150.png differ diff --git a/app/assets/ico/safari-pinned-tab.svg b/app/assets/ico/safari-pinned-tab.svg index 79ce7b6fa..d0509a572 100644 --- a/app/assets/ico/safari-pinned-tab.svg +++ b/app/assets/ico/safari-pinned-tab.svg @@ -1 +1,6 @@ - \ No newline at end of file + + + + + + \ No newline at end of file diff --git a/app/assets/images/logo.png b/app/assets/images/logo.png deleted file mode 100644 index 2e46594f2..000000000 Binary files a/app/assets/images/logo.png and /dev/null differ diff --git a/app/assets/images/logo_alt.png b/app/assets/images/logo_alt.png deleted file mode 100644 index a6c6707ca..000000000 Binary files a/app/assets/images/logo_alt.png and /dev/null differ diff --git a/app/assets/images/logo_alt.svg b/app/assets/images/logo_alt.svg index 90e164ca1..8d254e4e5 100644 --- a/app/assets/images/logo_alt.svg +++ b/app/assets/images/logo_alt.svg @@ -1,60 +1,14 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/app/assets/images/logo_alt_black.svg b/app/assets/images/logo_alt_black.svg new file mode 100644 index 000000000..d9243b464 --- /dev/null +++ b/app/assets/images/logo_alt_black.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/app/assets/images/logo_ico.png b/app/assets/images/logo_ico.png deleted file mode 100644 index b4bfd2924..000000000 Binary files a/app/assets/images/logo_ico.png and /dev/null differ diff --git a/app/assets/images/logo_small.png b/app/assets/images/logo_small.png deleted file mode 100644 index 76d3a46b0..000000000 Binary files a/app/assets/images/logo_small.png and /dev/null differ diff --git a/app/assets/images/logo_small_alt.png b/app/assets/images/logo_small_alt.png deleted file mode 100644 index a5bc64771..000000000 Binary files a/app/assets/images/logo_small_alt.png and /dev/null differ diff --git a/app/assets/images/purple-gradient.svg b/app/assets/images/purple-gradient.svg new file mode 100644 index 000000000..0b3bc7160 --- /dev/null +++ b/app/assets/images/purple-gradient.svg @@ -0,0 +1,522 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/docker/views/containers/edit/containerController.js b/app/docker/views/containers/edit/containerController.js index 78f153e27..f1ff8f27c 100644 --- a/app/docker/views/containers/edit/containerController.js +++ b/app/docker/views/containers/edit/containerController.js @@ -54,7 +54,7 @@ angular.module('portainer.docker').controller('ContainerController', [ $scope.computeDockerGPUCommand = () => { const gpuOptions = _.find($scope.container.HostConfig.DeviceRequests, function (o) { - return o.Driver === 'nvidia' || o.Capabilities[0][0] === 'gpu'; + return o.Driver === 'nvidia' || (o.Capabilities && o.Capabilities.length > 0 && o.Capabilities[0] > 0 && o.Capabilities[0][0] === 'gpu'); }); if (!gpuOptions) { return 'No GPU config found'; diff --git a/app/docker/views/images/edit/image.html b/app/docker/views/images/edit/image.html index 7bee83a2b..af37cd0e2 100644 --- a/app/docker/views/images/edit/image.html +++ b/app/docker/views/images/edit/image.html @@ -16,19 +16,19 @@ - + - + - + diff --git a/app/index.html b/app/index.html index 370070b48..52b9b5d10 100644 --- a/app/index.html +++ b/app/index.html @@ -20,7 +20,7 @@ - + @@ -47,7 +47,10 @@
- +
+ + +
diff --git a/app/kubernetes/react/components/index.ts b/app/kubernetes/react/components/index.ts index 27aa04444..cfb103823 100644 --- a/app/kubernetes/react/components/index.ts +++ b/app/kubernetes/react/components/index.ts @@ -92,6 +92,7 @@ export const ngModule = angular 'onChange', 'placeholder', 'value', + 'allowSelectAll', ]) ) .component( diff --git a/app/kubernetes/registries/kube-registry-access-view/kube-registry-access-view.html b/app/kubernetes/registries/kube-registry-access-view/kube-registry-access-view.html index 11184ae0f..5c5e68255 100644 --- a/app/kubernetes/registries/kube-registry-access-view/kube-registry-access-view.html +++ b/app/kubernetes/registries/kube-registry-access-view/kube-registry-access-view.html @@ -19,6 +19,7 @@ namespaces="$ctrl.resourcePools" placeholder="'Select one or more namespaces'" on-change="($ctrl.onChangeResourcePools)" + allow-select-all="true" >
diff --git a/app/kubernetes/views/applications/logs/logsController.js b/app/kubernetes/views/applications/logs/logsController.js index 66601d98b..37cae6cad 100644 --- a/app/kubernetes/views/applications/logs/logsController.js +++ b/app/kubernetes/views/applications/logs/logsController.js @@ -77,6 +77,7 @@ class KubernetesApplicationLogsController { await this.getApplicationLogsAsync(); } catch (err) { this.Notifications.error('Failure', err, 'Unable to retrieve application logs'); + this.stopRepeater(); } finally { this.state.viewReady = true; } diff --git a/app/kubernetes/views/configurations/configmap/edit/configMap.html b/app/kubernetes/views/configurations/configmap/edit/configMap.html index 89e1c38c5..70a2d4f1a 100644 --- a/app/kubernetes/views/configurations/configmap/edit/configMap.html +++ b/app/kubernetes/views/configurations/configmap/edit/configMap.html @@ -58,7 +58,7 @@ diff --git a/app/kubernetes/views/configurations/secret/edit/secret.html b/app/kubernetes/views/configurations/secret/edit/secret.html index 0309d356c..2e939c87e 100644 --- a/app/kubernetes/views/configurations/secret/edit/secret.html +++ b/app/kubernetes/views/configurations/secret/edit/secret.html @@ -65,7 +65,7 @@ diff --git a/app/kubernetes/views/deploy/deploy.html b/app/kubernetes/views/deploy/deploy.html index 5eda2d3a7..60e7b0144 100644 --- a/app/kubernetes/views/deploy/deploy.html +++ b/app/kubernetes/views/deploy/deploy.html @@ -31,7 +31,7 @@ -
+
- -
- + is-disabled="ctrl.formValues.namespace_toggle && ctrl.state.BuildMethod !== ctrl.BuildMethods.HELM || ctrl.state.isNamespaceInputDisabled" + value="ctrl.formValues.Namespace" + on-change="(ctrl.onChangeNamespace)" + options="ctrl.namespaceOptions" + > Namespaces specified in the manifest will be used @@ -66,10 +64,10 @@
-
+
Resource names specified in the manifest will be used
-
+
-
+
-
Selected Helm chart
diff --git a/app/kubernetes/views/deploy/deployController.js b/app/kubernetes/views/deploy/deployController.js index 89f416ac3..b44d3d7bb 100644 --- a/app/kubernetes/views/deploy/deployController.js +++ b/app/kubernetes/views/deploy/deployController.js @@ -101,9 +101,10 @@ class KubernetesDeployController { this.onChangeNamespace = this.onChangeNamespace.bind(this); } - onChangeNamespace() { + onChangeNamespace(namespaceName) { return this.$async(async () => { - const applications = await this.KubernetesApplicationService.get(this.formValues.Namespace); + this.formValues.Namespace = namespaceName; + const applications = await this.KubernetesApplicationService.get(namespaceName); const stacks = _.map(applications, (item) => item.StackName).filter((item) => item !== ''); this.stacks = _.uniq(stacks); }); @@ -371,6 +372,10 @@ class KubernetesDeployController { if (this.namespaces.length > 0) { this.formValues.Namespace = this.namespaces[0].Name; } + this.namespaceOptions = _.map(namespaces, (namespace) => ({ + label: namespace.Name, + value: namespace.Name, + })); } catch (err) { this.Notifications.error('Failure', err, 'Unable to load namespaces data'); } @@ -404,7 +409,8 @@ class KubernetesDeployController { } } - this.onChangeNamespace(); + this.onChangeNamespace(this.formValues.Namespace); + this.state.viewReady = true; this.$window.onbeforeunload = () => { diff --git a/app/kubernetes/views/stacks/logs/logsController.js b/app/kubernetes/views/stacks/logs/logsController.js index 536ea2ae4..d4e1b5ba7 100644 --- a/app/kubernetes/views/stacks/logs/logsController.js +++ b/app/kubernetes/views/stacks/logs/logsController.js @@ -104,6 +104,7 @@ class KubernetesStackLogsController { await this.getStackLogsAsync(); } catch (err) { this.Notifications.error('Failure', err, 'Unable to retrieve stack logs'); + this.stopRepeater(); } finally { this.state.viewReady = true; } diff --git a/app/portainer/components/custom-template-selector/custom-template-selector.html b/app/portainer/components/custom-template-selector/custom-template-selector.html index ce05aa1ce..cde665d49 100644 --- a/app/portainer/components/custom-template-selector/custom-template-selector.html +++ b/app/portainer/components/custom-template-selector/custom-template-selector.html @@ -1,7 +1,7 @@
-
+

diff --git a/app/portainer/react/components/index.ts b/app/portainer/react/components/index.ts index 8a9c1f589..9b2f7325d 100644 --- a/app/portainer/react/components/index.ts +++ b/app/portainer/react/components/index.ts @@ -9,6 +9,7 @@ import { withFormValidation } from '@/react-tools/withFormValidation'; import { GroupAssociationTable } from '@/react/portainer/environments/environment-groups/components/GroupAssociationTable'; import { AssociatedEnvironmentsSelector } from '@/react/portainer/environments/environment-groups/components/AssociatedEnvironmentsSelector'; import { withControlledInput } from '@/react-tools/withControlledInput'; +import { NamespacePortainerSelect } from '@/react/kubernetes/applications/components/NamespaceSelector/NamespaceSelector'; import { EnvironmentVariablesFieldset, @@ -199,11 +200,22 @@ export const ngModule = angular 'onChange', 'options', 'isMulti', + 'filterOption', 'isClearable', 'components', 'isLoading', 'noOptionsMessage', 'aria-label', + 'loadingMessage', + ]) + ) + .component( + 'namespacePortainerSelect', + r2a(NamespacePortainerSelect, [ + 'value', + 'onChange', + 'isDisabled', + 'options', ]) ) .component( @@ -235,6 +247,7 @@ export const ngModule = angular 'schema', 'fileName', 'placeholder', + 'showToolbar', ]) ) .component( diff --git a/app/portainer/views/auth/auth.html b/app/portainer/views/auth/auth.html index 09dadf050..2504141a7 100644 --- a/app/portainer/views/auth/auth.html +++ b/app/portainer/views/auth/auth.html @@ -4,7 +4,10 @@

- +
+ + +
diff --git a/app/portainer/views/init/admin/initAdmin.html b/app/portainer/views/init/admin/initAdmin.html index b5cfcfeb4..afff165b2 100644 --- a/app/portainer/views/init/admin/initAdmin.html +++ b/app/portainer/views/init/admin/initAdmin.html @@ -5,7 +5,10 @@
- +
+ + +
diff --git a/app/portainer/views/logout/logout.html b/app/portainer/views/logout/logout.html index fe9b2513d..95299d5d0 100644 --- a/app/portainer/views/logout/logout.html +++ b/app/portainer/views/logout/logout.html @@ -4,7 +4,10 @@
- +
+ + +
diff --git a/app/react-tools/test-mocks.ts b/app/react-tools/test-mocks.ts index 20fe7dee3..d9c7d273c 100644 --- a/app/react-tools/test-mocks.ts +++ b/app/react-tools/test-mocks.ts @@ -10,7 +10,7 @@ import { export function createMockUsers( count: number, - roles: Role | Role[] | ((id: UserId) => Role) = () => _.random(1, 3) + roles: Role | Role[] | ((id: UserId) => Role) ): User[] { return _.range(1, count + 1).map((value) => ({ Id: value, @@ -40,7 +40,14 @@ function getRoles( return roles; } - return roles[id]; + // Roles is an array + if (roles.length === 0) { + throw new Error('No roles provided'); + } + + // The number of roles is not necessarily the same length as the number of users + // so we need to distribute the roles evenly and consistently + return roles[(id - 1) % roles.length]; } export function createMockTeams(count: number): Team[] { diff --git a/app/react/components/CodeEditor/CodeEditor.module.css b/app/react/components/CodeEditor/CodeEditor.module.css index 2bf9cae88..6a02d3ed5 100644 --- a/app/react/components/CodeEditor/CodeEditor.module.css +++ b/app/react/components/CodeEditor/CodeEditor.module.css @@ -141,9 +141,11 @@ } .root :global(.cm-content[aria-readonly='true']) { - @apply bg-gray-3; - @apply th-dark:bg-gray-iron-10; - @apply th-highcontrast:bg-black; + /* make sure the bg has transparency, so that the selected text is visible */ + /* https://discuss.codemirror.net/t/how-do-i-get-selected-text-to-highlight/7115/2 */ + @apply bg-gray-3/50; + @apply th-dark:bg-gray-iron-10/50; + @apply th-highcontrast:bg-black/50; } .root :global(.cm-textfield) { diff --git a/app/react/components/CodeEditor/CodeEditor.tsx b/app/react/components/CodeEditor/CodeEditor.tsx index 3df9f4193..d841400f0 100644 --- a/app/react/components/CodeEditor/CodeEditor.tsx +++ b/app/react/components/CodeEditor/CodeEditor.tsx @@ -33,6 +33,7 @@ interface Props extends AutomationTestingProps { schema?: JSONSchema7; fileName?: string; placeholder?: string; + showToolbar?: boolean; } export const theme = createTheme({ @@ -75,6 +76,7 @@ export function CodeEditor({ 'data-cy': dataCy, fileName, placeholder, + showToolbar = true, }: Props) { const [isRollback, setIsRollback] = useState(false); @@ -94,38 +96,40 @@ export function CodeEditor({ return ( <> -
-
-
- {!!textTip && {textTip}} + {showToolbar && ( +
+
+
+ {!!textTip && {textTip}} +
+ {/* the copy button is in the file name header, when fileName is provided */} + {!fileName && ( +
+ + Copy + +
+ )}
- {/* the copy button is in the file name header, when fileName is provided */} - {!fileName && ( -
- - Copy - + {versions && ( +
+
+ +
)}
- {versions && ( -
-
- -
-
- )} -
+ )}
{fileName && ( diff --git a/app/react/components/CodeEditor/ShortcutsTooltip.tsx b/app/react/components/CodeEditor/ShortcutsTooltip.tsx new file mode 100644 index 000000000..e04cda2c8 --- /dev/null +++ b/app/react/components/CodeEditor/ShortcutsTooltip.tsx @@ -0,0 +1,52 @@ +import { BROWSER_OS_PLATFORM } from '@/react/constants'; + +import { Tooltip } from '@@/Tip/Tooltip'; + +const otherEditorConfig = { + tooltip: ( + <> +
Ctrl+F - Start searching
+
Ctrl+G - Find next
+
Ctrl+Shift+G - Find previous
+
Ctrl+Shift+F - Replace
+
Ctrl+Shift+R - Replace all
+
Alt+G - Jump to line
+
Persistent search:
+
Enter - Find next
+
Shift+Enter - Find previous
+ + ), + searchCmdLabel: 'Ctrl+F for search', +} as const; + +export const editorConfig = { + mac: { + tooltip: ( + <> +
Cmd+F - Start searching
+
Cmd+G - Find next
+
Cmd+Shift+G - Find previous
+
Cmd+Option+F - Replace
+
Cmd+Option+R - Replace all
+
Option+G - Jump to line
+
Persistent search:
+
Enter - Find next
+
Shift+Enter - Find previous
+ + ), + searchCmdLabel: 'Cmd+F for search', + }, + + lin: otherEditorConfig, + win: otherEditorConfig, +} as const; + +export function ShortcutsTooltip() { + return ( +
+ {editorConfig[BROWSER_OS_PLATFORM].searchCmdLabel} + + +
+ ); +} diff --git a/app/react/components/ExternalLink.tsx b/app/react/components/ExternalLink.tsx new file mode 100644 index 000000000..1bd839cad --- /dev/null +++ b/app/react/components/ExternalLink.tsx @@ -0,0 +1,32 @@ +import { ArrowUpRight } from 'lucide-react'; +import { PropsWithChildren } from 'react'; +import clsx from 'clsx'; + +import { AutomationTestingProps } from '@/types'; + +interface Props { + to: string; + className?: string; + showIcon?: boolean; +} + +export function ExternalLink({ + to, + className, + children, + showIcon = true, + 'data-cy': dataCy, +}: PropsWithChildren) { + return ( + + {children} + {showIcon && } + + ); +} diff --git a/app/react/components/FallbackImage.tsx b/app/react/components/FallbackImage.tsx index ee6956f24..eaa4f1272 100644 --- a/app/react/components/FallbackImage.tsx +++ b/app/react/components/FallbackImage.tsx @@ -27,5 +27,5 @@ export function FallbackImage({ src, fallbackIcon, alt, className }: Props) { } // fallback icon if there is an error loading the image - return <>{fallbackIcon}; + return
{fallbackIcon}
; } diff --git a/app/react/components/InformationPanel.tsx b/app/react/components/InformationPanel.tsx index b5c9dafc9..f25afadba 100644 --- a/app/react/components/InformationPanel.tsx +++ b/app/react/components/InformationPanel.tsx @@ -19,7 +19,7 @@ export function InformationPanel({ children, }: PropsWithChildren) { return ( - +
{title && ( diff --git a/app/react/components/ViewLoading/ViewLoading.tsx b/app/react/components/ViewLoading/ViewLoading.tsx index 5ade961bb..139c67637 100644 --- a/app/react/components/ViewLoading/ViewLoading.tsx +++ b/app/react/components/ViewLoading/ViewLoading.tsx @@ -1,7 +1,4 @@ import clsx from 'clsx'; -import { Settings } from 'lucide-react'; - -import { Icon } from '@@/Icon'; import styles from './ViewLoading.module.css'; @@ -18,12 +15,7 @@ export function ViewLoading({ message }: Props) {
- {message && ( - - {message} - - - )} + {message && {message}}
); } diff --git a/app/react/components/WebEditorForm.tsx b/app/react/components/WebEditorForm.tsx index 75031a454..84c37c0df 100644 --- a/app/react/components/WebEditorForm.tsx +++ b/app/react/components/WebEditorForm.tsx @@ -8,55 +8,14 @@ import { import { useTransitionHook } from '@uirouter/react'; import { JSONSchema7 } from 'json-schema'; -import { BROWSER_OS_PLATFORM } from '@/react/constants'; - import { CodeEditor } from '@@/CodeEditor'; -import { Tooltip } from '@@/Tip/Tooltip'; import { FormSectionTitle } from './form-components/FormSectionTitle'; import { FormError } from './form-components/FormError'; import { confirm } from './modals/confirm'; import { ModalType } from './modals'; import { buildConfirmButton } from './modals/utils'; - -const otherEditorConfig = { - tooltip: ( - <> -
Ctrl+F - Start searching
-
Ctrl+G - Find next
-
Ctrl+Shift+G - Find previous
-
Ctrl+Shift+F - Replace
-
Ctrl+Shift+R - Replace all
-
Alt+G - Jump to line
-
Persistent search:
-
Enter - Find next
-
Shift+Enter - Find previous
- - ), - searchCmdLabel: 'Ctrl+F for search', -} as const; - -export const editorConfig = { - mac: { - tooltip: ( - <> -
Cmd+F - Start searching
-
Cmd+G - Find next
-
Cmd+Shift+G - Find previous
-
Cmd+Option+F - Replace
-
Cmd+Option+R - Replace all
-
Option+G - Jump to line
-
Persistent search:
-
Enter - Find next
-
Shift+Enter - Find previous
- - ), - searchCmdLabel: 'Cmd+F for search', - }, - - lin: otherEditorConfig, - win: otherEditorConfig, -} as const; +import { ShortcutsTooltip } from './CodeEditor/ShortcutsTooltip'; type CodeEditorProps = ComponentProps; @@ -69,7 +28,7 @@ interface Props extends CodeEditorProps { export function WebEditorForm({ id, - titleContent = '', + titleContent = 'Web editor', hideTitle, children, error, @@ -81,10 +40,7 @@ export function WebEditorForm({
{!hideTitle && ( - <> - - {titleContent ?? null} - + {titleContent ?? null} )} {children && (
@@ -111,15 +67,11 @@ export function WebEditorForm({ ); } -function DefaultTitle({ id }: { id: string }) { +function DefaultTitle({ id, children }: { id: string; children?: ReactNode }) { return ( - Web editor -
- {editorConfig[BROWSER_OS_PLATFORM].searchCmdLabel} - - -
+ {children} +
); } diff --git a/app/react/components/datatables/NestedDatatable.tsx b/app/react/components/datatables/NestedDatatable.tsx index dfa7f6d54..17081e166 100644 --- a/app/react/components/datatables/NestedDatatable.tsx +++ b/app/react/components/datatables/NestedDatatable.tsx @@ -25,7 +25,7 @@ interface Props extends AutomationTestingProps { initialTableState?: Partial; isLoading?: boolean; initialSortBy?: BasicTableSettings['sortBy']; - + enablePagination?: boolean; /** * keyword to filter by */ @@ -42,6 +42,7 @@ export function NestedDatatable({ initialTableState = {}, isLoading, initialSortBy, + enablePagination = true, search, 'data-cy': dataCy, 'aria-label': ariaLabel, @@ -65,7 +66,7 @@ export function NestedDatatable({ getCoreRowModel: getCoreRowModel(), getFilteredRowModel: getFilteredRowModel(), getSortedRowModel: getSortedRowModel(), - getPaginationRowModel: getPaginationRowModel(), + ...(enablePagination && { getPaginationRowModel: getPaginationRowModel() }), }); return ( diff --git a/app/react/components/datatables/index.ts b/app/react/components/datatables/index.ts index 809efc23b..3ab420889 100644 --- a/app/react/components/datatables/index.ts +++ b/app/react/components/datatables/index.ts @@ -11,3 +11,4 @@ export { TableHeaderRow } from './TableHeaderRow'; export { TableRow } from './TableRow'; export { TableContent } from './TableContent'; export { TableFooter } from './TableFooter'; +export { TableSettingsMenuAutoRefresh } from './TableSettingsMenuAutoRefresh'; diff --git a/app/react/components/form-components/PortainerSelect.tsx b/app/react/components/form-components/PortainerSelect.tsx index 9ddf234da..6800d0013 100644 --- a/app/react/components/form-components/PortainerSelect.tsx +++ b/app/react/components/form-components/PortainerSelect.tsx @@ -5,15 +5,25 @@ import { } from 'react-select'; import _ from 'lodash'; import { AriaAttributes } from 'react'; +import { FilterOptionOption } from 'react-select/dist/declarations/src/filters'; import { AutomationTestingProps } from '@/types'; -import { Select as ReactSelect } from '@@/form-components/ReactSelect'; +import { + Creatable, + Select as ReactSelect, +} from '@@/form-components/ReactSelect'; export interface Option { value: TValue; label: string; disabled?: boolean; + [key: string]: unknown; +} + +export interface GroupOption { + label: string; + options: Option[]; } type Options = OptionsOrGroups< @@ -21,7 +31,7 @@ type Options = OptionsOrGroups< GroupBase> >; -interface SharedProps +interface SharedProps extends AutomationTestingProps, Pick { name?: string; @@ -32,9 +42,14 @@ interface SharedProps bindToBody?: boolean; isLoading?: boolean; noOptionsMessage?: () => string; + loadingMessage?: () => string; + filterOption?: ( + option: FilterOptionOption>, + rawInput: string + ) => boolean; } -interface MultiProps extends SharedProps { +interface MultiProps extends SharedProps { value: readonly TValue[]; onChange(value: TValue[]): void; options: Options; @@ -44,9 +59,12 @@ interface MultiProps extends SharedProps { true, GroupBase> >; + formatCreateLabel?: (input: string) => string; + onCreateOption?: (input: string) => void; + isCreatable?: boolean; } -interface SingleProps extends SharedProps { +interface SingleProps extends SharedProps { value: TValue; onChange(value: TValue | null): void; options: Options; @@ -58,9 +76,13 @@ interface SingleProps extends SharedProps { >; } -type Props = MultiProps | SingleProps; +export type PortainerSelectProps = + | MultiProps + | SingleProps; -export function PortainerSelect(props: Props) { +export function PortainerSelect( + props: PortainerSelectProps +) { return isMultiProps(props) ? ( // eslint-disable-next-line react/jsx-props-no-spreading @@ -71,7 +93,7 @@ export function PortainerSelect(props: Props) { } function isMultiProps( - props: Props + props: PortainerSelectProps ): props is MultiProps { return 'isMulti' in props && !!props.isMulti; } @@ -87,9 +109,11 @@ export function SingleSelect({ placeholder, isClearable, bindToBody, + filterOption, components, isLoading, noOptionsMessage, + loadingMessage, isMulti, ...aria }: SingleProps) { @@ -116,9 +140,11 @@ export function SingleSelect({ placeholder={placeholder} isDisabled={disabled} menuPortalTarget={bindToBody ? document.body : undefined} + filterOption={filterOption} components={components} isLoading={isLoading} noOptionsMessage={noOptionsMessage} + loadingMessage={loadingMessage} // eslint-disable-next-line react/jsx-props-no-spreading {...aria} /> @@ -159,14 +185,20 @@ export function MultiSelect({ disabled, isClearable, bindToBody, + filterOption, components, isLoading, noOptionsMessage, + loadingMessage, + formatCreateLabel, + onCreateOption, + isCreatable, ...aria }: Omit, 'isMulti'>) { const selectedOptions = findSelectedOptions(options, value); + const SelectComponent = isCreatable ? Creatable : ReactSelect; return ( - ({ placeholder={placeholder} isDisabled={disabled} menuPortalTarget={bindToBody ? document.body : undefined} + filterOption={filterOption} components={components} isLoading={isLoading} noOptionsMessage={noOptionsMessage} + loadingMessage={loadingMessage} + formatCreateLabel={formatCreateLabel} + onCreateOption={onCreateOption} // eslint-disable-next-line react/jsx-props-no-spreading {...aria} /> diff --git a/app/react/components/form-components/ReactSelect.tsx b/app/react/components/form-components/ReactSelect.tsx index a9f4e6282..c7ea47366 100644 --- a/app/react/components/form-components/ReactSelect.tsx +++ b/app/react/components/form-components/ReactSelect.tsx @@ -5,12 +5,14 @@ import ReactSelectAsync, { AsyncProps as ReactSelectAsyncProps, } from 'react-select/async'; import ReactSelect, { + components, GroupBase, + InputProps, OptionsOrGroups, Props as ReactSelectProps, } from 'react-select'; import clsx from 'clsx'; -import { RefAttributes, useMemo } from 'react'; +import { RefAttributes, useMemo, useCallback } from 'react'; import ReactSelectType from 'react-select/dist/declarations/src/Select'; import './ReactSelect.css'; @@ -52,6 +54,9 @@ type Props< | CreatableProps | RegularProps; +/** + * DO NOT use this component directly, use PortainerSelect instead. + */ export function Select< Option = DefaultOption, IsMulti extends boolean = false, @@ -68,24 +73,37 @@ export function Select< id: string; }) { const Component = isCreatable ? ReactSelectCreatable : ReactSelect; - const { options } = props; + const { + options, + 'data-cy': dataCy, + components: componentsProp, + ...rest + } = props; + + const memoizedComponents = useMemoizedSelectComponents< + Option, + IsMulti, + Group + >(dataCy, componentsProp); if ((options?.length || 0) > 1000) { return ( ); } return ( ); } @@ -94,13 +112,25 @@ export function Creatable< Option = DefaultOption, IsMulti extends boolean = false, Group extends GroupBase