Skip to content

K8SPSMDB-1537: connection string secrets#2397

Open
pooknull wants to merge 15 commits into
mainfrom
K8SPSMDB-1537
Open

K8SPSMDB-1537: connection string secrets#2397
pooknull wants to merge 15 commits into
mainfrom
K8SPSMDB-1537

Conversation

@pooknull

@pooknull pooknull commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

https://perconadev.atlassian.net/browse/K8SPSMDB-1537

CHANGE DESCRIPTION

This PR creates the following secrets:

  • <cluster>-databaseadmin-conn-str for the databaseAdmin user
  • <custom-user-secret-name>-conn-str for each non-external custom user

<cluster>-databaseadmin-conn-str can contain:

  • <user>_<replset>_connectionString: mongodb:// URI using internal replica-set addresses.
  • <user>_<replset>_connectionStringSrv: mongodb+srv:// URI using the replica-set service hostname.
  • <user>_<replset>_connectionStringExposed: created when the replica set is exposed and its exposed URI differs from its internal URI.
  • <user>_mongos_connectionString: created for sharded clusters using internal mongos addresses.
  • <user>_mongos_connectionStringExposed: created for sharded clusters when mongos servicePerPod is enabled.

<replset> keys are generated for every replica set, including the cfg replset

<custom-user-secret-name>-conn-str can contain:

For non-sharded clusters:

  • <user>_<replset>_connectionString
  • <user>_<replset>_connectionStringSrv
  • <user>_<replset>_connectionStringExposed, when applicable

For sharded clusters:

  • <user>_mongos_connectionString
  • <user>_mongos_connectionStringExposed, when mongos servicePerPod is enabled

CHECKLIST

Jira

  • Is the Jira ticket created and referenced properly?
  • Does the Jira ticket have the proper statuses for documentation (Needs Doc) and QA (Needs QA)?
  • Does the Jira ticket link to the proper milestone (Fix Version field)?

