diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 75414fa04..4324bf5a8 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -94,11 +94,6 @@ 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.32.0' - - '2.31.3' - - '2.31.2' - - '2.31.1' - - '2.31.0' - '2.30.1' - '2.30.0' - '2.29.2' @@ -106,9 +101,6 @@ body: - '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 0722c0b2e..f6035f298 100644 --- a/api/cli/cli.go +++ b/api/cli/cli.go @@ -61,8 +61,6 @@ 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 818025bdf..6261efbd9 100644 --- a/api/cmd/portainer/main.go +++ b/api/cmd/portainer/main.go @@ -52,7 +52,6 @@ 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" @@ -331,18 +330,6 @@ 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 { @@ -383,8 +370,7 @@ func buildServer(flags *portainer.CLIFlags) portainer.Server { gitService := git.NewService(shutdownCtx) - // Setting insecureSkipVerify to true to preserve the old behaviour. - openAMTService := openamt.NewService(true) + openAMTService := openamt.NewService() cryptoService := &crypto.Service{} @@ -451,7 +437,7 @@ func buildServer(flags *portainer.CLIFlags) portainer.Server { snapshotService.Start() - proxyManager.NewProxyFactory(dataStore, signatureService, reverseTunnelService, dockerClientFactory, kubernetesClientFactory, kubernetesTokenCacheManager, gitService, snapshotService, jwtService) + proxyManager.NewProxyFactory(dataStore, signatureService, reverseTunnelService, dockerClientFactory, kubernetesClientFactory, kubernetesTokenCacheManager, gitService, snapshotService) helmPackageManager, err := initHelmPackageManager() if err != nil { @@ -559,7 +545,6 @@ 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, @@ -593,7 +578,6 @@ 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 32a1b55c3..a0db7f4e0 100644 --- a/api/database/boltdb/db.go +++ b/api/database/boltdb/db.go @@ -138,8 +138,6 @@ 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 18839b60f..04af70b02 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(predicates ...func(T) bool) ([]T, error) + ReadAll() ([]T, error) Update(ID I, element *T) error Delete(ID I) error } @@ -56,13 +56,12 @@ func (service BaseDataService[T, I]) Exists(ID I) (bool, error) { return exists, err } -// ReadAll retrieves all the elements that satisfy all the provided predicates. -func (service BaseDataService[T, I]) ReadAll(predicates ...func(T) bool) ([]T, error) { +func (service BaseDataService[T, I]) ReadAll() ([]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(predicates...) + collection, err = service.Tx(tx).ReadAll() return err }) diff --git a/api/dataservices/base_test.go b/api/dataservices/base_test.go deleted file mode 100644 index e97a09963..000000000 --- a/api/dataservices/base_test.go +++ /dev/null @@ -1,92 +0,0 @@ -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 5d7e7eee0..d9915b64c 100644 --- a/api/dataservices/base_tx.go +++ b/api/dataservices/base_tx.go @@ -34,32 +34,13 @@ func (service BaseDataServiceTx[T, I]) Exists(ID I) (bool, error) { return service.Tx.KeyExists(service.Bucket, identifier) } -// ReadAll retrieves all the elements that satisfy all the provided predicates. -func (service BaseDataServiceTx[T, I]) ReadAll(predicates ...func(T) bool) ([]T, error) { +func (service BaseDataServiceTx[T, I]) ReadAll() ([]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), - FilterFn(&collection, filterFn), + AppendFn(&collection), ) } diff --git a/api/dataservices/edgegroup/tx.go b/api/dataservices/edgegroup/tx.go index 2fba688a6..19f37e011 100644 --- a/api/dataservices/edgegroup/tx.go +++ b/api/dataservices/edgegroup/tx.go @@ -17,29 +17,11 @@ func (service ServiceTx) UpdateEdgeGroupFunc(ID portainer.EdgeGroupID, updateFun } func (service ServiceTx) Create(group *portainer.EdgeGroup) error { - es := group.Endpoints - group.Endpoints = nil // Clear deprecated field - - err := service.Tx.CreateObject( + return service.Tx.CreateObject( BucketName, func(id uint64) (int, any) { group.ID = portainer.EdgeGroupID(id) return int(group.ID), group }, ) - - group.Endpoints = es // Restore endpoints after create - - return err -} - -func (service ServiceTx) Update(ID portainer.EdgeGroupID, group *portainer.EdgeGroup) error { - es := group.Endpoints - group.Endpoints = nil // Clear deprecated field - - err := service.BaseDataServiceTx.Update(ID, group) - - group.Endpoints = es // Restore endpoints after update - - return err } diff --git a/api/dataservices/endpointrelation/endpointrelation.go b/api/dataservices/endpointrelation/endpointrelation.go index 556a046bb..a81c258b9 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.UpdateTx(func(tx portainer.Transaction) error { + return service.connection.ViewTx(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.UpdateTx(func(tx portainer.Transaction) error { + return service.connection.ViewTx(func(tx portainer.Transaction) error { return service.Tx(tx).RemoveEndpointRelationsForEdgeStack(endpointIDs, edgeStackID) }) } diff --git a/api/datastore/migrate_data.go b/api/datastore/migrate_data.go index 2b53bbb9c..409936db8 100644 --- a/api/datastore/migrate_data.go +++ b/api/datastore/migrate_data.go @@ -85,7 +85,6 @@ func (store *Store) newMigratorParameters(version *models.Version, flags *portai EdgeStackService: store.EdgeStackService, EdgeStackStatusService: store.EdgeStackStatusService, EdgeJobService: store.EdgeJobService, - EdgeGroupService: store.EdgeGroupService, TunnelServerService: store.TunnelServerService, PendingActionsService: store.PendingActionsService, } diff --git a/api/datastore/migrator/migrate_2_32_0.go b/api/datastore/migrator/migrate_2_32_0.go deleted file mode 100644 index c32a63cad..000000000 --- a/api/datastore/migrator/migrate_2_32_0.go +++ /dev/null @@ -1,33 +0,0 @@ -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/migrate_2_33_0.go b/api/datastore/migrator/migrate_2_33_0.go deleted file mode 100644 index f000a780a..000000000 --- a/api/datastore/migrator/migrate_2_33_0.go +++ /dev/null @@ -1,23 +0,0 @@ -package migrator - -import ( - "github.com/portainer/portainer/api/roar" -) - -func (m *Migrator) migrateEdgeGroupEndpointsToRoars_2_33_0() error { - egs, err := m.edgeGroupService.ReadAll() - if err != nil { - return err - } - - for _, eg := range egs { - eg.EndpointIDs = roar.FromSlice(eg.Endpoints) - eg.Endpoints = nil - - if err := m.edgeGroupService.Update(eg.ID, &eg); err != nil { - return err - } - } - - return nil -} diff --git a/api/datastore/migrator/migrator.go b/api/datastore/migrator/migrator.go index df27cc0cd..992dd0b9d 100644 --- a/api/datastore/migrator/migrator.go +++ b/api/datastore/migrator/migrator.go @@ -6,7 +6,6 @@ import ( 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/edgegroup" "github.com/portainer/portainer/api/dataservices/edgejob" "github.com/portainer/portainer/api/dataservices/edgestack" "github.com/portainer/portainer/api/dataservices/edgestackstatus" @@ -61,7 +60,6 @@ type ( edgeStackService *edgestack.Service edgeStackStatusService *edgestackstatus.Service edgeJobService *edgejob.Service - edgeGroupService *edgegroup.Service TunnelServerService *tunnelserver.Service pendingActionsService *pendingactions.Service } @@ -91,7 +89,6 @@ type ( EdgeStackService *edgestack.Service EdgeStackStatusService *edgestackstatus.Service EdgeJobService *edgejob.Service - EdgeGroupService *edgegroup.Service TunnelServerService *tunnelserver.Service PendingActionsService *pendingactions.Service } @@ -123,13 +120,11 @@ func NewMigrator(parameters *MigratorParameters) *Migrator { edgeStackService: parameters.EdgeStackService, edgeStackStatusService: parameters.EdgeStackStatusService, edgeJobService: parameters.EdgeJobService, - edgeGroupService: parameters.EdgeGroupService, TunnelServerService: parameters.TunnelServerService, pendingActionsService: parameters.PendingActionsService, } migrator.initMigrations() - return migrator } @@ -254,10 +249,6 @@ func (m *Migrator) initMigrations() { m.addMigrations("2.31.0", m.migrateEdgeStacksStatuses_2_31_0) - m.addMigrations("2.32.0", m.addEndpointRelationForEdgeAgents_2_32_0) - - m.addMigrations("2.33.0", m.migrateEdgeGroupEndpointsToRoars_2_33_0) - // Add new migrations above... // One function per migration, each versions migration funcs in the same file. } diff --git a/api/datastore/test_data/output_24_to_latest.json b/api/datastore/test_data/output_24_to_latest.json index 5e8b0eefa..41a1b49df 100644 --- a/api/datastore/test_data/output_24_to_latest.json +++ b/api/datastore/test_data/output_24_to_latest.json @@ -121,10 +121,6 @@ "Ecr": { "Region": "" }, - "Github": { - "OrganisationName": "", - "UseOrganisation": false - }, "Gitlab": { "InstanceURL": "", "ProjectId": 0, @@ -615,7 +611,7 @@ "RequiredPasswordLength": 12 }, "KubeconfigExpiry": "0", - "KubectlShellImage": "portainer/kubectl-shell:2.32.0", + "KubectlShellImage": "portainer/kubectl-shell:2.31.0", "LDAPSettings": { "AnonymousMode": true, "AutoCreateUsers": true, @@ -780,7 +776,6 @@ "ImageCount": 9, "IsPodman": false, "NodeCount": 0, - "PerformanceMetrics": null, "RunningContainerCount": 5, "ServiceCount": 0, "StackCount": 2, @@ -944,7 +939,7 @@ } ], "version": { - "VERSION": "{\"SchemaVersion\":\"2.32.0\",\"MigratorCount\":1,\"Edition\":1,\"InstanceID\":\"463d5c47-0ea5-4aca-85b1-405ceefee254\"}" + "VERSION": "{\"SchemaVersion\":\"2.31.0\",\"MigratorCount\":1,\"Edition\":1,\"InstanceID\":\"463d5c47-0ea5-4aca-85b1-405ceefee254\"}" }, "webhooks": null } \ No newline at end of file diff --git a/api/git/azure_integration_test.go b/api/git/azure_integration_test.go index 5de18b303..3e297a129 100644 --- a/api/git/azure_integration_test.go +++ b/api/git/azure_integration_test.go @@ -58,15 +58,7 @@ func TestService_ClonePublicRepository_Azure(t *testing.T) { t.Run(tt.name, func(t *testing.T) { dst := t.TempDir() repositoryUrl := fmt.Sprintf(tt.args.repositoryURLFormat, tt.args.password) - err := service.CloneRepository( - dst, - repositoryUrl, - tt.args.referenceName, - "", - "", - gittypes.GitCredentialAuthType_Basic, - false, - ) + err := service.CloneRepository(dst, repositoryUrl, tt.args.referenceName, "", "", false) assert.NoError(t, err) assert.FileExists(t, filepath.Join(dst, "README.md")) }) @@ -81,15 +73,7 @@ func TestService_ClonePrivateRepository_Azure(t *testing.T) { dst := t.TempDir() - err := service.CloneRepository( - dst, - privateAzureRepoURL, - "refs/heads/main", - "", - pat, - gittypes.GitCredentialAuthType_Basic, - false, - ) + err := service.CloneRepository(dst, privateAzureRepoURL, "refs/heads/main", "", pat, false) assert.NoError(t, err) assert.FileExists(t, filepath.Join(dst, "README.md")) } @@ -100,14 +84,7 @@ func TestService_LatestCommitID_Azure(t *testing.T) { pat := getRequiredValue(t, "AZURE_DEVOPS_PAT") service := NewService(context.TODO()) - id, err := service.LatestCommitID( - privateAzureRepoURL, - "refs/heads/main", - "", - pat, - gittypes.GitCredentialAuthType_Basic, - false, - ) + id, err := service.LatestCommitID(privateAzureRepoURL, "refs/heads/main", "", pat, false) assert.NoError(t, err) assert.NotEmpty(t, id, "cannot guarantee commit id, but it should be not empty") } @@ -119,14 +96,7 @@ func TestService_ListRefs_Azure(t *testing.T) { username := getRequiredValue(t, "AZURE_DEVOPS_USERNAME") service := NewService(context.TODO()) - refs, err := service.ListRefs( - privateAzureRepoURL, - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - ) + refs, err := service.ListRefs(privateAzureRepoURL, username, accessToken, false, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(refs), 1) } @@ -138,8 +108,8 @@ func TestService_ListRefs_Azure_Concurrently(t *testing.T) { username := getRequiredValue(t, "AZURE_DEVOPS_USERNAME") service := newService(context.TODO(), repositoryCacheSize, 200*time.Millisecond) - go service.ListRefs(privateAzureRepoURL, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) - service.ListRefs(privateAzureRepoURL, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) + go service.ListRefs(privateAzureRepoURL, username, accessToken, false, false) + service.ListRefs(privateAzureRepoURL, username, accessToken, false, false) time.Sleep(2 * time.Second) } @@ -277,17 +247,7 @@ func TestService_ListFiles_Azure(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - paths, err := service.ListFiles( - tt.args.repositoryUrl, - tt.args.referenceName, - tt.args.username, - tt.args.password, - gittypes.GitCredentialAuthType_Basic, - false, - false, - tt.extensions, - false, - ) + paths, err := service.ListFiles(tt.args.repositoryUrl, tt.args.referenceName, tt.args.username, tt.args.password, false, false, tt.extensions, false) if tt.expect.shouldFail { assert.Error(t, err) if tt.expect.err != nil { @@ -310,28 +270,8 @@ func TestService_ListFiles_Azure_Concurrently(t *testing.T) { username := getRequiredValue(t, "AZURE_DEVOPS_USERNAME") service := newService(context.TODO(), repositoryCacheSize, 200*time.Millisecond) - go service.ListFiles( - privateAzureRepoURL, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) - service.ListFiles( - privateAzureRepoURL, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + go service.ListFiles(privateAzureRepoURL, "refs/heads/main", username, accessToken, false, false, []string{}, false) + service.ListFiles(privateAzureRepoURL, "refs/heads/main", username, accessToken, false, false, []string{}, false) time.Sleep(2 * time.Second) } diff --git a/api/git/backup.go b/api/git/backup.go index 6928f521a..286b51876 100644 --- a/api/git/backup.go +++ b/api/git/backup.go @@ -19,7 +19,6 @@ type CloneOptions struct { ReferenceName string Username string Password string - AuthType gittypes.GitCredentialAuthType // TLSSkipVerify skips SSL verification when cloning the Git repository TLSSkipVerify bool `example:"false"` } @@ -43,15 +42,7 @@ func CloneWithBackup(gitService portainer.GitService, fileService portainer.File cleanUp = true - if err := gitService.CloneRepository( - options.ProjectPath, - options.URL, - options.ReferenceName, - options.Username, - options.Password, - options.AuthType, - options.TLSSkipVerify, - ); err != nil { + if err := gitService.CloneRepository(options.ProjectPath, options.URL, options.ReferenceName, options.Username, options.Password, options.TLSSkipVerify); err != nil { cleanUp = false if err := filesystem.MoveDirectory(backupProjectPath, options.ProjectPath, false); err != nil { log.Warn().Err(err).Msg("failed restoring backup folder") diff --git a/api/git/git.go b/api/git/git.go index cf0c9f478..6c2835815 100644 --- a/api/git/git.go +++ b/api/git/git.go @@ -7,14 +7,12 @@ import ( "strings" gittypes "github.com/portainer/portainer/api/git/types" - "github.com/rs/zerolog/log" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/object" - "github.com/go-git/go-git/v5/plumbing/transport" githttp "github.com/go-git/go-git/v5/plumbing/transport/http" "github.com/go-git/go-git/v5/storage/memory" "github.com/pkg/errors" @@ -35,7 +33,7 @@ func (c *gitClient) download(ctx context.Context, dst string, opt cloneOption) e URL: opt.repositoryUrl, Depth: opt.depth, InsecureSkipTLS: opt.tlsSkipVerify, - Auth: getAuth(opt.authType, opt.username, opt.password), + Auth: getAuth(opt.username, opt.password), Tags: git.NoTags, } @@ -53,10 +51,7 @@ func (c *gitClient) download(ctx context.Context, dst string, opt cloneOption) e } if !c.preserveGitDirectory { - err := os.RemoveAll(filepath.Join(dst, ".git")) - if err != nil { - log.Error().Err(err).Msg("failed to remove .git directory") - } + os.RemoveAll(filepath.Join(dst, ".git")) } return nil @@ -69,7 +64,7 @@ func (c *gitClient) latestCommitID(ctx context.Context, opt fetchOption) (string }) listOptions := &git.ListOptions{ - Auth: getAuth(opt.authType, opt.username, opt.password), + Auth: getAuth(opt.username, opt.password), InsecureSkipTLS: opt.tlsSkipVerify, } @@ -99,23 +94,7 @@ func (c *gitClient) latestCommitID(ctx context.Context, opt fetchOption) (string return "", errors.Errorf("could not find ref %q in the repository", opt.referenceName) } -func getAuth(authType gittypes.GitCredentialAuthType, username, password string) transport.AuthMethod { - if password == "" { - return nil - } - - switch authType { - case gittypes.GitCredentialAuthType_Basic: - return getBasicAuth(username, password) - case gittypes.GitCredentialAuthType_Token: - return getTokenAuth(password) - default: - log.Warn().Msg("unknown git credentials authorization type, defaulting to None") - return nil - } -} - -func getBasicAuth(username, password string) *githttp.BasicAuth { +func getAuth(username, password string) *githttp.BasicAuth { if password != "" { if username == "" { username = "token" @@ -129,15 +108,6 @@ func getBasicAuth(username, password string) *githttp.BasicAuth { return nil } -func getTokenAuth(token string) *githttp.TokenAuth { - if token != "" { - return &githttp.TokenAuth{ - Token: token, - } - } - return nil -} - func (c *gitClient) listRefs(ctx context.Context, opt baseOption) ([]string, error) { rem := git.NewRemote(memory.NewStorage(), &config.RemoteConfig{ Name: "origin", @@ -145,7 +115,7 @@ func (c *gitClient) listRefs(ctx context.Context, opt baseOption) ([]string, err }) listOptions := &git.ListOptions{ - Auth: getAuth(opt.authType, opt.username, opt.password), + Auth: getAuth(opt.username, opt.password), InsecureSkipTLS: opt.tlsSkipVerify, } @@ -173,7 +143,7 @@ func (c *gitClient) listFiles(ctx context.Context, opt fetchOption) ([]string, e Depth: 1, SingleBranch: true, ReferenceName: plumbing.ReferenceName(opt.referenceName), - Auth: getAuth(opt.authType, opt.username, opt.password), + Auth: getAuth(opt.username, opt.password), InsecureSkipTLS: opt.tlsSkipVerify, Tags: git.NoTags, } diff --git a/api/git/git_integration_test.go b/api/git/git_integration_test.go index 6cb10253a..add10afd6 100644 --- a/api/git/git_integration_test.go +++ b/api/git/git_integration_test.go @@ -2,8 +2,6 @@ package git import ( "context" - "net/http" - "net/http/httptest" "path/filepath" "testing" "time" @@ -26,15 +24,7 @@ func TestService_ClonePrivateRepository_GitHub(t *testing.T) { dst := t.TempDir() repositoryUrl := privateGitRepoURL - err := service.CloneRepository( - dst, - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - ) + err := service.CloneRepository(dst, repositoryUrl, "refs/heads/main", username, accessToken, false) assert.NoError(t, err) assert.FileExists(t, filepath.Join(dst, "README.md")) } @@ -47,14 +37,7 @@ func TestService_LatestCommitID_GitHub(t *testing.T) { service := newService(context.TODO(), 0, 0) repositoryUrl := privateGitRepoURL - id, err := service.LatestCommitID( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - ) + id, err := service.LatestCommitID(repositoryUrl, "refs/heads/main", username, accessToken, false) assert.NoError(t, err) assert.NotEmpty(t, id, "cannot guarantee commit id, but it should be not empty") } @@ -67,7 +50,7 @@ func TestService_ListRefs_GitHub(t *testing.T) { service := newService(context.TODO(), 0, 0) repositoryUrl := privateGitRepoURL - refs, err := service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) + refs, err := service.ListRefs(repositoryUrl, username, accessToken, false, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(refs), 1) } @@ -80,8 +63,8 @@ func TestService_ListRefs_Github_Concurrently(t *testing.T) { service := newService(context.TODO(), repositoryCacheSize, 200*time.Millisecond) repositoryUrl := privateGitRepoURL - go service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) - service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) + go service.ListRefs(repositoryUrl, username, accessToken, false, false) + service.ListRefs(repositoryUrl, username, accessToken, false, false) time.Sleep(2 * time.Second) } @@ -219,17 +202,7 @@ func TestService_ListFiles_GitHub(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - paths, err := service.ListFiles( - tt.args.repositoryUrl, - tt.args.referenceName, - tt.args.username, - tt.args.password, - gittypes.GitCredentialAuthType_Basic, - false, - false, - tt.extensions, - false, - ) + paths, err := service.ListFiles(tt.args.repositoryUrl, tt.args.referenceName, tt.args.username, tt.args.password, false, false, tt.extensions, false) if tt.expect.shouldFail { assert.Error(t, err) if tt.expect.err != nil { @@ -253,28 +226,8 @@ func TestService_ListFiles_Github_Concurrently(t *testing.T) { username := getRequiredValue(t, "GITHUB_USERNAME") service := newService(context.TODO(), repositoryCacheSize, 200*time.Millisecond) - go service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) - service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + go service.ListFiles(repositoryUrl, "refs/heads/main", username, accessToken, false, false, []string{}, false) + service.ListFiles(repositoryUrl, "refs/heads/main", username, accessToken, false, false, []string{}, false) time.Sleep(2 * time.Second) } @@ -287,18 +240,8 @@ func TestService_purgeCache_Github(t *testing.T) { username := getRequiredValue(t, "GITHUB_USERNAME") service := NewService(context.TODO()) - service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) - service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + service.ListRefs(repositoryUrl, username, accessToken, false, false) + service.ListFiles(repositoryUrl, "refs/heads/main", username, accessToken, false, false, []string{}, false) assert.Equal(t, 1, service.repoRefCache.Len()) assert.Equal(t, 1, service.repoFileCache.Len()) @@ -318,18 +261,8 @@ func TestService_purgeCacheByTTL_Github(t *testing.T) { // 40*timeout is designed for giving enough time for ListRefs and ListFiles to cache the result service := newService(context.TODO(), 2, 40*timeout) - service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) - service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + service.ListRefs(repositoryUrl, username, accessToken, false, false) + service.ListFiles(repositoryUrl, "refs/heads/main", username, accessToken, false, false, []string{}, false) assert.Equal(t, 1, service.repoRefCache.Len()) assert.Equal(t, 1, service.repoFileCache.Len()) @@ -360,12 +293,12 @@ func TestService_HardRefresh_ListRefs_GitHub(t *testing.T) { service := newService(context.TODO(), 2, 0) repositoryUrl := privateGitRepoURL - refs, err := service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) + refs, err := service.ListRefs(repositoryUrl, username, accessToken, false, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(refs), 1) assert.Equal(t, 1, service.repoRefCache.Len()) - _, err = service.ListRefs(repositoryUrl, username, "fake-token", gittypes.GitCredentialAuthType_Basic, false, false) + _, err = service.ListRefs(repositoryUrl, username, "fake-token", false, false) assert.Error(t, err) assert.Equal(t, 1, service.repoRefCache.Len()) } @@ -378,46 +311,26 @@ func TestService_HardRefresh_ListRefs_And_RemoveAllCaches_GitHub(t *testing.T) { service := newService(context.TODO(), 2, 0) repositoryUrl := privateGitRepoURL - refs, err := service.ListRefs(repositoryUrl, username, accessToken, gittypes.GitCredentialAuthType_Basic, false, false) + refs, err := service.ListRefs(repositoryUrl, username, accessToken, false, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(refs), 1) assert.Equal(t, 1, service.repoRefCache.Len()) - files, err := service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + files, err := service.ListFiles(repositoryUrl, "refs/heads/main", username, accessToken, false, false, []string{}, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(files), 1) assert.Equal(t, 1, service.repoFileCache.Len()) - files, err = service.ListFiles( - repositoryUrl, - "refs/heads/test", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + files, err = service.ListFiles(repositoryUrl, "refs/heads/test", username, accessToken, false, false, []string{}, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(files), 1) assert.Equal(t, 2, service.repoFileCache.Len()) - _, err = service.ListRefs(repositoryUrl, username, "fake-token", gittypes.GitCredentialAuthType_Basic, false, false) + _, err = service.ListRefs(repositoryUrl, username, "fake-token", false, false) assert.Error(t, err) assert.Equal(t, 1, service.repoRefCache.Len()) - _, err = service.ListRefs(repositoryUrl, username, "fake-token", gittypes.GitCredentialAuthType_Basic, true, false) + _, err = service.ListRefs(repositoryUrl, username, "fake-token", true, false) assert.Error(t, err) assert.Equal(t, 1, service.repoRefCache.Len()) // The relevant file caches should be removed too @@ -431,72 +344,12 @@ func TestService_HardRefresh_ListFiles_GitHub(t *testing.T) { accessToken := getRequiredValue(t, "GITHUB_PAT") username := getRequiredValue(t, "GITHUB_USERNAME") repositoryUrl := privateGitRepoURL - files, err := service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{}, - false, - ) + files, err := service.ListFiles(repositoryUrl, "refs/heads/main", username, accessToken, false, false, []string{}, false) assert.NoError(t, err) assert.GreaterOrEqual(t, len(files), 1) assert.Equal(t, 1, service.repoFileCache.Len()) - _, err = service.ListFiles( - repositoryUrl, - "refs/heads/main", - username, - "fake-token", - gittypes.GitCredentialAuthType_Basic, - false, - true, - []string{}, - false, - ) + _, err = service.ListFiles(repositoryUrl, "refs/heads/main", username, "fake-token", false, true, []string{}, false) assert.Error(t, err) assert.Equal(t, 0, service.repoFileCache.Len()) } - -func TestService_CloneRepository_TokenAuth(t *testing.T) { - ensureIntegrationTest(t) - - service := newService(context.TODO(), 2, 0) - var requests []*http.Request - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requests = append(requests, r) - })) - accessToken := "test_access_token" - username := "test_username" - repositoryUrl := testServer.URL - - // Since we aren't hitting a real git server we ignore the error - _ = service.CloneRepository( - "test_dir", - repositoryUrl, - "refs/heads/main", - username, - accessToken, - gittypes.GitCredentialAuthType_Token, - false, - ) - - testServer.Close() - - if len(requests) != 1 { - t.Fatalf("expected 1 request sent but got %d", len(requests)) - } - - gotAuthHeader := requests[0].Header.Get("Authorization") - if gotAuthHeader == "" { - t.Fatal("no Authorization header in git request") - } - - expectedAuthHeader := "Bearer test_access_token" - if gotAuthHeader != expectedAuthHeader { - t.Fatalf("expected Authorization header %q but got %q", expectedAuthHeader, gotAuthHeader) - } -} diff --git a/api/git/git_test.go b/api/git/git_test.go index fc0db196d..81efa2688 100644 --- a/api/git/git_test.go +++ b/api/git/git_test.go @@ -38,7 +38,7 @@ func Test_ClonePublicRepository_Shallow(t *testing.T) { dir := t.TempDir() t.Logf("Cloning into %s", dir) - err := service.CloneRepository(dir, repositoryURL, referenceName, "", "", gittypes.GitCredentialAuthType_Basic, false) + err := service.CloneRepository(dir, repositoryURL, referenceName, "", "", false) assert.NoError(t, err) assert.Equal(t, 1, getCommitHistoryLength(t, err, dir), "cloned repo has incorrect depth") } @@ -50,7 +50,7 @@ func Test_ClonePublicRepository_NoGitDirectory(t *testing.T) { dir := t.TempDir() t.Logf("Cloning into %s", dir) - err := service.CloneRepository(dir, repositoryURL, referenceName, "", "", gittypes.GitCredentialAuthType_Basic, false) + err := service.CloneRepository(dir, repositoryURL, referenceName, "", "", false) assert.NoError(t, err) assert.NoDirExists(t, filepath.Join(dir, ".git")) } @@ -84,7 +84,7 @@ func Test_latestCommitID(t *testing.T) { repositoryURL := setup(t) referenceName := "refs/heads/main" - id, err := service.LatestCommitID(repositoryURL, referenceName, "", "", gittypes.GitCredentialAuthType_Basic, false) + id, err := service.LatestCommitID(repositoryURL, referenceName, "", "", false) assert.NoError(t, err) assert.Equal(t, "68dcaa7bd452494043c64252ab90db0f98ecf8d2", id) @@ -95,7 +95,7 @@ func Test_ListRefs(t *testing.T) { repositoryURL := setup(t) - fs, err := service.ListRefs(repositoryURL, "", "", gittypes.GitCredentialAuthType_Basic, false, false) + fs, err := service.ListRefs(repositoryURL, "", "", false, false) assert.NoError(t, err) assert.Equal(t, []string{"refs/heads/main"}, fs) @@ -107,17 +107,7 @@ func Test_ListFiles(t *testing.T) { repositoryURL := setup(t) referenceName := "refs/heads/main" - fs, err := service.ListFiles( - repositoryURL, - referenceName, - "", - "", - gittypes.GitCredentialAuthType_Basic, - false, - false, - []string{".yml"}, - false, - ) + fs, err := service.ListFiles(repositoryURL, referenceName, "", "", false, false, []string{".yml"}, false) assert.NoError(t, err) assert.Equal(t, []string{"docker-compose.yml"}, fs) @@ -265,7 +255,7 @@ func Test_listFilesPrivateRepository(t *testing.T) { name: "list tree with real repository and head ref but no credential", args: fetchOption{ baseOption: baseOption{ - repositoryUrl: privateGitRepoURL, + repositoryUrl: privateGitRepoURL + "fake", username: "", password: "", }, diff --git a/api/git/service.go b/api/git/service.go index 834e0c827..3e995eccd 100644 --- a/api/git/service.go +++ b/api/git/service.go @@ -8,7 +8,6 @@ import ( "time" lru "github.com/hashicorp/golang-lru" - gittypes "github.com/portainer/portainer/api/git/types" "github.com/rs/zerolog/log" "golang.org/x/sync/singleflight" ) @@ -23,7 +22,6 @@ type baseOption struct { repositoryUrl string username string password string - authType gittypes.GitCredentialAuthType tlsSkipVerify bool } @@ -125,22 +123,13 @@ func (service *Service) timerHasStopped() bool { // CloneRepository clones a git repository using the specified URL in the specified // destination folder. -func (service *Service) CloneRepository( - destination, - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) error { +func (service *Service) CloneRepository(destination, repositoryURL, referenceName, username, password string, tlsSkipVerify bool) error { options := cloneOption{ fetchOption: fetchOption{ baseOption: baseOption{ repositoryUrl: repositoryURL, username: username, password: password, - authType: authType, tlsSkipVerify: tlsSkipVerify, }, referenceName: referenceName, @@ -166,20 +155,12 @@ func (service *Service) cloneRepository(destination string, options cloneOption) } // LatestCommitID returns SHA1 of the latest commit of the specified reference -func (service *Service) LatestCommitID( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) (string, error) { +func (service *Service) LatestCommitID(repositoryURL, referenceName, username, password string, tlsSkipVerify bool) (string, error) { options := fetchOption{ baseOption: baseOption{ repositoryUrl: repositoryURL, username: username, password: password, - authType: authType, tlsSkipVerify: tlsSkipVerify, }, referenceName: referenceName, @@ -189,14 +170,7 @@ func (service *Service) LatestCommitID( } // ListRefs will list target repository's references without cloning the repository -func (service *Service) ListRefs( - repositoryURL, - username, - password string, - authType gittypes.GitCredentialAuthType, - hardRefresh bool, - tlsSkipVerify bool, -) ([]string, error) { +func (service *Service) ListRefs(repositoryURL, username, password string, hardRefresh bool, tlsSkipVerify bool) ([]string, error) { refCacheKey := generateCacheKey(repositoryURL, username, password, strconv.FormatBool(tlsSkipVerify)) if service.cacheEnabled && hardRefresh { // Should remove the cache explicitly, so that the following normal list can show the correct result @@ -222,7 +196,6 @@ func (service *Service) ListRefs( repositoryUrl: repositoryURL, username: username, password: password, - authType: authType, tlsSkipVerify: tlsSkipVerify, } @@ -242,62 +215,18 @@ var singleflightGroup = &singleflight.Group{} // ListFiles will list all the files of the target repository with specific extensions. // If extension is not provided, it will list all the files under the target repository -func (service *Service) ListFiles( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - dirOnly, - hardRefresh bool, - includedExts []string, - tlsSkipVerify bool, -) ([]string, error) { - repoKey := generateCacheKey( - repositoryURL, - referenceName, - username, - password, - strconv.FormatBool(tlsSkipVerify), - strconv.Itoa(int(authType)), - strconv.FormatBool(dirOnly), - ) +func (service *Service) ListFiles(repositoryURL, referenceName, username, password string, dirOnly, hardRefresh bool, includedExts []string, tlsSkipVerify bool) ([]string, error) { + repoKey := generateCacheKey(repositoryURL, referenceName, username, password, strconv.FormatBool(tlsSkipVerify), strconv.FormatBool(dirOnly)) fs, err, _ := singleflightGroup.Do(repoKey, func() (any, error) { - return service.listFiles( - repositoryURL, - referenceName, - username, - password, - authType, - dirOnly, - hardRefresh, - tlsSkipVerify, - ) + return service.listFiles(repositoryURL, referenceName, username, password, dirOnly, hardRefresh, tlsSkipVerify) }) return filterFiles(fs.([]string), includedExts), err } -func (service *Service) listFiles( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - dirOnly, - hardRefresh bool, - tlsSkipVerify bool, -) ([]string, error) { - repoKey := generateCacheKey( - repositoryURL, - referenceName, - username, - password, - strconv.FormatBool(tlsSkipVerify), - strconv.Itoa(int(authType)), - strconv.FormatBool(dirOnly), - ) +func (service *Service) listFiles(repositoryURL, referenceName, username, password string, dirOnly, hardRefresh bool, tlsSkipVerify bool) ([]string, error) { + repoKey := generateCacheKey(repositoryURL, referenceName, username, password, strconv.FormatBool(tlsSkipVerify), strconv.FormatBool(dirOnly)) if service.cacheEnabled && hardRefresh { // Should remove the cache explicitly, so that the following normal list can show the correct result @@ -318,7 +247,6 @@ func (service *Service) listFiles( repositoryUrl: repositoryURL, username: username, password: password, - authType: authType, tlsSkipVerify: tlsSkipVerify, }, referenceName: referenceName, diff --git a/api/git/types/types.go b/api/git/types/types.go index cb9d7cf03..12d95e093 100644 --- a/api/git/types/types.go +++ b/api/git/types/types.go @@ -1,21 +1,12 @@ package gittypes -import ( - "errors" -) +import "errors" var ( ErrIncorrectRepositoryURL = errors.New("git repository could not be found, please ensure that the URL is correct") ErrAuthenticationFailure = errors.New("authentication failed, please ensure that the git credentials are correct") ) -type GitCredentialAuthType int - -const ( - GitCredentialAuthType_Basic GitCredentialAuthType = iota - GitCredentialAuthType_Token -) - // RepoConfig represents a configuration for a repo type RepoConfig struct { // The repo url @@ -33,11 +24,10 @@ type RepoConfig struct { } type GitAuthentication struct { - Username string - Password string - AuthorizationType GitCredentialAuthType + Username string + Password string // Git credentials identifier when the value is not 0 - // When the value is 0, Username, Password, and Authtype are set without using saved credential + // When the value is 0, Username and Password are set without using saved credential // This is introduced since 2.15.0 GitCredentialID int `example:"0"` } diff --git a/api/git/update/update.go b/api/git/update/update.go index 780d6e046..203e361dd 100644 --- a/api/git/update/update.go +++ b/api/git/update/update.go @@ -29,14 +29,7 @@ func UpdateGitObject(gitService portainer.GitService, objId string, gitConfig *g return false, "", errors.WithMessagef(err, "failed to get credentials for %v", objId) } - newHash, err := gitService.LatestCommitID( - gitConfig.URL, - gitConfig.ReferenceName, - username, - password, - gittypes.GitCredentialAuthType_Basic, - gitConfig.TLSSkipVerify, - ) + newHash, err := gitService.LatestCommitID(gitConfig.URL, gitConfig.ReferenceName, username, password, gitConfig.TLSSkipVerify) if err != nil { return false, "", errors.WithMessagef(err, "failed to fetch latest commit id of %v", objId) } @@ -69,7 +62,6 @@ func UpdateGitObject(gitService portainer.GitService, objId string, gitConfig *g cloneParams.auth = &gitAuth{ username: username, password: password, - authType: gitConfig.Authentication.AuthorizationType, } } @@ -97,31 +89,14 @@ type cloneRepositoryParameters struct { } type gitAuth struct { - authType gittypes.GitCredentialAuthType username string password string } func cloneGitRepository(gitService portainer.GitService, cloneParams *cloneRepositoryParameters) error { if cloneParams.auth != nil { - return gitService.CloneRepository( - cloneParams.toDir, - cloneParams.url, - cloneParams.ref, - cloneParams.auth.username, - cloneParams.auth.password, - cloneParams.auth.authType, - cloneParams.tlsSkipVerify, - ) + return gitService.CloneRepository(cloneParams.toDir, cloneParams.url, cloneParams.ref, cloneParams.auth.username, cloneParams.auth.password, cloneParams.tlsSkipVerify) } - return gitService.CloneRepository( - cloneParams.toDir, - cloneParams.url, - cloneParams.ref, - "", - "", - gittypes.GitCredentialAuthType_Basic, - cloneParams.tlsSkipVerify, - ) + return gitService.CloneRepository(cloneParams.toDir, cloneParams.url, cloneParams.ref, "", "", cloneParams.tlsSkipVerify) } diff --git a/api/hostmanagement/openamt/openamt.go b/api/hostmanagement/openamt/openamt.go index 5843c1bdb..b27b78878 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(insecureSkipVerify bool) *Service { +func NewService() *Service { tlsConfig := crypto.CreateTLSConfiguration() - tlsConfig.InsecureSkipVerify = insecureSkipVerify + tlsConfig.InsecureSkipVerify = true return &Service{ httpsClient: &http.Client{ diff --git a/api/http/csrf/csrf.go b/api/http/csrf/csrf.go index 6205c9290..857d72c8b 100644 --- a/api/http/csrf/csrf.go +++ b/api/http/csrf/csrf.go @@ -2,7 +2,6 @@ package csrf import ( "crypto/rand" - "errors" "fmt" "net/http" "os" @@ -10,8 +9,7 @@ import ( "github.com/portainer/portainer/api/http/security" httperror "github.com/portainer/portainer/pkg/libhttp/error" - gcsrf "github.com/gorilla/csrf" - "github.com/rs/zerolog/log" + gorillacsrf "github.com/gorilla/csrf" "github.com/urfave/negroni" ) @@ -21,7 +19,7 @@ func SkipCSRFToken(w http.ResponseWriter) { w.Header().Set(csrfSkipHeader, "1") } -func WithProtect(handler http.Handler, trustedOrigins []string) (http.Handler, error) { +func WithProtect(handler http.Handler) (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 @@ -36,12 +34,10 @@ func WithProtect(handler http.Handler, trustedOrigins []string) (http.Handler, e return nil, fmt.Errorf("failed to generate CSRF token: %w", err) } - handler = gcsrf.Protect( + handler = gorillacsrf.Protect( token, - gcsrf.Path("/"), - gcsrf.Secure(false), - gcsrf.TrustedOrigins(trustedOrigins), - gcsrf.ErrorHandler(withErrorHandler(trustedOrigins)), + gorillacsrf.Path("/"), + gorillacsrf.Secure(false), )(handler) return withSkipCSRF(handler, isDockerDesktopExtension), nil @@ -59,7 +55,7 @@ func withSendCSRFToken(handler http.Handler) http.Handler { } if statusCode := sw.Status(); statusCode >= 200 && statusCode < 300 { - sw.Header().Set("X-CSRF-Token", gcsrf.Token(r)) + sw.Header().Set("X-CSRF-Token", gorillacsrf.Token(r)) } }) @@ -77,33 +73,9 @@ func withSkipCSRF(handler http.Handler, isDockerDesktopExtension bool) http.Hand } if skip { - r = gcsrf.UnsafeSkipCheck(r) + r = gorillacsrf.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 4df31c92c..989949daa 100644 --- a/api/http/handler/auth/authenticate.go +++ b/api/http/handler/auth/authenticate.go @@ -2,7 +2,6 @@ package auth import ( "net/http" - "strconv" "strings" portainer "github.com/portainer/portainer/api" @@ -83,11 +82,6 @@ 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 035ceabf8..3b7210fbf 100644 --- a/api/http/handler/auth/handler.go +++ b/api/http/handler/auth/handler.go @@ -8,7 +8,6 @@ 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" @@ -24,18 +23,16 @@ 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, kubernetesClientFactory *cli.ClientFactory) *Handler { +func NewHandler(bouncer security.BouncerService, rateLimiter *security.RateLimiter, passwordStrengthChecker security.PasswordStrengthChecker) *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 73288565d..977fafa69 100644 --- a/api/http/handler/auth/logout.go +++ b/api/http/handler/auth/logout.go @@ -2,7 +2,6 @@ package auth import ( "net/http" - "strconv" "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/logoutcontext" @@ -24,7 +23,6 @@ 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_git_fetch_test.go b/api/http/handler/customtemplates/customtemplate_git_fetch_test.go index b63db356d..60ed1666f 100644 --- a/api/http/handler/customtemplates/customtemplate_git_fetch_test.go +++ b/api/http/handler/customtemplates/customtemplate_git_fetch_test.go @@ -33,28 +33,13 @@ type TestGitService struct { targetFilePath string } -func (g *TestGitService) CloneRepository( - destination string, - repositoryURL, - referenceName string, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) error { +func (g *TestGitService) CloneRepository(destination string, repositoryURL, referenceName string, username, password string, tlsSkipVerify bool) error { time.Sleep(100 * time.Millisecond) return createTestFile(g.targetFilePath) } -func (g *TestGitService) LatestCommitID( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) (string, error) { +func (g *TestGitService) LatestCommitID(repositoryURL, referenceName, username, password string, tlsSkipVerify bool) (string, error) { return "", nil } @@ -71,26 +56,11 @@ type InvalidTestGitService struct { targetFilePath string } -func (g *InvalidTestGitService) CloneRepository( - dest, - repoUrl, - refName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) error { +func (g *InvalidTestGitService) CloneRepository(dest, repoUrl, refName, username, password string, tlsSkipVerify bool) error { return errors.New("simulate network error") } -func (g *InvalidTestGitService) LatestCommitID( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) (string, error) { +func (g *InvalidTestGitService) LatestCommitID(repositoryURL, referenceName, username, password string, tlsSkipVerify bool) (string, error) { return "", nil } diff --git a/api/http/handler/customtemplates/customtemplate_list.go b/api/http/handler/customtemplates/customtemplate_list.go index c96d61523..581b219ae 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.FilterInPlace(customTemplates, func(customTemplate portainer.CustomTemplate) bool { + customTemplates = slicesx.Filter(customTemplates, func(customTemplate portainer.CustomTemplate) bool { return customTemplate.EdgeTemplate == *edge }) } diff --git a/api/http/handler/customtemplates/customtemplate_update.go b/api/http/handler/customtemplates/customtemplate_update.go index f12eeb2e1..f14d228f3 100644 --- a/api/http/handler/customtemplates/customtemplate_update.go +++ b/api/http/handler/customtemplates/customtemplate_update.go @@ -37,16 +37,14 @@ type customTemplateUpdatePayload struct { RepositoryURL string `example:"https://github.com/openfaas/faas" validate:"required"` // Reference name of a Git repository hosting the Stack file RepositoryReferenceName string `example:"refs/heads/master"` - // Use authentication to clone the Git repository + // Use basic authentication to clone the Git repository RepositoryAuthentication bool `example:"true"` // Username used in basic authentication. Required when RepositoryAuthentication is true - // and RepositoryGitCredentialID is 0. Ignored if RepositoryAuthType is token + // and RepositoryGitCredentialID is 0 RepositoryUsername string `example:"myGitUsername"` - // Password used in basic authentication or token used in token authentication. - // Required when RepositoryAuthentication is true and RepositoryGitCredentialID is 0 + // Password used in basic authentication. Required when RepositoryAuthentication is true + // and RepositoryGitCredentialID is 0 RepositoryPassword string `example:"myGitPassword"` - // RepositoryAuthorizationType is the authorization type to use - RepositoryAuthorizationType gittypes.GitCredentialAuthType `example:"0"` // GitCredentialID used to identify the bound git credential. Required when RepositoryAuthentication // is true and RepositoryUsername/RepositoryPassword are not provided RepositoryGitCredentialID int `example:"0"` @@ -184,15 +182,12 @@ func (handler *Handler) customTemplateUpdate(w http.ResponseWriter, r *http.Requ repositoryUsername := "" repositoryPassword := "" - repositoryAuthType := gittypes.GitCredentialAuthType_Basic if payload.RepositoryAuthentication { repositoryUsername = payload.RepositoryUsername repositoryPassword = payload.RepositoryPassword - repositoryAuthType = payload.RepositoryAuthorizationType gitConfig.Authentication = &gittypes.GitAuthentication{ - Username: payload.RepositoryUsername, - Password: payload.RepositoryPassword, - AuthorizationType: payload.RepositoryAuthorizationType, + Username: payload.RepositoryUsername, + Password: payload.RepositoryPassword, } } @@ -202,7 +197,6 @@ func (handler *Handler) customTemplateUpdate(w http.ResponseWriter, r *http.Requ ReferenceName: gitConfig.ReferenceName, Username: repositoryUsername, Password: repositoryPassword, - AuthType: repositoryAuthType, TLSSkipVerify: gitConfig.TLSSkipVerify, }) if err != nil { @@ -211,14 +205,7 @@ func (handler *Handler) customTemplateUpdate(w http.ResponseWriter, r *http.Requ defer cleanBackup() - commitHash, err := handler.GitService.LatestCommitID( - gitConfig.URL, - gitConfig.ReferenceName, - repositoryUsername, - repositoryPassword, - repositoryAuthType, - gitConfig.TLSSkipVerify, - ) + commitHash, err := handler.GitService.LatestCommitID(gitConfig.URL, gitConfig.ReferenceName, repositoryUsername, repositoryPassword, gitConfig.TLSSkipVerify) if err != nil { return httperror.InternalServerError("Unable get latest commit id", fmt.Errorf("failed to fetch latest commit id of the template %v: %w", customTemplate.ID, err)) } diff --git a/api/http/handler/edgegroups/associated_endpoints.go b/api/http/handler/edgegroups/associated_endpoints.go index b26e94d0c..d03618c56 100644 --- a/api/http/handler/edgegroups/associated_endpoints.go +++ b/api/http/handler/edgegroups/associated_endpoints.go @@ -4,7 +4,6 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/internal/endpointutils" - "github.com/portainer/portainer/api/roar" ) type endpointSetType map[portainer.EndpointID]bool @@ -50,29 +49,22 @@ func GetEndpointsByTags(tx dataservices.DataStoreTx, tagIDs []portainer.TagID, p return results, nil } -func getTrustedEndpoints(tx dataservices.DataStoreTx, endpointIDs roar.Roar[portainer.EndpointID]) ([]portainer.EndpointID, error) { - var innerErr error - +func getTrustedEndpoints(tx dataservices.DataStoreTx, endpointIDs []portainer.EndpointID) ([]portainer.EndpointID, error) { results := []portainer.EndpointID{} - - endpointIDs.Iterate(func(endpointID portainer.EndpointID) bool { + for _, endpointID := range endpointIDs { endpoint, err := tx.Endpoint().Endpoint(endpointID) if err != nil { - innerErr = err - - return false + return nil, err } if !endpoint.UserTrusted { - return true + continue } results = append(results, endpoint.ID) + } - return true - }) - - return results, innerErr + return results, nil } func mapEndpointGroupToEndpoints(endpoints []portainer.Endpoint) map[portainer.EndpointGroupID]endpointSetType { diff --git a/api/http/handler/edgegroups/edgegroup_create.go b/api/http/handler/edgegroups/edgegroup_create.go index c074bffde..3988160f0 100644 --- a/api/http/handler/edgegroups/edgegroup_create.go +++ b/api/http/handler/edgegroups/edgegroup_create.go @@ -7,7 +7,6 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/internal/endpointutils" - "github.com/portainer/portainer/api/roar" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" ) @@ -53,7 +52,6 @@ func calculateEndpointsOrTags(tx dataservices.DataStoreTx, edgeGroup *portainer. } edgeGroup.Endpoints = endpointIDs - edgeGroup.EndpointIDs = roar.FromSlice(endpointIDs) return nil } @@ -96,7 +94,6 @@ func (handler *Handler) edgeGroupCreate(w http.ResponseWriter, r *http.Request) Dynamic: payload.Dynamic, TagIDs: []portainer.TagID{}, Endpoints: []portainer.EndpointID{}, - EndpointIDs: roar.Roar[portainer.EndpointID]{}, PartialMatch: payload.PartialMatch, } @@ -111,5 +108,5 @@ func (handler *Handler) edgeGroupCreate(w http.ResponseWriter, r *http.Request) return nil }) - return txResponse(w, shadowedEdgeGroup{EdgeGroup: *edgeGroup}, err) + return txResponse(w, edgeGroup, err) } diff --git a/api/http/handler/edgegroups/edgegroup_create_test.go b/api/http/handler/edgegroups/edgegroup_create_test.go deleted file mode 100644 index e7710432f..000000000 --- a/api/http/handler/edgegroups/edgegroup_create_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package edgegroups - -import ( - "net/http" - "net/http/httptest" - "strconv" - "strings" - "testing" - - portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/datastore" - "github.com/portainer/portainer/api/internal/testhelpers" - - "github.com/segmentio/encoding/json" - "github.com/stretchr/testify/require" -) - -func TestEdgeGroupCreateHandler(t *testing.T) { - _, store := datastore.MustNewTestStore(t, true, true) - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - - err := store.EndpointGroup().Create(&portainer.EndpointGroup{ - ID: 1, - Name: "Test Group", - }) - require.NoError(t, err) - - for i := range 3 { - err = store.Endpoint().Create(&portainer.Endpoint{ - ID: portainer.EndpointID(i + 1), - Name: "Test Endpoint " + strconv.Itoa(i+1), - Type: portainer.EdgeAgentOnDockerEnvironment, - GroupID: 1, - }) - require.NoError(t, err) - - err = store.EndpointRelation().Create(&portainer.EndpointRelation{ - EndpointID: portainer.EndpointID(i + 1), - EdgeStacks: map[portainer.EdgeStackID]bool{}, - }) - require.NoError(t, err) - } - - rr := httptest.NewRecorder() - - req := httptest.NewRequest( - http.MethodPost, - "/edge_groups", - strings.NewReader(`{"Name": "New Edge Group", "Endpoints": [1, 2, 3]}`), - ) - - handler.ServeHTTP(rr, req) - require.Equal(t, http.StatusOK, rr.Result().StatusCode) - - var responseGroup portainer.EdgeGroup - err = json.NewDecoder(rr.Body).Decode(&responseGroup) - require.NoError(t, err) - - require.ElementsMatch(t, []portainer.EndpointID{1, 2, 3}, responseGroup.Endpoints) -} diff --git a/api/http/handler/edgegroups/edgegroup_inspect.go b/api/http/handler/edgegroups/edgegroup_inspect.go index 76780ec1d..c17ac6b7c 100644 --- a/api/http/handler/edgegroups/edgegroup_inspect.go +++ b/api/http/handler/edgegroups/edgegroup_inspect.go @@ -5,7 +5,6 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" - "github.com/portainer/portainer/api/roar" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" ) @@ -34,9 +33,7 @@ func (handler *Handler) edgeGroupInspect(w http.ResponseWriter, r *http.Request) return err }) - edgeGroup.Endpoints = edgeGroup.EndpointIDs.ToSlice() - - return txResponse(w, shadowedEdgeGroup{EdgeGroup: *edgeGroup}, err) + return txResponse(w, edgeGroup, err) } func getEdgeGroup(tx dataservices.DataStoreTx, ID portainer.EdgeGroupID) (*portainer.EdgeGroup, error) { @@ -53,7 +50,7 @@ func getEdgeGroup(tx dataservices.DataStoreTx, ID portainer.EdgeGroupID) (*porta return nil, httperror.InternalServerError("Unable to retrieve environments and environment groups for Edge group", err) } - edgeGroup.EndpointIDs = roar.FromSlice(endpoints) + edgeGroup.Endpoints = endpoints } return edgeGroup, err diff --git a/api/http/handler/edgegroups/edgegroup_inspect_test.go b/api/http/handler/edgegroups/edgegroup_inspect_test.go deleted file mode 100644 index 5af282372..000000000 --- a/api/http/handler/edgegroups/edgegroup_inspect_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package edgegroups - -import ( - "net/http" - "net/http/httptest" - "strconv" - "testing" - - portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/datastore" - "github.com/portainer/portainer/api/internal/testhelpers" - "github.com/portainer/portainer/api/roar" - - "github.com/segmentio/encoding/json" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestEdgeGroupInspectHandler(t *testing.T) { - _, store := datastore.MustNewTestStore(t, true, true) - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - - err := store.EndpointGroup().Create(&portainer.EndpointGroup{ - ID: 1, - Name: "Test Group", - }) - require.NoError(t, err) - - for i := range 3 { - err = store.Endpoint().Create(&portainer.Endpoint{ - ID: portainer.EndpointID(i + 1), - Name: "Test Endpoint " + strconv.Itoa(i+1), - Type: portainer.EdgeAgentOnDockerEnvironment, - GroupID: 1, - }) - require.NoError(t, err) - - err = store.EndpointRelation().Create(&portainer.EndpointRelation{ - EndpointID: portainer.EndpointID(i + 1), - EdgeStacks: map[portainer.EdgeStackID]bool{}, - }) - require.NoError(t, err) - } - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Test Edge Group", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{1, 2, 3}), - }) - require.NoError(t, err) - - rr := httptest.NewRecorder() - - req := httptest.NewRequest( - http.MethodGet, - "/edge_groups/1", - nil, - ) - - handler.ServeHTTP(rr, req) - require.Equal(t, http.StatusOK, rr.Result().StatusCode) - - var responseGroup portainer.EdgeGroup - err = json.NewDecoder(rr.Body).Decode(&responseGroup) - require.NoError(t, err) - - assert.ElementsMatch(t, []portainer.EndpointID{1, 2, 3}, responseGroup.Endpoints) -} - -func TestEmptyEdgeGroupInspectHandler(t *testing.T) { - _, store := datastore.MustNewTestStore(t, true, true) - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - - err := store.EndpointGroup().Create(&portainer.EndpointGroup{ - ID: 1, - Name: "Test Group", - }) - require.NoError(t, err) - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Test Edge Group", - EndpointIDs: roar.Roar[portainer.EndpointID]{}, - }) - require.NoError(t, err) - - rr := httptest.NewRecorder() - - req := httptest.NewRequest( - http.MethodGet, - "/edge_groups/1", - nil, - ) - - handler.ServeHTTP(rr, req) - require.Equal(t, http.StatusOK, rr.Result().StatusCode) - - var responseGroup portainer.EdgeGroup - err = json.NewDecoder(rr.Body).Decode(&responseGroup) - require.NoError(t, err) - - // Make sure the frontend does not get a null value but a [] instead - require.NotNil(t, responseGroup.Endpoints) - require.Len(t, responseGroup.Endpoints, 0) -} - -func TestDynamicEdgeGroupInspectHandler(t *testing.T) { - _, store := datastore.MustNewTestStore(t, true, true) - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - - err := store.EndpointGroup().Create(&portainer.EndpointGroup{ - ID: 1, - Name: "Test Group", - }) - require.NoError(t, err) - - err = store.Tag().Create(&portainer.Tag{ - ID: 1, - Name: "Test Tag", - Endpoints: map[portainer.EndpointID]bool{ - 1: true, - 2: true, - 3: true, - }, - }) - require.NoError(t, err) - - for i := range 3 { - err = store.Endpoint().Create(&portainer.Endpoint{ - ID: portainer.EndpointID(i + 1), - Name: "Test Endpoint " + strconv.Itoa(i+1), - Type: portainer.EdgeAgentOnDockerEnvironment, - GroupID: 1, - TagIDs: []portainer.TagID{1}, - UserTrusted: true, - }) - require.NoError(t, err) - - err = store.EndpointRelation().Create(&portainer.EndpointRelation{ - EndpointID: portainer.EndpointID(i + 1), - EdgeStacks: map[portainer.EdgeStackID]bool{}, - }) - require.NoError(t, err) - } - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Test Edge Group", - Dynamic: true, - TagIDs: []portainer.TagID{1}, - }) - require.NoError(t, err) - - rr := httptest.NewRecorder() - - req := httptest.NewRequest( - http.MethodGet, - "/edge_groups/1", - nil, - ) - - handler.ServeHTTP(rr, req) - require.Equal(t, http.StatusOK, rr.Result().StatusCode) - - var responseGroup portainer.EdgeGroup - err = json.NewDecoder(rr.Body).Decode(&responseGroup) - require.NoError(t, err) - - require.ElementsMatch(t, []portainer.EndpointID{1, 2, 3}, responseGroup.Endpoints) -} diff --git a/api/http/handler/edgegroups/edgegroup_list.go b/api/http/handler/edgegroups/edgegroup_list.go index 87de867eb..bc67176fd 100644 --- a/api/http/handler/edgegroups/edgegroup_list.go +++ b/api/http/handler/edgegroups/edgegroup_list.go @@ -7,17 +7,11 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" - "github.com/portainer/portainer/api/roar" httperror "github.com/portainer/portainer/pkg/libhttp/error" ) -type shadowedEdgeGroup struct { - portainer.EdgeGroup - EndpointIds int `json:"EndpointIds,omitempty"` // Shadow to avoid exposing in the API -} - type decoratedEdgeGroup struct { - shadowedEdgeGroup + portainer.EdgeGroup HasEdgeStack bool `json:"HasEdgeStack"` HasEdgeJob bool `json:"HasEdgeJob"` EndpointTypes []portainer.EndpointType @@ -82,8 +76,8 @@ func getEdgeGroupList(tx dataservices.DataStoreTx) ([]decoratedEdgeGroup, error) } edgeGroup := decoratedEdgeGroup{ - shadowedEdgeGroup: shadowedEdgeGroup{EdgeGroup: orgEdgeGroup}, - EndpointTypes: []portainer.EndpointType{}, + EdgeGroup: orgEdgeGroup, + EndpointTypes: []portainer.EndpointType{}, } if edgeGroup.Dynamic { endpointIDs, err := GetEndpointsByTags(tx, edgeGroup.TagIDs, edgeGroup.PartialMatch) @@ -94,16 +88,15 @@ func getEdgeGroupList(tx dataservices.DataStoreTx) ([]decoratedEdgeGroup, error) edgeGroup.Endpoints = endpointIDs edgeGroup.TrustedEndpoints = endpointIDs } else { - trustedEndpoints, err := getTrustedEndpoints(tx, edgeGroup.EndpointIDs) + trustedEndpoints, err := getTrustedEndpoints(tx, edgeGroup.Endpoints) if err != nil { return nil, httperror.InternalServerError("Unable to retrieve environments for Edge group", err) } - edgeGroup.Endpoints = edgeGroup.EndpointIDs.ToSlice() edgeGroup.TrustedEndpoints = trustedEndpoints } - endpointTypes, err := getEndpointTypes(tx, edgeGroup.EndpointIDs) + endpointTypes, err := getEndpointTypes(tx, edgeGroup.Endpoints) if err != nil { return nil, httperror.InternalServerError("Unable to retrieve environment types for Edge group", err) } @@ -118,26 +111,15 @@ func getEdgeGroupList(tx dataservices.DataStoreTx) ([]decoratedEdgeGroup, error) return decoratedEdgeGroups, nil } -func getEndpointTypes(tx dataservices.DataStoreTx, endpointIds roar.Roar[portainer.EndpointID]) ([]portainer.EndpointType, error) { - var innerErr error - +func getEndpointTypes(tx dataservices.DataStoreTx, endpointIds []portainer.EndpointID) ([]portainer.EndpointType, error) { typeSet := map[portainer.EndpointType]bool{} - - endpointIds.Iterate(func(endpointID portainer.EndpointID) bool { + for _, endpointID := range endpointIds { endpoint, err := tx.Endpoint().Endpoint(endpointID) if err != nil { - innerErr = fmt.Errorf("failed fetching environment: %w", err) - - return false + return nil, fmt.Errorf("failed fetching environment: %w", err) } typeSet[endpoint.Type] = true - - return true - }) - - if innerErr != nil { - return nil, innerErr } endpointTypes := make([]portainer.EndpointType, 0, len(typeSet)) diff --git a/api/http/handler/edgegroups/edgegroup_list_test.go b/api/http/handler/edgegroups/edgegroup_list_test.go index bf084c377..b77b2966e 100644 --- a/api/http/handler/edgegroups/edgegroup_list_test.go +++ b/api/http/handler/edgegroups/edgegroup_list_test.go @@ -1,19 +1,11 @@ package edgegroups import ( - "net/http" - "net/http/httptest" - "strconv" "testing" portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/datastore" "github.com/portainer/portainer/api/internal/testhelpers" - "github.com/portainer/portainer/api/roar" - - "github.com/segmentio/encoding/json" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func Test_getEndpointTypes(t *testing.T) { @@ -46,7 +38,7 @@ func Test_getEndpointTypes(t *testing.T) { } for _, test := range tests { - ans, err := getEndpointTypes(datastore, roar.FromSlice(test.endpointIds)) + ans, err := getEndpointTypes(datastore, test.endpointIds) assert.NoError(t, err, "getEndpointTypes shouldn't fail") assert.ElementsMatch(t, test.expected, ans, "getEndpointTypes expected to return %b for %v, but returned %b", test.expected, test.endpointIds, ans) @@ -56,61 +48,6 @@ func Test_getEndpointTypes(t *testing.T) { func Test_getEndpointTypes_failWhenEndpointDontExist(t *testing.T) { datastore := testhelpers.NewDatastore(testhelpers.WithEndpoints([]portainer.Endpoint{})) - _, err := getEndpointTypes(datastore, roar.FromSlice([]portainer.EndpointID{1})) + _, err := getEndpointTypes(datastore, []portainer.EndpointID{1}) assert.Error(t, err, "getEndpointTypes should fail") } - -func TestEdgeGroupListHandler(t *testing.T) { - _, store := datastore.MustNewTestStore(t, true, true) - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - - err := store.EndpointGroup().Create(&portainer.EndpointGroup{ - ID: 1, - Name: "Test Group", - }) - require.NoError(t, err) - - for i := range 3 { - err = store.Endpoint().Create(&portainer.Endpoint{ - ID: portainer.EndpointID(i + 1), - Name: "Test Endpoint " + strconv.Itoa(i+1), - Type: portainer.EdgeAgentOnDockerEnvironment, - GroupID: 1, - }) - require.NoError(t, err) - - err = store.EndpointRelation().Create(&portainer.EndpointRelation{ - EndpointID: portainer.EndpointID(i + 1), - EdgeStacks: map[portainer.EdgeStackID]bool{}, - }) - require.NoError(t, err) - } - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Test Edge Group", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{1, 2, 3}), - }) - require.NoError(t, err) - - rr := httptest.NewRecorder() - - req := httptest.NewRequest( - http.MethodGet, - "/edge_groups", - nil, - ) - - handler.ServeHTTP(rr, req) - require.Equal(t, http.StatusOK, rr.Result().StatusCode) - - var responseGroups []decoratedEdgeGroup - err = json.NewDecoder(rr.Body).Decode(&responseGroups) - require.NoError(t, err) - - require.Len(t, responseGroups, 1) - require.ElementsMatch(t, []portainer.EndpointID{1, 2, 3}, responseGroups[0].Endpoints) - require.Len(t, responseGroups[0].TrustedEndpoints, 0) -} diff --git a/api/http/handler/edgegroups/edgegroup_update.go b/api/http/handler/edgegroups/edgegroup_update.go index 270bd10df..7831b634e 100644 --- a/api/http/handler/edgegroups/edgegroup_update.go +++ b/api/http/handler/edgegroups/edgegroup_update.go @@ -158,12 +158,12 @@ func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request) return nil }) - return txResponse(w, shadowedEdgeGroup{EdgeGroup: *edgeGroup}, err) + return txResponse(w, edgeGroup, err) } 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 { + if err != nil && !handler.DataStore.IsErrObjectNotFound(err) { return err } @@ -179,6 +179,12 @@ 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/edgegroups/edgegroup_update_test.go b/api/http/handler/edgegroups/edgegroup_update_test.go deleted file mode 100644 index dbecbdfcf..000000000 --- a/api/http/handler/edgegroups/edgegroup_update_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package edgegroups - -import ( - "net/http" - "net/http/httptest" - "strconv" - "strings" - "testing" - - portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/datastore" - "github.com/portainer/portainer/api/internal/testhelpers" - "github.com/portainer/portainer/api/roar" - - "github.com/segmentio/encoding/json" - "github.com/stretchr/testify/require" -) - -func TestEdgeGroupUpdateHandler(t *testing.T) { - _, store := datastore.MustNewTestStore(t, true, true) - - handler := NewHandler(testhelpers.NewTestRequestBouncer()) - handler.DataStore = store - - err := store.EndpointGroup().Create(&portainer.EndpointGroup{ - ID: 1, - Name: "Test Group", - }) - require.NoError(t, err) - - for i := range 3 { - err = store.Endpoint().Create(&portainer.Endpoint{ - ID: portainer.EndpointID(i + 1), - Name: "Test Endpoint " + strconv.Itoa(i+1), - Type: portainer.EdgeAgentOnDockerEnvironment, - GroupID: 1, - }) - require.NoError(t, err) - - err = store.EndpointRelation().Create(&portainer.EndpointRelation{ - EndpointID: portainer.EndpointID(i + 1), - EdgeStacks: map[portainer.EdgeStackID]bool{}, - }) - require.NoError(t, err) - } - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Test Edge Group", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{1}), - }) - require.NoError(t, err) - - rr := httptest.NewRecorder() - - req := httptest.NewRequest( - http.MethodPut, - "/edge_groups/1", - strings.NewReader(`{"Endpoints": [1, 2, 3]}`), - ) - - handler.ServeHTTP(rr, req) - require.Equal(t, http.StatusOK, rr.Result().StatusCode) - - var responseGroup portainer.EdgeGroup - err = json.NewDecoder(rr.Body).Decode(&responseGroup) - require.NoError(t, err) - - require.ElementsMatch(t, []portainer.EndpointID{1, 2, 3}, responseGroup.Endpoints) -} diff --git a/api/http/handler/edgestacks/edgestack_create_git.go b/api/http/handler/edgestacks/edgestack_create_git.go index a8775495d..d20e5b5c2 100644 --- a/api/http/handler/edgestacks/edgestack_create_git.go +++ b/api/http/handler/edgestacks/edgestack_create_git.go @@ -33,8 +33,6 @@ type edgeStackFromGitRepositoryPayload struct { RepositoryUsername string `example:"myGitUsername"` // Password used in basic authentication. Required when RepositoryAuthentication is true. RepositoryPassword string `example:"myGitPassword"` - // RepositoryAuthorizationType is the authorization type to use - RepositoryAuthorizationType gittypes.GitCredentialAuthType `example:"0"` // Path to the Stack file inside the Git repository FilePathInRepository string `example:"docker-compose.yml" default:"docker-compose.yml"` // List of identifiers of EdgeGroups @@ -127,9 +125,8 @@ func (handler *Handler) createEdgeStackFromGitRepository(r *http.Request, tx dat if payload.RepositoryAuthentication { repoConfig.Authentication = &gittypes.GitAuthentication{ - Username: payload.RepositoryUsername, - Password: payload.RepositoryPassword, - AuthorizationType: payload.RepositoryAuthorizationType, + Username: payload.RepositoryUsername, + Password: payload.RepositoryPassword, } } @@ -148,22 +145,12 @@ func (handler *Handler) storeManifestFromGitRepository(tx dataservices.DataStore projectPath = handler.FileService.GetEdgeStackProjectPath(stackFolder) repositoryUsername := "" repositoryPassword := "" - repositoryAuthType := gittypes.GitCredentialAuthType_Basic if repositoryConfig.Authentication != nil && repositoryConfig.Authentication.Password != "" { repositoryUsername = repositoryConfig.Authentication.Username repositoryPassword = repositoryConfig.Authentication.Password - repositoryAuthType = repositoryConfig.Authentication.AuthorizationType } - if err := handler.GitService.CloneRepository( - projectPath, - repositoryConfig.URL, - repositoryConfig.ReferenceName, - repositoryUsername, - repositoryPassword, - repositoryAuthType, - repositoryConfig.TLSSkipVerify, - ); 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_test.go b/api/http/handler/edgestacks/edgestack_create_test.go index 70252c25d..486cc09d0 100644 --- a/api/http/handler/edgestacks/edgestack_create_test.go +++ b/api/http/handler/edgestacks/edgestack_create_test.go @@ -8,10 +8,9 @@ import ( "testing" portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/roar" + "github.com/stretchr/testify/require" "github.com/segmentio/encoding/json" - "github.com/stretchr/testify/require" ) // Create @@ -25,7 +24,7 @@ func TestCreateAndInspect(t *testing.T) { Name: "EdgeGroup 1", Dynamic: false, TagIDs: nil, - EndpointIDs: roar.FromSlice([]portainer.EndpointID{endpoint.ID}), + Endpoints: []portainer.EndpointID{endpoint.ID}, PartialMatch: false, } diff --git a/api/http/handler/edgestacks/edgestack_list.go b/api/http/handler/edgestacks/edgestack_list.go index 1ea991c4b..b0df238c3 100644 --- a/api/http/handler/edgestacks/edgestack_list.go +++ b/api/http/handler/edgestacks/edgestack_list.go @@ -3,39 +3,10 @@ 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 @@ -43,122 +14,22 @@ type edgeStackListResponseItem struct { // @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) } - 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 { + if err := fillEdgeStackStatus(handler.DataStore, &edgeStacks[i]); 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, "" + return response.JSON(w, edgeStacks) } diff --git a/api/http/handler/edgestacks/edgestack_status_update.go b/api/http/handler/edgestacks/edgestack_status_update.go index 0ff6a9eff..4f99e7ab3 100644 --- a/api/http/handler/edgestacks/edgestack_status_update.go +++ b/api/http/handler/edgestacks/edgestack_status_update.go @@ -133,9 +133,7 @@ func (handler *Handler) updateEdgeStackStatus(tx dataservices.DataStoreTx, stack } environmentStatus, err := tx.EdgeStackStatus().Read(stackID, payload.EndpointID) - if err != nil && !tx.IsErrObjectNotFound(err) { - return err - } else if tx.IsErrObjectNotFound(err) { + if err != nil { environmentStatus = &portainer.EdgeStackStatusForEnv{ EndpointID: payload.EndpointID, Status: []portainer.EdgeStackDeploymentStatus{}, diff --git a/api/http/handler/edgestacks/edgestack_test.go b/api/http/handler/edgestacks/edgestack_test.go index 38fd4be55..91600117b 100644 --- a/api/http/handler/edgestacks/edgestack_test.go +++ b/api/http/handler/edgestacks/edgestack_test.go @@ -15,7 +15,6 @@ import ( "github.com/portainer/portainer/api/internal/edge/edgestacks" "github.com/portainer/portainer/api/internal/testhelpers" "github.com/portainer/portainer/api/jwt" - "github.com/portainer/portainer/api/roar" "github.com/pkg/errors" "github.com/stretchr/testify/require" @@ -104,7 +103,7 @@ func createEdgeStack(t *testing.T, store dataservices.DataStore, endpointID port Name: "EdgeGroup 1", Dynamic: false, TagIDs: nil, - EndpointIDs: roar.FromSlice([]portainer.EndpointID{endpointID}), + Endpoints: []portainer.EndpointID{endpointID}, PartialMatch: false, } diff --git a/api/http/handler/edgestacks/edgestack_update_test.go b/api/http/handler/edgestacks/edgestack_update_test.go index 8040af329..68baa4129 100644 --- a/api/http/handler/edgestacks/edgestack_update_test.go +++ b/api/http/handler/edgestacks/edgestack_update_test.go @@ -9,10 +9,9 @@ import ( "testing" portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/roar" + "github.com/stretchr/testify/require" "github.com/segmentio/encoding/json" - "github.com/stretchr/testify/require" ) // Update @@ -44,7 +43,7 @@ func TestUpdateAndInspect(t *testing.T) { Name: "EdgeGroup 2", Dynamic: false, TagIDs: nil, - EndpointIDs: roar.FromSlice([]portainer.EndpointID{newEndpoint.ID}), + Endpoints: []portainer.EndpointID{newEndpoint.ID}, PartialMatch: false, } @@ -113,7 +112,7 @@ func TestUpdateWithInvalidEdgeGroups(t *testing.T) { Name: "EdgeGroup 2", Dynamic: false, TagIDs: nil, - EndpointIDs: roar.FromSlice([]portainer.EndpointID{8889}), + Endpoints: []portainer.EndpointID{8889}, PartialMatch: false, } diff --git a/api/http/handler/endpointedge/endpointedge_status_inspect.go b/api/http/handler/endpointedge/endpointedge_status_inspect.go index 9bd341561..4d6368493 100644 --- a/api/http/handler/endpointedge/endpointedge_status_inspect.go +++ b/api/http/handler/endpointedge/endpointedge_status_inspect.go @@ -264,6 +264,9 @@ 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 526fc58de..ca9b12723 100644 --- a/api/http/handler/endpointedge/endpointedge_status_inspect_test.go +++ b/api/http/handler/endpointedge/endpointedge_status_inspect_test.go @@ -16,7 +16,6 @@ import ( "github.com/portainer/portainer/api/filesystem" "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/jwt" - "github.com/portainer/portainer/api/roar" "github.com/segmentio/encoding/json" "github.com/stretchr/testify/assert" @@ -367,8 +366,8 @@ func TestEdgeJobsResponse(t *testing.T) { unrelatedEndpoint := localCreateEndpoint(80, nil) staticEdgeGroup := portainer.EdgeGroup{ - ID: 1, - EndpointIDs: roar.FromSlice([]portainer.EndpointID{endpointFromStaticEdgeGroup.ID}), + ID: 1, + Endpoints: []portainer.EndpointID{endpointFromStaticEdgeGroup.ID}, } err := handler.DataStore.EdgeGroup().Create(&staticEdgeGroup) require.NoError(t, err) diff --git a/api/http/handler/endpointgroups/endpoints.go b/api/http/handler/endpointgroups/endpoints.go index 8b420f2a6..b34032d9e 100644 --- a/api/http/handler/endpointgroups/endpoints.go +++ b/api/http/handler/endpointgroups/endpoints.go @@ -21,10 +21,17 @@ func (handler *Handler) updateEndpointRelations(tx dataservices.DataStoreTx, end } endpointRelation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) - if err != nil { + if err != nil && !tx.IsErrObjectNotFound(err) { 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 3cfe934bc..1c6415023 100644 --- a/api/http/handler/endpoints/endpoint_create.go +++ b/api/http/handler/endpoints/endpoint_create.go @@ -563,10 +563,6 @@ 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 a9b4ae5dc..f26b9dd13 100644 --- a/api/http/handler/endpoints/endpoint_delete.go +++ b/api/http/handler/endpoints/endpoint_delete.go @@ -3,6 +3,7 @@ package endpoints import ( "errors" "net/http" + "slices" "strconv" portainer "github.com/portainer/portainer/api" @@ -199,7 +200,9 @@ func (handler *Handler) deleteEndpoint(tx dataservices.DataStoreTx, endpointID p } for _, edgeGroup := range edgeGroups { - edgeGroup.EndpointIDs.Remove(endpoint.ID) + edgeGroup.Endpoints = slices.DeleteFunc(edgeGroup.Endpoints, func(e portainer.EndpointID) bool { + return e == endpoint.ID + }) if err := tx.EdgeGroup().Update(edgeGroup.ID, &edgeGroup); err != nil { log.Warn().Err(err).Msg("Unable to update edge group") diff --git a/api/http/handler/endpoints/endpoint_delete_test.go b/api/http/handler/endpoints/endpoint_delete_test.go index 73b2b878b..309b45ffe 100644 --- a/api/http/handler/endpoints/endpoint_delete_test.go +++ b/api/http/handler/endpoints/endpoint_delete_test.go @@ -11,7 +11,6 @@ import ( "github.com/portainer/portainer/api/datastore" "github.com/portainer/portainer/api/http/proxy" "github.com/portainer/portainer/api/internal/testhelpers" - "github.com/portainer/portainer/api/roar" ) func TestEndpointDeleteEdgeGroupsConcurrently(t *testing.T) { @@ -22,7 +21,7 @@ func TestEndpointDeleteEdgeGroupsConcurrently(t *testing.T) { handler := NewHandler(testhelpers.NewTestRequestBouncer()) handler.DataStore = store handler.ProxyManager = proxy.NewManager(nil) - handler.ProxyManager.NewProxyFactory(nil, nil, nil, nil, nil, nil, nil, nil, nil) + handler.ProxyManager.NewProxyFactory(nil, nil, nil, nil, nil, nil, nil, nil) // Create all the environments and add them to the same edge group @@ -43,9 +42,9 @@ func TestEndpointDeleteEdgeGroupsConcurrently(t *testing.T) { } if err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "edgegroup-1", - EndpointIDs: roar.FromSlice(endpointIDs), + ID: 1, + Name: "edgegroup-1", + Endpoints: endpointIDs, }); err != nil { t.Fatal("could not create edge group:", err) } @@ -79,7 +78,7 @@ func TestEndpointDeleteEdgeGroupsConcurrently(t *testing.T) { t.Fatal("could not retrieve the edge group:", err) } - if edgeGroup.EndpointIDs.Len() > 0 { + if len(edgeGroup.Endpoints) > 0 { t.Fatal("the edge group is not consistent") } } diff --git a/api/http/handler/endpoints/endpoint_list.go b/api/http/handler/endpoints/endpoint_list.go index 43b14ad6a..86f1b1d3c 100644 --- a/api/http/handler/endpoints/endpoint_list.go +++ b/api/http/handler/endpoints/endpoint_list.go @@ -95,11 +95,12 @@ func (handler *Handler) endpointList(w http.ResponseWriter, r *http.Request) *ht return httperror.BadRequest("Invalid query parameters", err) } - filteredEndpoints, totalAvailableEndpoints, err := handler.filterEndpointsByQuery(endpoints, query, endpointGroups, edgeGroups, settings, securityContext) + filteredEndpoints := security.FilterEndpoints(endpoints, endpointGroups, securityContext) + + filteredEndpoints, totalAvailableEndpoints, err := handler.filterEndpointsByQuery(filteredEndpoints, query, endpointGroups, edgeGroups, settings) 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 5bc4a930d..e81bc34a9 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(tx, r, registries, endpoint, user, securityContext.UserMemberships) + registries, handleError := handler.filterRegistriesByAccess(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(tx dataservices.DataStoreTx, r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User, memberships []portainer.TeamMembership) ([]portainer.Registry, *httperror.HandlerError) { +func (handler *Handler) filterRegistriesByAccess(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(tx, r, registries, endpoint, user, memberships) + return handler.filterKubernetesEndpointRegistries(r, registries, endpoint, user, memberships) } -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) { +func (handler *Handler) filterKubernetesEndpointRegistries(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(tx dataservices.DataS return registries, nil } - return handler.filterKubernetesRegistriesByUserRole(tx, r, registries, endpoint, user) + return handler.filterKubernetesRegistriesByUserRole(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(tx dataservices.DataStoreTx, r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User) ([]portainer.Registry, *httperror.HandlerError) { +func (handler *Handler) filterKubernetesRegistriesByUserRole(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(tx dataservices.Dat return nil, httperror.InternalServerError("Unable to retrieve info from request context", err) } - userNamespaces, err := handler.userNamespaces(tx, endpoint, user) + userNamespaces, err := handler.userNamespaces(endpoint, user) if err != nil { return nil, httperror.InternalServerError("unable to retrieve user namespaces", err) } @@ -186,7 +186,7 @@ func (handler *Handler) filterKubernetesRegistriesByUserRole(tx dataservices.Dat return filterRegistriesByNamespaces(registries, endpoint.ID, userNamespaces), nil } -func (handler *Handler) userNamespaces(tx dataservices.DataStoreTx, endpoint *portainer.Endpoint, user *portainer.User) ([]string, error) { +func (handler *Handler) userNamespaces(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(tx dataservices.DataStoreTx, endpoint *po return nil, err } - userMemberships, err := tx.TeamMembership().TeamMembershipsByUserID(user.ID) + userMemberships, err := handler.DataStore.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 961cad147..9b6004d1c 100644 --- a/api/http/handler/endpoints/filter.go +++ b/api/http/handler/endpoints/filter.go @@ -11,10 +11,9 @@ 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/roar" + "github.com/portainer/portainer/api/slicesx" "github.com/portainer/portainer/pkg/libhttp/request" "github.com/pkg/errors" @@ -141,14 +140,11 @@ func (handler *Handler) filterEndpointsByQuery( groups []portainer.EndpointGroup, edgeGroups []portainer.EdgeGroup, settings *portainer.Settings, - context *security.RestrictedRequestContext, ) ([]portainer.Endpoint, int, error) { totalAvailableEndpoints := len(filteredEndpoints) if len(query.endpointIds) > 0 { - endpointIDs := roar.FromSlice(query.endpointIds) - - filteredEndpoints = filteredEndpointsByIds(filteredEndpoints, endpointIDs) + filteredEndpoints = filteredEndpointsByIds(filteredEndpoints, query.endpointIds) } if len(query.excludeIds) > 0 { @@ -185,16 +181,11 @@ 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 }) @@ -277,7 +268,7 @@ func filterEndpointsByEdgeStack(endpoints []portainer.Endpoint, edgeStackId port return nil, errors.WithMessage(err, "Unable to retrieve edge stack from the database") } - envIds := roar.Roar[portainer.EndpointID]{} + envIds := make([]portainer.EndpointID, 0) for _, edgeGroupdId := range stack.EdgeGroups { edgeGroup, err := datastore.EdgeGroup().Read(edgeGroupdId) if err != nil { @@ -289,37 +280,30 @@ func filterEndpointsByEdgeStack(endpoints []portainer.Endpoint, edgeStackId port if err != nil { return nil, errors.WithMessage(err, "Unable to retrieve environments and environment groups for Edge group") } - edgeGroup.EndpointIDs = roar.FromSlice(endpointIDs) + edgeGroup.Endpoints = endpointIDs } - envIds.Union(edgeGroup.EndpointIDs) + envIds = append(envIds, edgeGroup.Endpoints...) } if statusFilter != nil { - var innerErr error - - envIds.Iterate(func(envId portainer.EndpointID) bool { + n := 0 + for _, envId := range envIds { edgeStackStatus, err := datastore.EdgeStackStatus().Read(edgeStackId, envId) - if dataservices.IsErrObjectNotFound(err) { - return true - } else if err != nil { - innerErr = errors.WithMessagef(err, "Unable to retrieve edge stack status for environment %d", envId) - return false + if err != nil { + return nil, errors.WithMessagef(err, "Unable to retrieve edge stack status for environment %d", envId) } - if !endpointStatusInStackMatchesFilter(edgeStackStatus, portainer.EndpointID(envId), *statusFilter) { - envIds.Remove(envId) + if endpointStatusInStackMatchesFilter(edgeStackStatus, envId, *statusFilter) { + envIds[n] = envId + n++ } - - return true - }) - - if innerErr != nil { - return nil, innerErr } + envIds = envIds[:n] } - filteredEndpoints := filteredEndpointsByIds(endpoints, envIds) + uniqueIds := slicesx.Unique(envIds) + filteredEndpoints := filteredEndpointsByIds(endpoints, uniqueIds) return filteredEndpoints, nil } @@ -351,14 +335,16 @@ func filterEndpointsByEdgeGroupIDs(endpoints []portainer.Endpoint, edgeGroups [] } edgeGroups = edgeGroups[:n] - endpointIDSet := roar.Roar[portainer.EndpointID]{} + endpointIDSet := make(map[portainer.EndpointID]struct{}) for _, edgeGroup := range edgeGroups { - endpointIDSet.Union(edgeGroup.EndpointIDs) + for _, endpointID := range edgeGroup.Endpoints { + endpointIDSet[endpointID] = struct{}{} + } } n = 0 for _, endpoint := range endpoints { - if endpointIDSet.Contains(endpoint.ID) { + if _, exists := endpointIDSet[endpoint.ID]; exists { endpoints[n] = endpoint n++ } @@ -374,11 +360,12 @@ func filterEndpointsByExcludeEdgeGroupIDs(endpoints []portainer.Endpoint, edgeGr } n := 0 - excludeEndpointIDSet := roar.Roar[portainer.EndpointID]{} - + excludeEndpointIDSet := make(map[portainer.EndpointID]struct{}) for _, edgeGroup := range edgeGroups { if _, ok := excludeEdgeGroupIDSet[edgeGroup.ID]; ok { - excludeEndpointIDSet.Union(edgeGroup.EndpointIDs) + for _, endpointID := range edgeGroup.Endpoints { + excludeEndpointIDSet[endpointID] = struct{}{} + } } else { edgeGroups[n] = edgeGroup n++ @@ -388,7 +375,7 @@ func filterEndpointsByExcludeEdgeGroupIDs(endpoints []portainer.Endpoint, edgeGr n = 0 for _, endpoint := range endpoints { - if !excludeEndpointIDSet.Contains(endpoint.ID) { + if _, ok := excludeEndpointIDSet[endpoint.ID]; !ok { endpoints[n] = endpoint n++ } @@ -613,10 +600,15 @@ func endpointFullMatchTags(endpoint portainer.Endpoint, endpointGroup portainer. return len(missingTags) == 0 } -func filteredEndpointsByIds(endpoints []portainer.Endpoint, ids roar.Roar[portainer.EndpointID]) []portainer.Endpoint { +func filteredEndpointsByIds(endpoints []portainer.Endpoint, ids []portainer.EndpointID) []portainer.Endpoint { + idsSet := make(map[portainer.EndpointID]bool, len(ids)) + for _, id := range ids { + idsSet[id] = true + } + n := 0 for _, endpoint := range endpoints { - if ids.Contains(endpoint.ID) { + if idsSet[endpoint.ID] { endpoints[n] = endpoint n++ } diff --git a/api/http/handler/endpoints/filter_test.go b/api/http/handler/endpoints/filter_test.go index 642448b86..f19d0a276 100644 --- a/api/http/handler/endpoints/filter_test.go +++ b/api/http/handler/endpoints/filter_test.go @@ -6,13 +6,10 @@ 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/roar" "github.com/portainer/portainer/api/slicesx" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) type filterTest struct { @@ -177,7 +174,7 @@ func BenchmarkFilterEndpointsBySearchCriteria_PartialMatch(b *testing.B) { edgeGroups = append(edgeGroups, portainer.EdgeGroup{ ID: portainer.EdgeGroupID(i + 1), Name: "edge-group-" + strconv.Itoa(i+1), - EndpointIDs: roar.FromSlice(endpointIDs), + Endpoints: append([]portainer.EndpointID{}, endpointIDs...), Dynamic: true, TagIDs: []portainer.TagID{1, 2, 3}, PartialMatch: true, @@ -224,11 +221,11 @@ func BenchmarkFilterEndpointsBySearchCriteria_FullMatch(b *testing.B) { edgeGroups := []portainer.EdgeGroup{} for i := range 1000 { edgeGroups = append(edgeGroups, portainer.EdgeGroup{ - ID: portainer.EdgeGroupID(i + 1), - Name: "edge-group-" + strconv.Itoa(i+1), - EndpointIDs: roar.FromSlice(endpointIDs), - Dynamic: true, - TagIDs: []portainer.TagID{1}, + ID: portainer.EdgeGroupID(i + 1), + Name: "edge-group-" + strconv.Itoa(i+1), + Endpoints: append([]portainer.EndpointID{}, endpointIDs...), + Dynamic: true, + TagIDs: []portainer.TagID{1}, }) } @@ -266,7 +263,6 @@ func runTest(t *testing.T, test filterTest, handler *Handler, endpoints []portai []portainer.EndpointGroup{}, []portainer.EdgeGroup{}, &portainer.Settings{}, - &security.RestrictedRequestContext{IsAdmin: true}, ) is.NoError(err) @@ -302,127 +298,3 @@ func setupFilterTest(t *testing.T, endpoints []portainer.Endpoint) *Handler { return handler } - -func TestFilterEndpointsByEdgeStack(t *testing.T) { - _, store := datastore.MustNewTestStore(t, false, false) - - endpoints := []portainer.Endpoint{ - {ID: 1, Name: "Endpoint 1"}, - {ID: 2, Name: "Endpoint 2"}, - {ID: 3, Name: "Endpoint 3"}, - {ID: 4, Name: "Endpoint 4"}, - } - - edgeStackId := portainer.EdgeStackID(1) - - err := store.EdgeStack().Create(edgeStackId, &portainer.EdgeStack{ - ID: edgeStackId, - Name: "Test Edge Stack", - EdgeGroups: []portainer.EdgeGroupID{1, 2}, - }) - require.NoError(t, err) - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Edge Group 1", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{1}), - }) - require.NoError(t, err) - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 2, - Name: "Edge Group 2", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{2, 3}), - }) - require.NoError(t, err) - - es, err := filterEndpointsByEdgeStack(endpoints, edgeStackId, nil, store) - require.NoError(t, err) - require.Len(t, es, 3) - require.Contains(t, es, endpoints[0]) // Endpoint 1 - require.Contains(t, es, endpoints[1]) // Endpoint 2 - require.Contains(t, es, endpoints[2]) // Endpoint 3 - require.NotContains(t, es, endpoints[3]) // Endpoint 4 -} - -func TestFilterEndpointsByEdgeGroup(t *testing.T) { - _, store := datastore.MustNewTestStore(t, false, false) - - endpoints := []portainer.Endpoint{ - {ID: 1, Name: "Endpoint 1"}, - {ID: 2, Name: "Endpoint 2"}, - {ID: 3, Name: "Endpoint 3"}, - {ID: 4, Name: "Endpoint 4"}, - } - - err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Edge Group 1", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{1}), - }) - require.NoError(t, err) - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 2, - Name: "Edge Group 2", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{2, 3}), - }) - require.NoError(t, err) - - edgeGroups, err := store.EdgeGroup().ReadAll() - require.NoError(t, err) - - es, egs := filterEndpointsByEdgeGroupIDs(endpoints, edgeGroups, []portainer.EdgeGroupID{1, 2}) - require.NoError(t, err) - - require.Len(t, es, 3) - require.Contains(t, es, endpoints[0]) // Endpoint 1 - require.Contains(t, es, endpoints[1]) // Endpoint 2 - require.Contains(t, es, endpoints[2]) // Endpoint 3 - require.NotContains(t, es, endpoints[3]) // Endpoint 4 - - require.Len(t, egs, 2) - require.Equal(t, egs[0].ID, portainer.EdgeGroupID(1)) - require.Equal(t, egs[1].ID, portainer.EdgeGroupID(2)) -} - -func TestFilterEndpointsByExcludeEdgeGroupIDs(t *testing.T) { - _, store := datastore.MustNewTestStore(t, false, false) - - endpoints := []portainer.Endpoint{ - {ID: 1, Name: "Endpoint 1"}, - {ID: 2, Name: "Endpoint 2"}, - {ID: 3, Name: "Endpoint 3"}, - {ID: 4, Name: "Endpoint 4"}, - } - - err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 1, - Name: "Edge Group 1", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{1}), - }) - require.NoError(t, err) - - err = store.EdgeGroup().Create(&portainer.EdgeGroup{ - ID: 2, - Name: "Edge Group 2", - EndpointIDs: roar.FromSlice([]portainer.EndpointID{2, 3}), - }) - require.NoError(t, err) - - edgeGroups, err := store.EdgeGroup().ReadAll() - require.NoError(t, err) - - es, egs := filterEndpointsByExcludeEdgeGroupIDs(endpoints, edgeGroups, []portainer.EdgeGroupID{1}) - require.NoError(t, err) - - require.Len(t, es, 3) - require.Equal(t, es, []portainer.Endpoint{ - {ID: 2, Name: "Endpoint 2"}, - {ID: 3, Name: "Endpoint 3"}, - {ID: 4, Name: "Endpoint 4"}, - }) - - require.Len(t, egs, 1) - require.Equal(t, egs[0].ID, portainer.EdgeGroupID(2)) -} diff --git a/api/http/handler/endpoints/update_edge_relations.go b/api/http/handler/endpoints/update_edge_relations.go index c487519f0..1390c9fd4 100644 --- a/api/http/handler/endpoints/update_edge_relations.go +++ b/api/http/handler/endpoints/update_edge_relations.go @@ -17,7 +17,17 @@ func (handler *Handler) updateEdgeRelations(tx dataservices.DataStoreTx, endpoin relation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) if err != nil { - return errors.WithMessage(err, "Unable to retrieve environment relation inside the database") + 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") + } } endpointGroup, err := tx.EndpointGroup().Read(endpoint.GroupID) diff --git a/api/http/handler/endpoints/utils_update_edge_groups.go b/api/http/handler/endpoints/utils_update_edge_groups.go index 6207acbc5..bd9c413d7 100644 --- a/api/http/handler/endpoints/utils_update_edge_groups.go +++ b/api/http/handler/endpoints/utils_update_edge_groups.go @@ -1,11 +1,12 @@ package endpoints import ( + "slices" + + "github.com/pkg/errors" portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/set" - - "github.com/pkg/errors" ) func updateEnvironmentEdgeGroups(tx dataservices.DataStoreTx, newEdgeGroups []portainer.EdgeGroupID, environmentID portainer.EndpointID) (bool, error) { @@ -18,8 +19,10 @@ func updateEnvironmentEdgeGroups(tx dataservices.DataStoreTx, newEdgeGroups []po environmentEdgeGroupsSet := set.Set[portainer.EdgeGroupID]{} for _, edgeGroup := range edgeGroups { - if edgeGroup.EndpointIDs.Contains(environmentID) { - environmentEdgeGroupsSet[edgeGroup.ID] = true + for _, eID := range edgeGroup.Endpoints { + if eID == environmentID { + environmentEdgeGroupsSet[edgeGroup.ID] = true + } } } @@ -49,16 +52,20 @@ func updateEnvironmentEdgeGroups(tx dataservices.DataStoreTx, newEdgeGroups []po } removeEdgeGroups := environmentEdgeGroupsSet.Difference(newEdgeGroupsSet) - if err := updateSet(removeEdgeGroups, func(edgeGroup *portainer.EdgeGroup) { - edgeGroup.EndpointIDs.Remove(environmentID) - }); err != nil { + err = updateSet(removeEdgeGroups, func(edgeGroup *portainer.EdgeGroup) { + edgeGroup.Endpoints = slices.DeleteFunc(edgeGroup.Endpoints, func(eID portainer.EndpointID) bool { + return eID == environmentID + }) + }) + if err != nil { return false, err } addToEdgeGroups := newEdgeGroupsSet.Difference(environmentEdgeGroupsSet) - if err := updateSet(addToEdgeGroups, func(edgeGroup *portainer.EdgeGroup) { - edgeGroup.EndpointIDs.Add(environmentID) - }); err != nil { + err = updateSet(addToEdgeGroups, func(edgeGroup *portainer.EdgeGroup) { + edgeGroup.Endpoints = append(edgeGroup.Endpoints, environmentID) + }) + if err != nil { return false, err } diff --git a/api/http/handler/endpoints/utils_update_edge_groups_test.go b/api/http/handler/endpoints/utils_update_edge_groups_test.go index a57651fae..e89d501fb 100644 --- a/api/http/handler/endpoints/utils_update_edge_groups_test.go +++ b/api/http/handler/endpoints/utils_update_edge_groups_test.go @@ -6,7 +6,6 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/datastore" - "github.com/stretchr/testify/assert" ) @@ -15,9 +14,10 @@ func Test_updateEdgeGroups(t *testing.T) { groups := make([]portainer.EdgeGroup, len(names)) for index, name := range names { group := &portainer.EdgeGroup{ - Name: name, - Dynamic: false, - TagIDs: make([]portainer.TagID, 0), + Name: name, + Dynamic: false, + TagIDs: make([]portainer.TagID, 0), + Endpoints: make([]portainer.EndpointID, 0), } if err := store.EdgeGroup().Create(group); err != nil { @@ -35,8 +35,13 @@ func Test_updateEdgeGroups(t *testing.T) { group, err := store.EdgeGroup().Read(groupID) is.NoError(err) - is.True(group.EndpointIDs.Contains(endpointID), - "expected endpoint to be in group") + for _, endpoint := range group.Endpoints { + if endpoint == endpointID { + return + } + } + + is.Fail("expected endpoint to be in group") } } @@ -76,7 +81,7 @@ func Test_updateEdgeGroups(t *testing.T) { endpointGroups := groupsByName(groups, testCase.endpointGroupNames) for _, group := range endpointGroups { - group.EndpointIDs.Add(testCase.endpoint.ID) + group.Endpoints = append(group.Endpoints, testCase.endpoint.ID) err = store.EdgeGroup().Update(group.ID, &group) is.NoError(err) diff --git a/api/http/handler/endpoints/utils_update_tags_test.go b/api/http/handler/endpoints/utils_update_tags_test.go index 527f963a4..ee42e4e10 100644 --- a/api/http/handler/endpoints/utils_update_tags_test.go +++ b/api/http/handler/endpoints/utils_update_tags_test.go @@ -10,6 +10,7 @@ import ( ) func Test_updateTags(t *testing.T) { + createTags := func(store *datastore.Store, tagNames []string) ([]portainer.Tag, error) { tags := make([]portainer.Tag, len(tagNames)) for index, tagName := range tagNames { diff --git a/api/http/handler/file/handler.go b/api/http/handler/file/handler.go index 9e57478c8..66f81b64a 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, csp bool, wasInstanceDisabled func() bool) *Handler { +func NewHandler(assetPublicPath string, wasInstanceDisabled func() bool) *Handler { h := &Handler{ Handler: security.MWSecureHeaders( gzhttp.GzipHandler(http.FileServer(http.Dir(assetPublicPath))), featureflags.IsEnabled("hsts"), - csp, + featureflags.IsEnabled("csp"), ), wasInstanceDisabled: wasInstanceDisabled, } @@ -36,7 +36,6 @@ func isHTML(acceptContent []string) bool { return true } } - return false } @@ -44,13 +43,11 @@ 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/gitops/git_repo_file_preview.go b/api/http/handler/gitops/git_repo_file_preview.go index 43c08c870..1eaa52716 100644 --- a/api/http/handler/gitops/git_repo_file_preview.go +++ b/api/http/handler/gitops/git_repo_file_preview.go @@ -17,11 +17,10 @@ type fileResponse struct { } type repositoryFilePreviewPayload struct { - Repository string `json:"repository" example:"https://github.com/openfaas/faas" validate:"required"` - Reference string `json:"reference" example:"refs/heads/master"` - Username string `json:"username" example:"myGitUsername"` - Password string `json:"password" example:"myGitPassword"` - AuthorizationType gittypes.GitCredentialAuthType `json:"authorizationType"` + Repository string `json:"repository" example:"https://github.com/openfaas/faas" validate:"required"` + Reference string `json:"reference" example:"refs/heads/master"` + Username string `json:"username" example:"myGitUsername"` + Password string `json:"password" example:"myGitPassword"` // Path to file whose content will be read TargetFile string `json:"targetFile" example:"docker-compose.yml"` // TLSSkipVerify skips SSL verification when cloning the Git repository @@ -69,15 +68,7 @@ func (handler *Handler) gitOperationRepoFilePreview(w http.ResponseWriter, r *ht return httperror.InternalServerError("Unable to create temporary folder", err) } - err = handler.gitService.CloneRepository( - projectPath, - payload.Repository, - payload.Reference, - payload.Username, - payload.Password, - payload.AuthorizationType, - payload.TLSSkipVerify, - ) + err = handler.gitService.CloneRepository(projectPath, payload.Repository, payload.Reference, payload.Username, payload.Password, payload.TLSSkipVerify) if err != nil { if errors.Is(err, gittypes.ErrAuthenticationFailure) { return httperror.BadRequest("Invalid git credential", err) diff --git a/api/http/handler/handler.go b/api/http/handler/handler.go index 1704eb316..1ae55a002 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.32.0 +// @version 2.31.0 // @description.markdown api-description.md // @termsOfService diff --git a/api/http/handler/helm/helm_install.go b/api/http/handler/helm/helm_install.go index 33b0d82cd..83ae0db51 100644 --- a/api/http/handler/helm/helm_install.go +++ b/api/http/handler/helm/helm_install.go @@ -46,24 +46,18 @@ var errChartNameInvalid = errors.New("invalid chart name. " + // @produce json // @param id path int true "Environment(Endpoint) identifier" // @param payload body installChartPayload true "Chart details" -// @param dryRun query bool false "Dry run" // @success 201 {object} release.Release "Created" // @failure 401 "Unauthorized" // @failure 404 "Environment(Endpoint) or ServiceAccount not found" // @failure 500 "Server error" // @router /endpoints/{id}/kubernetes/helm [post] func (handler *Handler) helmInstall(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { - dryRun, err := request.RetrieveBooleanQueryParameter(r, "dryRun", true) - if err != nil { - return httperror.BadRequest("Invalid dryRun query parameter", err) - } - var payload installChartPayload if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return httperror.BadRequest("Invalid Helm install payload", err) } - release, err := handler.installChart(r, payload, dryRun) + release, err := handler.installChart(r, payload) if err != nil { return httperror.InternalServerError("Unable to install a chart", err) } @@ -100,7 +94,7 @@ func (p *installChartPayload) Validate(_ *http.Request) error { return nil } -func (handler *Handler) installChart(r *http.Request, p installChartPayload, dryRun bool) (*release.Release, error) { +func (handler *Handler) installChart(r *http.Request, p installChartPayload) (*release.Release, error) { clusterAccess, httperr := handler.getHelmClusterAccess(r) if httperr != nil { return nil, httperr.Err @@ -113,7 +107,6 @@ func (handler *Handler) installChart(r *http.Request, p installChartPayload, dry Namespace: p.Namespace, Repo: p.Repo, Atomic: p.Atomic, - DryRun: dryRun, KubernetesClusterAccess: clusterAccess, } @@ -141,14 +134,13 @@ func (handler *Handler) installChart(r *http.Request, p installChartPayload, dry return nil, err } - if !installOpts.DryRun { - manifest, err := handler.applyPortainerLabelsToHelmAppManifest(r, installOpts, release.Manifest) - if err != nil { - return nil, err - } - if err := handler.updateHelmAppManifest(r, manifest, installOpts.Namespace); err != nil { - return nil, err - } + manifest, err := handler.applyPortainerLabelsToHelmAppManifest(r, installOpts, release.Manifest) + if err != nil { + return nil, err + } + + if err := handler.updateHelmAppManifest(r, manifest, installOpts.Namespace); err != nil { + return nil, err } return release, nil diff --git a/api/http/handler/kubernetes/client.go b/api/http/handler/kubernetes/client.go index a7f2485e3..6612ab7f4 100644 --- a/api/http/handler/kubernetes/client.go +++ b/api/http/handler/kubernetes/client.go @@ -2,10 +2,8 @@ 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" @@ -27,13 +25,7 @@ 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) } - 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))) + pcli, err := handler.KubernetesClientFactory.GetPrivilegedKubeClient(endpoint) 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) diff --git a/api/http/handler/kubernetes/event.go b/api/http/handler/kubernetes/event.go index 25f024303..0e226d5ec 100644 --- a/api/http/handler/kubernetes/event.go +++ b/api/http/handler/kubernetes/event.go @@ -20,7 +20,7 @@ import ( // @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" +// @success 200 {object} models.Event[] "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." @@ -68,7 +68,7 @@ func (handler *Handler) getKubernetesEventsForNamespace(w http.ResponseWriter, r // @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" +// @success 200 {object} models.Event[] "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." diff --git a/api/http/handler/kubernetes/handler.go b/api/http/handler/kubernetes/handler.go index a8a5898c8..07f6bdf3f 100644 --- a/api/http/handler/kubernetes/handler.go +++ b/api/http/handler/kubernetes/handler.go @@ -146,7 +146,7 @@ func (h *Handler) getProxyKubeClient(r *http.Request) (portainer.KubeClient, *ht 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), strconv.Itoa(int(tokenData.ID))) + cli, ok := h.KubernetesClientFactory.GetProxyKubeClient(strconv.Itoa(endpointID), tokenData.Token) if !ok { return nil, httperror.InternalServerError("an error occurred during the getProxyKubeClient operation,failed to get proxy KubeClient", nil) } @@ -179,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), strconv.Itoa(int(tokenData.ID))) + _, ok := handler.KubernetesClientFactory.GetProxyKubeClient(strconv.Itoa(endpointID), tokenData.Token) if ok { next.ServeHTTP(w, r) return @@ -269,7 +269,7 @@ func (handler *Handler) kubeClientMiddleware(next http.Handler) http.Handler { return } - handler.KubernetesClientFactory.SetProxyKubeClient(strconv.Itoa(int(endpoint.ID)), strconv.Itoa(int(tokenData.ID)), kubeCli) + handler.KubernetesClientFactory.SetProxyKubeClient(strconv.Itoa(int(endpoint.ID)), tokenData.Token, kubeCli) next.ServeHTTP(w, r) }) } diff --git a/api/http/handler/kubernetes/namespaces.go b/api/http/handler/kubernetes/namespaces.go index 75dae9e69..2efde3b85 100644 --- a/api/http/handler/kubernetes/namespaces.go +++ b/api/http/handler/kubernetes/namespaces.go @@ -22,7 +22,6 @@ 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." @@ -37,12 +36,6 @@ 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") @@ -55,14 +48,6 @@ 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/registries/handler.go b/api/http/handler/registries/handler.go index 026039833..dee14885e 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/registryutils/access" + "github.com/portainer/portainer/api/internal/endpointutils" + "github.com/portainer/portainer/api/kubernetes" "github.com/portainer/portainer/api/kubernetes/cli" "github.com/portainer/portainer/api/pendingactions" httperror "github.com/portainer/portainer/pkg/libhttp/error" @@ -17,7 +17,6 @@ import ( "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/rs/zerolog/log" ) func hideFields(registry *portainer.Registry, hideAccesses bool) { @@ -57,20 +56,17 @@ 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) - // 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.Handle("/registries/{id}", httperror.LoggerHandler(handler.registryInspect)).Methods(http.MethodGet) authenticatedRouter.PathPrefix("/registries/proxies/gitlab").Handler(httperror.LoggerHandler(handler.proxyRequestsToGitlabAPIWithoutRegistry)) } @@ -92,7 +88,9 @@ 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) @@ -100,6 +98,11 @@ 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 @@ -125,68 +128,47 @@ func (handler *Handler) userHasRegistryAccess(r *http.Request, registry *portain return false, false, err } - // Use the enhanced registry access utility function that includes namespace validation - _, err = access.GetAccessibleRegistry( - handler.DataStore, - handler.K8sClientFactory, - securityContext.UserID, - endpointId, - registry.ID, - ) + memberships, err := handler.DataStore.TeamMembership().TeamMembershipsByUserID(user.ID) if err != nil { - return false, false, nil // No access + 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) - }) + // 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 } diff --git a/api/http/handler/registries/registry_access_test.go b/api/http/handler/registries/registry_access_test.go deleted file mode 100644 index 8231f4d66..000000000 --- a/api/http/handler/registries/registry_access_test.go +++ /dev/null @@ -1,89 +0,0 @@ -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 f606a953e..a1f0bd9c5 100644 --- a/api/http/handler/registries/registry_inspect.go +++ b/api/http/handler/registries/registry_inspect.go @@ -4,12 +4,10 @@ import ( "net/http" portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/http/security" + httperrors "github.com/portainer/portainer/api/http/errors" 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 @@ -33,11 +31,6 @@ 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) @@ -45,12 +38,14 @@ 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) } - // Check if user is admin to determine if we should hide sensitive fields - securityContext, err := security.RetrieveRestrictedRequestContext(r) + hasAccess, isAdmin, err := handler.userHasRegistryAccess(r, registry) 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, !securityContext.IsAdmin) + hideFields(registry, !isAdmin) return response.JSON(w, registry) } diff --git a/api/http/handler/stacks/stack_update_git.go b/api/http/handler/stacks/stack_update_git.go index 2bdf2b71f..8d0687694 100644 --- a/api/http/handler/stacks/stack_update_git.go +++ b/api/http/handler/stacks/stack_update_git.go @@ -19,15 +19,14 @@ import ( ) type stackGitUpdatePayload struct { - AutoUpdate *portainer.AutoUpdateSettings - Env []portainer.Pair - Prune bool - RepositoryReferenceName string - RepositoryAuthentication bool - RepositoryUsername string - RepositoryPassword string - RepositoryAuthorizationType gittypes.GitCredentialAuthType - TLSSkipVerify bool + AutoUpdate *portainer.AutoUpdateSettings + Env []portainer.Pair + Prune bool + RepositoryReferenceName string + RepositoryAuthentication bool + RepositoryUsername string + RepositoryPassword string + TLSSkipVerify bool } func (payload *stackGitUpdatePayload) Validate(r *http.Request) error { @@ -152,19 +151,11 @@ func (handler *Handler) stackUpdateGit(w http.ResponseWriter, r *http.Request) * } stack.GitConfig.Authentication = &gittypes.GitAuthentication{ - Username: payload.RepositoryUsername, - Password: password, - AuthorizationType: payload.RepositoryAuthorizationType, + Username: payload.RepositoryUsername, + Password: password, } - if _, err := handler.GitService.LatestCommitID( - stack.GitConfig.URL, - stack.GitConfig.ReferenceName, - stack.GitConfig.Authentication.Username, - stack.GitConfig.Authentication.Password, - stack.GitConfig.Authentication.AuthorizationType, - stack.GitConfig.TLSSkipVerify, - ); err != nil { + if _, err := handler.GitService.LatestCommitID(stack.GitConfig.URL, stack.GitConfig.ReferenceName, stack.GitConfig.Authentication.Username, stack.GitConfig.Authentication.Password, stack.GitConfig.TLSSkipVerify); err != nil { return httperror.InternalServerError("Unable to fetch git repository", err) } } else { diff --git a/api/http/handler/stacks/stack_update_git_redeploy.go b/api/http/handler/stacks/stack_update_git_redeploy.go index c595808aa..e65e1e70c 100644 --- a/api/http/handler/stacks/stack_update_git_redeploy.go +++ b/api/http/handler/stacks/stack_update_git_redeploy.go @@ -6,7 +6,6 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/git" - gittypes "github.com/portainer/portainer/api/git/types" httperrors "github.com/portainer/portainer/api/http/errors" "github.com/portainer/portainer/api/http/security" k "github.com/portainer/portainer/api/kubernetes" @@ -20,13 +19,12 @@ import ( ) type stackGitRedployPayload struct { - RepositoryReferenceName string - RepositoryAuthentication bool - RepositoryUsername string - RepositoryPassword string - RepositoryAuthorizationType gittypes.GitCredentialAuthType - Env []portainer.Pair - Prune bool + RepositoryReferenceName string + RepositoryAuthentication bool + RepositoryUsername string + RepositoryPassword string + Env []portainer.Pair + Prune bool // Force a pulling to current image with the original tag though the image is already the latest PullImage bool `example:"false"` @@ -137,16 +135,13 @@ func (handler *Handler) stackGitRedeploy(w http.ResponseWriter, r *http.Request) repositoryUsername := "" repositoryPassword := "" - repositoryAuthType := gittypes.GitCredentialAuthType_Basic if payload.RepositoryAuthentication { repositoryPassword = payload.RepositoryPassword - repositoryAuthType = payload.RepositoryAuthorizationType // When the existing stack is using the custom username/password and the password is not updated, // the stack should keep using the saved username/password if repositoryPassword == "" && stack.GitConfig != nil && stack.GitConfig.Authentication != nil { repositoryPassword = stack.GitConfig.Authentication.Password - repositoryAuthType = stack.GitConfig.Authentication.AuthorizationType } repositoryUsername = payload.RepositoryUsername } @@ -157,7 +152,6 @@ func (handler *Handler) stackGitRedeploy(w http.ResponseWriter, r *http.Request) ReferenceName: stack.GitConfig.ReferenceName, Username: repositoryUsername, Password: repositoryPassword, - AuthType: repositoryAuthType, TLSSkipVerify: stack.GitConfig.TLSSkipVerify, } @@ -172,7 +166,7 @@ func (handler *Handler) stackGitRedeploy(w http.ResponseWriter, r *http.Request) return err } - newHash, err := handler.GitService.LatestCommitID(stack.GitConfig.URL, stack.GitConfig.ReferenceName, repositoryUsername, repositoryPassword, repositoryAuthType, stack.GitConfig.TLSSkipVerify) + newHash, err := handler.GitService.LatestCommitID(stack.GitConfig.URL, stack.GitConfig.ReferenceName, repositoryUsername, repositoryPassword, stack.GitConfig.TLSSkipVerify) if err != nil { return httperror.InternalServerError("Unable get latest commit id", errors.WithMessagef(err, "failed to fetch latest commit id of the stack %v", stack.ID)) } diff --git a/api/http/handler/stacks/update_kubernetes_stack.go b/api/http/handler/stacks/update_kubernetes_stack.go index 42ecbaa04..95195bb10 100644 --- a/api/http/handler/stacks/update_kubernetes_stack.go +++ b/api/http/handler/stacks/update_kubernetes_stack.go @@ -27,13 +27,12 @@ type kubernetesFileStackUpdatePayload struct { } type kubernetesGitStackUpdatePayload struct { - RepositoryReferenceName string - RepositoryAuthentication bool - RepositoryUsername string - RepositoryPassword string - RepositoryAuthorizationType gittypes.GitCredentialAuthType - AutoUpdate *portainer.AutoUpdateSettings - TLSSkipVerify bool + RepositoryReferenceName string + RepositoryAuthentication bool + RepositoryUsername string + RepositoryPassword string + AutoUpdate *portainer.AutoUpdateSettings + TLSSkipVerify bool } func (payload *kubernetesFileStackUpdatePayload) Validate(r *http.Request) error { @@ -77,19 +76,11 @@ func (handler *Handler) updateKubernetesStack(r *http.Request, stack *portainer. } stack.GitConfig.Authentication = &gittypes.GitAuthentication{ - Username: payload.RepositoryUsername, - Password: password, - AuthorizationType: payload.RepositoryAuthorizationType, + Username: payload.RepositoryUsername, + Password: password, } - if _, err := handler.GitService.LatestCommitID( - stack.GitConfig.URL, - stack.GitConfig.ReferenceName, - stack.GitConfig.Authentication.Username, - stack.GitConfig.Authentication.Password, - stack.GitConfig.Authentication.AuthorizationType, - stack.GitConfig.TLSSkipVerify, - ); err != nil { + if _, err := handler.GitService.LatestCommitID(stack.GitConfig.URL, stack.GitConfig.ReferenceName, stack.GitConfig.Authentication.Username, stack.GitConfig.Authentication.Password, stack.GitConfig.TLSSkipVerify); err != nil { return httperror.InternalServerError("Unable to fetch git repository", err) } } diff --git a/api/http/handler/tags/tag_delete.go b/api/http/handler/tags/tag_delete.go index f8f1b7786..4f8554faf 100644 --- a/api/http/handler/tags/tag_delete.go +++ b/api/http/handler/tags/tag_delete.go @@ -8,7 +8,6 @@ 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" @@ -59,9 +58,6 @@ 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) } @@ -107,10 +103,15 @@ func deleteTag(tx dataservices.DataStoreTx, tagID portainer.TagID) error { return httperror.InternalServerError("Unable to retrieve edge stacks from 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 _, 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) + } + } } + for _, edgeGroup := range edgeGroups { edgeGroup.TagIDs = slices.DeleteFunc(edgeGroup.TagIDs, func(t portainer.TagID) bool { return t == tagID @@ -122,16 +123,6 @@ 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) @@ -140,12 +131,19 @@ 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, edgeJobs []portainer.EdgeJob) error { +func updateEndpointRelations(tx dataservices.DataStoreTx, endpoint portainer.Endpoint, edgeGroups []portainer.EdgeGroup, edgeStacks []portainer.EdgeStack) error { endpointRelation, err := tx.EndpointRelation().EndpointRelation(endpoint.ID) - if err != nil { + if err != nil && !tx.IsErrObjectNotFound(err) { 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 @@ -159,25 +157,5 @@ func updateEndpointRelations(tx dataservices.DataStoreTx, endpoint portainer.End endpointRelation.EdgeStacks = stacksSet - 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 + return tx.EndpointRelation().UpdateEndpointRelation(endpoint.ID, endpointRelation) } diff --git a/api/http/handler/tags/tag_delete_test.go b/api/http/handler/tags/tag_delete_test.go index c933610c5..cabf20963 100644 --- a/api/http/handler/tags/tag_delete_test.go +++ b/api/http/handler/tags/tag_delete_test.go @@ -8,20 +8,23 @@ import ( "testing" portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/dataservices" - portainerDsErrors "github.com/portainer/portainer/api/dataservices/errors" "github.com/portainer/portainer/api/datastore" "github.com/portainer/portainer/api/internal/testhelpers" - "github.com/portainer/portainer/api/roar" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestTagDeleteEdgeGroupsConcurrently(t *testing.T) { const tagsCount = 100 - handler, store := setUpHandler(t) + _, 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 + // Create all the tags and add them to the same edge group var tagIDs []portainer.TagID @@ -81,128 +84,3 @@ 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", - EndpointIDs: roar.FromSlice([]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.Equal(t, 0, dynamicEdgeGroup.EndpointIDs.Len(), "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.Equal(t, 1, staticEdgeGroup.EndpointIDs.Len(), "static edge group should have one endpoint") - assert.True(t, staticEdgeGroup.EndpointIDs.Contains(endpoint2.ID), "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) - require.NoError(t, err) - - err = deleteTag(store, 1) - require.NoError(t, 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/template_file.go b/api/http/handler/templates/template_file.go index f9ec0135c..b834eeed9 100644 --- a/api/http/handler/templates/template_file.go +++ b/api/http/handler/templates/template_file.go @@ -5,7 +5,6 @@ import ( "slices" portainer "github.com/portainer/portainer/api" - gittypes "github.com/portainer/portainer/api/git/types" httperror "github.com/portainer/portainer/pkg/libhttp/error" "github.com/portainer/portainer/pkg/libhttp/request" "github.com/portainer/portainer/pkg/libhttp/response" @@ -72,15 +71,7 @@ func (handler *Handler) templateFile(w http.ResponseWriter, r *http.Request) *ht defer handler.cleanUp(projectPath) - if err := handler.GitService.CloneRepository( - projectPath, - template.Repository.URL, - "", - "", - "", - gittypes.GitCredentialAuthType_Basic, - false, - ); err != nil { + if err := handler.GitService.CloneRepository(projectPath, template.Repository.URL, "", "", "", false); err != nil { return httperror.InternalServerError("Unable to clone git repository", err) } diff --git a/api/http/handler/templates/utils_fetch_templates.go b/api/http/handler/templates/utils_fetch_templates.go index fc5c97125..73f9bad56 100644 --- a/api/http/handler/templates/utils_fetch_templates.go +++ b/api/http/handler/templates/utils_fetch_templates.go @@ -40,13 +40,11 @@ func (handler *Handler) fetchTemplates() (*listResponse, *httperror.HandlerError } defer resp.Body.Close() - if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + err = json.NewDecoder(resp.Body).Decode(&body) + if 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 d7edde333..b69e93db3 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, nil, tokenData.ID, endpointID, payload.RegistryID) + _, err = access.GetAccessibleRegistry(handler.DataStore, 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 94133c49a..7a026fcd7 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, nil, tokenData.ID, webhook.EndpointID, payload.RegistryID) + _, err = access.GetAccessibleRegistry(handler.DataStore, 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 0050e4300..c88731dd3 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,6 +51,7 @@ 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 e746fd819..668346098 100644 --- a/api/http/middlewares/plaintext_http_request.go +++ b/api/http/middlewares/plaintext_http_request.go @@ -3,7 +3,6 @@ package middlewares import ( "net/http" "slices" - "strings" "github.com/gorilla/csrf" ) @@ -17,45 +16,6 @@ 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) @@ -64,7 +24,7 @@ func (h *plainTextHTTPRequestHandler) ServeHTTP(w http.ResponseWriter, r *http.R req := r // If original request was HTTPS (via proxy), keep CSRF checks. - if !isHTTPSRequest(r) { + if xfproto := r.Header.Get("X-Forwarded-Proto"); xfproto != "https" { req = csrf.PlaintextHTTPRequest(r) } diff --git a/api/http/middlewares/plaintext_http_request_test.go b/api/http/middlewares/plaintext_http_request_test.go deleted file mode 100644 index 33912be80..000000000 --- a/api/http/middlewares/plaintext_http_request_test.go +++ /dev/null @@ -1,173 +0,0 @@ -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 4759d9214..fcb49b23d 100644 --- a/api/http/models/kubernetes/application.go +++ b/api/http/models/kubernetes/application.go @@ -38,30 +38,14 @@ 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 { - 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"` + Status string `json:"Status"` } type Configuration struct { @@ -88,8 +72,8 @@ type TLSInfo struct { // Existing types type K8sApplicationResource struct { - CPURequest float64 `json:"CpuRequest,omitempty"` - CPULimit float64 `json:"CpuLimit,omitempty"` - MemoryRequest int64 `json:"MemoryRequest,omitempty"` - MemoryLimit int64 `json:"MemoryLimit,omitempty"` + CPURequest float64 `json:"CpuRequest"` + CPULimit float64 `json:"CpuLimit"` + MemoryRequest int64 `json:"MemoryRequest"` + MemoryLimit int64 `json:"MemoryLimit"` } diff --git a/api/http/proxy/factory/docker/access_control.go b/api/http/proxy/factory/docker/access_control.go index ac25a7b7a..e945d38da 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.FilterInPlace(xs, func(x string) bool { return len(x) > 0 }) + xs = slicesx.Filter(xs, func(x string) bool { return len(x) > 0 }) return slicesx.Unique(xs) } diff --git a/api/http/proxy/factory/docker/registry.go b/api/http/proxy/factory/docker/registry.go index 7036853c7..ecf7935f1 100644 --- a/api/http/proxy/factory/docker/registry.go +++ b/api/http/proxy/factory/docker/registry.go @@ -55,13 +55,12 @@ func createRegistryAuthenticationHeader( return } - if err = registryutils.PrepareRegistryCredentials(dataStore, matchingRegistry); err != nil { + if err = registryutils.EnsureRegTokenValid(dataStore, matchingRegistry); err != nil { return } authenticationHeader.Serveraddress = matchingRegistry.URL - authenticationHeader.Username = matchingRegistry.Username - authenticationHeader.Password = matchingRegistry.Password + authenticationHeader.Username, authenticationHeader.Password, err = registryutils.GetRegEffectiveCredential(matchingRegistry) return } diff --git a/api/http/proxy/factory/docker/transport.go b/api/http/proxy/factory/docker/transport.go index dae72ecc1..49f1cd501 100644 --- a/api/http/proxy/factory/docker/transport.go +++ b/api/http/proxy/factory/docker/transport.go @@ -15,7 +15,6 @@ import ( portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" - gittypes "github.com/portainer/portainer/api/git/types" "github.com/portainer/portainer/api/http/proxy/factory/utils" "github.com/portainer/portainer/api/http/security" "github.com/portainer/portainer/api/internal/authorization" @@ -419,14 +418,7 @@ func (transport *Transport) updateDefaultGitBranch(request *http.Request) error } repositoryURL := remote[:len(remote)-4] - latestCommitID, err := transport.gitService.LatestCommitID( - repositoryURL, - "", - "", - "", - gittypes.GitCredentialAuthType_Basic, - false, - ) + latestCommitID, err := transport.gitService.LatestCommitID(repositoryURL, "", "", "", false) if err != nil { return err } diff --git a/api/http/proxy/factory/factory.go b/api/http/proxy/factory/factory.go index b45629630..28d05dec5 100644 --- a/api/http/proxy/factory/factory.go +++ b/api/http/proxy/factory/factory.go @@ -24,12 +24,11 @@ type ( kubernetesTokenCacheManager *kubernetes.TokenCacheManager gitService portainer.GitService snapshotService portainer.SnapshotService - jwtService portainer.JWTService } ) // NewProxyFactory returns a pointer to a new instance of a ProxyFactory -func NewProxyFactory(dataStore dataservices.DataStore, signatureService portainer.DigitalSignatureService, tunnelService portainer.ReverseTunnelService, clientFactory *dockerclient.ClientFactory, kubernetesClientFactory *cli.ClientFactory, kubernetesTokenCacheManager *kubernetes.TokenCacheManager, gitService portainer.GitService, snapshotService portainer.SnapshotService, jwtService portainer.JWTService) *ProxyFactory { +func NewProxyFactory(dataStore dataservices.DataStore, signatureService portainer.DigitalSignatureService, tunnelService portainer.ReverseTunnelService, clientFactory *dockerclient.ClientFactory, kubernetesClientFactory *cli.ClientFactory, kubernetesTokenCacheManager *kubernetes.TokenCacheManager, gitService portainer.GitService, snapshotService portainer.SnapshotService) *ProxyFactory { return &ProxyFactory{ dataStore: dataStore, signatureService: signatureService, @@ -39,7 +38,6 @@ func NewProxyFactory(dataStore dataservices.DataStore, signatureService portaine kubernetesTokenCacheManager: kubernetesTokenCacheManager, gitService: gitService, snapshotService: snapshotService, - jwtService: jwtService, } } diff --git a/api/http/proxy/factory/github/client.go b/api/http/proxy/factory/github/client.go deleted file mode 100644 index 74dcfb994..000000000 --- a/api/http/proxy/factory/github/client.go +++ /dev/null @@ -1,108 +0,0 @@ -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 deleted file mode 100644 index 13d07e18b..000000000 --- a/api/http/proxy/factory/gitlab/client.go +++ /dev/null @@ -1,130 +0,0 @@ -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 new file mode 100644 index 000000000..7e1804c45 --- /dev/null +++ b/api/http/proxy/factory/gitlab/transport.go @@ -0,0 +1,34 @@ +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.go b/api/http/proxy/factory/kubernetes.go index ea08467e5..eceee181a 100644 --- a/api/http/proxy/factory/kubernetes.go +++ b/api/http/proxy/factory/kubernetes.go @@ -38,7 +38,7 @@ func (factory *ProxyFactory) newKubernetesLocalProxy(endpoint *portainer.Endpoin return nil, err } - transport, err := kubernetes.NewLocalTransport(tokenManager, endpoint, factory.kubernetesClientFactory, factory.dataStore, factory.jwtService) + transport, err := kubernetes.NewLocalTransport(tokenManager, endpoint, factory.kubernetesClientFactory, factory.dataStore) if err != nil { return nil, err } @@ -74,7 +74,7 @@ func (factory *ProxyFactory) newKubernetesEdgeHTTPProxy(endpoint *portainer.Endp endpointURL.Scheme = "http" proxy := NewSingleHostReverseProxyWithHostHeader(endpointURL) - proxy.Transport = kubernetes.NewEdgeTransport(factory.dataStore, factory.signatureService, factory.reverseTunnelService, endpoint, tokenManager, factory.kubernetesClientFactory, factory.jwtService) + proxy.Transport = kubernetes.NewEdgeTransport(factory.dataStore, factory.signatureService, factory.reverseTunnelService, endpoint, tokenManager, factory.kubernetesClientFactory) return proxy, nil } @@ -105,7 +105,7 @@ func (factory *ProxyFactory) newKubernetesAgentHTTPSProxy(endpoint *portainer.En } proxy := NewSingleHostReverseProxyWithHostHeader(remoteURL) - proxy.Transport = kubernetes.NewAgentTransport(factory.signatureService, tlsConfig, tokenManager, endpoint, factory.kubernetesClientFactory, factory.dataStore, factory.jwtService) + proxy.Transport = kubernetes.NewAgentTransport(factory.signatureService, tlsConfig, tokenManager, endpoint, factory.kubernetesClientFactory, factory.dataStore) return proxy, nil } diff --git a/api/http/proxy/factory/kubernetes/agent_transport.go b/api/http/proxy/factory/kubernetes/agent_transport.go index b127b85fd..b6ab548ae 100644 --- a/api/http/proxy/factory/kubernetes/agent_transport.go +++ b/api/http/proxy/factory/kubernetes/agent_transport.go @@ -16,7 +16,7 @@ type agentTransport struct { } // NewAgentTransport returns a new transport that can be used to send signed requests to a Portainer agent -func NewAgentTransport(signatureService portainer.DigitalSignatureService, tlsConfig *tls.Config, tokenManager *tokenManager, endpoint *portainer.Endpoint, k8sClientFactory *cli.ClientFactory, dataStore dataservices.DataStore, jwtService portainer.JWTService) *agentTransport { +func NewAgentTransport(signatureService portainer.DigitalSignatureService, tlsConfig *tls.Config, tokenManager *tokenManager, endpoint *portainer.Endpoint, k8sClientFactory *cli.ClientFactory, dataStore dataservices.DataStore) *agentTransport { transport := &agentTransport{ baseTransport: newBaseTransport( &http.Transport{ @@ -26,7 +26,6 @@ func NewAgentTransport(signatureService portainer.DigitalSignatureService, tlsCo endpoint, k8sClientFactory, dataStore, - jwtService, ), signatureService: signatureService, } diff --git a/api/http/proxy/factory/kubernetes/edge_transport.go b/api/http/proxy/factory/kubernetes/edge_transport.go index 73946114e..4eed6934a 100644 --- a/api/http/proxy/factory/kubernetes/edge_transport.go +++ b/api/http/proxy/factory/kubernetes/edge_transport.go @@ -16,7 +16,7 @@ type edgeTransport struct { } // NewAgentTransport returns a new transport that can be used to send signed requests to a Portainer Edge agent -func NewEdgeTransport(dataStore dataservices.DataStore, signatureService portainer.DigitalSignatureService, reverseTunnelService portainer.ReverseTunnelService, endpoint *portainer.Endpoint, tokenManager *tokenManager, k8sClientFactory *cli.ClientFactory, jwtService portainer.JWTService) *edgeTransport { +func NewEdgeTransport(dataStore dataservices.DataStore, signatureService portainer.DigitalSignatureService, reverseTunnelService portainer.ReverseTunnelService, endpoint *portainer.Endpoint, tokenManager *tokenManager, k8sClientFactory *cli.ClientFactory) *edgeTransport { transport := &edgeTransport{ reverseTunnelService: reverseTunnelService, signatureService: signatureService, @@ -26,7 +26,6 @@ func NewEdgeTransport(dataStore dataservices.DataStore, signatureService portain endpoint, k8sClientFactory, dataStore, - jwtService, ), } diff --git a/api/http/proxy/factory/kubernetes/local_transport.go b/api/http/proxy/factory/kubernetes/local_transport.go index 6fe255ff6..4ae4082d9 100644 --- a/api/http/proxy/factory/kubernetes/local_transport.go +++ b/api/http/proxy/factory/kubernetes/local_transport.go @@ -14,7 +14,7 @@ type localTransport struct { } // NewLocalTransport returns a new transport that can be used to send requests to the local Kubernetes API -func NewLocalTransport(tokenManager *tokenManager, endpoint *portainer.Endpoint, k8sClientFactory *cli.ClientFactory, dataStore dataservices.DataStore, jwtService portainer.JWTService) (*localTransport, error) { +func NewLocalTransport(tokenManager *tokenManager, endpoint *portainer.Endpoint, k8sClientFactory *cli.ClientFactory, dataStore dataservices.DataStore) (*localTransport, error) { config, err := crypto.CreateTLSConfigurationFromBytes(nil, nil, nil, true, true) if err != nil { return nil, err @@ -29,7 +29,6 @@ func NewLocalTransport(tokenManager *tokenManager, endpoint *portainer.Endpoint, endpoint, k8sClientFactory, dataStore, - jwtService, ), } diff --git a/api/http/proxy/factory/kubernetes/pods.go b/api/http/proxy/factory/kubernetes/pods.go index a2e5f1860..6c36e079a 100644 --- a/api/http/proxy/factory/kubernetes/pods.go +++ b/api/http/proxy/factory/kubernetes/pods.go @@ -2,18 +2,12 @@ package kubernetes import ( "net/http" - "strings" ) -func (transport *baseTransport) proxyPodsRequest(request *http.Request, namespace string) (*http.Response, error) { +func (transport *baseTransport) proxyPodsRequest(request *http.Request, namespace, requestPath string) (*http.Response, error) { if request.Method == http.MethodDelete { transport.refreshRegistry(request, namespace) } - if request.Method == http.MethodPost && strings.Contains(request.URL.Path, "/exec") { - if err := transport.addTokenForExec(request); err != nil { - return nil, err - } - } return transport.executeKubernetesRequest(request) } diff --git a/api/http/proxy/factory/kubernetes/transport.go b/api/http/proxy/factory/kubernetes/transport.go index b4d06bcce..76e9daa68 100644 --- a/api/http/proxy/factory/kubernetes/transport.go +++ b/api/http/proxy/factory/kubernetes/transport.go @@ -26,17 +26,15 @@ type baseTransport struct { endpoint *portainer.Endpoint k8sClientFactory *cli.ClientFactory dataStore dataservices.DataStore - jwtService portainer.JWTService } -func newBaseTransport(httpTransport *http.Transport, tokenManager *tokenManager, endpoint *portainer.Endpoint, k8sClientFactory *cli.ClientFactory, dataStore dataservices.DataStore, jwtService portainer.JWTService) *baseTransport { +func newBaseTransport(httpTransport *http.Transport, tokenManager *tokenManager, endpoint *portainer.Endpoint, k8sClientFactory *cli.ClientFactory, dataStore dataservices.DataStore) *baseTransport { return &baseTransport{ httpTransport: httpTransport, tokenManager: tokenManager, endpoint: endpoint, k8sClientFactory: k8sClientFactory, dataStore: dataStore, - jwtService: jwtService, } } @@ -60,7 +58,6 @@ 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"): @@ -84,7 +81,7 @@ func (transport *baseTransport) proxyNamespacedRequest(request *http.Request, fu switch { case strings.HasPrefix(requestPath, "pods"): - return transport.proxyPodsRequest(request, namespace) + return transport.proxyPodsRequest(request, namespace, requestPath) case strings.HasPrefix(requestPath, "deployments"): return transport.proxyDeploymentsRequest(request, namespace, requestPath) case requestPath == "" && request.Method == "DELETE": @@ -94,23 +91,6 @@ func (transport *baseTransport) proxyNamespacedRequest(request *http.Request, fu } } -// addTokenForExec injects a kubeconfig token into the request header -// this is only used with kubeconfig for kubectl exec requests -func (transport *baseTransport) addTokenForExec(request *http.Request) error { - tokenData, err := security.RetrieveTokenData(request) - if err != nil { - return err - } - - token, err := transport.jwtService.GenerateTokenForKubeconfig(tokenData) - if err != nil { - return err - } - - request.Header.Set("Authorization", "Bearer "+token) - return nil -} - func (transport *baseTransport) executeKubernetesRequest(request *http.Request) (*http.Response, error) { resp, err := transport.httpTransport.RoundTrip(request) diff --git a/api/http/proxy/factory/kubernetes/transport_test.go b/api/http/proxy/factory/kubernetes/transport_test.go deleted file mode 100644 index 713714d93..000000000 --- a/api/http/proxy/factory/kubernetes/transport_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package kubernetes - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/datastore" - "github.com/portainer/portainer/api/http/security" - "github.com/portainer/portainer/api/jwt" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// MockJWTService implements portainer.JWTService for testing -type MockJWTService struct { - generateTokenFunc func(data *portainer.TokenData) (string, error) -} - -func (m *MockJWTService) GenerateToken(data *portainer.TokenData) (string, time.Time, error) { - if m.generateTokenFunc != nil { - token, err := m.generateTokenFunc(data) - return token, time.Now().Add(24 * time.Hour), err - } - return "mock-token", time.Now().Add(24 * time.Hour), nil -} - -func (m *MockJWTService) GenerateTokenForKubeconfig(data *portainer.TokenData) (string, error) { - if m.generateTokenFunc != nil { - return m.generateTokenFunc(data) - } - return "mock-kubeconfig-token", nil -} - -func (m *MockJWTService) ParseAndVerifyToken(token string) (*portainer.TokenData, string, time.Time, error) { - return &portainer.TokenData{ID: 1, Username: "mock", Role: portainer.AdministratorRole}, "mock-id", time.Now().Add(24 * time.Hour), nil -} - -func (m *MockJWTService) SetUserSessionDuration(userSessionDuration time.Duration) { - // Mock implementation - not used in tests -} - -func TestBaseTransport_AddTokenForExec(t *testing.T) { - // Setup test store and JWT service - _, store := datastore.MustNewTestStore(t, true, false) - - // Create test users - adminUser := &portainer.User{ - ID: 1, - Username: "admin", - Role: portainer.AdministratorRole, - } - err := store.User().Create(adminUser) - require.NoError(t, err) - - standardUser := &portainer.User{ - ID: 2, - Username: "standard", - Role: portainer.StandardUserRole, - } - err = store.User().Create(standardUser) - require.NoError(t, err) - - // Create JWT service - jwtService, err := jwt.NewService("24h", store) - require.NoError(t, err) - - // Create base transport - transport := &baseTransport{ - jwtService: jwtService, - } - - tests := []struct { - name string - tokenData *portainer.TokenData - setupRequest func(*http.Request) *http.Request - expectError bool - errorMsg string - expectPanic bool - verifyResponse func(*testing.T, *http.Request, *portainer.TokenData) - }{ - { - name: "admin user - successful token generation", - tokenData: &portainer.TokenData{ - ID: adminUser.ID, - Username: adminUser.Username, - Role: adminUser.Role, - }, - setupRequest: func(req *http.Request) *http.Request { - return req.WithContext(security.StoreTokenData(req, &portainer.TokenData{ - ID: adminUser.ID, - Username: adminUser.Username, - Role: adminUser.Role, - })) - }, - expectError: false, - verifyResponse: func(t *testing.T, req *http.Request, tokenData *portainer.TokenData) { - authHeader := req.Header.Get("Authorization") - assert.NotEmpty(t, authHeader) - assert.True(t, strings.HasPrefix(authHeader, "Bearer ")) - - token := authHeader[7:] // Remove "Bearer " prefix - parsedTokenData, _, _, err := jwtService.ParseAndVerifyToken(token) - assert.NoError(t, err) - assert.Equal(t, tokenData.ID, parsedTokenData.ID) - assert.Equal(t, tokenData.Username, parsedTokenData.Username) - assert.Equal(t, tokenData.Role, parsedTokenData.Role) - }, - }, - { - name: "standard user - successful token generation", - tokenData: &portainer.TokenData{ - ID: standardUser.ID, - Username: standardUser.Username, - Role: standardUser.Role, - }, - setupRequest: func(req *http.Request) *http.Request { - return req.WithContext(security.StoreTokenData(req, &portainer.TokenData{ - ID: standardUser.ID, - Username: standardUser.Username, - Role: standardUser.Role, - })) - }, - expectError: false, - verifyResponse: func(t *testing.T, req *http.Request, tokenData *portainer.TokenData) { - authHeader := req.Header.Get("Authorization") - assert.NotEmpty(t, authHeader) - assert.True(t, strings.HasPrefix(authHeader, "Bearer ")) - - token := authHeader[7:] // Remove "Bearer " prefix - parsedTokenData, _, _, err := jwtService.ParseAndVerifyToken(token) - assert.NoError(t, err) - assert.Equal(t, tokenData.ID, parsedTokenData.ID) - assert.Equal(t, tokenData.Username, parsedTokenData.Username) - assert.Equal(t, tokenData.Role, parsedTokenData.Role) - }, - }, - { - name: "request without token data in context", - tokenData: nil, - setupRequest: func(req *http.Request) *http.Request { - return req // Don't add token data to context - }, - expectError: true, - errorMsg: "Unable to find JWT data in request context", - }, - { - name: "request with nil token data", - tokenData: nil, - setupRequest: func(req *http.Request) *http.Request { - return req.WithContext(security.StoreTokenData(req, nil)) - }, - expectPanic: true, - }, - { - name: "JWT service failure", - tokenData: &portainer.TokenData{ - ID: 1, - Username: "test", - Role: portainer.AdministratorRole, - }, - setupRequest: func(req *http.Request) *http.Request { - return req.WithContext(security.StoreTokenData(req, &portainer.TokenData{ - ID: 1, - Username: "test", - Role: portainer.AdministratorRole, - })) - }, - expectPanic: true, - }, - { - name: "verify authorization header format", - tokenData: &portainer.TokenData{ - ID: adminUser.ID, - Username: adminUser.Username, - Role: adminUser.Role, - }, - setupRequest: func(req *http.Request) *http.Request { - return req.WithContext(security.StoreTokenData(req, &portainer.TokenData{ - ID: adminUser.ID, - Username: adminUser.Username, - Role: adminUser.Role, - })) - }, - expectError: false, - verifyResponse: func(t *testing.T, req *http.Request, tokenData *portainer.TokenData) { - authHeader := req.Header.Get("Authorization") - assert.NotEmpty(t, authHeader) - assert.True(t, strings.HasPrefix(authHeader, "Bearer ")) - - token := authHeader[7:] // Remove "Bearer " prefix - assert.NotEmpty(t, token) - assert.Greater(t, len(token), 0, "Token should not be empty") - }, - }, - { - name: "verify header is overwritten on subsequent calls", - tokenData: &portainer.TokenData{ - ID: adminUser.ID, - Username: adminUser.Username, - Role: adminUser.Role, - }, - setupRequest: func(req *http.Request) *http.Request { - req = req.WithContext(security.StoreTokenData(req, &portainer.TokenData{ - ID: adminUser.ID, - Username: adminUser.Username, - Role: adminUser.Role, - })) - // Set an existing Authorization header - req.Header.Set("Authorization", "Bearer old-token") - return req - }, - expectError: false, - verifyResponse: func(t *testing.T, req *http.Request, tokenData *portainer.TokenData) { - authHeader := req.Header.Get("Authorization") - assert.NotEqual(t, "Bearer old-token", authHeader) - assert.True(t, strings.HasPrefix(authHeader, "Bearer ")) - - token := authHeader[7:] // Remove "Bearer " prefix - parsedTokenData, _, _, err := jwtService.ParseAndVerifyToken(token) - assert.NoError(t, err) - assert.Equal(t, tokenData.ID, parsedTokenData.ID) - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create request - request := httptest.NewRequest("GET", "/", nil) - request = tt.setupRequest(request) - - // Determine which transport to use based on test case - var testTransport *baseTransport - if tt.name == "JWT service failure" { - testTransport = &baseTransport{ - jwtService: nil, - } - } else { - testTransport = transport - } - - // Call the function - if tt.expectPanic { - assert.Panics(t, func() { - _ = testTransport.addTokenForExec(request) - }) - return - } - - err := testTransport.addTokenForExec(request) - - // Check results - if tt.expectError { - assert.Error(t, err) - if tt.errorMsg != "" { - assert.Contains(t, err.Error(), tt.errorMsg) - } - } else { - assert.NoError(t, err) - if tt.verifyResponse != nil { - tt.verifyResponse(t, request, tt.tokenData) - } - } - }) - } -} - -func TestBaseTransport_AddTokenForExec_Integration(t *testing.T) { - // Create a test HTTP server to capture requests - var capturedRequest *http.Request - var capturedHeaders http.Header - - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - capturedRequest = r - capturedHeaders = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte("success")) - })) - defer testServer.Close() - - // Create mock JWT service - mockJWTService := &MockJWTService{ - generateTokenFunc: func(data *portainer.TokenData) (string, error) { - return "mock-token-" + data.Username, nil - }, - } - - // Create base transport - transport := &baseTransport{ - httpTransport: &http.Transport{}, - jwtService: mockJWTService, - } - - tests := []struct { - name string - tokenData *portainer.TokenData - requestPath string - expectedToken string - }{ - { - name: "admin user exec request", - tokenData: &portainer.TokenData{ - ID: 1, - Username: "admin", - Role: portainer.AdministratorRole, - }, - requestPath: "/api/endpoints/1/kubernetes/api/v1/namespaces/default/pods/test-pod/exec", - expectedToken: "mock-token-admin", - }, - { - name: "standard user exec request", - tokenData: &portainer.TokenData{ - ID: 2, - Username: "standard", - Role: portainer.StandardUserRole, - }, - requestPath: "/api/endpoints/1/kubernetes/api/v1/namespaces/default/pods/test-pod/exec", - expectedToken: "mock-token-standard", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Reset captured data - capturedRequest = nil - capturedHeaders = nil - - // Create request to the test server - request, err := http.NewRequest("POST", testServer.URL+tt.requestPath, strings.NewReader("")) - require.NoError(t, err) - - // Add token data to request context - request = request.WithContext(security.StoreTokenData(request, tt.tokenData)) - - // Call proxyPodsRequest which triggers addTokenForExec for POST /exec requests - resp, err := transport.proxyPodsRequest(request, "default") - require.NoError(t, err) - defer resp.Body.Close() - - // Verify the response - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Verify the request was captured - assert.NotNil(t, capturedRequest) - assert.Equal(t, "POST", capturedRequest.Method) - assert.Equal(t, tt.requestPath, capturedRequest.URL.Path) - - // Verify the authorization header was set correctly - capturedAuthHeader := capturedHeaders.Get("Authorization") - assert.NotEmpty(t, capturedAuthHeader) - assert.True(t, strings.HasPrefix(capturedAuthHeader, "Bearer ")) - assert.Equal(t, "Bearer "+tt.expectedToken, capturedAuthHeader) - }) - } -} diff --git a/api/http/proxy/factory/reverse_proxy.go b/api/http/proxy/factory/reverse_proxy.go index a1bb3fa28..c40e6c485 100644 --- a/api/http/proxy/factory/reverse_proxy.go +++ b/api/http/proxy/factory/reverse_proxy.go @@ -9,20 +9,17 @@ import ( // Note that we discard any non-canonical headers by design var allowedHeaders = map[string]struct{}{ - "Accept": {}, - "Accept-Encoding": {}, - "Accept-Language": {}, - "Cache-Control": {}, - "Connection": {}, - "Content-Length": {}, - "Content-Type": {}, - "Private-Token": {}, - "Upgrade": {}, - "User-Agent": {}, - "X-Portaineragent-Target": {}, - "X-Portainer-Volumename": {}, - "X-Registry-Auth": {}, - "X-Stream-Protocol-Version": {}, + "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 diff --git a/api/http/proxy/manager.go b/api/http/proxy/manager.go index 477bc547b..16f822028 100644 --- a/api/http/proxy/manager.go +++ b/api/http/proxy/manager.go @@ -32,8 +32,8 @@ func NewManager(kubernetesClientFactory *cli.ClientFactory) *Manager { } } -func (manager *Manager) NewProxyFactory(dataStore dataservices.DataStore, signatureService portainer.DigitalSignatureService, tunnelService portainer.ReverseTunnelService, clientFactory *dockerclient.ClientFactory, kubernetesClientFactory *cli.ClientFactory, kubernetesTokenCacheManager *kubernetes.TokenCacheManager, gitService portainer.GitService, snapshotService portainer.SnapshotService, jwtService portainer.JWTService) { - manager.proxyFactory = factory.NewProxyFactory(dataStore, signatureService, tunnelService, clientFactory, kubernetesClientFactory, kubernetesTokenCacheManager, gitService, snapshotService, jwtService) +func (manager *Manager) NewProxyFactory(dataStore dataservices.DataStore, signatureService portainer.DigitalSignatureService, tunnelService portainer.ReverseTunnelService, clientFactory *dockerclient.ClientFactory, kubernetesClientFactory *cli.ClientFactory, kubernetesTokenCacheManager *kubernetes.TokenCacheManager, gitService portainer.GitService, snapshotService portainer.SnapshotService) { + manager.proxyFactory = factory.NewProxyFactory(dataStore, signatureService, tunnelService, clientFactory, kubernetesClientFactory, kubernetesTokenCacheManager, gitService, snapshotService) } // CreateAndRegisterEndpointProxy creates a new HTTP reverse proxy based on environment(endpoint) properties and adds it to the registered proxies. diff --git a/api/http/security/bouncer.go b/api/http/security/bouncer.go index 55b7faecc..eb240692d 100644 --- a/api/http/security/bouncer.go +++ b/api/http/security/bouncer.go @@ -35,7 +35,6 @@ 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 @@ -73,7 +72,7 @@ func NewRequestBouncer(dataStore dataservices.DataStore, jwtService portainer.JW jwtService: jwtService, apiKeyService: apiKeyService, hsts: featureflags.IsEnabled("hsts"), - csp: true, + csp: featureflags.IsEnabled("csp"), } go b.cleanUpExpiredJWT() @@ -81,11 +80,6 @@ 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 { @@ -534,7 +528,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 js.hsforms.net; frame-ancestors 'none';") + w.Header().Set("Content-Security-Policy", "script-src 'self' cdn.matomo.cloud") } 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 3dd42fdc5..4d84dcfee 100644 --- a/api/http/security/bouncer_test.go +++ b/api/http/security/bouncer_test.go @@ -530,34 +530,3 @@ 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 8f073ce58..88d131650 100644 --- a/api/http/server.go +++ b/api/http/server.go @@ -77,7 +77,6 @@ type Server struct { AuthorizationService *authorization.Service BindAddress string BindAddressHTTPS string - CSP bool HTTPEnabled bool AssetsPath string Status *portainer.Status @@ -114,7 +113,6 @@ type Server struct { PendingActionsService *pendingactions.PendingActionsService PlatformService platform.Service PullLimitCheckDisabled bool - TrustedOrigins []string } // Start starts the HTTP server @@ -122,16 +120,13 @@ 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, server.KubernetesClientFactory) + var authHandler = auth.NewHandler(requestBouncer, rateLimiter, passwordStrengthChecker) authHandler.DataStore = server.DataStore authHandler.CryptoService = server.CryptoService authHandler.JWTService = server.JWTService @@ -204,7 +199,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"), server.CSP, adminMonitor.WasInstanceDisabled) + var fileHandler = file.NewHandler(filepath.Join(server.AssetsPath, "public"), adminMonitor.WasInstanceDisabled) var endpointHelmHandler = helm.NewHandler(requestBouncer, server.DataStore, server.JWTService, server.KubernetesDeployer, server.HelmPackageManager, server.KubeClusterAccessService) @@ -341,7 +336,7 @@ func (server *Server) Start() error { handler = middlewares.WithPanicLogger(middlewares.WithSlowRequestsLogger(handler)) - handler, err := csrf.WithProtect(handler, server.TrustedOrigins) + handler, err := csrf.WithProtect(handler) if err != nil { return errors.Wrap(err, "failed to create CSRF middleware") } diff --git a/api/internal/edge/edgegroup.go b/api/internal/edge/edgegroup.go index eae4fedce..64aa296a5 100644 --- a/api/internal/edge/edgegroup.go +++ b/api/internal/edge/edgegroup.go @@ -1,6 +1,8 @@ package edge import ( + "slices" + portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/internal/endpointutils" @@ -10,7 +12,7 @@ import ( // EdgeGroupRelatedEndpoints returns a list of environments(endpoints) related to this Edge group func EdgeGroupRelatedEndpoints(edgeGroup *portainer.EdgeGroup, endpoints []portainer.Endpoint, endpointGroups []portainer.EndpointGroup) []portainer.EndpointID { if !edgeGroup.Dynamic { - return edgeGroup.EndpointIDs.ToSlice() + return edgeGroup.Endpoints } endpointGroupsMap := map[portainer.EndpointGroupID]*portainer.EndpointGroup{} @@ -70,7 +72,7 @@ func GetEndpointsFromEdgeGroups(edgeGroupIDs []portainer.EdgeGroupID, datastore // edgeGroupRelatedToEndpoint returns true if edgeGroup is associated with environment(endpoint) func edgeGroupRelatedToEndpoint(edgeGroup *portainer.EdgeGroup, endpoint *portainer.Endpoint, endpointGroup *portainer.EndpointGroup) bool { if !edgeGroup.Dynamic { - return edgeGroup.EndpointIDs.Contains(endpoint.ID) + return slices.Contains(edgeGroup.Endpoints, endpoint.ID) } endpointTags := tag.Set(endpoint.TagIDs) diff --git a/api/internal/edge/edgegroup_benchmark_test.go b/api/internal/edge/edgegroup_benchmark_test.go deleted file mode 100644 index 861db09fc..000000000 --- a/api/internal/edge/edgegroup_benchmark_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package edge - -import ( - "testing" - - portainer "github.com/portainer/portainer/api" - "github.com/portainer/portainer/api/datastore" - "github.com/portainer/portainer/api/roar" - - "github.com/rs/zerolog" - "github.com/stretchr/testify/require" -) - -const n = 1_000_000 - -func BenchmarkWriteEdgeGroupOld(b *testing.B) { - zerolog.SetGlobalLevel(zerolog.ErrorLevel) - - _, store := datastore.MustNewTestStore(b, false, false) - - var endpointIDs []portainer.EndpointID - - for i := range n { - endpointIDs = append(endpointIDs, portainer.EndpointID(i+1)) - } - - for b.Loop() { - err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - Name: "Test Edge Group", - Endpoints: endpointIDs, - }) - require.NoError(b, err) - } -} - -func BenchmarkWriteEdgeGroupNew(b *testing.B) { - zerolog.SetGlobalLevel(zerolog.ErrorLevel) - - _, store := datastore.MustNewTestStore(b, false, false) - - var ts []portainer.EndpointID - - for i := range n { - ts = append(ts, portainer.EndpointID(i+1)) - } - - endpointIDs := roar.FromSlice(ts) - - for b.Loop() { - err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - Name: "Test Edge Group", - EndpointIDs: endpointIDs, - }) - require.NoError(b, err) - } -} - -func BenchmarkReadEdgeGroupOld(b *testing.B) { - zerolog.SetGlobalLevel(zerolog.ErrorLevel) - - _, store := datastore.MustNewTestStore(b, false, false) - - var endpointIDs []portainer.EndpointID - - for i := range n { - endpointIDs = append(endpointIDs, portainer.EndpointID(i+1)) - } - - err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - Name: "Test Edge Group", - Endpoints: endpointIDs, - }) - require.NoError(b, err) - - for b.Loop() { - _, err := store.EdgeGroup().ReadAll() - require.NoError(b, err) - } -} - -func BenchmarkReadEdgeGroupNew(b *testing.B) { - zerolog.SetGlobalLevel(zerolog.ErrorLevel) - - _, store := datastore.MustNewTestStore(b, false, false) - - var ts []portainer.EndpointID - - for i := range n { - ts = append(ts, portainer.EndpointID(i+1)) - } - - endpointIDs := roar.FromSlice(ts) - - err := store.EdgeGroup().Create(&portainer.EdgeGroup{ - Name: "Test Edge Group", - EndpointIDs: endpointIDs, - }) - require.NoError(b, err) - - for b.Loop() { - _, err := store.EdgeGroup().ReadAll() - require.NoError(b, err) - } -} diff --git a/api/internal/edge/edgestacks/service.go b/api/internal/edge/edgestacks/service.go index c0ecb5caf..5932a5ec8 100644 --- a/api/internal/edge/edgestacks/service.go +++ b/api/internal/edge/edgestacks/service.go @@ -129,6 +129,9 @@ 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) } diff --git a/api/internal/endpointutils/endpointutils.go b/api/internal/endpointutils/endpointutils.go index f596ae0d5..6b7eb1c2d 100644 --- a/api/internal/endpointutils/endpointutils.go +++ b/api/internal/endpointutils/endpointutils.go @@ -249,19 +249,3 @@ 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 bfa5181c0..0d14cba39 100644 --- a/api/internal/registryutils/access/access.go +++ b/api/internal/registryutils/access/access.go @@ -2,82 +2,40 @@ 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 false, err + return } if user.Role == portainer.AdministratorRole { - return true, nil - } - - endpoint, err := dataStore.Endpoint().Endpoint(endpointID) - if err != nil { - return false, err + return true, err } teamMemberships, err := dataStore.TeamMembership().TeamMembershipsByUserID(userID) if err != nil { - return false, err + return } - // 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 hasPermission, nil + return } // 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, @@ -88,7 +46,7 @@ func GetAccessibleRegistry( return } - hasPermission, err := hasPermission(dataStore, k8sClientFactory, userID, endpointID, registry) + hasPermission, err := hasPermission(dataStore, 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 6e9a754bf..cbcceb982 100644 --- a/api/internal/registryutils/ecr_reg_token.go +++ b/api/internal/registryutils/ecr_reg_token.go @@ -62,26 +62,3 @@ 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 19254f540..392f21e97 100644 --- a/api/internal/testhelpers/datastore.go +++ b/api/internal/testhelpers/datastore.go @@ -7,7 +7,6 @@ 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{} @@ -153,17 +152,8 @@ type stubUserService struct { users []portainer.User } -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) BucketName() string { return "users" } +func (s *stubUserService) ReadAll() ([]portainer.User, error) { return s.users, nil } func (s *stubUserService) UsersByRole(role portainer.UserRole) ([]portainer.User, error) { return s.users, nil } @@ -181,16 +171,8 @@ type stubEdgeJobService struct { jobs []portainer.EdgeJob } -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 -} +func (s *stubEdgeJobService) BucketName() string { return "edgejobs" } +func (s *stubEdgeJobService) ReadAll() ([]portainer.EdgeJob, error) { return s.jobs, nil } // WithEdgeJobs option will instruct testDatastore to return provided jobs func WithEdgeJobs(js []portainer.EdgeJob) datastoreOption { @@ -380,14 +362,8 @@ func (s *stubStacksService) Read(ID portainer.StackID) (*portainer.Stack, error) return nil, errors.ErrObjectNotFound } -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) ReadAll() ([]portainer.Stack, error) { + return s.stacks, nil } func (s *stubStacksService) StacksByEndpointID(endpointID portainer.EndpointID) ([]portainer.Stack, error) { diff --git a/api/internal/testhelpers/git_service.go b/api/internal/testhelpers/git_service.go index 6b1a352ee..6af1b6459 100644 --- a/api/internal/testhelpers/git_service.go +++ b/api/internal/testhelpers/git_service.go @@ -1,9 +1,6 @@ package testhelpers -import ( - portainer "github.com/portainer/portainer/api" - gittypes "github.com/portainer/portainer/api/git/types" -) +import portainer "github.com/portainer/portainer/api" type gitService struct { cloneErr error @@ -18,50 +15,18 @@ func NewGitService(cloneErr error, id string) portainer.GitService { } } -func (g *gitService) CloneRepository( - destination, - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) error { +func (g *gitService) CloneRepository(destination, repositoryURL, referenceName, username, password string, tlsSkipVerify bool) error { return g.cloneErr } -func (g *gitService) LatestCommitID( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, -) (string, error) { +func (g *gitService) LatestCommitID(repositoryURL, referenceName, username, password string, tlsSkipVerify bool) (string, error) { return g.id, nil } -func (g *gitService) ListRefs( - repositoryURL, - username, - password string, - authType gittypes.GitCredentialAuthType, - hardRefresh bool, - tlsSkipVerify bool, -) ([]string, error) { +func (g *gitService) ListRefs(repositoryURL, username, password string, hardRefresh bool, tlsSkipVerify bool) ([]string, error) { return nil, nil } -func (g *gitService) ListFiles( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - dirOnly, - hardRefresh bool, - includedExts []string, - tlsSkipVerify bool, -) ([]string, error) { +func (g *gitService) ListFiles(repositoryURL, referenceName, username, password string, dirOnly, hardRefresh bool, includedExts []string, tlsSkipVerify bool) ([]string, error) { return nil, nil } diff --git a/api/internal/testhelpers/request_bouncer.go b/api/internal/testhelpers/request_bouncer.go index 0586dffef..b89154549 100644 --- a/api/internal/testhelpers/request_bouncer.go +++ b/api/internal/testhelpers/request_bouncer.go @@ -60,8 +60,6 @@ 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/client.go b/api/kubernetes/cli/client.go index 550ade1d3..a40a865f1 100644 --- a/api/kubernetes/cli/client.go +++ b/api/kubernetes/cli/client.go @@ -77,26 +77,9 @@ 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 { @@ -121,24 +104,6 @@ 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. @@ -191,9 +156,8 @@ func (factory *ClientFactory) createCachedPrivilegedKubeClient(endpoint *portain } return &KubeClient{ - cli: cli, - instanceID: factory.instanceID, - IsKubeAdmin: true, + cli: cli, + instanceID: factory.instanceID, }, nil } diff --git a/api/kubernetes/cli/client_test.go b/api/kubernetes/cli/client_test.go deleted file mode 100644 index 993a966e3..000000000 --- a/api/kubernetes/cli/client_test.go +++ /dev/null @@ -1,22 +0,0 @@ -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/namespace.go b/api/kubernetes/cli/namespace.go index 560b91e75..11307d651 100644 --- a/api/kubernetes/cli/namespace.go +++ b/api/kubernetes/cli/namespace.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "net/http" - "sort" "strconv" "time" @@ -352,34 +351,6 @@ 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("") @@ -438,10 +409,5 @@ 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 3ccda4107..b3b917a08 100644 --- a/api/portainer.go +++ b/api/portainer.go @@ -7,18 +7,17 @@ import ( "net/http" "time" - gittypes "github.com/portainer/portainer/api/git/types" - models "github.com/portainer/portainer/api/http/models/kubernetes" - "github.com/portainer/portainer/api/roar" - "github.com/portainer/portainer/pkg/featureflags" - httperror "github.com/portainer/portainer/pkg/libhttp/error" - "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" "k8s.io/apimachinery/pkg/version" @@ -111,7 +110,6 @@ type ( AdminPassword *string AdminPasswordFile *string Assets *string - CSP *bool Data *string FeatureFlags *[]string EnableEdgeComputeFeatures *bool @@ -141,7 +139,6 @@ type ( LogMode *string KubectlShellImage *string PullLimitCheckDisabled *bool - TrustedOrigins *string } // CustomTemplateVariableDefinition @@ -216,34 +213,26 @@ 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"` - 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"` + 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"` } // DockerContainerSnapshot is an extent of Docker's Container struct @@ -266,15 +255,12 @@ type ( // EdgeGroup represents an Edge group EdgeGroup struct { // EdgeGroup Identifier - ID EdgeGroupID `json:"Id" example:"1"` - Name string `json:"Name"` - Dynamic bool `json:"Dynamic"` - TagIDs []TagID `json:"TagIds"` - EndpointIDs roar.Roar[EndpointID] `json:"EndpointIds"` - PartialMatch bool `json:"PartialMatch"` - - // Deprecated: only used for API responses - Endpoints []EndpointID `json:"Endpoints"` + ID EdgeGroupID `json:"Id" example:"1"` + Name string `json:"Name"` + Dynamic bool `json:"Dynamic"` + TagIDs []TagID `json:"TagIds"` + Endpoints []EndpointID `json:"Endpoints"` + PartialMatch bool `json:"PartialMatch"` } // EdgeGroupID represents an Edge group identifier @@ -607,12 +593,6 @@ 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 @@ -640,16 +620,15 @@ 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"` - UnhealthyEventCount int `json:"UnhealthyEventCount"` - 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"` + NamespaceOwner string `json:"NamespaceOwner"` + IsSystem bool `json:"IsSystem"` + IsDefault bool `json:"IsDefault"` + ResourceQuota *corev1.ResourceQuota `json:"ResourceQuota"` } K8sNodeLimits struct { @@ -681,13 +660,12 @@ 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"` - PerformanceMetrics *PerformanceMetrics `json:"PerformanceMetrics"` + Time int64 `json:"Time"` + KubernetesVersion string `json:"KubernetesVersion"` + NodeCount int `json:"NodeCount"` + TotalCPU int64 `json:"TotalCPU"` + TotalMemory int64 `json:"TotalMemory"` + DiagnosticsData *DiagnosticsData `json:"DiagnosticsData"` } // KubernetesConfiguration represents the configuration of a Kubernetes environment(endpoint) @@ -833,7 +811,6 @@ 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"` @@ -1542,42 +1519,10 @@ type ( // GitService represents a service for managing Git GitService interface { - CloneRepository( - destination string, - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, - ) error - LatestCommitID( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - tlsSkipVerify bool, - ) (string, error) - ListRefs( - repositoryURL, - username, - password string, - authType gittypes.GitCredentialAuthType, - hardRefresh bool, - tlsSkipVerify bool, - ) ([]string, error) - ListFiles( - repositoryURL, - referenceName, - username, - password string, - authType gittypes.GitCredentialAuthType, - dirOnly, - hardRefresh bool, - includeExts []string, - tlsSkipVerify bool, - ) ([]string, error) + CloneRepository(destination string, repositoryURL, referenceName, username, password string, tlsSkipVerify bool) error + LatestCommitID(repositoryURL, referenceName, username, password string, tlsSkipVerify bool) (string, error) + ListRefs(repositoryURL, username, password string, hardRefresh bool, tlsSkipVerify bool) ([]string, error) + ListFiles(repositoryURL, referenceName, username, password string, dirOnly, hardRefresh bool, includeExts []string, tlsSkipVerify bool) ([]string, error) } // OpenAMTService represents a service for managing OpenAMT @@ -1783,7 +1728,7 @@ type ( const ( // APIVersion is the version number of the Portainer API - APIVersion = "2.32.0" + APIVersion = "2.31.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 @@ -1842,10 +1787,6 @@ const ( 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 @@ -2015,8 +1956,6 @@ const ( DockerHubRegistry // EcrRegistry represents an ECR registry EcrRegistry - // Github container registry - GithubRegistry ) const ( diff --git a/api/roar/roar.go b/api/roar/roar.go deleted file mode 100644 index 6edc67f75..000000000 --- a/api/roar/roar.go +++ /dev/null @@ -1,145 +0,0 @@ -package roar - -import ( - "fmt" - - "github.com/RoaringBitmap/roaring/v2" -) - -type Roar[T ~int] struct { - rb *roaring.Bitmap -} - -// Iterate iterates over the bitmap, calling the given callback with each value in the bitmap. If the callback returns -// false, the iteration is halted. -// The iteration results are undefined if the bitmap is modified (e.g., with Add or Remove). -// There is no guarantee as to what order the values will be iterated. -func (r *Roar[T]) Iterate(f func(T) bool) { - if r.rb == nil { - return - } - - r.rb.Iterate(func(e uint32) bool { - return f(T(e)) - }) -} - -// Len returns the number of elements contained in the bitmap -func (r *Roar[T]) Len() int { - if r.rb == nil { - return 0 - } - - return int(r.rb.GetCardinality()) -} - -// Remove removes the given element from the bitmap -func (r *Roar[T]) Remove(e T) { - if r.rb == nil { - return - } - - r.rb.Remove(uint32(e)) -} - -// Add adds the given element to the bitmap -func (r *Roar[T]) Add(e T) { - if r.rb == nil { - r.rb = roaring.New() - } - - r.rb.AddInt(int(e)) -} - -// Contains returns whether the bitmap contains the given element or not -func (r *Roar[T]) Contains(e T) bool { - if r.rb == nil { - return false - } - - return r.rb.ContainsInt(int(e)) -} - -// Union combines the elements of the given bitmap with this bitmap -func (r *Roar[T]) Union(other Roar[T]) { - if other.rb == nil { - return - } else if r.rb == nil { - r.rb = roaring.New() - } - - r.rb.Or(other.rb) -} - -// Intersection modifies this bitmap to only contain elements that are also in the other bitmap -func (r *Roar[T]) Intersection(other Roar[T]) { - if other.rb == nil { - if r.rb != nil { - r.rb.Clear() - } - - return - } - - if r.rb == nil { - r.rb = roaring.New() - } - - r.rb.And(other.rb) -} - -// ToSlice converts the bitmap to a slice of elements -func (r *Roar[T]) ToSlice() []T { - if r.rb == nil { - return make([]T, 0) - } - - slice := make([]T, 0, r.rb.GetCardinality()) - r.rb.Iterate(func(e uint32) bool { - slice = append(slice, T(e)) - - return true - }) - - return slice -} - -func (r *Roar[T]) MarshalJSON() ([]byte, error) { - if r.rb == nil { - return []byte("null"), nil - } - - r.rb.RunOptimize() - - buf, err := r.rb.ToBase64() - if err != nil { - return nil, fmt.Errorf("failed to encode roaring bitmap: %w", err) - } - - return fmt.Appendf(nil, `"%s"`, buf), nil -} - -func (r *Roar[T]) UnmarshalJSON(data []byte) error { - if len(data) == 0 || string(data) == "null" { - return nil - } - - r.rb = roaring.New() - - _, err := r.rb.FromBase64(string(data[1 : len(data)-1])) - - return err -} - -// FromSlice creates a Roar by adding all elements from the provided slices -func FromSlice[T ~int](ess ...[]T) Roar[T] { - var r Roar[T] - - for _, es := range ess { - for _, e := range es { - r.Add(e) - } - } - - return r -} diff --git a/api/roar/roar_test.go b/api/roar/roar_test.go deleted file mode 100644 index ed5103ad5..000000000 --- a/api/roar/roar_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package roar - -import ( - "slices" - "strings" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestRoar(t *testing.T) { - r := Roar[int]{} - require.Equal(t, 0, r.Len()) - - r.Add(1) - require.Equal(t, 1, r.Len()) - require.True(t, r.Contains(1)) - require.False(t, r.Contains(2)) - - r.Add(2) - require.Equal(t, 2, r.Len()) - require.True(t, r.Contains(2)) - - r.Remove(1) - require.Equal(t, 1, r.Len()) - require.False(t, r.Contains(1)) - - s := FromSlice([]int{3, 4, 5}) - require.Equal(t, 3, s.Len()) - require.True(t, s.Contains(3)) - require.True(t, s.Contains(4)) - require.True(t, s.Contains(5)) - - r.Union(s) - require.Equal(t, 4, r.Len()) - require.True(t, r.Contains(2)) - require.True(t, r.Contains(3)) - require.True(t, r.Contains(4)) - require.True(t, r.Contains(5)) - - r.Iterate(func(id int) bool { - require.True(t, slices.Contains([]int{2, 3, 4, 5}, id)) - - return true - }) - - rSlice := r.ToSlice() - require.EqualValues(t, []int{2, 3, 4, 5}, rSlice) - - r.Intersection(FromSlice([]int{4})) - require.Equal(t, 1, r.Len()) - require.True(t, r.Contains(4)) - require.False(t, r.Contains(2)) - require.False(t, r.Contains(3)) - require.False(t, r.Contains(5)) - - b, err := r.MarshalJSON() - require.NoError(t, err) - require.NotEqual(t, "null", string(b)) - require.True(t, strings.HasPrefix(string(b), `"`)) - require.True(t, strings.HasSuffix(string(b), `"`)) -} - -func TestNilSafety(t *testing.T) { - var r, s, u Roar[int] - - r.Iterate(func(id int) bool { - require.Fail(t, "should not iterate over nil Roar") - - return true - }) - - b, err := r.MarshalJSON() - require.NoError(t, err) - require.Equal(t, "null", string(b)) - - err = r.UnmarshalJSON([]byte("null")) - require.NoError(t, err) - require.Equal(t, 0, r.Len()) - - r.Contains(1) - r.Remove(1) - - require.Equal(t, 0, r.Len()) - require.Empty(t, r.ToSlice()) - - r.Add(1) - require.Equal(t, 1, r.Len()) - require.False(t, r.Contains(2)) - - s.Union(r) - require.Equal(t, 1, s.Len()) - require.True(t, s.Contains(1)) - - r.Union(u) - require.Equal(t, 1, r.Len()) - require.True(t, r.Contains(1)) - - s.Intersection(u) - require.Equal(t, 0, s.Len()) - - u.Intersection(r) - require.Equal(t, 0, u.Len()) -} - -func TestJSON(t *testing.T) { - var r, u Roar[int] - - r.Add(1) - r.Add(2) - r.Add(3) - - b, err := r.MarshalJSON() - require.NoError(t, err) - require.NotEqual(t, "null", string(b)) - - err = u.UnmarshalJSON(b) - require.NoError(t, err) - require.Equal(t, 3, u.Len()) - require.True(t, u.Contains(1)) - require.True(t, u.Contains(2)) - require.True(t, u.Contains(3)) -} diff --git a/api/slicesx/filter.go b/api/slicesx/filter.go deleted file mode 100644 index 13dc12105..000000000 --- a/api/slicesx/filter.go +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 36f97fa10..000000000 --- a/api/slicesx/filter_test.go +++ /dev/null @@ -1,96 +0,0 @@ -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 deleted file mode 100644 index 56a77f3e9..000000000 --- a/api/slicesx/flatten.go +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 6875c4e6b..000000000 --- a/api/slicesx/flatten_test.go +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 377a54215..000000000 --- a/api/slicesx/includes.go +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index a3f074c1c..000000000 --- a/api/slicesx/includes_test.go +++ /dev/null @@ -1,76 +0,0 @@ -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 deleted file mode 100644 index 7e24bdd0d..000000000 --- a/api/slicesx/map.go +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index a2cd2256d..000000000 --- a/api/slicesx/map_test.go +++ /dev/null @@ -1,43 +0,0 @@ -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/unique.go b/api/slicesx/slices.go similarity index 51% rename from api/slicesx/unique.go rename to api/slicesx/slices.go index 8659b0778..b7e0aa0ef 100644 --- a/api/slicesx/unique.go +++ b/api/slicesx/slices.go @@ -1,5 +1,27 @@ 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/slices_test.go b/api/slicesx/slices_test.go new file mode 100644 index 000000000..d75f9b559 --- /dev/null +++ b/api/slicesx/slices_test.go @@ -0,0 +1,127 @@ +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 deleted file mode 100644 index 1bb8a76fe..000000000 --- a/api/slicesx/slicesx_test.go +++ /dev/null @@ -1,29 +0,0 @@ -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/unique_test.go b/api/slicesx/unique_test.go deleted file mode 100644 index 8ff967ca6..000000000 --- a/api/slicesx/unique_test.go +++ /dev/null @@ -1,46 +0,0 @@ -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/api/stacks/stackutils/gitops.go b/api/stacks/stackutils/gitops.go index 566a2a2e2..d035b783d 100644 --- a/api/stacks/stackutils/gitops.go +++ b/api/stacks/stackutils/gitops.go @@ -19,23 +19,13 @@ var ( func DownloadGitRepository(config gittypes.RepoConfig, gitService portainer.GitService, getProjectPath func() string) (string, error) { username := "" password := "" - authType := gittypes.GitCredentialAuthType_Basic if config.Authentication != nil { username = config.Authentication.Username password = config.Authentication.Password - authType = config.Authentication.AuthorizationType } projectPath := getProjectPath() - err := gitService.CloneRepository( - projectPath, - config.URL, - config.ReferenceName, - username, - password, - authType, - config.TLSSkipVerify, - ) + err := gitService.CloneRepository(projectPath, config.URL, config.ReferenceName, username, password, config.TLSSkipVerify) if err != nil { if errors.Is(err, gittypes.ErrAuthenticationFailure) { newErr := git.ErrInvalidGitCredential @@ -46,14 +36,7 @@ func DownloadGitRepository(config gittypes.RepoConfig, gitService portainer.GitS return "", newErr } - commitID, err := gitService.LatestCommitID( - config.URL, - config.ReferenceName, - username, - password, - authType, - config.TLSSkipVerify, - ) + commitID, err := gitService.LatestCommitID(config.URL, config.ReferenceName, username, password, config.TLSSkipVerify) if err != nil { newErr := fmt.Errorf("unable to fetch git repository id: %w", err) return "", newErr diff --git a/app/assets/css/button.css b/app/assets/css/button.css index 547d9fdc0..0aece2a15 100644 --- a/app/assets/css/button.css +++ b/app/assets/css/button.css @@ -29,79 +29,43 @@ fieldset[disabled] .btn { } .btn.btn-primary { - @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; + @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; } .btn.btn-primary:active, .btn.btn-primary.active, .open > .dropdown-toggle.btn-primary { - @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; + @apply border-blue-5 bg-blue-9; } .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus { - @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; + @apply bg-blue-8; } /* Button Secondary */ .btn.btn-secondary { @apply border border-solid; - @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 border-blue-8 bg-blue-2 text-blue-9; + @apply hover:bg-blue-3; - @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; + @apply th-dark:border-blue-7 th-dark:bg-gray-10 th-dark:text-blue-3; + @apply th-dark:hover:bg-blue-11; } .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-error-5 bg-error-8 text-white; + @apply border-blue-5 bg-error-8 text-white; } .btn.btn-dangerlight { @@ -110,10 +74,6 @@ 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; @@ -130,18 +90,15 @@ fieldset[disabled] .btn { /* secondary-grey */ .btn.btn-default, .btn.btn-light { - @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; + @apply border-gray-5 bg-white text-gray-7; + @apply hover:border-gray-5 hover:bg-gray-3 hover:text-gray-9; /* 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, @@ -162,17 +119,42 @@ fieldset[disabled] .btn { .input-group-btn .btn.active, .btn-group .btn.active { - @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; + @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; +} + +/* focus */ + +.btn.btn-primary:focus, +.btn.btn-secondary:focus, +.btn.btn-light:focus { + @apply border-blue-5; +} + +.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); } .btn.btn-icon:focus { box-shadow: none !important; } -.btn:focus { - box-shadow: 0px 0px 0px 2px var(--tw-shadow-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); } a.no-link, diff --git a/app/assets/css/colors.json b/app/assets/css/colors.json index 94d3c2015..55f2922e5 100644 --- a/app/assets/css/colors.json +++ b/app/assets/css/colors.json @@ -1,31 +1,6 @@ { "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 dbbea4766..acd26fb58 100644 --- a/app/assets/css/react-datetime-picker-override.css +++ b/app/assets/css/react-datetime-picker-override.css @@ -12,40 +12,35 @@ /* Extending Calendar.css from react-daterange-picker__calendar */ -.react-calendar { +.react-daterange-picker__calendar .react-calendar { background: var(--bg-calendar-color); color: var(--text-main-color); - @apply th-dark:bg-gray-iron-10; } /* calendar nav buttons */ -.react-calendar__navigation button:disabled { +.react-daterange-picker__calendar .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-calendar__navigation button:enabled:hover, -.react-calendar__navigation button:enabled:focus { +.react-daterange-picker__calendar .react-calendar__navigation button:enabled:hover, +.react-daterange-picker__calendar .react-calendar__navigation button:enabled:focus { background: var(--bg-daterangepicker-color); - @apply th-dark:bg-gray-iron-7; } /* date tile */ -.react-calendar__tile:disabled { +.react-daterange-picker__calendar .react-calendar__tile:disabled { + background: var(--bg-calendar-color); @apply opacity-60; @apply brightness-95 th-dark:brightness-110; - @apply th-dark:bg-gray-iron-7; } - -.react-calendar__tile:enabled:hover, -.react-calendar__tile:enabled:focus { +.react-daterange-picker__calendar .react-calendar__tile:enabled:hover, +.react-daterange-picker__calendar .react-calendar__tile:enabled:focus { background: var(--bg-daterangepicker-hover); - @apply th-dark:bg-gray-iron-7; } /* today's date tile */ -.react-calendar__tile--now { +.react-daterange-picker__calendar .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; } @@ -53,27 +48,23 @@ .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-calendar__tile--hasActive { +.react-daterange-picker__calendar .react-calendar__tile--hasActive { background: var(--bg-daterangepicker-end-date); color: var(--text-daterangepicker-end-date); - @apply th-dark:bg-gray-iron-7; } -.react-calendar__tile--hasActive:enabled:hover, -.react-calendar__tile--hasActive:enabled:focus { +.react-daterange-picker__calendar .react-calendar__tile--hasActive:enabled:hover, +.react-daterange-picker__calendar .react-calendar__tile--hasActive:enabled:focus { background: var(--bg-daterangepicker-hover); color: var(--text-daterangepicker-hover); - @apply th-dark:bg-gray-iron-7; } -.react-calendar__tile--active:enabled:hover, -.react-calendar__tile--active:enabled:focus { +.react-daterange-picker__calendar .react-calendar__tile--active:enabled:hover, +.react-daterange-picker__calendar .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 @@ -84,10 +75,9 @@ } /* on range select hover */ -.react-calendar--selectRange .react-calendar__tile--hover { +.react-daterange-picker__calendar .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; } /* @@ -121,5 +111,4 @@ .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 318e0d9e4..eb2d36882 100644 --- a/app/assets/css/theme.css +++ b/app/assets/css/theme.css @@ -3,16 +3,6 @@ --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; @@ -68,8 +58,6 @@ --grey-58: #ebf4f8; --grey-59: #e6e6e6; --grey-61: rgb(231, 231, 231); - --grey-62: #fdfdfd; - --grey-63: #121212; --blue-1: #219; --blue-2: #337ab7; @@ -111,16 +99,17 @@ /* Default Theme */ --bg-card-color: var(--white-color); --bg-main-color: var(--white-color); - --bg-body-color: var(--grey-62); + --bg-body-color: var(--grey-9); --bg-checkbox-border-color: var(--grey-49); - --bg-sidebar-color: var(--graphite-700); - --bg-sidebar-nav-color: var(--graphite-600); + --bg-sidebar-color: var(--ui-blue-10); + --bg-sidebar-nav-color: var(--ui-blue-11); --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); @@ -139,8 +128,7 @@ --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(--mist-50); - --bg-motd-btn-color: var(--graphite-700); + --bg-motd-body-color: var(--grey-20); --bg-item-highlighted-color: var(--grey-21); --bg-item-highlighted-null-color: var(--grey-14); --bg-panel-body-color: var(--white-color); @@ -156,6 +144,8 @@ --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); @@ -187,6 +177,7 @@ --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); @@ -198,8 +189,6 @@ --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); @@ -214,7 +203,6 @@ --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); @@ -230,8 +218,7 @@ --border-pre-color: var(--grey-43); --border-pagination-span-color: var(--ui-white); --border-pagination-hover-color: var(--ui-white); - --border-motd-body-color: var(--mist-300); - --border-panel-color: var(--mist-300); + --border-panel-color: var(--white-color); --border-input-sm-color: var(--grey-47); --border-daterangepicker-color: var(--grey-19); --border-calendar-table: var(--white-color); @@ -278,7 +265,8 @@ --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-63); + --bg-body-color: var(--grey-2); + --bg-btn-default-color: var(--grey-3); --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); @@ -286,6 +274,8 @@ --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); @@ -306,8 +296,7 @@ --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(--graphite-800); - --bg-motd-btn-color: var(--mist-100); + --bg-motd-body-color: var(--grey-1); --bg-item-highlighted-color: var(--grey-2); --bg-item-highlighted-null-color: var(--grey-2); --bg-panel-body-color: var(--grey-1); @@ -327,6 +316,8 @@ --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); @@ -357,6 +348,7 @@ --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); @@ -368,8 +360,6 @@ --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); @@ -384,7 +374,6 @@ --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); @@ -402,7 +391,6 @@ --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); @@ -462,7 +450,6 @@ --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); @@ -494,8 +481,11 @@ --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); @@ -533,8 +523,6 @@ --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); @@ -565,7 +553,6 @@ --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 12e0fc947..74fa94d4e 100644 --- a/app/assets/css/vendor-override.css +++ b/app/assets/css/vendor-override.css @@ -201,18 +201,8 @@ pre { background-color: var(--bg-progress-color); } -.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); +.motd-body { + background-color: var(--bg-motd-body-color) !important; } .panel-body { @@ -418,10 +408,14 @@ input:-webkit-autofill { } .sidebar.tippy-box[data-placement^='right'] > .tippy-arrow:before { - border-right: 8px solid var(--graphite-600); + border-right: 8px solid var(--ui-blue-9); 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 236db0e2b..8f31e405a 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 52848e019..cc95d0044 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 f05e9c161..aeea31ce8 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 8c60e5d9f..f7a26b564 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 8735718a2..d1ccc9cea 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 066969400..28ed661f9 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 140c1b494..b7679d482 100644 --- a/app/assets/ico/logomark.svg +++ b/app/assets/ico/logomark.svg @@ -1,12 +1,35 @@ - - - - - + + + + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + diff --git a/app/assets/ico/mstile-150x150.png b/app/assets/ico/mstile-150x150.png index f48374538..5e7eb6873 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 d0509a572..79ce7b6fa 100644 --- a/app/assets/ico/safari-pinned-tab.svg +++ b/app/assets/ico/safari-pinned-tab.svg @@ -1,6 +1 @@ - - - - - - \ 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 new file mode 100644 index 000000000..2e46594f2 Binary files /dev/null and b/app/assets/images/logo.png differ diff --git a/app/assets/images/logo_alt.png b/app/assets/images/logo_alt.png new file mode 100644 index 000000000..a6c6707ca Binary files /dev/null and b/app/assets/images/logo_alt.png differ diff --git a/app/assets/images/logo_alt.svg b/app/assets/images/logo_alt.svg index 8d254e4e5..90e164ca1 100644 --- a/app/assets/images/logo_alt.svg +++ b/app/assets/images/logo_alt.svg @@ -1,14 +1,60 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/images/logo_alt_black.svg b/app/assets/images/logo_alt_black.svg deleted file mode 100644 index d9243b464..000000000 --- a/app/assets/images/logo_alt_black.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/app/assets/images/logo_ico.png b/app/assets/images/logo_ico.png new file mode 100644 index 000000000..b4bfd2924 Binary files /dev/null and b/app/assets/images/logo_ico.png differ diff --git a/app/assets/images/logo_small.png b/app/assets/images/logo_small.png new file mode 100644 index 000000000..76d3a46b0 Binary files /dev/null and b/app/assets/images/logo_small.png differ diff --git a/app/assets/images/logo_small_alt.png b/app/assets/images/logo_small_alt.png new file mode 100644 index 000000000..a5bc64771 Binary files /dev/null and b/app/assets/images/logo_small_alt.png differ diff --git a/app/assets/images/purple-gradient.svg b/app/assets/images/purple-gradient.svg deleted file mode 100644 index 0b3bc7160..000000000 --- a/app/assets/images/purple-gradient.svg +++ /dev/null @@ -1,522 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/docker/views/images/edit/image.html b/app/docker/views/images/edit/image.html index af37cd0e2..7bee83a2b 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 3045fe547..370070b48 100644 --- a/app/index.html +++ b/app/index.html @@ -20,7 +20,7 @@ - + @@ -31,8 +31,8 @@
@@ -47,10 +47,7 @@
-
- - -
+
diff --git a/app/kubernetes/__module.js b/app/kubernetes/__module.js index 5fb223a40..adb937cce 100644 --- a/app/kubernetes/__module.js +++ b/app/kubernetes/__module.js @@ -83,13 +83,6 @@ angular.module('portainer.kubernetes', ['portainer.app', registriesModule, custo }); } - // EE-5842: do not redirect shell views when the env is removed - const nextTransition = $state.transition && $state.transition.to(); - const nextTransitionName = nextTransition ? nextTransition.name : ''; - if (nextTransitionName === 'kubernetes.kubectlshell' && !endpoint) { - return; - } - const kubeTypes = [ PortainerEndpointTypes.KubernetesLocalEnvironment, PortainerEndpointTypes.AgentOnKubernetesEnvironment, @@ -127,11 +120,6 @@ angular.module('portainer.kubernetes', ['portainer.app', registriesModule, custo EndpointProvider.clean(); Notifications.error('Failed loading environment', e); } - // Prevent redirect to home for shell views when environment is unreachable - // Show toast error instead (handled above in Notifications.error) - if (nextTransitionName === 'kubernetes.kubectlshell') { - return; - } $state.go('portainer.home', params, { reload: true, inherit: false }); return false; } @@ -436,17 +424,6 @@ angular.module('portainer.kubernetes', ['portainer.app', registriesModule, custo }, }; - const kubectlShell = { - name: 'kubernetes.kubectlshell', - url: '/kubectl-shell', - views: { - 'content@': { - component: 'kubectlShellView', - }, - 'sidebar@': {}, - }, - }; - const dashboard = { name: 'kubernetes.dashboard', url: '/dashboard', @@ -680,7 +657,6 @@ angular.module('portainer.kubernetes', ['portainer.app', registriesModule, custo $stateRegistryProvider.register(deploy); $stateRegistryProvider.register(node); $stateRegistryProvider.register(nodeStats); - $stateRegistryProvider.register(kubectlShell); $stateRegistryProvider.register(resourcePools); $stateRegistryProvider.register(namespaceCreation); $stateRegistryProvider.register(resourcePool); diff --git a/app/kubernetes/react/components/index.ts b/app/kubernetes/react/components/index.ts index cfb103823..27aa04444 100644 --- a/app/kubernetes/react/components/index.ts +++ b/app/kubernetes/react/components/index.ts @@ -92,7 +92,6 @@ export const ngModule = angular 'onChange', 'placeholder', 'value', - 'allowSelectAll', ]) ) .component( diff --git a/app/kubernetes/react/views/index.ts b/app/kubernetes/react/views/index.ts index aeb161dcd..e4043985f 100644 --- a/app/kubernetes/react/views/index.ts +++ b/app/kubernetes/react/views/index.ts @@ -24,7 +24,6 @@ import { AccessView } from '@/react/kubernetes/namespaces/AccessView/AccessView' import { JobsView } from '@/react/kubernetes/more-resources/JobsView/JobsView'; import { ClusterView } from '@/react/kubernetes/cluster/ClusterView'; import { HelmApplicationView } from '@/react/kubernetes/helm/HelmApplicationView'; -import { KubectlShellView } from '@/react/kubernetes/cluster/KubectlShell/KubectlShellView'; export const viewsModule = angular .module('portainer.kubernetes.react.views', []) @@ -85,10 +84,6 @@ export const viewsModule = angular 'kubernetesHelmApplicationView', r2a(withUIRouter(withReactQuery(withCurrentUser(HelmApplicationView))), []) ) - .component( - 'kubectlShellView', - r2a(withUIRouter(withReactQuery(withCurrentUser(KubectlShellView))), []) - ) .component( 'kubernetesClusterView', r2a(withUIRouter(withReactQuery(withCurrentUser(ClusterView))), []) 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 5c5e68255..11184ae0f 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,7 +19,6 @@ 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 37cae6cad..66601d98b 100644 --- a/app/kubernetes/views/applications/logs/logsController.js +++ b/app/kubernetes/views/applications/logs/logsController.js @@ -77,7 +77,6 @@ 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/deploy/deploy.html b/app/kubernetes/views/deploy/deploy.html index 60e7b0144..d57d0caa7 100644 --- a/app/kubernetes/views/deploy/deploy.html +++ b/app/kubernetes/views/deploy/deploy.html @@ -40,15 +40,17 @@
- +
- + data-cy="namespace-select" + ng-disabled="ctrl.formValues.namespace_toggle && ctrl.state.BuildMethod !== ctrl.BuildMethods.HELM" + class="form-control" + ng-model="ctrl.formValues.Namespace" + ng-change="ctrl.onChangeNamespace()" + ng-options="namespace.Name as namespace.Name for namespace in ctrl.namespaces" + > Namespaces specified in the manifest will be used @@ -184,6 +186,7 @@
+
Selected Helm chart
diff --git a/app/kubernetes/views/deploy/deployController.js b/app/kubernetes/views/deploy/deployController.js index b44d3d7bb..89f416ac3 100644 --- a/app/kubernetes/views/deploy/deployController.js +++ b/app/kubernetes/views/deploy/deployController.js @@ -101,10 +101,9 @@ class KubernetesDeployController { this.onChangeNamespace = this.onChangeNamespace.bind(this); } - onChangeNamespace(namespaceName) { + onChangeNamespace() { return this.$async(async () => { - this.formValues.Namespace = namespaceName; - const applications = await this.KubernetesApplicationService.get(namespaceName); + const applications = await this.KubernetesApplicationService.get(this.formValues.Namespace); const stacks = _.map(applications, (item) => item.StackName).filter((item) => item !== ''); this.stacks = _.uniq(stacks); }); @@ -372,10 +371,6 @@ 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'); } @@ -409,8 +404,7 @@ class KubernetesDeployController { } } - this.onChangeNamespace(this.formValues.Namespace); - + this.onChangeNamespace(); 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 d4e1b5ba7..536ea2ae4 100644 --- a/app/kubernetes/views/stacks/logs/logsController.js +++ b/app/kubernetes/views/stacks/logs/logsController.js @@ -104,7 +104,6 @@ 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/react/components/index.ts b/app/portainer/react/components/index.ts index 9b2f7325d..4b1c03608 100644 --- a/app/portainer/react/components/index.ts +++ b/app/portainer/react/components/index.ts @@ -9,7 +9,6 @@ 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, @@ -200,22 +199,11 @@ export const ngModule = angular 'onChange', 'options', 'isMulti', - 'filterOption', 'isClearable', 'components', 'isLoading', 'noOptionsMessage', 'aria-label', - 'loadingMessage', - ]) - ) - .component( - 'namespacePortainerSelect', - r2a(NamespacePortainerSelect, [ - 'value', - 'onChange', - 'isDisabled', - 'options', ]) ) .component( diff --git a/app/portainer/views/auth/auth.html b/app/portainer/views/auth/auth.html index 2504141a7..09dadf050 100644 --- a/app/portainer/views/auth/auth.html +++ b/app/portainer/views/auth/auth.html @@ -4,10 +4,7 @@
-
- - -
+
diff --git a/app/portainer/views/init/admin/initAdmin.html b/app/portainer/views/init/admin/initAdmin.html index afff165b2..b5cfcfeb4 100644 --- a/app/portainer/views/init/admin/initAdmin.html +++ b/app/portainer/views/init/admin/initAdmin.html @@ -5,10 +5,7 @@
-
- - -
+
diff --git a/app/portainer/views/logout/logout.html b/app/portainer/views/logout/logout.html index 95299d5d0..fe9b2513d 100644 --- a/app/portainer/views/logout/logout.html +++ b/app/portainer/views/logout/logout.html @@ -4,10 +4,7 @@
-
- - -
+
diff --git a/app/react-tools/test-mocks.ts b/app/react-tools/test-mocks.ts index d9c7d273c..20fe7dee3 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) + roles: Role | Role[] | ((id: UserId) => Role) = () => _.random(1, 3) ): User[] { return _.range(1, count + 1).map((value) => ({ Id: value, @@ -40,14 +40,7 @@ function getRoles( return roles; } - // 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]; + return roles[id]; } export function createMockTeams(count: number): Team[] { diff --git a/app/react/common/utils/numbers.test.ts b/app/react/common/utils/numbers.test.ts deleted file mode 100644 index 0cd6004a5..000000000 --- a/app/react/common/utils/numbers.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -/* eslint-disable @typescript-eslint/no-loss-of-precision */ - -import { abbreviateNumber } from './numbers'; - -describe('abbreviateNumber', () => { - test('errors', () => { - expect(() => abbreviateNumber(Number.NaN)).toThrowError(); - expect(() => abbreviateNumber(1, -1)).toThrowError(); - expect(() => abbreviateNumber(1, 21)).toThrowError(); - }); - - test('zero', () => { - expect(abbreviateNumber(0)).toBe('0'); - expect(abbreviateNumber(-0)).toBe('0'); - }); - - test('decimals=0', () => { - const cases: [number, string][] = [ - [123, '123'], - [123_123, '123k'], - [123_123_123, '123M'], - [123_123_123_123, '123G'], - [123_123_123_123_123, '123T'], - [123_123_123_123_123_123, '123P'], - [123_123_123_123_123_123_123, '123E'], - [123_123_123_123_123_123_123_123, '123Z'], - [123_123_123_123_123_123_123_123_123, '123Y'], - [123_123_123_123_123_123_123_123_123_123, '123123Y'], - ]; - cases.forEach(([num, str]) => { - expect(abbreviateNumber(num, 0)).toBe(str); - expect(abbreviateNumber(-num, 0)).toBe(`-${str}`); - }); - }); - - test('decimals=1 (default)', () => { - const cases: [number, string][] = [ - [123, '123'], - [123_123, '123.1k'], - [123_123_123, '123.1M'], - [123_123_123_123, '123.1G'], - [123_123_123_123_123, '123.1T'], - [123_123_123_123_123_123, '123.1P'], - [123_123_123_123_123_123_123, '123.1E'], - [123_123_123_123_123_123_123_123, '123.1Z'], - [123_123_123_123_123_123_123_123_123, '123.1Y'], - [123_123_123_123_123_123_123_123_123_123, '123123.1Y'], - ]; - cases.forEach(([num, str]) => { - expect(abbreviateNumber(num)).toBe(str); - expect(abbreviateNumber(-num)).toBe(`-${str}`); - }); - }); - - test('decimals=10', () => { - const cases: [number, string][] = [ - [123, '123'], - [123_123, '123.123k'], - [123_123_123, '123.123123M'], - [123_123_123_123, '123.123123123G'], - [123_123_123_123_123, '123.1231231231T'], - [123_123_123_123_123_123, '123.1231231231P'], - [123_123_123_123_123_123_123, '123.1231231231E'], - [123_123_123_123_123_123_123_123, '123.1231231231Z'], - [123_123_123_123_123_123_123_123_123, '123.1231231231Y'], - [123_123_123_123_123_123_123_123_123_123, '123123.1231231231Y'], - ]; - cases.forEach(([num, str]) => { - expect(abbreviateNumber(num, 10)).toBe(str); - expect(abbreviateNumber(-num, 10)).toBe(`-${str}`); - }); - }); -}); - -/* eslint-enable @typescript-eslint/no-loss-of-precision */ diff --git a/app/react/common/utils/numbers.ts b/app/react/common/utils/numbers.ts deleted file mode 100644 index 617da47ae..000000000 --- a/app/react/common/utils/numbers.ts +++ /dev/null @@ -1,45 +0,0 @@ -const suffixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; - -/** - * Converts a number to a human-readable abbreviated format - * Uses base 10 and standard SI prefixes - * - * @param num - The number to abbreviate - * @param decimals - Number of decimal places (default: 1) - * @returns Abbreviated number as string (e.g., "90k", "123M") - */ -export function abbreviateNumber(num: number, decimals: number = 1): string { - if (Number.isNaN(num)) { - throw new Error('Invalid number'); - } - - if (decimals < 0 || decimals > 20) { - throw new Error('Invalid decimals. Must be in [0;20] range'); - } - - const isNegative = num < 0; - const absNum = Math.abs(num); - - if (absNum === 0) { - return '0'; - } - - let exponent = Math.floor(Math.log10(absNum) / 3); - - if (exponent > suffixes.length - 1) { - exponent = suffixes.length - 1; - } - - if (exponent < 0) { - exponent = 0; - } - - const value = absNum / 1000 ** exponent; - - const roundedValue = - exponent > 0 ? Number(value.toFixed(decimals)) : Math.floor(value); - - const finalValue = isNegative ? -roundedValue : roundedValue; - - return `${finalValue}${suffixes[exponent]}`; -} diff --git a/app/react/components/CodeEditor/CodeEditor.test.tsx b/app/react/components/CodeEditor/CodeEditor.test.tsx index a269cd192..7b100b0e3 100644 --- a/app/react/components/CodeEditor/CodeEditor.test.tsx +++ b/app/react/components/CodeEditor/CodeEditor.test.tsx @@ -122,7 +122,7 @@ test('should apply custom height', async () => { ); - const editor = await findByRole('textbox'); + const editor = (await findByRole('textbox')).parentElement?.parentElement; expect(editor).toHaveStyle({ height: customHeight }); }); diff --git a/app/react/components/CodeEditor/useCodeEditorExtensions.ts b/app/react/components/CodeEditor/useCodeEditorExtensions.ts index 8050b59da..3b46a543e 100644 --- a/app/react/components/CodeEditor/useCodeEditorExtensions.ts +++ b/app/react/components/CodeEditor/useCodeEditorExtensions.ts @@ -48,7 +48,7 @@ function yamlLanguage(schema?: JSONSchema7) { syntaxHighlighting(oneDarkHighlightStyle), // explicitly setting lineNumbers() as an extension ensures that the gutter order is the same between the diff viewer and the code editor lineNumbers(), - !!schema && lintGutter(), + lintGutter(), keymap.of([...defaultKeymap, ...completionKeymap, ...lintKeymap]), // only show completions when a schema is provided !!schema && diff --git a/app/react/components/ExternalLink.tsx b/app/react/components/ExternalLink.tsx index 1bd839cad..ef16dcb66 100644 --- a/app/react/components/ExternalLink.tsx +++ b/app/react/components/ExternalLink.tsx @@ -1,20 +1,20 @@ -import { ArrowUpRight } from 'lucide-react'; +import { ExternalLink as ExternalLinkIcon } from 'lucide-react'; import { PropsWithChildren } from 'react'; import clsx from 'clsx'; import { AutomationTestingProps } from '@/types'; +import { Icon } from '@@/Icon'; + interface Props { to: string; className?: string; - showIcon?: boolean; } export function ExternalLink({ to, className, children, - showIcon = true, 'data-cy': dataCy, }: PropsWithChildren) { return ( @@ -23,10 +23,10 @@ export function ExternalLink({ target="_blank" rel="noreferrer" data-cy={dataCy} - className={clsx('inline-flex align-baseline', className)} + className={clsx('inline-flex items-center gap-1', className)} > - {children} - {showIcon && } + + {children} ); } diff --git a/app/react/components/FallbackImage.tsx b/app/react/components/FallbackImage.tsx index eaa4f1272..ee6956f24 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 f25afadba..b5c9dafc9 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 139c67637..5ade961bb 100644 --- a/app/react/components/ViewLoading/ViewLoading.tsx +++ b/app/react/components/ViewLoading/ViewLoading.tsx @@ -1,4 +1,7 @@ import clsx from 'clsx'; +import { Settings } from 'lucide-react'; + +import { Icon } from '@@/Icon'; import styles from './ViewLoading.module.css'; @@ -15,7 +18,12 @@ export function ViewLoading({ message }: Props) {
- {message && {message}} + {message && ( + + {message} + + + )}
); } diff --git a/app/react/components/datatables/index.ts b/app/react/components/datatables/index.ts index 3ab420889..809efc23b 100644 --- a/app/react/components/datatables/index.ts +++ b/app/react/components/datatables/index.ts @@ -11,4 +11,3 @@ 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/FormSection/FormSection.tsx b/app/react/components/form-components/FormSection/FormSection.tsx index 51dbab534..6ea747762 100644 --- a/app/react/components/form-components/FormSection/FormSection.tsx +++ b/app/react/components/form-components/FormSection/FormSection.tsx @@ -12,7 +12,6 @@ interface Props { titleClassName?: string; className?: string; htmlFor?: string; - setIsDefaultFolded?: (isDefaultFolded: boolean) => void; } export function FormSection({ @@ -24,7 +23,6 @@ export function FormSection({ titleClassName, className, htmlFor = '', - setIsDefaultFolded, }: PropsWithChildren) { const [isExpanded, setIsExpanded] = useState(!defaultFolded); const id = `foldingButton${title}`; @@ -41,10 +39,7 @@ export function FormSection({ isExpanded={isExpanded} data-cy={id} id={id} - onClick={() => { - setIsExpanded((isExpanded) => !isExpanded); - setIsDefaultFolded?.(isExpanded); - }} + onClick={() => setIsExpanded((isExpanded) => !isExpanded)} /> )} diff --git a/app/react/components/form-components/PortainerSelect.tsx b/app/react/components/form-components/PortainerSelect.tsx index 6800d0013..9ddf234da 100644 --- a/app/react/components/form-components/PortainerSelect.tsx +++ b/app/react/components/form-components/PortainerSelect.tsx @@ -5,25 +5,15 @@ 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 { - Creatable, - Select as ReactSelect, -} from '@@/form-components/ReactSelect'; +import { 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< @@ -31,7 +21,7 @@ type Options = OptionsOrGroups< GroupBase> >; -interface SharedProps +interface SharedProps extends AutomationTestingProps, Pick { name?: string; @@ -42,14 +32,9 @@ 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; @@ -59,12 +44,9 @@ 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; @@ -76,13 +58,9 @@ interface SingleProps extends SharedProps { >; } -export type PortainerSelectProps = - | MultiProps - | SingleProps; +type Props = MultiProps | SingleProps; -export function PortainerSelect( - props: PortainerSelectProps -) { +export function PortainerSelect(props: Props) { return isMultiProps(props) ? ( // eslint-disable-next-line react/jsx-props-no-spreading @@ -93,7 +71,7 @@ export function PortainerSelect( } function isMultiProps( - props: PortainerSelectProps + props: Props ): props is MultiProps { return 'isMulti' in props && !!props.isMulti; } @@ -109,11 +87,9 @@ export function SingleSelect({ placeholder, isClearable, bindToBody, - filterOption, components, isLoading, noOptionsMessage, - loadingMessage, isMulti, ...aria }: SingleProps) { @@ -140,11 +116,9 @@ 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} /> @@ -185,20 +159,14 @@ 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 c7ea47366..a9f4e6282 100644 --- a/app/react/components/form-components/ReactSelect.tsx +++ b/app/react/components/form-components/ReactSelect.tsx @@ -5,14 +5,12 @@ 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, useCallback } from 'react'; +import { RefAttributes, useMemo } from 'react'; import ReactSelectType from 'react-select/dist/declarations/src/Select'; import './ReactSelect.css'; @@ -54,9 +52,6 @@ type Props< | CreatableProps | RegularProps; -/** - * DO NOT use this component directly, use PortainerSelect instead. - */ export function Select< Option = DefaultOption, IsMulti extends boolean = false, @@ -73,37 +68,24 @@ export function Select< id: string; }) { const Component = isCreatable ? ReactSelectCreatable : ReactSelect; - const { - options, - 'data-cy': dataCy, - components: componentsProp, - ...rest - } = props; - - const memoizedComponents = useMemoizedSelectComponents< - Option, - IsMulti, - Group - >(dataCy, componentsProp); + const { options } = props; if ((options?.length || 0) > 1000) { return ( ); } return ( ); } @@ -112,25 +94,13 @@ export function Creatable< Option = DefaultOption, IsMulti extends boolean = false, Group extends GroupBase
diff --git a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ReleaseTabs.tsx b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ReleaseTabs.tsx index d8a84a214..0aa05960c 100644 --- a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ReleaseTabs.tsx +++ b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ReleaseTabs.tsx @@ -11,7 +11,7 @@ import { Badge } from '@@/Badge'; import { Icon } from '@@/Icon'; import { HelmRelease } from '../../types'; -import { useHelmHistory } from '../../helmReleaseQueries/useHelmHistory'; +import { useHelmHistory } from '../queries/useHelmHistory'; import { ManifestDetails } from './ManifestDetails'; import { NotesDetails } from './NotesDetails'; diff --git a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.test.tsx b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.test.tsx index 100b68fc0..1bae99912 100644 --- a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.test.tsx +++ b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.test.tsx @@ -3,7 +3,8 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { withTestRouter } from '@/react/test-utils/withRouter'; import { withTestQueryProvider } from '@/react/test-utils/withTestQuery'; -import { GenericResource } from '@/react/kubernetes/helm/types'; + +import { GenericResource } from '../../../types'; import { ResourcesTable } from './ResourcesTable'; @@ -21,7 +22,7 @@ vi.mock('@/react/hooks/useEnvironmentId', () => ({ useEnvironmentId: () => mockUseEnvironmentId(), })); -vi.mock('@/react/kubernetes/helm/helmReleaseQueries/useHelmRelease', () => ({ +vi.mock('../../queries/useHelmRelease', () => ({ useHelmRelease: () => mockUseHelmRelease(), })); diff --git a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.tsx b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.tsx index e661e964c..1757535ba 100644 --- a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.tsx +++ b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/ResourcesTable.tsx @@ -1,7 +1,6 @@ import { useCurrentStateAndParams } from '@uirouter/react'; import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; -import { useHelmRelease } from '@/react/kubernetes/helm/helmReleaseQueries/useHelmRelease'; import { Datatable, TableSettingsMenu } from '@@/datatables'; import { @@ -14,6 +13,8 @@ import { Widget } from '@@/Widget'; import { TableSettingsMenuAutoRefresh } from '@@/datatables/TableSettingsMenuAutoRefresh'; import { TextTip } from '@@/Tip/TextTip'; +import { useHelmRelease } from '../../queries/useHelmRelease'; + import { columns } from './columns'; import { useResourceRows } from './useResourceRows'; diff --git a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/useResourceRows.ts b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/useResourceRows.ts index c16b0e885..ac90271f8 100644 --- a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/useResourceRows.ts +++ b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/ResourcesTable/useResourceRows.ts @@ -1,9 +1,9 @@ import { useMemo } from 'react'; -import { GenericResource } from '@/react/kubernetes/helm/types'; - import { StatusBadgeType } from '@@/StatusBadge'; +import { GenericResource } from '../../../types'; + import { ResourceLink, ResourceRow } from './types'; // from defined routes in app/kubernetes/__module.js diff --git a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/useHelmReleaseToCompare.ts b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/useHelmReleaseToCompare.ts index e15e189fa..814f03a6a 100644 --- a/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/useHelmReleaseToCompare.ts +++ b/app/react/kubernetes/helm/HelmApplicationView/ReleaseDetails/useHelmReleaseToCompare.ts @@ -1,7 +1,7 @@ import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; import { HelmRelease } from '../../types'; -import { useHelmRelease } from '../../helmReleaseQueries/useHelmRelease'; +import { useHelmRelease } from '../queries/useHelmRelease'; import { DiffViewMode } from './DiffControl'; diff --git a/app/react/kubernetes/helm/helmReleaseQueries/useHelmHistory.ts b/app/react/kubernetes/helm/HelmApplicationView/queries/useHelmHistory.ts similarity index 88% rename from app/react/kubernetes/helm/helmReleaseQueries/useHelmHistory.ts rename to app/react/kubernetes/helm/HelmApplicationView/queries/useHelmHistory.ts index 1f69a8a5b..41d6ab375 100644 --- a/app/react/kubernetes/helm/helmReleaseQueries/useHelmHistory.ts +++ b/app/react/kubernetes/helm/HelmApplicationView/queries/useHelmHistory.ts @@ -4,9 +4,7 @@ import { EnvironmentId } from '@/react/portainer/environments/types'; import { withGlobalError } from '@/react-tools/react-query'; import axios, { parseAxiosError } from '@/portainer/services/axios'; -import { HelmRelease } from '../types'; - -import { queryKeys } from './query-keys'; +import { HelmRelease } from '../../types'; export function useHelmHistory( environmentId: EnvironmentId, @@ -14,7 +12,7 @@ export function useHelmHistory( namespace: string ) { return useQuery( - queryKeys.releaseHistory(environmentId, namespace, name), + [environmentId, 'helm', 'releases', namespace, name, 'history'], () => getHelmHistory(environmentId, name, namespace), { enabled: !!environmentId && !!name && !!namespace, diff --git a/app/react/kubernetes/helm/helmReleaseQueries/useHelmRelease.ts b/app/react/kubernetes/helm/HelmApplicationView/queries/useHelmRelease.ts similarity index 91% rename from app/react/kubernetes/helm/helmReleaseQueries/useHelmRelease.ts rename to app/react/kubernetes/helm/HelmApplicationView/queries/useHelmRelease.ts index 4f377fb7a..cdf465c16 100644 --- a/app/react/kubernetes/helm/helmReleaseQueries/useHelmRelease.ts +++ b/app/react/kubernetes/helm/HelmApplicationView/queries/useHelmRelease.ts @@ -4,9 +4,7 @@ import { EnvironmentId } from '@/react/portainer/environments/types'; import { withGlobalError } from '@/react-tools/react-query'; import axios, { parseAxiosError } from '@/portainer/services/axios'; -import { HelmRelease } from '../types'; - -import { queryKeys } from './query-keys'; +import { HelmRelease } from '../../types'; type Options = { select?: (data: HelmRelease) => T; @@ -29,7 +27,15 @@ export function useHelmRelease( const { select, showResources, refetchInterval, revision, staleTime } = options; return useQuery( - queryKeys.release(environmentId, namespace, name, revision, showResources), + [ + environmentId, + 'helm', + 'releases', + namespace, + name, + revision, + showResources, + ], () => getHelmRelease(environmentId, name, { namespace, diff --git a/app/react/kubernetes/helm/helmReleaseQueries/useHelmRollbackMutation.ts b/app/react/kubernetes/helm/HelmApplicationView/queries/useHelmRollbackMutation.ts similarity index 88% rename from app/react/kubernetes/helm/helmReleaseQueries/useHelmRollbackMutation.ts rename to app/react/kubernetes/helm/HelmApplicationView/queries/useHelmRollbackMutation.ts index 81b1bff39..6aea3ad29 100644 --- a/app/react/kubernetes/helm/helmReleaseQueries/useHelmRollbackMutation.ts +++ b/app/react/kubernetes/helm/HelmApplicationView/queries/useHelmRollbackMutation.ts @@ -7,9 +7,7 @@ import { withGlobalError, } from '@/react-tools/react-query'; import axios from '@/portainer/services/axios'; -import { queryKeys as applicationsQueryKeys } from '@/react/kubernetes/applications/queries/query-keys'; - -import { queryKeys } from './query-keys'; +import { queryKeys } from '@/react/kubernetes/applications/queries/query-keys'; /** * Parameters for helm rollback operation @@ -56,8 +54,8 @@ export function useHelmRollbackMutation(environmentId: EnvironmentId) { rollbackRelease({ releaseName, params, environmentId }), ...withGlobalError('Unable to rollback Helm release'), ...withInvalidate(queryClient, [ - queryKeys.releases(environmentId), - applicationsQueryKeys.applications(environmentId), + [environmentId, 'helm', 'releases'], + queryKeys.applications(environmentId), ]), }); } diff --git a/app/react/kubernetes/helm/helmReleaseQueries/useUninstallHelmAppMutation.ts b/app/react/kubernetes/helm/HelmApplicationView/queries/useUninstallHelmAppMutation.ts similarity index 94% rename from app/react/kubernetes/helm/helmReleaseQueries/useUninstallHelmAppMutation.ts rename to app/react/kubernetes/helm/HelmApplicationView/queries/useUninstallHelmAppMutation.ts index 16341eb76..7daa5835c 100644 --- a/app/react/kubernetes/helm/helmReleaseQueries/useUninstallHelmAppMutation.ts +++ b/app/react/kubernetes/helm/HelmApplicationView/queries/useUninstallHelmAppMutation.ts @@ -5,8 +5,6 @@ import { withGlobalError, withInvalidate } from '@/react-tools/react-query'; import { queryKeys as applicationsQueryKeys } from '@/react/kubernetes/applications/queries/query-keys'; import { EnvironmentId } from '@/react/portainer/environments/types'; -import { queryKeys } from './query-keys'; - export function useUninstallHelmAppMutation(environmentId: EnvironmentId) { const queryClient = useQueryClient(); return useMutation({ @@ -18,7 +16,6 @@ export function useUninstallHelmAppMutation(environmentId: EnvironmentId) { namespace?: string; }) => uninstallHelmApplication(environmentId, releaseName, namespace), ...withInvalidate(queryClient, [ - queryKeys.releases(environmentId), applicationsQueryKeys.applications(environmentId), ]), ...withGlobalError('Unable to uninstall helm application'), diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.test.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.test.tsx index ca3aa4c3a..80d39eb3e 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.test.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.test.tsx @@ -36,15 +36,14 @@ vi.mock('@/portainer/services/notifications', () => ({ ), })); -vi.mock('../helmReleaseQueries/useUpdateHelmReleaseMutation', () => ({ +vi.mock('../queries/useUpdateHelmReleaseMutation', () => ({ useUpdateHelmReleaseMutation: vi.fn(() => ({ mutateAsync: vi.fn((...args) => mockMutate(...args)), isLoading: false, })), - updateHelmRelease: vi.fn(() => Promise.resolve({})), })); -vi.mock('../helmChartSourceQueries/useHelmRepoVersions', () => ({ +vi.mock('../queries/useHelmRepoVersions', () => ({ useHelmRepoVersions: vi.fn(() => ({ data: [ { Version: '1.0.0', AppVersion: '1.0.0' }, @@ -99,7 +98,6 @@ function renderComponent({ selectedChart={selectedChart} namespace={namespace} name={name} - isRepoAvailable /> )), user diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.tsx index 2bed5b58f..669dbd46c 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmInstallForm.tsx @@ -11,11 +11,7 @@ import { confirmGenericDiscard } from '@@/modals/confirm'; import { Option } from '@@/form-components/PortainerSelect'; import { Chart } from '../types'; -import { useUpdateHelmReleaseMutation } from '../helmReleaseQueries/useUpdateHelmReleaseMutation'; -import { - ChartVersion, - useHelmRepoVersions, -} from '../helmChartSourceQueries/useHelmRepoVersions'; +import { useUpdateHelmReleaseMutation } from '../queries/useUpdateHelmReleaseMutation'; import { HelmInstallInnerForm } from './HelmInstallInnerForm'; import { HelmInstallFormValues } from './types'; @@ -24,39 +20,22 @@ type Props = { selectedChart: Chart; namespace?: string; name?: string; - isRepoAvailable: boolean; }; -export function HelmInstallForm({ - selectedChart, - namespace, - name, - isRepoAvailable, -}: Props) { +export function HelmInstallForm({ selectedChart, namespace, name }: Props) { const environmentId = useEnvironmentId(); const router = useRouter(); const analytics = useAnalytics(); - const helmRepoVersionsQuery = useHelmRepoVersions( - selectedChart.name, - 60 * 60 * 1000, // 1 hour - [ - { - repo: selectedChart.repo, - }, - ] - ); - const versions = helmRepoVersionsQuery.data; - const versionOptions: Option[] = versions.map( + const versionOptions: Option[] = selectedChart.versions.map( (version, index) => ({ - label: index === 0 ? `${version.Version} (latest)` : version.Version, + label: index === 0 ? `${version} (latest)` : version, value: version, }) ); const defaultVersion = versionOptions[0]?.value; const initialValues: HelmInstallFormValues = { values: '', - version: defaultVersion?.Version ?? '', - repo: defaultVersion?.Repo ?? selectedChart.repo ?? '', + version: defaultVersion ?? '', }; const installHelmChartMutation = useUpdateHelmReleaseMutation(environmentId); @@ -76,8 +55,6 @@ export function HelmInstallForm({ namespace={namespace} name={name} versionOptions={versionOptions} - isVersionsLoading={helmRepoVersionsQuery.isInitialLoading} - isRepoAvailable={isRepoAvailable} /> ); diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmInstallInnerForm.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmInstallInnerForm.tsx index 77ba91ca1..9f85a0b48 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmInstallInnerForm.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmInstallInnerForm.tsx @@ -1,18 +1,14 @@ import { Form, useFormikContext } from 'formik'; -import { useMemo, useState } from 'react'; - -import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; +import { useMemo } from 'react'; +import { FormActions } from '@@/form-components/FormActions'; import { FormControl } from '@@/form-components/FormControl'; import { Option, PortainerSelect } from '@@/form-components/PortainerSelect'; import { FormSection } from '@@/form-components/FormSection'; -import { LoadingButton } from '@@/buttons'; import { Chart } from '../types'; -import { useHelmChartValues } from '../helmChartSourceQueries/useHelmChartValues'; +import { useHelmChartValues } from '../queries/useHelmChartValues'; import { HelmValuesInput } from '../components/HelmValuesInput'; -import { ChartVersion } from '../helmChartSourceQueries/useHelmRepoVersions'; -import { ManifestPreviewFormSection } from '../components/ManifestPreviewFormSection'; import { HelmInstallFormValues } from './types'; @@ -20,9 +16,7 @@ type Props = { selectedChart: Chart; namespace?: string; name?: string; - versionOptions: Option[]; - isVersionsLoading: boolean; - isRepoAvailable: boolean; + versionOptions: Option[]; }; export function HelmInstallInnerForm({ @@ -30,60 +24,21 @@ export function HelmInstallInnerForm({ namespace, name, versionOptions, - isVersionsLoading, - isRepoAvailable, }: Props) { - const environmentId = useEnvironmentId(); - const [previewIsValid, setPreviewIsValid] = useState(false); const { values, setFieldValue, isSubmitting } = useFormikContext(); - const selectedVersion: ChartVersion | undefined = useMemo( - () => - versionOptions.find( - (v) => - v.value.Version === values.version && - v.value.Repo === selectedChart.repo - )?.value ?? versionOptions[0]?.value, - [versionOptions, values.version, selectedChart.repo] - ); - - const repoParams = { + const chartValuesRefQuery = useHelmChartValues({ + chart: selectedChart.name, repo: selectedChart.repo, - }; - // use isLatestVersionFetched to cache the latest version, to avoid duplicate fetches - const isLatestVersionFetched = - // if no version is selected, the latest version gets fetched - !versionOptions.length || - // otherwise check if the selected version is the latest version - (selectedVersion?.Version === versionOptions[0]?.value.Version && - selectedVersion?.Repo === versionOptions[0]?.value.Repo); - const chartValuesRefQuery = useHelmChartValues( - { - chart: selectedChart.name, - version: values?.version, - ...repoParams, - }, - isLatestVersionFetched - ); + version: values?.version, + }); - const payload = useMemo( - () => ({ - name: name || '', - namespace: namespace || '', - chart: selectedChart.name, - version: values?.version, - repo: selectedChart.repo, - values: values.values, - }), - [ - name, - namespace, - selectedChart.name, - values?.version, - selectedChart.repo, - values.values, - ] + const selectedVersion = useMemo( + () => + versionOptions.find((v) => v.value === values.version)?.value ?? + versionOptions[0]?.value, + [versionOptions, values.version] ); return ( @@ -93,18 +48,14 @@ export function HelmInstallInnerForm({ - + value={selectedVersion} options={versionOptions} - noOptionsMessage={() => 'No versions found'} - placeholder="Select a version" onChange={(version) => { if (version) { - setFieldValue('version', version.Version); - setFieldValue('repo', version.Repo); + setFieldValue('version', version); } }} data-cy="helm-version-input" @@ -117,23 +68,15 @@ export function HelmInstallInnerForm({ isValuesRefLoading={chartValuesRefQuery.isInitialLoading} /> -
- - Install - + /> ); } diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmTemplates.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmTemplates.tsx index 5675ff5d7..ffd122cd2 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmTemplates.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmTemplates.tsx @@ -1,20 +1,15 @@ import { useState } from 'react'; +import { compact } from 'lodash'; import { useCurrentUser } from '@/react/hooks/useUser'; -import { FormSection } from '@@/form-components/FormSection'; - -import { useHelmHTTPChartList } from '../helmChartSourceQueries/useHelmChartList'; import { Chart } from '../types'; -import { - HelmRegistrySelect, - RepoValue, -} from '../components/HelmRegistrySelect'; -import { useHelmRepoOptions } from '../helmChartSourceQueries/useHelmRepositories'; +import { useHelmChartList } from '../queries/useHelmChartList'; +import { useHelmRegistries } from '../queries/useHelmRegistries'; -import { HelmInstallForm } from './HelmInstallForm'; -import { HelmTemplatesSelectedItem } from './HelmTemplatesSelectedItem'; import { HelmTemplatesList } from './HelmTemplatesList'; +import { HelmTemplatesSelectedItem } from './HelmTemplatesSelectedItem'; +import { HelmInstallForm } from './HelmInstallForm'; interface Props { onSelectHelmChart: (chartName: string) => void; @@ -24,60 +19,11 @@ interface Props { export function HelmTemplates({ onSelectHelmChart, namespace, name }: Props) { const [selectedChart, setSelectedChart] = useState(null); - const [selectedRepo, setSelectedRepo] = useState(null); + const [selectedRegistry, setSelectedRegistry] = useState(null); + const { user } = useCurrentUser(); - const chartListQuery = useHelmHTTPChartList( - user.Id, - selectedRepo?.repoUrl ?? '', - !!selectedRepo?.repoUrl - ); - const repoOptionsQuery = useHelmRepoOptions(); - const isRepoAvailable = - !!repoOptionsQuery.data && repoOptionsQuery.data.length > 0; - - return ( -
-
- - {selectedChart ? ( - <> - - - - ) : ( - <> - - {selectedRepo && ( - - )} - - )} - -
-
- ); - + const helmReposQuery = useHelmRegistries(); + const chartListQuery = useHelmChartList(user.Id, compact([selectedRegistry])); function clearHelmChart() { setSelectedChart(null); onSelectHelmChart(''); @@ -87,4 +33,33 @@ export function HelmTemplates({ onSelectHelmChart, namespace, name }: Props) { setSelectedChart(chart); onSelectHelmChart(chart.name); } + + return ( +
+
+ {selectedChart ? ( + <> + + + + ) : ( + + )} +
+
+ ); } diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.test.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.test.tsx index bfaa6e7e8..98b96e9a4 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.test.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.test.tsx @@ -46,63 +46,25 @@ const mockCharts: Chart[] = [ const selectActionMock = vi.fn(); -const mockUseEnvironmentId = vi.fn(() => 1); - -vi.mock('@/react/hooks/useEnvironmentId', () => ({ - useEnvironmentId: () => mockUseEnvironmentId(), -})); - -// Mock the helm registries query -vi.mock('../queries/useHelmRegistries', () => ({ - useHelmRegistries: vi.fn(() => ({ - data: ['https://example.com', 'https://example.com/2'], - isInitialLoading: false, - isError: false, - })), -})); - -// Mock the environment registries query -vi.mock( - '@/react/portainer/environments/queries/useEnvironmentRegistries', - () => ({ - useEnvironmentRegistries: vi.fn(() => ({ - data: [ - { Id: 1, URL: 'https://registry.example.com' }, - { Id: 2, URL: 'https://registry2.example.com' }, - ], - isInitialLoading: false, - isError: false, - })), - }) -); - function renderComponent({ loading = false, charts = mockCharts, selectAction = selectActionMock, - selectedRegistry = { - repoUrl: 'https://example.com', - name: 'Test Registry', - }, -}: { - loading?: boolean; - charts?: Chart[]; - selectAction?: (chart: Chart) => void; - selectedRegistry?: { - repoUrl?: string; - name?: string; - } | null; + selectedRegistry = '', } = {}) { const user = new UserViewModel({ Username: 'user' }); + const registries = ['https://example.com', 'https://example.com/2']; const Wrapped = withTestQueryProvider( withUserProvider( withTestRouter(() => ( {}} /> )), user @@ -119,10 +81,8 @@ describe('HelmTemplatesList', () => { it('should display title and charts list', async () => { renderComponent(); - // Check for the title with registry name - expect( - screen.getByText('Select a helm chart from Test Registry') - ).toBeInTheDocument(); + // Check for the title + expect(screen.getByText('Helm chart')).toBeInTheDocument(); // Check for charts expect(screen.getByText('test-chart-1')).toBeInTheDocument(); @@ -200,27 +160,21 @@ describe('HelmTemplatesList', () => { }); it('should show empty message when no charts are available and a registry is selected', async () => { - renderComponent({ - charts: [], - selectedRegistry: { - repoUrl: 'https://example.com', - name: 'Test Registry', - }, - }); + renderComponent({ charts: [], selectedRegistry: 'https://example.com' }); // Check for empty message expect( - screen.getByText('No helm charts available in this repository.') + screen.getByText('No helm charts available in this registry.') ).toBeInTheDocument(); }); it("should show 'select registry' message when no charts are available and no registry is selected", async () => { - renderComponent({ charts: [], selectedRegistry: null }); + renderComponent({ charts: [] }); // Check for message expect( screen.getByText( - 'Please select a repository to view available Helm charts.' + 'Please select a registry to view available Helm charts.' ) ).toBeInTheDocument(); }); diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.tsx index 3d9e86578..1b02bed1d 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesList.tsx @@ -1,47 +1,59 @@ import { useState, useMemo } from 'react'; +import { components, OptionProps } from 'react-select'; -import { PortainerSelect } from '@/react/components/form-components/PortainerSelect'; +import { + PortainerSelect, + Option, +} from '@/react/components/form-components/PortainerSelect'; +import { Link } from '@/react/components/Link'; +import { InsightsBox } from '@@/InsightsBox'; import { SearchBar } from '@@/datatables/SearchBar'; import { InlineLoader } from '@@/InlineLoader'; import { Chart } from '../types'; -import { RepoValue } from '../components/HelmRegistrySelect'; import { HelmTemplatesListItem } from './HelmTemplatesListItem'; interface Props { - isLoadingCharts: boolean; + isLoading: boolean; charts?: Chart[]; selectAction: (chart: Chart) => void; - selectedRegistry: RepoValue | null; + registries: string[]; + selectedRegistry: string | null; + setSelectedRegistry: (registry: string | null) => void; } export function HelmTemplatesList({ - isLoadingCharts, + isLoading, charts = [], selectAction, + registries, selectedRegistry, + setSelectedRegistry, }: Props) { const [textFilter, setTextFilter] = useState(''); const [selectedCategory, setSelectedCategory] = useState(null); const categories = useMemo(() => getCategories(charts), [charts]); + const registryOptions = useMemo( + () => + registries.map((registry) => ({ + label: registry, + value: registry, + })), + [registries] + ); const filteredCharts = useMemo( () => getFilteredCharts(charts, textFilter, selectedCategory), [charts, textFilter, selectedCategory] ); - const isSelectedRegistryEmpty = - !isLoadingCharts && charts.length === 0 && selectedRegistry; - return (
-
-
- Select a helm chart from {selectedRegistry?.name} -
+
+
Helm chart
-
+
+ +
+ +
+
+
+ Select the Helm chart to use. Bring further Helm charts into your + selection list via{' '} + + User settings - Helm repositories + + . +
+ + + At present Portainer does not support OCI format Helm charts. + Support for OCI charts will be available in a future release. +
+ If you would like to provide feedback on OCI support or get access + to early releases to test this functionality,{' '} + + please get in touch + + . + + } + /> +
{filteredCharts.map((chart) => ( @@ -77,7 +138,7 @@ export function HelmTemplatesList({
No Helm charts found
)} - {isLoadingCharts && ( + {isLoading && (
Loading helm charts... @@ -90,15 +151,15 @@ export function HelmTemplatesList({
)} - {isSelectedRegistryEmpty && ( + {!isLoading && charts.length === 0 && selectedRegistry && (
- No helm charts available in this repository. + No helm charts available in this registry.
)} {!selectedRegistry && (
- Please select a repository to view available Helm charts. + Please select a registry to view available Helm charts.
)}
@@ -106,6 +167,20 @@ export function HelmTemplatesList({ ); } +// truncate the registry text, because some registry names are urls, which are too long +function RegistryOption(props: OptionProps>) { + const { data: registry } = props; + + return ( +
+ {/* eslint-disable-next-line react/jsx-props-no-spreading */} + + {registry.value} + +
+ ); +} + /** * Get categories from charts * @param charts - The charts to get the categories from diff --git a/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesSelectedItem.tsx b/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesSelectedItem.tsx index cc85170e2..d6685f3c6 100644 --- a/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesSelectedItem.tsx +++ b/app/react/kubernetes/helm/HelmTemplates/HelmTemplatesSelectedItem.tsx @@ -26,7 +26,7 @@ export function HelmTemplatesSelectedItem({
diff --git a/app/react/kubernetes/helm/HelmTemplates/types.ts b/app/react/kubernetes/helm/HelmTemplates/types.ts index 61a8451c9..df0b09374 100644 --- a/app/react/kubernetes/helm/HelmTemplates/types.ts +++ b/app/react/kubernetes/helm/HelmTemplates/types.ts @@ -1,5 +1,4 @@ export type HelmInstallFormValues = { values: string; version: string; - repo: string; }; diff --git a/app/react/kubernetes/helm/components/HelmRegistrySelect.test.tsx b/app/react/kubernetes/helm/components/HelmRegistrySelect.test.tsx deleted file mode 100644 index 5934e75ba..000000000 --- a/app/react/kubernetes/helm/components/HelmRegistrySelect.test.tsx +++ /dev/null @@ -1,242 +0,0 @@ -import { render, screen } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { vi } from 'vitest'; - -import selectEvent from '@/react/test-utils/react-select'; -import { withTestQueryProvider } from '@/react/test-utils/withTestQuery'; -import { withUserProvider } from '@/react/test-utils/withUserProvider'; -import { withTestRouter } from '@/react/test-utils/withRouter'; -import { UserViewModel } from '@/portainer/models/user'; -import { RegistryTypes } from '@/react/portainer/registries/types/registry'; -import { useCurrentUser } from '@/react/hooks/useUser'; -import { User, Role } from '@/portainer/users/types'; - -import { HelmRegistrySelect, RepoValue } from './HelmRegistrySelect'; - -// Mock the hooks with factory functions - preserve other exports -vi.mock('@/react/hooks/useUser', async () => { - const actual = await vi.importActual('@/react/hooks/useUser'); - return { - ...actual, - useCurrentUser: vi.fn(), - }; -}); - -const mockOnRegistryChange = vi.fn(); - -const defaultProps = { - selectedRegistry: null, - onRegistryChange: mockOnRegistryChange, - isRepoAvailable: true, - isLoading: false, - isError: false, - repoOptions: [], -}; - -const mockRepoOptions = [ - { - value: { - repoUrl: 'https://charts.bitnami.com/bitnami', - name: 'Bitnami', - type: RegistryTypes.CUSTOM, - }, - label: 'Bitnami', - }, - { - value: { - repoUrl: 'https://kubernetes-charts.storage.googleapis.com', - name: 'Stable', - type: RegistryTypes.CUSTOM, - }, - label: 'Stable', - }, -]; - -interface MockUserHookReturn { - user: User; - isPureAdmin: boolean; -} - -interface UserProps { - isPureAdmin?: boolean; -} - -// Get the mocked functions -const mockUseCurrentUser = vi.mocked(useCurrentUser); - -function renderComponent(props = {}, userProps: UserProps = {}) { - const userResult: MockUserHookReturn = { - user: { - Id: 1, - Username: 'admin', - Role: Role.Admin, - EndpointAuthorizations: {}, - UseCache: false, - ThemeSettings: { - color: 'auto', - }, - }, - isPureAdmin: userProps.isPureAdmin || false, - }; - - mockUseCurrentUser.mockReturnValue(userResult); - - const Component = withTestQueryProvider( - withUserProvider( - withTestRouter(HelmRegistrySelect), - new UserViewModel({ Username: 'admin', Role: 1 }) - ) - ); - - return render(); -} - -describe('HelmRegistrySelect', () => { - beforeEach(() => { - vi.clearAllMocks(); - mockUseCurrentUser.mockClear(); - }); - - describe('Basic rendering', () => { - it('should render with default placeholder', () => { - renderComponent(); - expect(screen.getByText('Select a repository')).toBeInTheDocument(); - }); - - it('should render with custom placeholder', () => { - renderComponent({ placeholder: 'Custom placeholder' }); - expect(screen.getByText('Custom placeholder')).toBeInTheDocument(); - }); - - it('should render loading state', () => { - renderComponent({ isLoading: true }); - expect(screen.getByRole('combobox')).toBeInTheDocument(); - }); - - it('should render error state', () => { - renderComponent({ isError: true }); - expect( - screen.getByText('Unable to load registry options.') - ).toBeInTheDocument(); - }); - }); - - describe('Repository options', () => { - it('should display repository options', async () => { - const user = userEvent.setup(); - renderComponent({ repoOptions: mockRepoOptions }); - - const select = screen.getByRole('combobox'); - await user.click(select); - - expect(screen.getByText('Bitnami')).toBeInTheDocument(); - expect(screen.getByText('Stable')).toBeInTheDocument(); - }); - - it.skip('should call onRegistryChange when option is selected', async () => { - // Skipping this test due to react-select testing complexity - // The onChange functionality is covered by integration tests - renderComponent({ repoOptions: mockRepoOptions }); - - const select = screen.getByRole('combobox'); - await selectEvent.select(select, 'Bitnami'); - - expect(mockOnRegistryChange).toHaveBeenCalledWith({ - repoUrl: 'https://charts.bitnami.com/bitnami', - name: 'Bitnami', - type: RegistryTypes.CUSTOM, - }); - }); - - it('should show selected repository value', () => { - const selectedRegistry: RepoValue = { - repoUrl: 'https://charts.bitnami.com/bitnami', - name: 'Bitnami', - type: RegistryTypes.CUSTOM, - }; - - renderComponent({ - selectedRegistry, - repoOptions: mockRepoOptions, - }); - - // Since the component uses PortainerSelect which manages the display value, - // we verify the props are correctly passed by checking the select element exists - expect(screen.getByRole('combobox')).toBeInTheDocument(); - }); - }); - - describe('No repositories warning', () => { - it('should show no repositories warning when no repos are available', () => { - renderComponent({ - isRepoAvailable: false, - namespace: 'test-namespace', - }); - - expect( - screen.getByText(/There are no repositories available./) - ).toBeInTheDocument(); - }); - - it('should not show warning when loading', () => { - renderComponent({ - isRepoAvailable: false, - namespace: 'test-namespace', - isLoading: true, - }); - - expect( - screen.queryByText('There are no repositories available.') - ).not.toBeInTheDocument(); - }); - - it('should not show warning when no namespace is provided', () => { - renderComponent({ - isRepoAvailable: false, - }); - - expect( - screen.queryByText('There are no repositories available.') - ).not.toBeInTheDocument(); - }); - }); - - describe('Tooltip content', () => { - it('should render the component with label and tooltip', () => { - renderComponent({}, { isPureAdmin: true }); - - // Verify that the component renders the main label - expect(screen.getByText('Helm chart source')).toBeInTheDocument(); - - expect(screen.getByRole('combobox')).toBeInTheDocument(); - }); - }); - - describe('Loading and error states', () => { - it('should not show no repos warning when loading', () => { - renderComponent({ - isLoading: true, - isRepoAvailable: false, - repoOptions: [], - namespace: 'test-namespace', - }); - - expect( - screen.queryByText('There are no repositories available.') - ).not.toBeInTheDocument(); - }); - - it('should show error when API fails', () => { - renderComponent({ - isLoading: false, - isError: true, - isRepoAvailable: false, - namespace: 'test-namespace', - }); - - expect( - screen.getByText('Unable to load registry options.') - ).toBeInTheDocument(); - }); - }); -}); diff --git a/app/react/kubernetes/helm/components/HelmRegistrySelect.tsx b/app/react/kubernetes/helm/components/HelmRegistrySelect.tsx deleted file mode 100644 index 55569f900..000000000 --- a/app/react/kubernetes/helm/components/HelmRegistrySelect.tsx +++ /dev/null @@ -1,156 +0,0 @@ -import { GroupBase } from 'react-select'; - -import { - PortainerSelect, - Option, -} from '@/react/components/form-components/PortainerSelect'; -import { useCurrentUser } from '@/react/hooks/useUser'; -import { RegistryTypes } from '@/react/portainer/registries/types/registry'; - -import { FormControl } from '@@/form-components/FormControl'; -import { Alert } from '@@/Alert'; -import { Link } from '@@/Link'; -import { TextTip } from '@@/Tip/TextTip'; - -export type RepoValue = { - repoUrl?: string; // set for traditional https helm repos - name?: string; - type?: RegistryTypes; -}; - -interface Props { - selectedRegistry: RepoValue | null; - onRegistryChange: (registry: RepoValue | null) => void; - namespace?: string; - placeholder?: string; - 'data-cy'?: string; - isRepoAvailable: boolean; - isLoading: boolean; - isError: boolean; - repoOptions: GroupBase>[]; -} - -export function HelmRegistrySelect({ - selectedRegistry, - onRegistryChange, - namespace, - placeholder = 'Select a repository', - 'data-cy': dataCy = 'helm-registry-select', - isRepoAvailable, - isLoading, - isError, - repoOptions, -}: Props) { - const { isPureAdmin } = useCurrentUser(); - - return ( - } - > - - placeholder={placeholder} - value={selectedRegistry ?? {}} - options={repoOptions} - isLoading={isLoading} - onChange={onRegistryChange} - isClearable - bindToBody - data-cy={dataCy} - /> - - {isError && Unable to load registry options.} - - ); -} - -function HelmChartSourceTooltip({ isPureAdmin }: { isPureAdmin: boolean }) { - if (isPureAdmin) { - return ( - <> - -
- - - ); - } - - // Non-admin - return ; -} - -function NoReposWarning({ - hasNoRepos, - isLoading, - namespace, - isPureAdmin, -}: { - hasNoRepos: boolean; - isLoading: boolean; - namespace?: string; - isPureAdmin: boolean; -}) { - if (!hasNoRepos || isLoading || !namespace) { - return null; - } - - return ( - - There are no repositories available. - - - ); -} - -function CreateRepoMessage({ isPureAdmin }: { isPureAdmin: boolean }) { - if (isPureAdmin) { - return ( - <> - -
- - - ); - } - - // Non-admin - return ; -} - -function CreateUserRepoMessage() { - return ( - <> - You can define repositories in the{' '} - - User settings - Helm repositories - - . - - ); -} - -function CreateGlobalRepoMessage() { - return ( - <> - You can also define repositories in the{' '} - - Portainer settings - - . - - ); -} diff --git a/app/react/kubernetes/helm/components/ManifestPreviewFormSection.test.tsx b/app/react/kubernetes/helm/components/ManifestPreviewFormSection.test.tsx deleted file mode 100644 index 6ca6f2841..000000000 --- a/app/react/kubernetes/helm/components/ManifestPreviewFormSection.test.tsx +++ /dev/null @@ -1,197 +0,0 @@ -import { render, screen } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { vi } from 'vitest'; - -import { withTestQueryProvider } from '@/react/test-utils/withTestQuery'; -import { withUserProvider } from '@/react/test-utils/withUserProvider'; -import { withTestRouter } from '@/react/test-utils/withRouter'; -import { UserViewModel } from '@/portainer/models/user'; - -import { ManifestPreviewFormSection } from './ManifestPreviewFormSection'; - -// Mock the necessary hooks -const mockUseHelmDryRun = vi.fn(); -const mockUseDebouncedValue = vi.fn(); - -vi.mock('../helmReleaseQueries/useHelmDryRun', () => ({ - useHelmDryRun: (...args: unknown[]) => mockUseHelmDryRun(...args), -})); - -vi.mock('@/react/hooks/useDebouncedValue', () => ({ - useDebouncedValue: (value: unknown, delay: number) => - mockUseDebouncedValue(value, delay), -})); - -// Mock the CodeEditor and DiffViewer components -vi.mock('@@/CodeEditor', () => ({ - CodeEditor: ({ - 'data-cy': dataCy, - value, - }: { - 'data-cy'?: string; - value: string; - }) => ( -
- {value} -
- ), -})); - -vi.mock('@@/CodeEditor/DiffViewer', () => ({ - DiffViewer: ({ - 'data-cy': dataCy, - originalCode, - newCode, - }: { - 'data-cy'?: string; - originalCode: string; - newCode: string; - }) => ( -
-
{originalCode}
-
{newCode}
-
- ), -})); - -const mockOnChangePreviewValidation = vi.fn(); - -const defaultProps = { - payload: { - name: 'test-release', - namespace: 'test-namespace', - chart: 'test-chart', - version: '1.0.0', - repo: 'test-repo', - }, - onChangePreviewValidation: mockOnChangePreviewValidation, - title: 'Manifest Preview', - environmentId: 1, -}; - -function renderComponent(props = {}) { - const user = new UserViewModel({ Username: 'user', Role: 1 }); - - const Component = withTestQueryProvider( - withUserProvider( - withTestRouter(() => ( - - )), - user - ) - ); - - return render(); -} - -describe('ManifestPreviewFormSection', () => { - beforeEach(() => { - vi.clearAllMocks(); - // Default mock for useDebouncedValue - returns the value as-is - mockUseDebouncedValue.mockImplementation((value) => value); - }); - - it('should show loading and no form section when loading', () => { - mockUseHelmDryRun.mockReturnValue({ - isInitialLoading: true, - isError: false, - data: undefined, - }); - - renderComponent(); - - expect( - screen.getByText('Generating manifest preview...') - ).toBeInTheDocument(); - expect(screen.queryByText('Manifest Preview')).not.toBeInTheDocument(); - }); - - it('should show error and no form section when error', () => { - mockUseHelmDryRun.mockReturnValue({ - isInitialLoading: false, - isError: true, - error: { message: 'Invalid chart configuration' }, - data: undefined, - }); - - renderComponent(); - - expect( - screen.getByText('Error with Helm chart configuration') - ).toBeInTheDocument(); - expect(screen.getByText('Invalid chart configuration')).toBeInTheDocument(); - expect(screen.queryByText('Manifest Preview')).not.toBeInTheDocument(); - }); - - it('should show single code editor when only the generated manifest is available', async () => { - const mockManifest = 'apiVersion: v1\nkind: Pod\nmetadata:\n name: test'; - - mockUseHelmDryRun.mockReturnValue({ - isInitialLoading: false, - isError: false, - data: { manifest: mockManifest }, - }); - - renderComponent(); - - expect(screen.getByText('Manifest Preview')).toBeInTheDocument(); - - // Expand the FormSection to see the content - const expandButton = screen.getByLabelText('Expand'); - await userEvent.click(expandButton); - - // Check that the manifest content is rendered (from the HTML, we can see it's there) - expect( - screen.getByText(/apiVersion/, { exact: false }) - ).toBeInTheDocument(); - expect(screen.getByText(/test/, { exact: false })).toBeInTheDocument(); - }); - - it('should show the diff when the current and generated manifest are available', async () => { - const currentManifest = 'apiVersion: v1\nkind: Pod\nmetadata:\n name: old'; - const newManifest = 'apiVersion: v1\nkind: Pod\nmetadata:\n name: new'; - - mockUseHelmDryRun.mockReturnValue({ - isInitialLoading: false, - isError: false, - data: { manifest: newManifest }, - }); - - renderComponent({ currentManifest }); - - expect(screen.getByText('Manifest Preview')).toBeInTheDocument(); - - // Expand the FormSection to see the content - const expandButton = screen.getByLabelText('Expand'); - await userEvent.click(expandButton); - - // Check that both old and new manifest content is rendered - expect(screen.getByText(/old/, { exact: false })).toBeInTheDocument(); - expect(screen.getByText(/new/, { exact: false })).toBeInTheDocument(); - }); - - it('should call onChangePreviewValidation with correct validation state', () => { - mockUseHelmDryRun.mockReturnValue({ - isInitialLoading: false, - isError: false, - data: { manifest: 'test' }, - }); - - renderComponent(); - - expect(mockOnChangePreviewValidation).toHaveBeenCalledWith(true); - }); - - it('should call onChangePreviewValidation with false when error occurs', () => { - mockUseHelmDryRun.mockReturnValue({ - isInitialLoading: false, - isError: true, - error: { message: 'Error' }, - data: undefined, - }); - - renderComponent(); - - expect(mockOnChangePreviewValidation).toHaveBeenCalledWith(false); - }); -}); diff --git a/app/react/kubernetes/helm/components/ManifestPreviewFormSection.tsx b/app/react/kubernetes/helm/components/ManifestPreviewFormSection.tsx deleted file mode 100644 index fa651fe1a..000000000 --- a/app/react/kubernetes/helm/components/ManifestPreviewFormSection.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { useEffect, useState } from 'react'; - -import { useDebouncedValue } from '@/react/hooks/useDebouncedValue'; -import { EnvironmentId } from '@/react/portainer/environments/types'; - -import { FormSection } from '@@/form-components/FormSection'; -import { CodeEditor } from '@@/CodeEditor'; -import { DiffViewer } from '@@/CodeEditor/DiffViewer'; -import { InlineLoader } from '@@/InlineLoader'; -import { Alert } from '@@/Alert'; -import { TextTip } from '@@/Tip/TextTip'; - -import { useHelmDryRun } from '../helmReleaseQueries/useHelmDryRun'; -import { UpdateHelmReleasePayload } from '../types'; - -type Props = { - payload: UpdateHelmReleasePayload; - onChangePreviewValidation: (isValid: boolean) => void; - currentManifest?: string; // only true on upgrade, not install - title: string; - environmentId: EnvironmentId; -}; - -export function ManifestPreviewFormSection({ - payload, - currentManifest, - onChangePreviewValidation, - title, - environmentId, -}: Props) { - const debouncedPayload = useDebouncedValue(payload, 500); - const manifestPreviewQuery = useHelmDryRun(environmentId, debouncedPayload); - const [isFolded, setIsFolded] = useState(true); - - useEffect(() => { - onChangePreviewValidation(!manifestPreviewQuery.isError); - }, [manifestPreviewQuery.isError, onChangePreviewValidation]); - - if ( - !debouncedPayload.name || - !debouncedPayload.namespace || - !debouncedPayload.chart - ) { - return null; - } - - // only show loading state or the error to keep the view simple (omitting the preview section because there is nothing to preview) - if (manifestPreviewQuery.isInitialLoading) { - return Generating manifest preview...; - } - - if (manifestPreviewQuery.isError) { - return ( - - {manifestPreviewQuery.error?.message || - 'Error generating manifest preview'} - - ); - } - - return ( - - - - ); -} - -function ManifestPreview({ - currentManifest, - newManifest, -}: { - currentManifest?: string; - newManifest: string; -}) { - if (!newManifest) { - return No manifest preview available; - } - - if (currentManifest) { - return ( - - ); - } - - return ( - - ); -} diff --git a/app/react/kubernetes/helm/helmChartSourceQueries/query-keys.ts b/app/react/kubernetes/helm/helmChartSourceQueries/query-keys.ts deleted file mode 100644 index d9b75313c..000000000 --- a/app/react/kubernetes/helm/helmChartSourceQueries/query-keys.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { EnvironmentId } from '@/react/portainer/environments/types'; -import { UserId } from '@/portainer/users/types'; - -export const queryKeys = { - // Environment-scoped Helm queries (following kubernetes pattern) - base: (environmentId: EnvironmentId) => - ['environments', environmentId, 'kubernetes', 'helm'] as const, - - // User's helm repositories/registries - registries: (userId: UserId) => ['helm', 'registries', userId] as const, - - // Chart repository searches (global, not environment-specific) - repositories: (chart: string, repo?: string, useCache?: boolean) => - ['helm', 'repositories', chart, repo, useCache] as const, - - // Chart listings from repositories (user-specific) - charts: (userId: UserId, repository: string) => - ['helm', 'charts', userId, repository] as const, - - // Chart values (global, cached by chart/version) - chartValues: (repo: string, chart: string, version: string | 'latest') => - ['helm', 'chart-values', repo, chart, version] as const, - - chartVersions: ( - sourceId: number | string, - chart: string, - useCache?: boolean - ) => ['helm', 'registries', sourceId, chart, 'versions', useCache] as const, -}; diff --git a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmChartList.ts b/app/react/kubernetes/helm/helmChartSourceQueries/useHelmChartList.ts deleted file mode 100644 index 5d15d8945..000000000 --- a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmChartList.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { compact } from 'lodash'; -import { useQuery } from '@tanstack/react-query'; - -import axios from '@/portainer/services/axios'; -import { withGlobalError } from '@/react-tools/react-query'; - -import { Chart, HelmChartsResponse } from '../types'; - -import { queryKeys } from './query-keys'; - -/** - * React hook to fetch helm charts from the provided HTTP repository. - * Charts are loaded from the specified repository URL. - * - * @param userId User ID - * @param repository Repository URL to fetch charts from - * @param enabled Flag indicating if the query should be enabled - * @returns Query result containing helm charts - */ -export function useHelmHTTPChartList( - userId: number, - repository: string, - enabled: boolean -) { - return useQuery({ - queryKey: queryKeys.charts(userId, repository), - queryFn: () => getChartsFromRepo(repository), - enabled: !!userId && !!repository && enabled, - // one request takes a long time, so fail early to get feedback to the user faster - retry: false, - ...withGlobalError(`Unable to retrieve Helm charts from ${repository}`), - cacheTime: 1000 * 60 * 60 * 8, // 8 hours so that the chart list populates faster (keep stale time the same to always revalidate) - }); -} - -async function getChartsFromRepo(repo: string): Promise { - try { - // Construct the URL with required repo parameter - const response = await axios.get('templates/helm', { - params: { repo }, - }); - - return compact( - Object.values(response.data.entries).map((versions) => - versions[0] - ? { - ...versions[0], - repo, - // versions are within this response too, so we don't need a new query to fetch versions when this is used - versions: versions.map((v) => v.version), - } - : null - ) - ); - } catch (error) { - // Ignore errors from chart repositories as some may error but others may not - return []; - } -} diff --git a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmRepositories.ts b/app/react/kubernetes/helm/helmChartSourceQueries/useHelmRepositories.ts deleted file mode 100644 index e382164cb..000000000 --- a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmRepositories.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { compact } from 'lodash'; - -import axios, { parseAxiosError } from '@/portainer/services/axios'; -import { UserId } from '@/portainer/users/types'; -import { withGlobalError } from '@/react-tools/react-query'; -import { useCurrentUser } from '@/react/hooks/useUser'; -import { Option } from '@/react/components/form-components/PortainerSelect'; - -import { HelmRegistriesResponse } from '../types'; -import { RepoValue } from '../components/HelmRegistrySelect'; - -import { queryKeys } from './query-keys'; - -/** - * Hook to fetch all Helm registries for the current user - */ -export function useUserHelmRepositories({ - select, -}: { - select?: (registries: HelmRegistriesResponse) => T; -} = {}) { - const { user } = useCurrentUser(); - return useQuery( - queryKeys.registries(user.Id), - async () => getUserHelmRepositories(user.Id), - { - enabled: !!user.Id, - select, - ...withGlobalError('Unable to retrieve helm registries'), - } - ); -} - -export function useHelmRepoOptions() { - return useUserHelmRepositories({ - select: (registries) => { - const registryArray = flattenHelmRegistries(registries); - const repoOptions = registryArray - .map>((registry) => ({ - label: registry, - value: { - repoUrl: registry, - isOCI: false, - name: registry, - }, - })) - .sort((a, b) => a.label.localeCompare(b.label)); - return [ - { - label: 'Helm Repositories', - options: repoOptions, - }, - { - label: 'OCI Registries', - options: [ - { - label: - 'Installing from an OCI registry is a Portainer Business Feature', - value: {}, - disabled: true, - }, - ], - }, - ]; - }, - }); -} - -/** - * Get Helm repositories for user - */ -async function getUserHelmRepositories(userId: UserId) { - try { - const { data } = await axios.get( - `users/${userId}/helm/repositories` - ); - return data; - } catch (err) { - throw parseAxiosError(err, 'Unable to retrieve helm repositories for user'); - } -} - -/** get the unique global and user registries in one array */ -export function flattenHelmRegistries(registries: HelmRegistriesResponse) { - // compact will remove the global repository if it's empty - const repos = compact([ - registries.GlobalRepository.toLowerCase(), - ...registries.UserRepositories.map((repo) => repo.URL.toLowerCase()), - ]); - return [...new Set(repos)]; -} diff --git a/app/react/kubernetes/helm/helmReleaseQueries/query-keys.ts b/app/react/kubernetes/helm/helmReleaseQueries/query-keys.ts deleted file mode 100644 index c12ad5c96..000000000 --- a/app/react/kubernetes/helm/helmReleaseQueries/query-keys.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { EnvironmentId } from '@/react/portainer/environments/types'; -import { environmentQueryKeys } from '@/react/portainer/environments/queries/query-keys'; - -import { UpdateHelmReleasePayload } from '../types'; - -export const queryKeys = { - // Environment-scoped Helm queries (following kubernetes pattern) - base: (environmentId: EnvironmentId) => - [ - ...environmentQueryKeys.item(environmentId), - 'kubernetes', - 'helm', - ] as const, - - // Helm releases (environment-specific) - releases: (environmentId: EnvironmentId) => - [...queryKeys.base(environmentId), 'releases'] as const, - - release: ( - environmentId: EnvironmentId, - namespace: string, - name: string, - revision?: number, - showResources?: boolean - ) => - [ - ...queryKeys.releases(environmentId), - namespace, - name, - revision, - showResources, - ] as const, - - releaseHistory: ( - environmentId: EnvironmentId, - namespace: string, - name: string - ) => - [...queryKeys.release(environmentId, namespace, name), 'history'] as const, - - // Environment-specific install operations - installDryRun: ( - environmentId: EnvironmentId, - payload: UpdateHelmReleasePayload - ) => - [...queryKeys.base(environmentId), 'install', 'dry-run', payload] as const, -}; diff --git a/app/react/kubernetes/helm/helmReleaseQueries/useHelmDryRun.ts b/app/react/kubernetes/helm/helmReleaseQueries/useHelmDryRun.ts deleted file mode 100644 index f36c4204d..000000000 --- a/app/react/kubernetes/helm/helmReleaseQueries/useHelmDryRun.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { useQuery, UseQueryResult } from '@tanstack/react-query'; - -import { EnvironmentId } from '@/react/portainer/environments/types'; -import PortainerError from '@/portainer/error'; - -import { HelmRelease, UpdateHelmReleasePayload } from '../types'; - -import { updateHelmRelease } from './useUpdateHelmReleaseMutation'; -import { queryKeys } from './query-keys'; - -export function useHelmDryRun( - environmentId: EnvironmentId, - payload: UpdateHelmReleasePayload -): UseQueryResult { - return useQuery({ - queryKey: queryKeys.installDryRun(environmentId, payload), - queryFn: () => - // use updateHelmRelease as if it were a get request with dryRun. The payload is debounced to prevent too many requests. - updateHelmRelease( - environmentId, - payload, - { dryRun: true }, - { - errorMessage: 'Unable to get Helm manifest preview', - } - ), - // don't display error toast, handle it within the component - enabled: - !!payload.repo && - !!payload.chart && - !!payload.name && - !!payload.namespace && - !!payload.version, - retry: false, - refetchOnWindowFocus: false, - staleTime: 1000 * 60, // small 1 minute stale time to reduce the number of requests - }); -} diff --git a/app/react/kubernetes/helm/queries/useHelmChartList.ts b/app/react/kubernetes/helm/queries/useHelmChartList.ts new file mode 100644 index 000000000..5824236bc --- /dev/null +++ b/app/react/kubernetes/helm/queries/useHelmChartList.ts @@ -0,0 +1,75 @@ +import { useQueries } from '@tanstack/react-query'; +import { compact, flatMap } from 'lodash'; +import { useMemo } from 'react'; + +import axios from '@/portainer/services/axios'; +import { withGlobalError } from '@/react-tools/react-query'; + +import { Chart, HelmChartsResponse } from '../types'; + +/** + * React hook to fetch helm charts from the provided repositories + * Charts from each repository are loaded independently, allowing the UI + * to show charts as they become available instead of waiting for all + * repositories to load + * + * @param userId User ID + * @param repositories List of repository URLs to fetch charts from + */ +export function useHelmChartList(userId: number, repositories: string[] = []) { + // Fetch charts from each repository in parallel as separate queries + const chartQueries = useQueries({ + queries: useMemo( + () => + repositories.map((repo) => ({ + queryKey: [userId, repo, 'helm-charts'], + queryFn: () => getChartsFromRepo(repo), + enabled: !!userId && repositories.length > 0, + // one request takes a long time, so fail early to get feedback to the user faster + retries: false, + ...withGlobalError(`Unable to retrieve Helm charts from ${repo}`), + })), + [repositories, userId] + ), + }); + + // Combine the results for easier consumption by components + const allCharts = useMemo( + () => flatMap(compact(chartQueries.map((q) => q.data))), + [chartQueries] + ); + + return { + // Data from all repositories that have loaded so far + data: allCharts, + // Overall loading state + isInitialLoading: chartQueries.some((q) => q.isInitialLoading), + // Overall error state + isError: chartQueries.some((q) => q.isError), + }; +} + +async function getChartsFromRepo(repo: string): Promise { + try { + // Construct the URL with required repo parameter + const response = await axios.get('templates/helm', { + params: { repo }, + }); + + return compact( + Object.values(response.data.entries).map((versions) => + versions[0] + ? { + ...versions[0], + repo, + // versions are within this response too, so we don't need a new query to fetch versions when this is used + versions: versions.map((v) => v.version), + } + : null + ) + ); + } catch (error) { + // Ignore errors from chart repositories as some may error but others may not + return []; + } +} diff --git a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmChartValues.ts b/app/react/kubernetes/helm/queries/useHelmChartValues.ts similarity index 51% rename from app/react/kubernetes/helm/helmChartSourceQueries/useHelmChartValues.ts rename to app/react/kubernetes/helm/queries/useHelmChartValues.ts index 04fa071f6..2c1a95995 100644 --- a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmChartValues.ts +++ b/app/react/kubernetes/helm/queries/useHelmChartValues.ts @@ -3,37 +3,12 @@ import { useQuery } from '@tanstack/react-query'; import axios, { parseAxiosError } from '@/portainer/services/axios'; import { withGlobalError } from '@/react-tools/react-query'; -import { queryKeys } from './query-keys'; - type Params = { - /** The name of the chart to get the values for */ chart: string; - /** The repository URL or registry ID */ repo: string; - /** The version of the chart to get the values for */ version?: string; }; -export function useHelmChartValues(params: Params, isLatestVersion = false) { - const hasValidRepoUrl = !!params.repo; - return useQuery({ - queryKey: queryKeys.chartValues( - params.repo, - params.chart, - // if the latest version is fetched, use the latest version key to cache the latest version - isLatestVersion ? 'latest' : params.version || 'latest' - ), - queryFn: () => getHelmChartValues(params), - enabled: !!params.chart && hasValidRepoUrl, - select: (data) => ({ - values: data, - }), - retry: 1, - staleTime: 60 * 1000 * 20, // 60 minutes, because values are not expected to change often - ...withGlobalError('Unable to get Helm chart values'), - }); -} - async function getHelmChartValues(params: Params) { try { const response = await axios.get(`/templates/helm/values`, { @@ -41,6 +16,19 @@ async function getHelmChartValues(params: Params) { }); return response.data; } catch (err) { - throw parseAxiosError(err, 'Unable to get Helm chart values'); + throw parseAxiosError(err as Error, 'Unable to get Helm chart values'); } } + +export function useHelmChartValues(params: Params) { + return useQuery({ + queryKey: ['helm-chart-values', params.repo, params.chart, params.version], + queryFn: () => getHelmChartValues(params), + enabled: !!params.chart && !!params.repo, + select: (data) => ({ + values: data, + }), + staleTime: 60 * 1000 * 20, // 60 minutes, because values are not expected to change often + ...withGlobalError('Unable to get Helm chart values'), + }); +} diff --git a/app/react/kubernetes/helm/queries/useHelmRegistries.ts b/app/react/kubernetes/helm/queries/useHelmRegistries.ts new file mode 100644 index 000000000..f48fb72fa --- /dev/null +++ b/app/react/kubernetes/helm/queries/useHelmRegistries.ts @@ -0,0 +1,43 @@ +import { useQuery } from '@tanstack/react-query'; +import { compact } from 'lodash'; + +import axios, { parseAxiosError } from '@/portainer/services/axios'; +import { UserId } from '@/portainer/users/types'; +import { withGlobalError } from '@/react-tools/react-query'; +import { useCurrentUser } from '@/react/hooks/useUser'; + +import { HelmRegistriesResponse } from '../types'; + +/** + * Hook to fetch all Helm registries for the current user + */ +export function useHelmRegistries() { + const { user } = useCurrentUser(); + return useQuery( + ['helm', 'registries'], + async () => getHelmRegistries(user.Id), + { + enabled: !!user.Id, + ...withGlobalError('Unable to retrieve helm registries'), + } + ); +} + +/** + * Get Helm registries for user + */ +async function getHelmRegistries(userId: UserId) { + try { + const { data } = await axios.get( + `users/${userId}/helm/repositories` + ); + const repos = compact([ + // compact will remove the global repository if it's empty + data.GlobalRepository.toLowerCase(), + ...data.UserRepositories.map((repo) => repo.URL.toLowerCase()), + ]); + return [...new Set(repos)]; + } catch (err) { + throw parseAxiosError(err, 'Unable to retrieve helm repositories for user'); + } +} diff --git a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmRepoVersions.ts b/app/react/kubernetes/helm/queries/useHelmRepoVersions.ts similarity index 67% rename from app/react/kubernetes/helm/helmChartSourceQueries/useHelmRepoVersions.ts rename to app/react/kubernetes/helm/queries/useHelmRepoVersions.ts index 6245243cd..006b74599 100644 --- a/app/react/kubernetes/helm/helmChartSourceQueries/useHelmRepoVersions.ts +++ b/app/react/kubernetes/helm/queries/useHelmRepoVersions.ts @@ -5,28 +5,19 @@ import { compact, flatMap } from 'lodash'; import { withGlobalError } from '@/react-tools/react-query'; import axios, { parseAxiosError } from '@/portainer/services/axios'; -import { queryKeys } from './query-keys'; - interface HelmSearch { entries: Entries; } interface Entries { - [key: string]: { version: string; appVersion: string }[]; + [key: string]: { version: string }[]; } export interface ChartVersion { - Chart?: string; Repo: string; - Label?: string; Version: string; - AppVersion?: string; } -type RepoSource = { - repo?: string; -}; - /** * React hook to get a list of available versions for a chart from specified repositories * @@ -38,21 +29,21 @@ type RepoSource = { export function useHelmRepoVersions( chart: string, staleTime: number, - repoSources: RepoSource[] = [], + repositories: string[] = [], useCache: boolean = true ) { // Fetch versions from each repository in parallel as separate queries const versionQueries = useQueries({ queries: useMemo( () => - repoSources.map(({ repo }) => ({ - queryKey: queryKeys.chartVersions(repo || '', chart), - queryFn: () => getSearchHelmRepo({ repo, chart, useCache }), - enabled: !!chart && !!repo, + repositories.map((repo) => ({ + queryKey: ['helm', 'repositories', chart, repo, useCache], + queryFn: () => getSearchHelmRepo(repo, chart, useCache), + enabled: !!chart && repositories.length > 0, staleTime, ...withGlobalError(`Unable to retrieve versions from ${repo}`), })), - [repoSources, chart, staleTime, useCache] + [repositories, chart, staleTime, useCache] ), }); @@ -64,37 +55,30 @@ export function useHelmRepoVersions( return { data: allVersions, - isInitialLoading: versionQueries.some((q) => q.isInitialLoading), + isInitialLoading: versionQueries.some((q) => q.isLoading), isError: versionQueries.some((q) => q.isError), isFetching: versionQueries.some((q) => q.isFetching), refetch: () => Promise.all(versionQueries.map((q) => q.refetch())), }; } -type SearchRepoParams = { - repo?: string; - chart: string; - useCache?: boolean; -}; - /** * Get Helm repositories for user */ async function getSearchHelmRepo( - params: SearchRepoParams + repo: string, + chart: string, + useCache: boolean = true ): Promise { try { const { data } = await axios.get(`templates/helm`, { - params, + params: { repo, chart, useCache }, }); - // if separated by '/', take the last part - const chartKey = params.chart.split('/').pop() || params.chart; - const versions = data.entries[chartKey]; + const versions = data.entries[chart]; return ( versions?.map((v) => ({ - Repo: params.repo ?? '', + Repo: repo, Version: v.version, - AppVersion: v.appVersion, })) ?? [] ); } catch (err) { diff --git a/app/react/kubernetes/helm/helmReleaseQueries/useUpdateHelmReleaseMutation.ts b/app/react/kubernetes/helm/queries/useUpdateHelmReleaseMutation.ts similarity index 63% rename from app/react/kubernetes/helm/helmReleaseQueries/useUpdateHelmReleaseMutation.ts rename to app/react/kubernetes/helm/queries/useUpdateHelmReleaseMutation.ts index 689ebac3a..f2278ae58 100644 --- a/app/react/kubernetes/helm/helmReleaseQueries/useUpdateHelmReleaseMutation.ts +++ b/app/react/kubernetes/helm/queries/useUpdateHelmReleaseMutation.ts @@ -7,48 +7,30 @@ import { EnvironmentId } from '@/react/portainer/environments/types'; import { HelmRelease, UpdateHelmReleasePayload } from '../types'; -import { queryKeys } from './query-keys'; - export function useUpdateHelmReleaseMutation(environmentId: EnvironmentId) { const queryClient = useQueryClient(); return useMutation({ mutationFn: (payload: UpdateHelmReleasePayload) => updateHelmRelease(environmentId, payload), ...withInvalidate(queryClient, [ - queryKeys.releases(environmentId), + [environmentId, 'helm', 'releases'], applicationsQueryKeys.applications(environmentId), ]), - ...withGlobalError('Unable to update Helm release'), + ...withGlobalError('Unable to uninstall helm application'), }); } -type UpdateHelmReleaseParams = { - dryRun?: boolean; -}; - -type UpdateHelmReleaseOptions = { - errorMessage?: string; -}; - -export async function updateHelmRelease( +async function updateHelmRelease( environmentId: EnvironmentId, - payload: UpdateHelmReleasePayload, - params: UpdateHelmReleaseParams = {}, - options: UpdateHelmReleaseOptions = {} + payload: UpdateHelmReleasePayload ) { try { const { data } = await axios.post( `endpoints/${environmentId}/kubernetes/helm`, - payload, - { - params, - } + payload ); return data; } catch (err) { - throw parseAxiosError( - err, - options.errorMessage ?? 'Unable to update helm release' - ); + throw parseAxiosError(err, 'Unable to update helm release'); } } diff --git a/app/react/kubernetes/helm/types.ts b/app/react/kubernetes/helm/types.ts index 208745944..3094f84b2 100644 --- a/app/react/kubernetes/helm/types.ts +++ b/app/react/kubernetes/helm/types.ts @@ -91,7 +91,7 @@ export interface HelmChartResponse { versions: string[]; } -export interface HelmRegistryResponse { +export interface HelmRepositoryResponse { Id: number; UserId: number; URL: string; @@ -99,7 +99,7 @@ export interface HelmRegistryResponse { export interface HelmRegistriesResponse { GlobalRepository: string; - UserRepositories: HelmRegistryResponse[]; + UserRepositories: HelmRepositoryResponse[]; } export interface HelmChartsResponse { @@ -108,13 +108,21 @@ export interface HelmChartsResponse { generated: string; } +export interface InstallChartPayload { + Name: string; + Repo: string; + Chart: string; + Values: string; + Namespace: string; + Version?: string; +} + export interface UpdateHelmReleasePayload { namespace: string; values?: string; - repo: string; + repo?: string; name: string; chart: string; - appVersion?: string; version?: string; atomic?: boolean; } diff --git a/app/react/kubernetes/more-resources/ClusterRolesView/ClusterRolesDatatable/queries/useClusterRoles.ts b/app/react/kubernetes/more-resources/ClusterRolesView/ClusterRolesDatatable/queries/useClusterRoles.ts index f27ffe642..dbacc4f4c 100644 --- a/app/react/kubernetes/more-resources/ClusterRolesView/ClusterRolesDatatable/queries/useClusterRoles.ts +++ b/app/react/kubernetes/more-resources/ClusterRolesView/ClusterRolesDatatable/queries/useClusterRoles.ts @@ -21,7 +21,7 @@ export function useClusterRoles( }, { ...withGlobalError('Unable to get cluster roles'), - refetchInterval: options?.autoRefreshRate, + ...options, } ); } diff --git a/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/command.tsx b/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/command.tsx index 2d1977a0a..04e6e155f 100644 --- a/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/command.tsx +++ b/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/command.tsx @@ -3,5 +3,5 @@ import { columnHelper } from './helper'; export const command = columnHelper.accessor((row) => row.Command, { header: 'Command', id: 'command', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), }); diff --git a/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/schedule.tsx b/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/schedule.tsx index f979240e8..60a673eb0 100644 --- a/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/schedule.tsx +++ b/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/schedule.tsx @@ -3,5 +3,5 @@ import { columnHelper } from './helper'; export const schedule = columnHelper.accessor((row) => row.Schedule, { header: 'Schedule', id: 'schedule', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), }); diff --git a/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/timezone.tsx b/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/timezone.tsx index 3b262b93b..54bb35a79 100644 --- a/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/timezone.tsx +++ b/app/react/kubernetes/more-resources/JobsView/CronJobsDatatable/columns/timezone.tsx @@ -3,5 +3,5 @@ import { columnHelper } from './helper'; export const timezone = columnHelper.accessor((row) => row.Timezone, { header: 'Timezone', id: 'timezone', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), }); diff --git a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/command.tsx b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/command.tsx index 2d1977a0a..04e6e155f 100644 --- a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/command.tsx +++ b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/command.tsx @@ -3,5 +3,5 @@ import { columnHelper } from './helper'; export const command = columnHelper.accessor((row) => row.Command, { header: 'Command', id: 'command', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), }); diff --git a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/duration.tsx b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/duration.tsx index b189d5a7a..23cfcaf34 100644 --- a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/duration.tsx +++ b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/duration.tsx @@ -3,5 +3,5 @@ import { columnHelper } from './helper'; export const duration = columnHelper.accessor((row) => row.Duration, { header: 'Duration', id: 'duration', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), }); diff --git a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/finished.tsx b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/finished.tsx index cf8e5b5e3..b3bcb4e0f 100644 --- a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/finished.tsx +++ b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/finished.tsx @@ -3,5 +3,5 @@ import { columnHelper } from './helper'; export const finished = columnHelper.accessor((row) => row.FinishTime, { header: 'Finished', id: 'finished', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), }); diff --git a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/started.tsx b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/started.tsx index 8ea383c64..eff7f2465 100644 --- a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/started.tsx +++ b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/started.tsx @@ -7,6 +7,6 @@ export const started = columnHelper.accessor( { header: 'Started', id: 'started', - cell: ({ getValue }) => getValue() ?? '', + cell: ({ getValue }) => getValue(), } ); diff --git a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/status.tsx b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/status.tsx index 93ecb66a2..2f6ad1768 100644 --- a/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/status.tsx +++ b/app/react/kubernetes/more-resources/JobsView/JobsDatatable/columns/status.tsx @@ -26,7 +26,7 @@ function Cell({ row: { original: item } }: CellContext) { }, ])} /> - {item.Status ?? ''} + {item.Status} {item.Status === 'Failed' && ( remainingNamespaces ); diff --git a/app/react/kubernetes/namespaces/ListView/columns/useColumns.tsx b/app/react/kubernetes/namespaces/ListView/columns/useColumns.tsx index ba5eaf159..541c2315f 100644 --- a/app/react/kubernetes/namespaces/ListView/columns/useColumns.tsx +++ b/app/react/kubernetes/namespaces/ListView/columns/useColumns.tsx @@ -1,17 +1,13 @@ import _ from 'lodash'; import { useMemo } from 'react'; -import { AlertTriangle } from 'lucide-react'; import { isoDate } from '@/portainer/filters/filters'; import { useAuthorizations } from '@/react/hooks/useUser'; -import { pluralize } from '@/portainer/helpers/strings'; import { Link } from '@@/Link'; import { StatusBadge } from '@@/StatusBadge'; import { Badge } from '@@/Badge'; import { SystemBadge } from '@@/Badge/SystemBadge'; -import { TooltipWithChildren } from '@@/Tip/TooltipWithChildren'; -import { Icon } from '@@/Icon'; import { helper } from './helper'; import { actions } from './actions'; @@ -49,34 +45,12 @@ export function useColumns() { }), helper.accessor('Status', { header: 'Status', - cell({ getValue, row: { original: item } }) { + cell({ getValue }) { const status = getValue(); return ( -
- - {status.phase} - - {item.UnhealthyEventCount > 0 && ( - - - - - - {item.UnhealthyEventCount}{' '} - {pluralize(item.UnhealthyEventCount, 'warning')} - - - - - )} -
+ + {status.phase} + ); function getColor(status?: string) { diff --git a/app/react/kubernetes/namespaces/queries/queryKeys.ts b/app/react/kubernetes/namespaces/queries/queryKeys.ts index 6c0a04676..ecfe4ea58 100644 --- a/app/react/kubernetes/namespaces/queries/queryKeys.ts +++ b/app/react/kubernetes/namespaces/queries/queryKeys.ts @@ -5,7 +5,7 @@ import { EnvironmentId } from '@/react/portainer/environments/types'; export const queryKeys = { list: ( environmentId: EnvironmentId, - options?: { withResourceQuota?: boolean; withUnhealthyEvents?: boolean } + options?: { withResourceQuota?: boolean } ) => compact([ 'environments', @@ -13,7 +13,6 @@ export const queryKeys = { 'kubernetes', 'namespaces', options?.withResourceQuota, - options?.withUnhealthyEvents, ]), namespace: (environmentId: EnvironmentId, namespace: string) => [ diff --git a/app/react/kubernetes/namespaces/queries/useNamespacesQuery.ts b/app/react/kubernetes/namespaces/queries/useNamespacesQuery.ts index e7977db84..6e521e0aa 100644 --- a/app/react/kubernetes/namespaces/queries/useNamespacesQuery.ts +++ b/app/react/kubernetes/namespaces/queries/useNamespacesQuery.ts @@ -8,32 +8,20 @@ import { PortainerNamespace } from '../types'; import { queryKeys } from './queryKeys'; -export function useNamespacesQuery( +export function useNamespacesQuery( environmentId: EnvironmentId, - options?: { - autoRefreshRate?: number; - withResourceQuota?: boolean; - withUnhealthyEvents?: boolean; - select?: (namespaces: PortainerNamespace[]) => T; - } + options?: { autoRefreshRate?: number; withResourceQuota?: boolean } ) { return useQuery( queryKeys.list(environmentId, { withResourceQuota: !!options?.withResourceQuota, - withUnhealthyEvents: !!options?.withUnhealthyEvents, }), - async () => - getNamespaces( - environmentId, - options?.withResourceQuota, - options?.withUnhealthyEvents - ), + async () => getNamespaces(environmentId, options?.withResourceQuota), { ...withGlobalError('Unable to get namespaces.'), refetchInterval() { return options?.autoRefreshRate ?? false; }, - select: options?.select, } ); } @@ -41,13 +29,9 @@ export function useNamespacesQuery( // getNamespaces is used to retrieve namespaces using the Portainer backend with caching export async function getNamespaces( environmentId: EnvironmentId, - withResourceQuota?: boolean, - withUnhealthyEvents?: boolean + withResourceQuota?: boolean ) { - const params = { - withResourceQuota, - withUnhealthyEvents, - }; + const params = withResourceQuota ? { withResourceQuota } : {}; try { const { data: namespaces } = await axios.get( `kubernetes/${environmentId}/namespaces`, diff --git a/app/react/kubernetes/namespaces/types.ts b/app/react/kubernetes/namespaces/types.ts index f3626e675..ba4abb744 100644 --- a/app/react/kubernetes/namespaces/types.ts +++ b/app/react/kubernetes/namespaces/types.ts @@ -10,7 +10,6 @@ export interface PortainerNamespace { Id: string; Name: string; Status: NamespaceStatus; - UnhealthyEventCount: number; Annotations: Record | null; CreationDate: string; NamespaceOwner: string; diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.test.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.test.tsx deleted file mode 100644 index e8539826c..000000000 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.test.tsx +++ /dev/null @@ -1,145 +0,0 @@ -import { render, screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { HttpResponse } from 'msw'; - -import { withTestRouter } from '@/react/test-utils/withRouter'; -import { withUserProvider } from '@/react/test-utils/withUserProvider'; -import { withTestQueryProvider } from '@/react/test-utils/withTestQuery'; -import { createMockUsers } from '@/react-tools/test-mocks'; -import { server, http } from '@/setup-tests/server'; - -import { ServicesDatatable } from './ServicesDatatable'; - -vi.mock('@/react/hooks/useEnvironmentId', () => ({ - useEnvironmentId: () => 1, -})); - -vi.mock('@/portainer/services/notifications', () => ({ - notifyError: vi.fn(), - notifySuccess: vi.fn(), -})); -function createMockServices(count: number) { - return Array.from({ length: count }, (_, i) => { - let namespace = 'default'; - if (i % 3 === 0) { - namespace = 'kube-system'; - } else if (i % 2 !== 0) { - namespace = 'my-namespace'; - } - - let type = 'ClusterIP'; - if (i % 4 === 1) { - type = 'NodePort'; - } else if (i % 4 === 2) { - type = 'LoadBalancer'; - } else if (i % 4 === 3) { - type = 'ExternalName'; - } - - return { - UID: `service-${i}`, - Name: `service-${i}`, - Namespace: namespace, - Type: type, - Ports: [{ Port: 80 + i, TargetPort: 8080 + i, Protocol: 'TCP' }], - Selector: { app: `app-${i}` }, - CreationTimestamp: new Date(Date.now() - i * 1000 * 60).toISOString(), - ApplicationOwner: '', - Applications: [{ Name: `app-${i}` }], - }; - }); -} - -const mockServices = createMockServices(4); - -const mockNamespaces = [ - { - Name: 'default', - IsSystem: false, - Status: 'Active', - CreationTimestamp: '2024-01-01T00:00:00Z', - }, - { - Name: 'kube-system', - IsSystem: true, - Status: 'Active', - CreationTimestamp: '2024-01-01T00:00:00Z', - }, - { - Name: 'my-namespace', - IsSystem: false, - Status: 'Active', - CreationTimestamp: '2024-01-01T00:00:00Z', - }, -]; - -beforeEach(() => { - server.use( - http.get('/api/kubernetes/1/services', () => - HttpResponse.json(mockServices) - ), - http.get('/api/kubernetes/1/namespaces', () => - HttpResponse.json(mockNamespaces) - ) - ); -}); -const mockUser = { - // Admin user - ...createMockUsers(1, 1)[0], -}; - -function createTestComponent() { - return withTestRouter( - withUserProvider(withTestQueryProvider(ServicesDatatable), mockUser), - { - route: '/kubernetes/services', - stateConfig: [ - { - name: 'kubernetes.services', - url: '/kubernetes/services', - params: { endpointId: '1' }, - }, - ], - } - ); -} - -describe('ServicesDatatable', () => { - it('renders services data correctly', async () => { - const TestComponent = createTestComponent(); - render(); - - expect(await screen.findByText('service-1')).toBeInTheDocument(); - expect(screen.getByText('service-2')).toBeInTheDocument(); - }); - - it('should filter system resources correctly when toggled', async () => { - const TestComponent = createTestComponent(); - render(); - - const settingsButton = screen.getByRole('button', { name: /settings/i }); - await userEvent.click(settingsButton); - - await waitFor(() => { - expect(screen.queryByText('service-0')).not.toBeInTheDocument(); - }); - - const systemToggle = await screen.findByTestId('show-system-resources'); - await userEvent.click(systemToggle); - - await waitFor(() => { - expect(screen.queryByText('service-0')).toBeInTheDocument(); - }); - - expect(screen.getByText('service-3')).toBeInTheDocument(); - expect(screen.getByText('service-1')).toBeInTheDocument(); - expect(screen.getByText('service-2')).toBeInTheDocument(); - }); - - it('should show loading state when data is loading', async () => { - const TestComponent = createTestComponent(); - render(); - - expect(screen.getByText('Loading...')).toBeInTheDocument(); - }); -}); diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx index 265808564..4786eaf2f 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx @@ -16,7 +16,6 @@ import { DefaultDatatableSettings } from '@/react/kubernetes/datatables/DefaultD import { SystemResourceDescription } from '@/react/kubernetes/datatables/SystemResourceDescription'; import { useNamespacesQuery } from '@/react/kubernetes/namespaces/queries/useNamespacesQuery'; import { CreateFromManifestButton } from '@/react/kubernetes/components/CreateFromManifestButton'; -import { createStore } from '@/react/kubernetes/datatables/default-kube-datatable-store'; import { Datatable, Table, TableSettingsMenu } from '@@/datatables'; import { useTableState } from '@@/datatables/useTableState'; @@ -26,6 +25,7 @@ import { useMutationDeleteServices, useClusterServices } from '../../service'; import { Service } from '../../types'; import { columns } from './columns'; +import { createStore } from './datatable-store'; import { ServiceRowData } from './types'; const storageKey = 'k8sServicesDatatable'; @@ -34,53 +34,52 @@ const settingsStore = createStore(storageKey); export function ServicesDatatable() { const tableState = useTableState(settingsStore, storageKey); const environmentId = useEnvironmentId(); - const { data: namespaces, ...namespacesQuery } = useNamespacesQuery( - environmentId, - { - select: (namespacesArray) => - namespacesArray?.reduce>( - (acc, namespace) => { - acc[namespace.Name] = namespace; - return acc; - }, - {} - ), - } - ); - const { authorized: canWrite } = useAuthorizations(['K8sServiceW']); - const { authorized: canAccessSystemResources } = useAuthorizations( - 'K8sAccessSystemNamespaces' - ); + const { data: namespacesArray, ...namespacesQuery } = + useNamespacesQuery(environmentId); const { data: services, ...servicesQuery } = useClusterServices( environmentId, { autoRefreshRate: tableState.autoRefreshRate * 1000, withApplications: true, - select: (services) => - services?.filter( - (service) => - (canAccessSystemResources && tableState.showSystemResources) || - !namespaces?.[service.Namespace]?.IsSystem - ), } ); - const servicesWithIsSystem = useServicesRowData(services || [], namespaces); + const namespaces: Record = {}; + if (Array.isArray(namespacesArray)) { + for (let i = 0; i < namespacesArray.length; i++) { + const namespace = namespacesArray[i]; + namespaces[namespace.Name] = namespace; + } + } + + const { authorized: canWrite } = useAuthorizations(['K8sServiceW']); + const readOnly = !canWrite; + const { authorized: canAccessSystemResources } = useAuthorizations( + 'K8sAccessSystemNamespaces' + ); + const filteredServices = services?.filter( + (service) => + (canAccessSystemResources && tableState.showSystemResources) || + !namespaces?.[service.Namespace]?.IsSystem + ); + + const servicesWithIsSystem = useServicesRowData( + filteredServices || [], + namespaces + ); return ( row.UID} isRowSelectable={(row) => !namespaces?.[row.original.Namespace]?.IsSystem} - disableSelect={!canWrite} + disableSelect={readOnly} renderTableActions={(selectedRows) => ( )} diff --git a/app/react/kubernetes/services/service.ts b/app/react/kubernetes/services/service.ts index a7cdbc7f2..a36f25db9 100644 --- a/app/react/kubernetes/services/service.ts +++ b/app/react/kubernetes/services/service.ts @@ -23,21 +23,18 @@ export const queryKeys = { * * @returns The result of the query. */ -export function useClusterServices( +export function useClusterServices( environmentId: EnvironmentId, - options?: { - autoRefreshRate?: number; - withApplications?: boolean; - select?: (services: Service[]) => T; - } + options?: { autoRefreshRate?: number; withApplications?: boolean } ) { return useQuery( queryKeys.clusterServices(environmentId), async () => getClusterServices(environmentId, options?.withApplications), { ...withGlobalError('Unable to get services.'), - refetchInterval: options?.autoRefreshRate, - select: options?.select, + refetchInterval() { + return options?.autoRefreshRate ?? false; + }, } ); } diff --git a/app/react/kubernetes/volumes/ListView/VolumesDatatable.tsx b/app/react/kubernetes/volumes/ListView/VolumesDatatable.tsx index 032fe63aa..b81f60e9a 100644 --- a/app/react/kubernetes/volumes/ListView/VolumesDatatable.tsx +++ b/app/react/kubernetes/volumes/ListView/VolumesDatatable.tsx @@ -16,17 +16,12 @@ import { } from '../../datatables/DefaultDatatableSettings'; import { SystemResourceDescription } from '../../datatables/SystemResourceDescription'; import { useNamespacesQuery } from '../../namespaces/queries/useNamespacesQuery'; -import { - convertToVolumeViewModels, - useAllVolumesQuery, -} from '../queries/useVolumesQuery'; +import { useAllVolumesQuery } from '../queries/useVolumesQuery'; import { isSystemNamespace } from '../../namespaces/queries/useIsSystemNamespace'; import { useDeleteVolumes } from '../queries/useDeleteVolumes'; import { isVolumeUsed } from '../utils'; -import { K8sVolumeInfo } from '../types'; import { columns } from './columns'; -import { VolumeViewModel } from './types'; export function VolumesDatatable() { const tableState = useTableStateWithStorage( @@ -50,15 +45,21 @@ export function VolumesDatatable() { const namespaces = namespaceListQuery.data ?? []; const volumesQuery = useAllVolumesQuery(envId, { refetchInterval: tableState.autoRefreshRate * 1000, - select: transformAndFilterVolumes, }); const volumes = volumesQuery.data ?? []; + const filteredVolumes = tableState.showSystemResources + ? volumes + : volumes.filter( + (volume) => + !isSystemNamespace(volume.ResourcePool.Namespace.Name, namespaces) + ); + return ( ); - - function transformAndFilterVolumes( - volumes: K8sVolumeInfo[] - ): VolumeViewModel[] { - const transformedVolumes = convertToVolumeViewModels(volumes); - return transformedVolumes.filter( - (volume) => - tableState.showSystemResources || - !isSystemNamespace(volume.ResourcePool.Namespace.Name, namespaces) - ); - } } diff --git a/app/react/kubernetes/volumes/queries/useDeleteVolumes.ts b/app/react/kubernetes/volumes/queries/useDeleteVolumes.ts index 7732c2b58..78d5a295d 100644 --- a/app/react/kubernetes/volumes/queries/useDeleteVolumes.ts +++ b/app/react/kubernetes/volumes/queries/useDeleteVolumes.ts @@ -36,7 +36,7 @@ export function useDeleteVolumes(environmentId: EnvironmentId) { ); } queryClient.invalidateQueries(queryKeys.storages(environmentId)); - return queryClient.invalidateQueries(queryKeys.volumes(environmentId)); + queryClient.invalidateQueries(queryKeys.volumes(environmentId)); }, ...withGlobalError('Unable to remove volumes'), }); diff --git a/app/react/kubernetes/volumes/queries/useNamespaceVolumes.ts b/app/react/kubernetes/volumes/queries/useNamespaceVolumes.ts new file mode 100644 index 000000000..cdf6b6ee0 --- /dev/null +++ b/app/react/kubernetes/volumes/queries/useNamespaceVolumes.ts @@ -0,0 +1,51 @@ +import { useQuery } from '@tanstack/react-query'; + +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { withGlobalError } from '@/react-tools/react-query'; +import axios, { parseAxiosError } from '@/portainer/services/axios'; + +import { K8sVolumeInfo } from '../types'; + +import { queryKeys } from './query-keys'; +import { convertToVolumeViewModels } from './useVolumesQuery'; + +// useQuery to get a list of all volumes in a cluster +export function useNamespaceVolumes( + environmentId: EnvironmentId, + namespace: string, + queryOptions?: { + refetchInterval?: number; + withApplications?: boolean; + } +) { + return useQuery( + queryKeys.volumes(environmentId), + () => + getNamespaceVolumes(environmentId, namespace, { + withApplications: queryOptions?.withApplications ?? false, + }), + { + enabled: !!namespace, + refetchInterval: queryOptions?.refetchInterval, + select: convertToVolumeViewModels, + ...withGlobalError('Unable to retrieve volumes'), + } + ); +} + +// get all volumes in a cluster +async function getNamespaceVolumes( + environmentId: EnvironmentId, + namespace: string, + params?: { withApplications: boolean } +) { + try { + const { data } = await axios.get( + `/kubernetes/${environmentId}/namespaces/${namespace}/volumes`, + { params } + ); + return data; + } catch (e) { + throw parseAxiosError(e, 'Unable to retrieve volumes'); + } +} diff --git a/app/react/kubernetes/volumes/queries/useVolumesQuery.ts b/app/react/kubernetes/volumes/queries/useVolumesQuery.ts index 646065758..94b30345b 100644 --- a/app/react/kubernetes/volumes/queries/useVolumesQuery.ts +++ b/app/react/kubernetes/volumes/queries/useVolumesQuery.ts @@ -14,11 +14,10 @@ import { appOwnerLabel } from '../../applications/constants'; import { queryKeys } from './query-keys'; // useQuery to get a list of all volumes in a cluster -export function useAllVolumesQuery( +export function useAllVolumesQuery( environmentId: EnvironmentId, queryOptions?: { refetchInterval?: number; - select?: (volumes: K8sVolumeInfo[]) => T[]; } ) { return useQuery( @@ -26,7 +25,7 @@ export function useAllVolumesQuery( () => getAllVolumes(environmentId, { withApplications: true }), { refetchInterval: queryOptions?.refetchInterval, - select: queryOptions?.select, + select: convertToVolumeViewModels, ...withGlobalError('Unable to retrieve volumes'), } ); diff --git a/app/react/portainer/HomeView/EnvironmentList/KubeconfigButton/KubeconfigButton.tsx b/app/react/portainer/HomeView/EnvironmentList/KubeconfigButton/KubeconfigButton.tsx index 393c55f9c..f2b20857d 100644 --- a/app/react/portainer/HomeView/EnvironmentList/KubeconfigButton/KubeconfigButton.tsx +++ b/app/react/portainer/HomeView/EnvironmentList/KubeconfigButton/KubeconfigButton.tsx @@ -7,7 +7,6 @@ import { trackEvent } from '@/angulartics.matomo/analytics-services'; import { Query } from '@/react/portainer/environments/queries/useEnvironmentList'; import { Button } from '@@/buttons'; -import { TooltipWithChildren } from '@@/Tip/TooltipWithChildren'; import { KubeconfigPrompt } from './KubeconfigPrompt'; @@ -24,41 +23,23 @@ export function KubeconfigButton({ environments, envQueryParams }: Props) { isKubernetesEnvironment(env.Type) ); - const isHttp = window.location.protocol === 'http:'; - const noKubeEnvs = kubeEnvs.length === 0; - const isDisabled = noKubeEnvs || isHttp; - - let tooltipMessage = ''; - if (isHttp) { - tooltipMessage = - 'Kubeconfig download is not available when Portainer is accessed via HTTP. Please use HTTPS'; - } else if (noKubeEnvs) { - tooltipMessage = 'No Kubernetes environments detected'; + if (!isKubeconfigButtonVisible()) { + return null; } - const button = ( - - ); - return ( <> - {isDisabled ? ( - - {button} - - ) : ( - button - )} + {prompt()} ); @@ -79,6 +60,10 @@ export function KubeconfigButton({ environments, envQueryParams }: Props) { setIsOpen(false); } + function isKubeconfigButtonVisible() { + return window.location.protocol === 'https:'; + } + function prompt() { return ( isOpen && ( diff --git a/app/react/portainer/access-control/AccessControlPanel/AccessControlPanelDetails.tsx b/app/react/portainer/access-control/AccessControlPanel/AccessControlPanelDetails.tsx index f53015cea..725e115cd 100644 --- a/app/react/portainer/access-control/AccessControlPanel/AccessControlPanelDetails.tsx +++ b/app/react/portainer/access-control/AccessControlPanel/AccessControlPanelDetails.tsx @@ -201,10 +201,8 @@ function InheritanceMessage({ return ( -
- - {children} -
+ + {children} diff --git a/app/react/portainer/account/AccountView/.keep b/app/react/portainer/account/AccountView/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/react/portainer/account/AccountView/HelmRepositoryDatatable/HelmRepositoryDatatable.tsx b/app/react/portainer/account/AccountView/HelmRepositoryDatatable/HelmRepositoryDatatable.tsx index bad68c293..7ed2f4651 100644 --- a/app/react/portainer/account/AccountView/HelmRepositoryDatatable/HelmRepositoryDatatable.tsx +++ b/app/react/portainer/account/AccountView/HelmRepositoryDatatable/HelmRepositoryDatatable.tsx @@ -81,25 +81,21 @@ export function HelmRepositoryDatatable() { function HelmDatatableDescription({ isAdmin }: { isAdmin: boolean }) { return ( -

- Adding a Helm repository here makes it available only in your Portainer - user account. The Helm charts from these repositories (along with the - globally set Helm repository) are shown in the 'Create from - Code' screen. -

- {isAdmin && ( - <> - To manage your helm repositories globally, navigate to{' '} - - Settings > General - - . - + Adding a Helm repo here only makes it available in your own user + account's Portainer UI. Helm charts are pulled down from these repos + (plus the{' '} + {isAdmin ? ( + + globally-set Helm repo + + ) : ( + globally-set Helm repo )} + ) and shown in the Create from code screen's Helm charts list.
); } diff --git a/app/react/portainer/account/AccountView/HelmRepositoryDatatable/helm-repositories.service.ts b/app/react/portainer/account/AccountView/HelmRepositoryDatatable/helm-repositories.service.ts index 8916dfb41..c12ed9ffa 100644 --- a/app/react/portainer/account/AccountView/HelmRepositoryDatatable/helm-repositories.service.ts +++ b/app/react/portainer/account/AccountView/HelmRepositoryDatatable/helm-repositories.service.ts @@ -4,8 +4,6 @@ import axios, { parseAxiosError } from '@/portainer/services/axios'; import { success as notifySuccess } from '@/portainer/services/notifications'; import { withError } from '@/react-tools/react-query'; import { pluralize } from '@/portainer/helpers/strings'; -import { queryKeys } from '@/react/kubernetes/helm/helmChartSourceQueries/query-keys'; -import { useCurrentUser } from '@/react/hooks/useUser'; import { CreateHelmRepositoryPayload, @@ -54,12 +52,11 @@ export async function deleteHelmRepositories(repos: HelmRepository[]) { export function useDeleteHelmRepositoryMutation() { const queryClient = useQueryClient(); - const { user } = useCurrentUser(); return useMutation(deleteHelmRepository, { onSuccess: (_, helmRepository) => { notifySuccess('Helm repository deleted successfully', helmRepository.URL); - return queryClient.invalidateQueries(queryKeys.registries(user.Id)); + return queryClient.invalidateQueries(['helmrepositories']); }, ...withError('Unable to delete Helm repository'), }); @@ -67,7 +64,6 @@ export function useDeleteHelmRepositoryMutation() { export function useDeleteHelmRepositoriesMutation() { const queryClient = useQueryClient(); - const { user } = useCurrentUser(); return useMutation(deleteHelmRepositories, { onSuccess: () => { @@ -79,31 +75,26 @@ export function useDeleteHelmRepositoriesMutation() { 'repositories' )} deleted successfully` ); - return queryClient.invalidateQueries(queryKeys.registries(user.Id)); + return queryClient.invalidateQueries(['helmrepositories']); }, ...withError('Unable to delete Helm repositories'), }); } export function useHelmRepositories(userId: number) { - return useQuery( - queryKeys.registries(userId), - () => getHelmRepositories(userId), - { - staleTime: 20, - ...withError('Unable to retrieve Helm repositories'), - } - ); + return useQuery(['helmrepositories'], () => getHelmRepositories(userId), { + staleTime: 20, + ...withError('Unable to retrieve Helm repositories'), + }); } export function useCreateHelmRepositoryMutation() { const queryClient = useQueryClient(); - const { user } = useCurrentUser(); return useMutation(createHelmRepository, { onSuccess: (_, payload) => { notifySuccess('Helm repository created successfully', payload.URL); - return queryClient.invalidateQueries(queryKeys.registries(user.Id)); + return queryClient.invalidateQueries(['helmrepositories']); }, ...withError('Unable to create Helm repository'), }); diff --git a/app/react/portainer/account/AccountView/theme-options.tsx b/app/react/portainer/account/AccountView/theme-options.tsx index 21c1d00d9..c76ddaa2f 100644 --- a/app/react/portainer/account/AccountView/theme-options.tsx +++ b/app/react/portainer/account/AccountView/theme-options.tsx @@ -7,24 +7,28 @@ export const options = [ id: 'light', icon: , label: 'Light Theme', + description: 'Default color mode', value: 'light', }, { id: 'dark', icon: , label: 'Dark Theme', + description: 'Dark color mode', value: 'dark', }, { id: 'highcontrast', icon: , label: 'High Contrast', + description: 'High contrast color mode', value: 'highcontrast', }, { id: 'auto', icon: , - label: 'System Theme', + label: 'Auto', + description: 'Sync with system theme', value: 'auto', }, ]; diff --git a/app/react/portainer/environments/queries/query-keys.ts b/app/react/portainer/environments/queries/query-keys.ts index 5cb21a348..ed0600c19 100644 --- a/app/react/portainer/environments/queries/query-keys.ts +++ b/app/react/portainer/environments/queries/query-keys.ts @@ -3,11 +3,6 @@ import { EnvironmentId } from '../types'; export const environmentQueryKeys = { base: () => ['environments'] as const, item: (id: EnvironmentId) => [...environmentQueryKeys.base(), id] as const, - registries: (environmentId: EnvironmentId, namespace?: string) => - [ - ...environmentQueryKeys.base(), - environmentId, - 'registries', - namespace, - ] as const, + registries: (environmentId: EnvironmentId) => + [...environmentQueryKeys.base(), environmentId, 'registries'] as const, }; diff --git a/app/react/portainer/environments/queries/useEnvironmentRegistries.ts b/app/react/portainer/environments/queries/useEnvironmentRegistries.ts index c25ffa157..19588b5ca 100644 --- a/app/react/portainer/environments/queries/useEnvironmentRegistries.ts +++ b/app/react/portainer/environments/queries/useEnvironmentRegistries.ts @@ -14,28 +14,17 @@ export function useEnvironmentRegistries>( environmentId: EnvironmentId, queryOptions: GenericRegistriesQueryOptions = {} ) { - const { namespace } = queryOptions; return useGenericRegistriesQuery( - environmentQueryKeys.registries(environmentId, namespace), - () => getEnvironmentRegistries(environmentId, { namespace }), + environmentQueryKeys.registries(environmentId), + () => getEnvironmentRegistries(environmentId), queryOptions ); } -type Params = { - namespace?: string; -}; - -async function getEnvironmentRegistries( - environmentId: EnvironmentId, - params: Params -) { +async function getEnvironmentRegistries(environmentId: EnvironmentId) { try { const { data } = await axios.get>( - buildUrl(environmentId, 'registries'), - { - params, - } + buildUrl(environmentId, 'registries') ); return data; } catch (err) { diff --git a/app/react/portainer/registries/CreateView/options.tsx b/app/react/portainer/registries/CreateView/options.tsx index 984eaa892..b6802e60b 100644 --- a/app/react/portainer/registries/CreateView/options.tsx +++ b/app/react/portainer/registries/CreateView/options.tsx @@ -1,56 +1,62 @@ -import { BadgeIcon } from '@@/BadgeIcon'; +import { Edit } from 'lucide-react'; -import { RegistryTypes } from '../types/registry'; -import { registryIconMap, registryLabelMap } from '../utils/constants'; +import Docker from '@/assets/ico/vendor/docker.svg?c'; +import Ecr from '@/assets/ico/vendor/ecr.svg?c'; +import Quay from '@/assets/ico/vendor/quay.svg?c'; +import Proget from '@/assets/ico/vendor/proget.svg?c'; +import Azure from '@/assets/ico/vendor/azure.svg?c'; +import Gitlab from '@/assets/ico/vendor/gitlab.svg?c'; + +import { BadgeIcon } from '@@/BadgeIcon'; export const options = [ { id: 'registry_dockerhub', - icon: registryIconMap[RegistryTypes.DOCKERHUB], - label: registryLabelMap[RegistryTypes.DOCKERHUB], + icon: Docker, + label: 'DockerHub', description: 'DockerHub authenticated account', - value: String(RegistryTypes.DOCKERHUB), + value: '6', }, { id: 'registry_aws_ecr', - icon: registryIconMap[RegistryTypes.ECR], - label: registryLabelMap[RegistryTypes.ECR], + icon: Ecr, + label: 'AWS ECR', description: 'Amazon elastic container registry', - value: String(RegistryTypes.ECR), + value: '7', }, { id: 'registry_quay', - icon: registryIconMap[RegistryTypes.QUAY], - label: registryLabelMap[RegistryTypes.QUAY], + icon: Quay, + label: 'Quay.io', description: 'Quay container registry', - value: String(RegistryTypes.QUAY), + value: '1', }, { id: 'registry_proget', - icon: registryIconMap[RegistryTypes.PROGET], - label: registryLabelMap[RegistryTypes.PROGET], + icon: Proget, + label: 'ProGet', description: 'ProGet container registry', - value: String(RegistryTypes.PROGET), + value: '5', }, { id: 'registry_azure', - icon: registryIconMap[RegistryTypes.AZURE], - label: registryLabelMap[RegistryTypes.AZURE], + icon: Azure, + label: 'Azure', description: 'Azure container registry', - value: String(RegistryTypes.AZURE), + value: '2', }, { id: 'registry_gitlab', - icon: registryIconMap[RegistryTypes.GITLAB], - label: registryLabelMap[RegistryTypes.GITLAB], + icon: Gitlab, + label: 'GitLab', description: 'GitLab container registry', - value: String(RegistryTypes.GITLAB), + value: '4', }, { id: 'registry_custom', - icon: , - label: registryLabelMap[RegistryTypes.CUSTOM], + icon: , + label: 'Custom registry', description: 'Define your own registry', - value: String(RegistryTypes.CUSTOM), + value: '3', }, ]; diff --git a/app/react/portainer/registries/queries/build-url.ts b/app/react/portainer/registries/queries/build-url.ts index f490ec406..3f76215bd 100644 --- a/app/react/portainer/registries/queries/build-url.ts +++ b/app/react/portainer/registries/queries/build-url.ts @@ -1,17 +1,13 @@ import { RegistryId } from '../types/registry'; -export function buildUrl(registryId: RegistryId, resource?: 'repositories') { - let url = '/registries'; +export function buildUrl(registryId: RegistryId) { + const base = '/registries'; if (registryId) { - url += `/${registryId}`; + return `${base}/${registryId}`; } - if (resource) { - url += `/${resource}`; - } - - return url; + return base; } export function buildProxyUrl(registryId: RegistryId) { diff --git a/app/react/portainer/registries/queries/useRegistries.ts b/app/react/portainer/registries/queries/useRegistries.ts index 4ea5aad6e..007ab70cb 100644 --- a/app/react/portainer/registries/queries/useRegistries.ts +++ b/app/react/portainer/registries/queries/useRegistries.ts @@ -24,8 +24,6 @@ export type GenericRegistriesQueryOptions = { onSuccess?: (data: T) => void; /** is used to hide the default registry from the list of registries, regardless of the user's settings. Kubernetes views use this. */ hideDefault?: boolean; - /** is used to filter the registries by namespace. Kubernetes views use this. */ - namespace?: string; }; export function useGenericRegistriesQuery( diff --git a/app/react/portainer/registries/repositories/ItemView/TagsDatatable/TagsDatatable.test.tsx b/app/react/portainer/registries/repositories/ItemView/TagsDatatable/TagsDatatable.test.tsx deleted file mode 100644 index 6ec8599e1..000000000 --- a/app/react/portainer/registries/repositories/ItemView/TagsDatatable/TagsDatatable.test.tsx +++ /dev/null @@ -1,169 +0,0 @@ -import { render, screen } from '@testing-library/react'; -import { vi } from 'vitest'; - -import { withTestQueryProvider } from '@/react/test-utils/withTestQuery'; -import { withTestRouter } from '@/react/test-utils/withRouter'; - -import { TagsDatatable } from './TagsDatatable'; -import { Tag } from './types'; -import { RepositoryTagViewModel } from './view-model'; - -// Mock the necessary hooks -const mockUseCurrentStateAndParams = vi.fn(); - -vi.mock('@uirouter/react', async (importOriginal: () => Promise) => ({ - ...(await importOriginal()), - useCurrentStateAndParams: () => mockUseCurrentStateAndParams(), -})); - -// Mock the Link component to capture route parameters and generate proper hrefs -vi.mock('@@/Link', () => ({ - Link: ({ - children, - params, - 'data-cy': dataCy, - title, - }: { - children: React.ReactNode; - params?: Record; - 'data-cy'?: string; - title?: string; - }) => { - // Simulate href generation based on route and params - // For 'portainer.registries.registry.repository.tag' route - const baseParams = { - endpointId: '1', - id: '1', - repository: 'test-repo', - ...params, - }; - - const tag = (baseParams as Record).tag || ''; - const href = `/endpoints/${baseParams.endpointId}/registries/${baseParams.id}/repositories/${baseParams.repository}/tags/${tag}`; - - return ( - - {children} - - ); - }, -})); - -vi.mock('../../queries/useTagDetails', () => ({ - useTagDetails: vi.fn( - ( - params, - { select }: { select?: (data: RepositoryTagViewModel) => string } = {} - ) => { - const data: RepositoryTagViewModel = { - Name: params.tag, - Os: 'linux', - Architecture: 'amd64', - ImageId: `sha256:${params.tag}123`, - Size: 1024, - ImageDigest: '', - ManifestV2: { - digest: `sha256:${params.tag}123`, - schemaVersion: 2, - mediaType: 'application/vnd.docker.distribution.manifest.v2+json', - config: { - digest: `sha256:${params.tag}123`, - mediaType: 'application/vnd.docker.container.image.v1+json', - size: 1024, - }, - layers: [], - }, - History: [], - }; - - return { - data: select?.(data) || data, - isLoading: false, - error: null, - }; - } - ), -})); - -// Create mock data -const mockTags: Tag[] = [ - { Name: 'latest' }, - { Name: 'v1.0.0' }, - { Name: 'dev-branch' }, - { Name: 'feature/new-ui' }, -]; - -const defaultProps = { - dataset: mockTags, - advancedFeaturesAvailable: true, - onRemove: vi.fn(), - onRetag: vi.fn().mockResolvedValue(undefined), -}; - -function renderComponent() { - const Wrapped = withTestQueryProvider( - withTestRouter(() => ) - ); - return render(); -} - -describe('TagsDatatable', () => { - beforeEach(() => { - // Set up default mock values - mockUseCurrentStateAndParams.mockReturnValue({ - params: { - endpointId: '1', - id: '1', - repository: 'test-repo', - }, - }); - }); - - it('renders basic table structure', () => { - renderComponent(); - expect(screen.getByText('Tags')).toBeInTheDocument(); - expect(screen.getByPlaceholderText('Search...')).toBeInTheDocument(); - }); - - it('renders tag data in table', () => { - renderComponent(); - - // Check that our mock tags are rendered somewhere in the table - expect(screen.getByText('latest')).toBeInTheDocument(); - expect(screen.getByText('v1.0.0')).toBeInTheDocument(); - expect(screen.getByText('dev-branch')).toBeInTheDocument(); - expect(screen.getByText('feature/new-ui')).toBeInTheDocument(); - }); - - it('creates correct hrefs for tag name links', () => { - renderComponent(); - - // Get the links by their data-cy attributes - const latestLink = screen.getByTestId( - 'registry-tag-name_latest' - ) as HTMLAnchorElement; - const v100Link = screen.getByTestId( - 'registry-tag-name_v1.0.0' - ) as HTMLAnchorElement; - const devBranchLink = screen.getByTestId( - 'registry-tag-name_dev-branch' - ) as HTMLAnchorElement; - const featureLink = screen.getByTestId( - 'registry-tag-name_feature/new-ui' - ) as HTMLAnchorElement; - - // Verify the exact path portion of the href - expect(new URL(latestLink.href).pathname).toBe( - '/endpoints/1/registries/1/repositories/test-repo/tags/latest' - ); - expect(new URL(v100Link.href).pathname).toBe( - '/endpoints/1/registries/1/repositories/test-repo/tags/v1.0.0' - ); - expect(new URL(devBranchLink.href).pathname).toBe( - '/endpoints/1/registries/1/repositories/test-repo/tags/dev-branch' - ); - expect(new URL(featureLink.href).pathname).toBe( - '/endpoints/1/registries/1/repositories/test-repo/tags/feature/new-ui' - ); - }); -}); diff --git a/app/react/portainer/registries/repositories/ItemView/TagsDatatable/columns/useColumns.ts b/app/react/portainer/registries/repositories/ItemView/TagsDatatable/columns/useColumns.ts index bcedccb47..4f07b5bec 100644 --- a/app/react/portainer/registries/repositories/ItemView/TagsDatatable/columns/useColumns.ts +++ b/app/react/portainer/registries/repositories/ItemView/TagsDatatable/columns/useColumns.ts @@ -4,7 +4,7 @@ import _ from 'lodash'; import { humanize } from '@/portainer/filters/filters'; import { trimSHA } from '@/docker/filters/utils'; -import { buildNameColumnFromObject } from '@@/datatables/buildNameColumn'; +import { buildNameColumn } from '@@/datatables/buildNameColumn'; import { Tag } from '../types'; @@ -13,13 +13,13 @@ import { buildCell } from './buildCell'; import { actions } from './actions'; const columns = [ - buildNameColumnFromObject({ - nameKey: 'Name', - path: 'portainer.registries.registry.repository.tag', - dataCy: 'registry-tag-name', - idParam: 'tag', - idGetter: (item) => item.Name, - }), + buildNameColumn( + 'Name', + 'portainer.registries.registry.repository.tag', + 'tag', + 'registry-tag-name', + (item) => item.Name + ), helper.display({ header: 'OS/Architecture', cell: buildCell((model) => `${model.Os}/${model.Architecture}`), diff --git a/app/react/portainer/registries/utils/constants.tsx b/app/react/portainer/registries/utils/constants.tsx deleted file mode 100644 index e20ee285f..000000000 --- a/app/react/portainer/registries/utils/constants.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { Edit } from 'lucide-react'; - -import Docker from '@/assets/ico/vendor/docker.svg?c'; -import Ecr from '@/assets/ico/vendor/ecr.svg?c'; -import Quay from '@/assets/ico/vendor/quay.svg?c'; -import Proget from '@/assets/ico/vendor/proget.svg?c'; -import Azure from '@/assets/ico/vendor/azure.svg?c'; -import Gitlab from '@/assets/ico/vendor/gitlab.svg?c'; - -import { RegistryTypes } from '../types/registry'; - -export const registryLabelMap: Record = { - [RegistryTypes.ANONYMOUS]: 'Anonymous', - [RegistryTypes.DOCKERHUB]: 'DockerHub', - [RegistryTypes.ECR]: 'AWS ECR', - [RegistryTypes.QUAY]: 'Quay.io', - [RegistryTypes.PROGET]: 'ProGet', - [RegistryTypes.AZURE]: 'Azure', - [RegistryTypes.GITLAB]: 'GitLab', - [RegistryTypes.CUSTOM]: 'Custom registry', - [RegistryTypes.GITHUB]: 'GitHub', -}; - -export const registryIconMap = { - [RegistryTypes.DOCKERHUB]: Docker, - [RegistryTypes.ECR]: Ecr, - [RegistryTypes.QUAY]: Quay, - [RegistryTypes.PROGET]: Proget, - [RegistryTypes.AZURE]: Azure, - [RegistryTypes.GITLAB]: Gitlab, - [RegistryTypes.CUSTOM]: Edit, - // github and anonymous don't have an icon - [RegistryTypes.GITHUB]: null, - [RegistryTypes.ANONYMOUS]: null, -}; diff --git a/app/react/portainer/settings/SettingsView/KubeSettingsPanel/HelmSection.tsx b/app/react/portainer/settings/SettingsView/KubeSettingsPanel/HelmSection.tsx index 0c21140aa..e5d519174 100644 --- a/app/react/portainer/settings/SettingsView/KubeSettingsPanel/HelmSection.tsx +++ b/app/react/portainer/settings/SettingsView/KubeSettingsPanel/HelmSection.tsx @@ -4,7 +4,7 @@ import { TextTip } from '@@/Tip/TextTip'; import { FormControl } from '@@/form-components/FormControl'; import { FormSection } from '@@/form-components/FormSection'; import { Input } from '@@/form-components/Input'; -import { ExternalLink } from '@@/ExternalLink'; +import { InsightsBox } from '@@/InsightsBox'; export function HelmSection() { const [{ name }, { error }] = useField('helmRepositoryUrl'); @@ -13,17 +13,39 @@ export function HelmSection() {
- You can specify the URL to your own{' '} - - Helm repository - {' '} - here. + official documentation + {' '} + for more details.
+ + At present Portainer does not support OCI format Helm charts. + Support for OCI charts will be available in a future release. If you + would like to provide feedback on OCI support or get access to early + releases to test this functionality,{' '} + + please get in touch + + . + + } + className="block w-fit mt-2 mb-1" + /> + { const inputElement = screen.getByDisplayValue(value.VAR1); await user.clear(inputElement); - expect(onChange).toHaveBeenCalledWith({ VAR1: undefined }); + expect(onChange).toHaveBeenCalledWith({ VAR1: '' }); const newValue = 'New Value'; await user.type(inputElement, newValue); @@ -107,14 +107,11 @@ test('validates env vars fieldset', () => { ]); const validData = { VAR1: 'Value 1', VAR2: 'Value 2' }; - const emptyData = { VAR1: '', VAR2: 'Value 2' }; - const undefinedData = { VAR1: undefined, VAR2: 'Value 2' }; + const invalidData = { VAR1: '', VAR2: 'Value 2' }; const validResult = schema.isValidSync(validData); - const emptyResult = schema.isValidSync(emptyData); - const undefinedResult = schema.isValidSync(undefinedData); + const invalidResult = schema.isValidSync(invalidData); expect(validResult).toBe(true); - expect(emptyResult).toBe(true); - expect(undefinedResult).toBe(true); + expect(invalidResult).toBe(false); }); diff --git a/app/react/portainer/templates/app-templates/DeployFormWidget/EnvVarsFieldset.tsx b/app/react/portainer/templates/app-templates/DeployFormWidget/EnvVarsFieldset.tsx index a1281772f..dad33af07 100644 --- a/app/react/portainer/templates/app-templates/DeployFormWidget/EnvVarsFieldset.tsx +++ b/app/react/portainer/templates/app-templates/DeployFormWidget/EnvVarsFieldset.tsx @@ -6,7 +6,7 @@ import { TemplateEnv } from '@/react/portainer/templates/app-templates/types'; import { FormControl } from '@@/form-components/FormControl'; import { Input, Select } from '@@/form-components/Input'; -type Value = Record; +type Value = Record; export { type Value as EnvVarsValue }; @@ -27,7 +27,7 @@ export function EnvVarsFieldset({ handleChange(env.name, value)} errors={errors?.[env.name]} /> @@ -36,7 +36,7 @@ export function EnvVarsFieldset({ ); function handleChange(name: string, envValue: string) { - onChange({ ...values, [name]: envValue || undefined }); + onChange({ ...values, [name]: envValue }); } } @@ -55,7 +55,7 @@ function Item({ return ( @@ -101,9 +101,7 @@ export function envVarsFieldsetValidation( ): SchemaOf { return object( Object.fromEntries( - definitions - .filter((v) => !v.preset) - .map((v) => [v.name, string().optional()]) + definitions.map((v) => [v.name, string().required('Required')]) ) ); } diff --git a/app/react/portainer/templates/app-templates/DeployFormWidget/StackDeployForm/types.ts b/app/react/portainer/templates/app-templates/DeployFormWidget/StackDeployForm/types.ts index f40d79c56..d94a2412e 100644 --- a/app/react/portainer/templates/app-templates/DeployFormWidget/StackDeployForm/types.ts +++ b/app/react/portainer/templates/app-templates/DeployFormWidget/StackDeployForm/types.ts @@ -2,6 +2,6 @@ import { AccessControlFormData } from '@/react/portainer/access-control/types'; export interface FormValues { name: string; - envVars: Record; + envVars: Record; accessControl: AccessControlFormData; } diff --git a/app/react/portainer/templates/app-templates/view-model.ts b/app/react/portainer/templates/app-templates/view-model.ts index 3619caa20..94ea24bc3 100644 --- a/app/react/portainer/templates/app-templates/view-model.ts +++ b/app/react/portainer/templates/app-templates/view-model.ts @@ -88,8 +88,10 @@ function setTemplatesV3(this: TemplateViewModel, template: AppTemplate) { this.Id = template.id; } +let templateV2ID = 0; + function setTemplatesV2(this: TemplateViewModel, template: AppTemplate) { - this.Id = template.id; + this.Id = templateV2ID++; this.Title = template.title; this.Type = template.type; this.Description = template.description; diff --git a/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamAssociationSelector.stories.tsx b/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamAssociationSelector.stories.tsx index 9c7fa8a32..d4d4142f7 100644 --- a/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamAssociationSelector.stories.tsx +++ b/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamAssociationSelector.stories.tsx @@ -2,7 +2,7 @@ import { Meta } from '@storybook/react'; import { useMemo, useState } from 'react'; import { createMockUsers } from '@/react-tools/test-mocks'; -import { Role } from '@/portainer/users/types'; +import { Role, User } from '@/portainer/users/types'; import { UserViewModel } from '@/portainer/models/user'; import { UserContext } from '@/react/hooks/useUser'; @@ -28,7 +28,7 @@ function Example({ userRole }: Args) { () => ({ user: new UserViewModel({ Role: userRole }) }), [userRole] ); - const [users] = useState(createMockUsers(20, Role.Standard)); + const [users] = useState(createMockUsers(20) as User[]); const [memberships] = useState[]>( users diff --git a/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamMembersList/TeamMembersList.stories.tsx b/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamMembersList/TeamMembersList.stories.tsx index efe4cc908..6f2e53f1e 100644 --- a/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamMembersList/TeamMembersList.stories.tsx +++ b/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/TeamMembersList/TeamMembersList.stories.tsx @@ -28,7 +28,7 @@ function Example({ userRole }: Args) { [userRole] ); - const [users] = useState(createMockUsers(20, Role.Standard)); + const [users] = useState(createMockUsers(20)); const [roles] = useState( Object.fromEntries( users.map((user) => [ diff --git a/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/UsersList/UsersList.stories.tsx b/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/UsersList/UsersList.stories.tsx index 8966d6fad..bbbcc6498 100644 --- a/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/UsersList/UsersList.stories.tsx +++ b/app/react/portainer/users/teams/ItemView/TeamAssociationSelector/UsersList/UsersList.stories.tsx @@ -1,10 +1,6 @@ import { Meta } from '@storybook/react'; -import { useMemo } from 'react'; import { createMockUsers } from '@/react-tools/test-mocks'; -import { Role } from '@/portainer/users/types'; -import { UserContext } from '@/react/hooks/useUser'; -import { UserViewModel } from '@/portainer/models/user'; import { UsersList } from './UsersList'; @@ -17,25 +13,10 @@ export default meta; export { Example }; -interface Args { - userRole: Role; +function Example() { + const users = createMockUsers(20); + + return ; } -function Example({ userRole }: Args) { - const userProviderState = useMemo( - () => ({ user: new UserViewModel({ Role: userRole }) }), - [userRole] - ); - - const users = createMockUsers(20, Role.Standard); - - return ( - - - - ); -} - -Example.args = { - userRole: Role.Admin, -}; +Example.args = {}; diff --git a/app/react/sidebar/EnvironmentSidebar.module.css b/app/react/sidebar/EnvironmentSidebar.module.css index 2400d635a..56165048c 100644 --- a/app/react/sidebar/EnvironmentSidebar.module.css +++ b/app/react/sidebar/EnvironmentSidebar.module.css @@ -1,11 +1,12 @@ .root { background-color: var(--bg-sidebar-nav-color); + border-color: var(--border-sidebar-color); } .closeBtn { - background-color: transparent; + background-color: var(--bg-btn-default-color); } .closeBtn:hover { - background-color: var(--graphite-500); + background-color: var(--bg-btn-default-hover-color); } diff --git a/app/react/sidebar/EnvironmentSidebar.tsx b/app/react/sidebar/EnvironmentSidebar.tsx index bea5f86c1..2e51b449c 100644 --- a/app/react/sidebar/EnvironmentSidebar.tsx +++ b/app/react/sidebar/EnvironmentSidebar.tsx @@ -36,7 +36,7 @@ export function EnvironmentSidebar() { } return ( -
+
{environment ? ( ) : ( @@ -151,7 +151,7 @@ function Title({ environment, onClear }: TitleProps) { onClick={onClear} className={clsx( styles.closeBtn, - 'ml-auto mr-2 flex h-5 w-5 items-center justify-center rounded border-0 p-1 text-sm text-white transition-colors duration-200' + 'ml-auto mr-2 flex h-5 w-5 items-center justify-center rounded border-0 p-1 text-sm text-gray-5 transition-colors duration-200 hover:text-white be:text-gray-6 be:hover:text-white' )} > diff --git a/app/react/sidebar/Footer/Footer.tsx b/app/react/sidebar/Footer/Footer.tsx index 7374857c5..0c6636a3e 100644 --- a/app/react/sidebar/Footer/Footer.tsx +++ b/app/react/sidebar/Footer/Footer.tsx @@ -7,6 +7,7 @@ import { UpdateNotification } from './UpdateNotifications'; import { BuildInfoModalButton } from './BuildInfoModal'; import '@reach/dialog/styles.css'; import styles from './Footer.module.css'; +import Logo from './portainer_logo.svg?c'; export function Footer() { return isBE ? : ; @@ -18,6 +19,7 @@ function CEFooter() { + Community Edition @@ -41,7 +43,7 @@ function BEFooter() { function FooterContent({ children }: PropsWithChildren) { return ( -
+
{children}
); diff --git a/app/react/sidebar/Footer/portainer_logo.svg b/app/react/sidebar/Footer/portainer_logo.svg new file mode 100644 index 000000000..1bf390370 --- /dev/null +++ b/app/react/sidebar/Footer/portainer_logo.svg @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/react/sidebar/Header.module.css b/app/react/sidebar/Header.module.css index 82a002e8a..002dad966 100644 --- a/app/react/sidebar/Header.module.css +++ b/app/react/sidebar/Header.module.css @@ -1,5 +1,9 @@ .logo { display: inline; max-height: 55px; - max-width: min(100%, 220px); + max-width: min(100%, 230px); +} + +.collapseBtn:hover { + background-color: var(--bg-btn-default-hover-color); } diff --git a/app/react/sidebar/Header.test.tsx b/app/react/sidebar/Header.test.tsx deleted file mode 100644 index e8fc9104a..000000000 --- a/app/react/sidebar/Header.test.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import { render, screen } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; - -import { withTestRouter } from '@/react/test-utils/withRouter'; - -import { Context } from './useSidebarState'; -import { Header } from './Header'; - -vi.mock('@/react/portainer/feature-flags/feature-flags.service', () => ({ - isBE: false, -})); - -function renderComponent( - props = {}, - sidebarState = { isOpen: true, toggle: vi.fn() } -) { - const Wrapped = withTestRouter(Header); - - return render( - - - - ); -} - -describe('Header', () => { - it('should render with default logo when no custom logo provided', () => { - renderComponent(); - - const logo = screen.getByAltText('Logo'); - expect(logo).toBeInTheDocument(); - expect(logo).toHaveAttribute( - 'src', - expect.stringContaining('portainer_logo-CE.svg') - ); - }); - - it('should render with custom logo when provided', () => { - const customLogo = 'https://example.com/custom-logo.png'; - renderComponent({ logo: customLogo }); - - const logo = screen.getByAltText('Logo'); - expect(logo).toBeInTheDocument(); - expect(logo).toHaveAttribute('src', customLogo); - }); - - it('should show "Powered by" section when sidebar is open and custom logo is provided', () => { - const customLogo = 'https://example.com/custom-logo.png'; - renderComponent({ logo: customLogo }); - - expect(screen.getByText('Powered by')).toBeInTheDocument(); - expect(screen.getByText('portainer community')).toBeInTheDocument(); - }); - - it('should not show "Powered by" section when no custom logo', () => { - renderComponent(); - - expect(screen.queryByText('Powered by')).not.toBeInTheDocument(); - }); - - it('should not show "Powered by" section when sidebar is closed', () => { - const customLogo = 'https://example.com/custom-logo.png'; - renderComponent({ logo: customLogo }, { isOpen: false, toggle: vi.fn() }); - - expect(screen.queryByText('Powered by')).not.toBeInTheDocument(); - }); - - it('should apply flex-wrap class to logo container', () => { - renderComponent(); - - const logoContainer = screen.getByTestId( - 'portainerSidebar-homeImage' - ).parentElement; - expect(logoContainer).toHaveClass('flex-wrap'); - }); - - it('should apply justify-center class when sidebar is closed', () => { - renderComponent({}, { isOpen: false, toggle: vi.fn() }); - - const logoContainer = screen.getByTestId( - 'portainerSidebar-homeImage' - ).parentElement; - expect(logoContainer).toHaveClass('justify-center'); - }); - - it('should not apply justify-center class when sidebar is open', () => { - renderComponent(); - - const logoContainer = screen.getByTestId( - 'portainerSidebar-homeImage' - ).parentElement; - expect(logoContainer).not.toHaveClass('justify-center'); - }); - - it('should toggle sidebar when toggle button is clicked', async () => { - const user = userEvent.setup(); - const mockToggle = vi.fn(); - renderComponent({}, { isOpen: true, toggle: mockToggle }); - - const toggleButton = screen.getByRole('button', { name: 'Toggle Sidebar' }); - await user.click(toggleButton); - - expect(mockToggle).toHaveBeenCalledTimes(1); - }); - - it('should show chevron left icon when sidebar is open', () => { - renderComponent(); - - const toggleButton = screen.getByRole('button', { name: 'Toggle Sidebar' }); - expect(toggleButton).toBeInTheDocument(); - }); - - it('should show chevron right icon when sidebar is closed', () => { - renderComponent({}, { isOpen: false, toggle: vi.fn() }); - - const toggleButton = screen.getByRole('button', { name: 'Toggle Sidebar' }); - expect(toggleButton).toBeInTheDocument(); - }); - - it('should use small logo when sidebar is closed', () => { - renderComponent({}, { isOpen: false, toggle: vi.fn() }); - - const logo = screen.getByAltText('Logo'); - expect(logo).toHaveAttribute( - 'src', - expect.stringContaining('logomark-CE.svg') - ); - }); - - it('should apply max-height class to logo when sidebar is closed', () => { - renderComponent({}, { isOpen: false, toggle: vi.fn() }); - - const logo = screen.getByAltText('Logo'); - expect(logo).toHaveClass('!max-h-[27px]'); - }); - - it('should not apply max-height class to logo when sidebar is open', () => { - renderComponent(); - - const logo = screen.getByAltText('Logo'); - expect(logo).not.toHaveClass('!max-h-[27px]'); - }); -}); diff --git a/app/react/sidebar/Header.tsx b/app/react/sidebar/Header.tsx index 4a4a5036c..60b24b883 100644 --- a/app/react/sidebar/Header.tsx +++ b/app/react/sidebar/Header.tsx @@ -2,13 +2,12 @@ import { ChevronsLeft, ChevronsRight } from 'lucide-react'; import clsx from 'clsx'; import { isBE } from '@/react/portainer/feature-flags/feature-flags.service'; +import smallLogo from '@/assets/ico/logomark.svg'; import { Link } from '@@/Link'; import fullLogoBE from './portainer_logo-BE.svg'; import fullLogoCE from './portainer_logo-CE.svg'; -import smallLogoBE from './logomark-BE.svg'; -import smallLogoCE from './logomark-CE.svg'; import { useSidebarState } from './useSidebarState'; import styles from './Header.module.css'; @@ -21,11 +20,7 @@ export function Header({ logo: customLogo }: Props) { return (
-
+
); diff --git a/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShell.module.css b/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShell.module.css new file mode 100644 index 000000000..ae491fa46 --- /dev/null +++ b/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShell.module.css @@ -0,0 +1,47 @@ +.root { + position: fixed; + background: #000; + bottom: 0; + left: 0; + width: 100vw; + z-index: 1000; + height: 495px; + border-top-left-radius: 8px; + border-top-right-radius: 8px; +} + +.root.minimized { + height: 35px; + border-top-left-radius: 8px; + border-top-right-radius: 8px; +} + +.header { + height: 35px; + border-top-left-radius: 8px; + border-top-right-radius: 8px; + display: flex; + justify-content: space-between; + align-items: center; + color: #424242; + background: rgb(245, 245, 245); + border-top: 1px solid rgb(190, 190, 190); + + padding: 0 16px; +} + +.title { + font-weight: 500; + font-size: 14px; +} + +.actions button { + padding: 0; + border: 0; +} + +.terminal-container .loading-message { + position: fixed; + padding: 10px 16px 0px 16px; + color: #fff; +} diff --git a/app/react/kubernetes/cluster/KubectlShell/KubectlShellView.tsx b/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShell.tsx similarity index 52% rename from app/react/kubernetes/cluster/KubectlShell/KubectlShellView.tsx rename to app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShell.tsx index 521d873ea..ac609983e 100644 --- a/app/react/kubernetes/cluster/KubectlShell/KubectlShellView.tsx +++ b/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShell.tsx @@ -1,39 +1,56 @@ import { Terminal } from 'xterm'; import { fit } from 'xterm/lib/addons/fit/fit'; import { useCallback, useEffect, useRef, useState } from 'react'; +import clsx from 'clsx'; +import { RotateCw, X, Terminal as TerminalIcon } from 'lucide-react'; -import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; import { baseHref } from '@/portainer/helpers/pathHelper'; -import { terminalClose } from '@/portainer/services/terminal-window'; +import { + terminalClose, + terminalResize, +} from '@/portainer/services/terminal-window'; import { EnvironmentId } from '@/react/portainer/environments/types'; import { error as notifyError } from '@/portainer/services/notifications'; -import { Alert } from '@@/Alert'; +import { Icon } from '@@/Icon'; import { Button } from '@@/buttons'; -type Socket = WebSocket | null; -type ShellState = 'loading' | 'connected' | 'disconnected'; +import styles from './KubectlShell.module.css'; -export function KubectlShellView() { - const environmentId = useEnvironmentId(); +interface ShellState { + socket: WebSocket | null; + minimized: boolean; +} + +interface Props { + environmentId: EnvironmentId; + onClose(): void; +} + +export function KubeCtlShell({ environmentId, onClose }: Props) { const [terminal] = useState(new Terminal()); - const [socket, setSocket] = useState(null); - const [shellState, setShellState] = useState('loading'); + const [shell, setShell] = useState({ + socket: null, + minimized: false, + }); + + const { socket } = shell; const terminalElem = useRef(null); - const closeTerminal = useCallback(() => { + const handleClose = useCallback(() => { terminalClose(); // only css trick socket?.close(); terminal.dispose(); - setShellState('disconnected'); - }, [terminal, socket]); + onClose(); + }, [onClose, terminal, socket]); const openTerminal = useCallback(() => { if (!terminalElem.current) { return; } + terminal.open(terminalElem.current); terminal.setOption('cursorBlink', true); terminal.focus(); @@ -41,11 +58,6 @@ export function KubectlShellView() { terminal.writeln('#Run kubectl commands inside here'); terminal.writeln('#e.g. kubectl get all'); terminal.writeln(''); - setShellState('connected'); - }, [terminal]); - - const resizeTerminal = useCallback(() => { - fit(terminal); }, [terminal]); // refresh socket listeners on socket updates @@ -61,10 +73,10 @@ export function KubectlShellView() { terminal.writeUtf8(encoded); } function onClose() { - closeTerminal(); + handleClose(); } function onError(e: Event) { - closeTerminal(); + handleClose(); if (socket?.readyState !== WebSocket.CLOSED) { notifyError( 'Failure', @@ -85,63 +97,89 @@ export function KubectlShellView() { socket.removeEventListener('close', onClose); socket.removeEventListener('error', onError); }; - }, [closeTerminal, openTerminal, socket, terminal]); + }, [handleClose, openTerminal, socket, terminal]); // on component load/destroy useEffect(() => { const socket = new WebSocket(buildUrl(environmentId)); - setSocket(socket); - setShellState('loading'); + setShell((shell) => ({ ...shell, socket })); terminal.onData((data) => socket.send(data)); terminal.onKey(({ domEvent }) => { if (domEvent.ctrlKey && domEvent.code === 'KeyD') { close(); - setShellState('disconnected'); } }); - window.addEventListener('resize', resizeTerminal); + window.addEventListener('resize', () => terminalResize()); function close() { socket.close(); terminal.dispose(); - window.removeEventListener('resize', resizeTerminal); + window.removeEventListener('resize', terminalResize); } return close; - }, [environmentId, terminal, resizeTerminal]); + }, [environmentId, terminal]); return ( -
- {shellState === 'loading' && ( -
Loading Terminal...
- )} - {shellState === 'disconnected' && ( -
- -
- - -
-
+
+
+
+ + kubectl shell
- )} -
+
+ + + +
+
+ +
+
Loading Terminal...
+
); + function clearScreen() { + terminal.clear(); + } + + function toggleMinimize() { + if (shell.minimized) { + terminalResize(); + setShell((shell) => ({ ...shell, minimized: false })); + } else { + terminalClose(); + setShell((shell) => ({ ...shell, minimized: true })); + } + } + function buildUrl(environmentId: EnvironmentId) { const params = { endpointId: environmentId, diff --git a/app/react/sidebar/KubernetesSidebar/KubectlShellButton.tsx b/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShellButton.tsx similarity index 69% rename from app/react/sidebar/KubernetesSidebar/KubectlShellButton.tsx rename to app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShellButton.tsx index 1745c6a3e..0d08a03c8 100644 --- a/app/react/sidebar/KubernetesSidebar/KubectlShellButton.tsx +++ b/app/react/sidebar/KubernetesSidebar/KubectlShell/KubectlShellButton.tsx @@ -1,27 +1,32 @@ +import { useState } from 'react'; +import { createPortal } from 'react-dom'; import { Terminal } from 'lucide-react'; import clsx from 'clsx'; -import { v4 as uuidv4 } from 'uuid'; import { EnvironmentId } from '@/react/portainer/environments/types'; import { useAnalytics } from '@/react/hooks/useAnalytics'; -import { baseHref } from '@/portainer/helpers/pathHelper'; import { Button } from '@@/buttons'; -import { useSidebarState } from '../useSidebarState'; -import { SidebarTooltip } from '../SidebarItem/SidebarTooltip'; +import { useSidebarState } from '../../useSidebarState'; +import { SidebarTooltip } from '../../SidebarItem/SidebarTooltip'; + +import { KubeCtlShell } from './KubectlShell'; interface Props { environmentId: EnvironmentId; } export function KubectlShellButton({ environmentId }: Props) { const { isOpen: isSidebarOpen } = useSidebarState(); + + const [open, setOpen] = useState(false); const { trackEvent } = useAnalytics(); const button = (