Tests

  • Is an E2E test/test case added for the new feature/change?
  • Are unit tests added where appropriate?
  • Are OpenShift compare files changed for E2E tests (compare/*-oc.yml)?

Config/Logging/Testability

  • Are all needed new/changed options added to default YAML files?
  • Are all needed new/changed options added to the Helm Chart?
  • Did we add proper logging messages for operator actions?
  • Did we ensure compatibility with the previous version or cluster upgrade process?
  • Does the change support oldest and newest supported MongoDB version?
  • Does the change support oldest and newest supported Kubernetes version?

Copilot AI review requested due to automatic review settings June 11, 2026 09:10
@pull-request-size pull-request-size Bot added the size/XXL 1000+ lines label Jun 11, 2026
@github-actions github-actions Bot added the tests label Jun 11, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds support for generating and maintaining Kubernetes Secrets containing MongoDB connection strings (standard and SRV) for the database admin user and for custom users, alongside some naming/URI-building refactors to support this.

Changes:

  • Introduces reconciliation logic to create/update per-user “connection string” Secrets (system databaseAdmin + custom users) and extends E2E coverage to validate the secrets work.
  • Refactors Mongo client configuration to support authSource and to generate mongodb:// and mongodb+srv:// URIs from a shared config object.
  • Centralizes Service/Secret naming helpers and updates service discovery to accommodate mongos “service-per-pod” addressing.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
pkg/psmdb/service.go Uses naming helpers, adjusts mongos address lookup signature, minor refactors.
pkg/psmdb/mongo/mongo.go Adds URI/SRVURI builders and Config.Options(); refactors Dial to use Options().
pkg/psmdb/client.go Splits config building from dialing; adds AuthSource plumbing and MongosConfig/MongoConfig helpers.
pkg/psmdb/client_test.go Adds unit tests validating URI/SRVURI generation across DNS modes and mongos exposure modes.
pkg/naming/service.go Adds service naming helper functions for replsets and mongos services.
pkg/naming/secret.go Adds naming functions for new connection-string Secrets.
pkg/controller/perconaservermongodb/users.go Ensures database admin connection string Secret is created during user reconciliation.
pkg/controller/perconaservermongodb/status.go Updates mongos address lookup to pass service-per-pod mode.
pkg/controller/perconaservermongodb/service.go Uses naming helpers for mongos service creation/removal.
pkg/controller/perconaservermongodb/secrets.go Refactors credential lookup; adds ensureConnectionStringSecret() helper for conn-str Secrets.
pkg/controller/perconaservermongodb/secrets_test.go Adds unit tests for ensureConnectionStringSecret() and reconcileUsers conn-str behavior.
pkg/controller/perconaservermongodb/custom_users.go Creates per-custom-user connection string Secret (non-external users).
pkg/apis/psmdb/v1/psmdb_types.go Adds role→secret-key mapping helpers for system user creds.
e2e-tests/custom-users-roles-sharded/run Extends E2E to verify generated connection strings authenticate successfully.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/naming/secret.go
Comment thread pkg/psmdb/mongo/mongo.go
Comment thread pkg/controller/perconaservermongodb/secrets.go
Copilot AI review requested due to automatic review settings June 11, 2026 14:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 5 comments.

Comment thread pkg/psmdb/mongo/mongo.go Outdated
Comment thread pkg/naming/secret.go
Comment thread pkg/controller/perconaservermongodb/secrets.go
Comment thread pkg/controller/perconaservermongodb/secrets.go Outdated
Comment thread pkg/controller/perconaservermongodb/users.go
Copilot AI review requested due to automatic review settings June 12, 2026 11:30
@pooknull pooknull marked this pull request as ready for review June 12, 2026 11:31
@pooknull pooknull requested a review from jvpasinatto as a code owner June 12, 2026 11:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 3 comments.

Comment thread pkg/controller/perconaservermongodb/users.go
Comment on lines +99 to +106
if rs.Expose.Enabled {
cfg, err := psmdb.MongoConfig(ctx, cl, cr, rs, cred, true)
if err != nil {
return errors.Wrap(err, "mongo config")
}
if exposedConnStr := cfg.URI(); exposedConnStr != connStr {
connStrSecret.Data[key+"_connectionStringExposed"] = []byte(exposedConnStr)
}
Comment thread pkg/psmdb/mongo/mongo.go
egegunes
egegunes previously approved these changes Jun 15, 2026
@egegunes egegunes added this to the v1.23.0 milestone Jun 15, 2026
}

_, err := controllerutil.CreateOrUpdate(ctx, cl, connStrSecret, func() error {
connStrSecret.Data = make(map[string][]byte)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're resetting the data here, doesn't it mean that in case of custom users, only the last one in the list is present in the secret, and all others before it get wiped out? Did you test it? I think the e2e test does not assert anything about the prev users in the Secret no?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread pkg/naming/secret.go

func SecretCustomUserConnStrName(cr *api.PerconaServerMongoDB, user *api.User) string {
return user.SecretName(cr) + "-conn-str"
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we have several custom users and don't use for them passwordSecretRef
in my-cluster-name-custom-user-secret-conn-str we keep only last user.

  users:
  - name: alice
    db: admin
    roles:
      - name: clusterAdmin
        db: admin
      - name: userAdminAnyDatabase
        db: admin
  - name: bob
    db: admin
    roles:
      - name: read
        db: admin
 kubectl get secret my-cluster-name-custom-user-secret-conn-str \
  -o jsonpath='{.data}' | python3 -c \
  "import sys,json; [print(k) for k in json.load(sys.stdin).keys()]"
bob_mongos_connectionString

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gkech

gkech commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

I think that @nmarukovich and @mayankshah1607 comments underline the same issue because If we reset Data, only the last user is kept

Copilot AI review requested due to automatic review settings June 18, 2026 14:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 2 comments.

Comment thread pkg/psmdb/service.go
Comment on lines +261 to 263
func GetMongosAddrs(ctx context.Context, cl client.Client, cr *api.PerconaServerMongoDB, useInternalAddr bool, servicePerPod bool) ([]string, error) {
if !servicePerPod {
host, err := MongosHost(ctx, cl, cr, nil, useInternalAddr)
Comment on lines +184 to +188
mongosCfg, err := psmdb.MongosConfig(ctx, cl, cr, cred, true, servicePerPod)
if err != nil {
return errors.Wrap(err, "mongos config")
}
data[keyPrefix+"_mongos_connectionString"] = []byte(mongosCfg.URI())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pooknull could you please check this comment

Copilot AI review requested due to automatic review settings June 18, 2026 18:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 5 comments.

Comment thread pkg/controller/perconaservermongodb/users.go
Comment on lines +38 to 46
func getCredentials(secret *corev1.Secret, role api.SystemUserRole) (psmdb.Credentials, error) {
creds := psmdb.Credentials{}
usersSecret, err := getUserSecret(ctx, cl, cr, name)
if err != nil {
return creds, errors.Wrap(err, "failed to get user secret")
}

switch role {
case api.RoleDatabaseAdmin:
creds.Username = string(usersSecret.Data[api.EnvMongoDBDatabaseAdminUser])
creds.Password = string(usersSecret.Data[api.EnvMongoDBDatabaseAdminPassword])
case api.RoleClusterAdmin:
creds.Username = string(usersSecret.Data[api.EnvMongoDBClusterAdminUser])
creds.Password = string(usersSecret.Data[api.EnvMongoDBClusterAdminPassword])
case api.RoleUserAdmin:
creds.Username = string(usersSecret.Data[api.EnvMongoDBUserAdminUser])
creds.Password = string(usersSecret.Data[api.EnvMongoDBUserAdminPassword])
case api.RoleClusterMonitor:
creds.Username = string(usersSecret.Data[api.EnvMongoDBClusterMonitorUser])
creds.Password = string(usersSecret.Data[api.EnvMongoDBClusterMonitorPassword])
case api.RoleBackup:
creds.Username = string(usersSecret.Data[api.EnvMongoDBBackupUser])
creds.Password = string(usersSecret.Data[api.EnvMongoDBBackupPassword])
case api.RoleSearch:
creds.Username = string(usersSecret.Data[api.EnvMongoDBSearchUser])
creds.Password = string(usersSecret.Data[api.EnvMongoDBSearchPassword])
default:
return creds, errors.Errorf("not implemented for role: %s", role)
envKeyUser, envKeyPass := role.EnvKeyUsername(), role.EnvKeyPassword()
if envKeyUser == "" || envKeyPass == "" {
return creds, errors.Errorf("invalid role %s", string(role))
}
creds.Username = string(secret.Data[envKeyUser])
creds.Password = string(secret.Data[envKeyPass])

Comment thread pkg/controller/perconaservermongodb/custom_users.go
Comment thread pkg/psmdb/mongo/mongo.go
Comment thread pkg/psmdb/service.go
Comment on lines +342 to 348
svcName := naming.MongosServiceName(cr)
if cr.Spec.Sharding.Mongos.Expose.ServicePerPod {
if pod == nil {
return "", errors.New("mongos pod is required for service-per-pod exposure")
}
svcName = pod.Name
}
gkech
gkech previously approved these changes Jun 22, 2026
Copilot AI review requested due to automatic review settings June 22, 2026 11:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 4 comments.

Comment thread pkg/controller/perconaservermongodb/secrets.go
Comment thread pkg/controller/perconaservermongodb/secrets.go
Comment thread pkg/controller/perconaservermongodb/secrets.go
Comment on lines +154 to +159
if includeReplsets {
for _, rs := range cr.GetAllReplsets() {
cfg, err := psmdb.MongoConfig(ctx, cl, cr, cr.Spec.ClusterServiceDNSMode, rs, cred, false)
if err != nil {
return errors.Wrap(err, "mongo config")
}
@pooknull pooknull requested a review from gkech June 22, 2026 22:27
@JNKPercona

Copy link
Copy Markdown
Collaborator
Test Name Result Time
arbiter passed 00:11:14
balancer passed 00:18:14
cert-management-policy passed 00:08:56
clustersync passed 00:15:14
cross-site-sharded passed 00:18:38
custom-replset-name passed 00:09:51
custom-tls passed 00:14:15
custom-users-roles passed 00:10:16
custom-users-roles-sharded passed 00:12:41
data-at-rest-encryption passed 00:13:09
data-sharded passed 00:21:42
demand-backup passed 00:21:25
demand-backup-eks-credentials-irsa passed 00:00:07
demand-backup-fs passed 00:23:11
demand-backup-if-unhealthy passed 00:08:12
demand-backup-incremental-aws passed 00:11:50
demand-backup-incremental-azure passed 00:11:35
demand-backup-incremental-gcp-native passed 00:12:16
demand-backup-incremental-gcp-s3 passed 00:11:15
demand-backup-incremental-minio passed 00:26:07
demand-backup-incremental-sharded-aws failure 00:17:30
demand-backup-incremental-sharded-azure failure 00:16:18
demand-backup-incremental-sharded-gcp-native failure 00:17:05
demand-backup-incremental-sharded-gcp-s3 failure 00:16:47
demand-backup-incremental-sharded-minio passed 00:27:16
demand-backup-logical-minio-native-tls passed 00:09:38
demand-backup-physical-parallel passed 00:09:10
demand-backup-physical-aws passed 00:12:12
demand-backup-physical-azure passed 00:12:13
demand-backup-physical-gcp-s3 passed 00:14:32
demand-backup-gcs-workload-identity passed 00:00:06
demand-backup-physical-gcp-native passed 00:12:22
demand-backup-physical-minio passed 00:21:42
demand-backup-physical-minio-native passed 00:26:31
demand-backup-physical-minio-native-tls passed 00:19:56
demand-backup-physical-sharded-parallel passed 00:11:08
demand-backup-physical-sharded-aws failure 00:17:49
demand-backup-physical-sharded-azure failure 00:18:01
demand-backup-physical-sharded-gcp-native failure 00:17:04
demand-backup-physical-sharded-minio passed 00:17:08
demand-backup-physical-sharded-minio-native passed 00:17:47
demand-backup-sharded passed 00:25:34
demand-backup-snapshot passed 00:37:56
demand-backup-snapshot-vault passed 00:20:48
disabled-auth passed 00:15:35
expose-sharded passed 00:37:52
finalizer passed 00:10:03
ignore-labels-annotations passed 00:07:50
init-deploy passed 00:13:10
ldap passed 00:09:03
ldap-tls passed 00:12:32
limits passed 00:06:16
liveness passed 00:08:58
mongod-major-upgrade passed 00:13:00
mongod-major-upgrade-sharded passed 00:20:49
monitoring-2-0 passed 00:24:05
monitoring-pmm3 passed 00:45:03
multi-cluster-service passed 00:14:39
multi-storage passed 00:19:05
non-voting-and-hidden passed 00:16:42
one-pod passed 00:07:54
operator-self-healing-chaos passed 00:12:41
pitr passed 00:37:48
pitr-physical passed 01:02:19
pitr-sharded passed 00:22:29
pitr-to-new-cluster passed 00:25:58
pitr-physical-backup-source passed 00:54:55
preinit-updates passed 00:05:07
pvc-auto-resize passed 00:14:22
pvc-resize passed 00:16:11
recover-no-primary passed 00:31:14
replset-overrides passed 00:18:24
replset-remapping passed 00:17:25
replset-remapping-sharded passed 00:17:47
rs-shard-migration passed 00:13:24
scaling passed 00:11:24
scheduled-backup passed 00:18:12
security-context passed 00:07:07
self-healing-chaos passed 00:15:20
service-per-pod passed 00:18:46
serviceless-external-nodes failure 00:03:33
smart-update passed 00:08:07
split-horizon passed 00:13:53
split-horizon-manual-tls passed 00:12:39
stable-resource-version passed 00:04:31
storage passed 00:07:24
tls-issue-cert-manager passed 00:28:34
unsafe-psa passed 00:08:09
upgrade passed 00:10:08
upgrade-consistency passed 00:07:44
upgrade-consistency-sharded-tls passed 00:54:52
upgrade-sharded passed 00:19:34
upgrade-partial-backup passed 00:16:29
users passed 00:17:41
users-vault passed 00:13:25
vector-search passed 00:00:07
vector-search-sharded passed 00:00:07
version-service passed 00:25:44
Summary Value
Tests Run 98/98
Job Duration 03:12:08
Total Test Time 27:33:40

commit: b574baa
image: perconalab/percona-server-mongodb-operator:PR-2397-b574baaaa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants