Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix(serviceaccount): delete role mappings when a service account is deleted (#13266)

Vikrant Gupta0376eec24fbf
diff --git a/pkg/modules/serviceaccount/implserviceaccount/module.go b/pkg/modules/serviceaccount/implserviceaccount/module.go
index 111e7cf1df..39b947e44b 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/module.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/module.go
@@ -176,7 +176,11 @@ func (module *module) Delete(ctx context.Context, orgID valuer.UUID, id valuer.U
return err
}
- // update the status but do not delete the role mappings as we will use them for audits
+ err = module.store.DeleteServiceAccountRolesByServiceAccountID(ctx, id)
+ if err != nil {
+ return err
+ }
+
err = module.store.Update(ctx, orgID, serviceAccount.ServiceAccount)
if err != nil {
return err
diff --git a/pkg/modules/serviceaccount/implserviceaccount/store.go b/pkg/modules/serviceaccount/implserviceaccount/store.go
index 71aadb8bca..bf65352c16 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/store.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/store.go
@@ -243,6 +243,21 @@ func (store *store) DeleteServiceAccountRole(ctx context.Context, serviceAccount
return nil
}
+func (store *store) DeleteServiceAccountRolesByServiceAccountID(ctx context.Context, serviceAccountID valuer.UUID) error {
+ _, err := store.
+ sqlstore.
+ BunDBCtx(ctx).
+ NewDelete().
+ Model(new(serviceaccounttypes.ServiceAccountRole)).
+ Where("service_account_id = ?", serviceAccountID).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
func (store *store) CreateFactorAPIKey(ctx context.Context, storable *serviceaccounttypes.FactorAPIKey) error {
_, err := store.
sqlstore.
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index dc63364adf..758c591d5e 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -265,6 +265,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewBackfillTelegramChannelSpecFactory(),
sqlmigration.NewAddMetricsFieldTuplesFactory(sqlstore),
sqlmigration.NewAddGCPConnectionMethodFactory(),
+ sqlmigration.NewDeleteOrphanSARolesFactory(),
)
}
diff --git a/pkg/sqlmigration/139_delete_orphan_sa_roles.go b/pkg/sqlmigration/139_delete_orphan_sa_roles.go
new file mode 100644
index 0000000000..dce11c0540
--- /dev/null
+++ b/pkg/sqlmigration/139_delete_orphan_sa_roles.go
@@ -0,0 +1,74 @@
+package sqlmigration
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/migrate"
+)
+
+type deleteOrphanSARoles struct{}
+
+type serviceAccount139 struct {
+ bun.BaseModel `bun:"table:service_account"`
+
+ ID string `bun:"id,pk"`
+ Status string `bun:"status"`
+}
+
+type serviceAccountRole139 struct {
+ bun.BaseModel `bun:"table:service_account_role"`
+
+ ServiceAccountID string `bun:"service_account_id"`
+}
+
+func NewDeleteOrphanSARolesFactory() factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(
+ factory.MustNewName("delete_orphan_sa_roles"),
+ func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &deleteOrphanSARoles{}, nil
+ },
+ )
+}
+
+func (migration *deleteOrphanSARoles) Register(migrations *migrate.Migrations) error {
+ return migrations.Register(migration.Up, migration.Down)
+}
+
+func (migration *deleteOrphanSARoles) Up(ctx context.Context, db *bun.DB) error {
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ var deletedServiceAccountIDs []string
+ err = tx.NewSelect().
+ Model(new(serviceAccount139)).
+ Column("id").
+ Where("status = ?", "deleted").
+ Scan(ctx, &deletedServiceAccountIDs)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ if len(deletedServiceAccountIDs) > 0 {
+ _, err = tx.NewDelete().
+ Model(new(serviceAccountRole139)).
+ Where("service_account_id IN (?)", bun.In(deletedServiceAccountIDs)).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+ }
+
+ return tx.Commit()
+}
+
+func (migration *deleteOrphanSARoles) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/types/serviceaccounttypes/service_acccount.go b/pkg/types/serviceaccounttypes/service_acccount.go
index 5809d64af1..8d262342e2 100644
--- a/pkg/types/serviceaccounttypes/service_acccount.go
+++ b/pkg/types/serviceaccounttypes/service_acccount.go
@@ -269,6 +269,7 @@ type Store interface {
CreateServiceAccountRole(context.Context, *ServiceAccountRole) error
GetServiceAccountRoleByOrgIDAndID(context.Context, valuer.UUID, valuer.UUID) (*ServiceAccountRole, error)
DeleteServiceAccountRole(context.Context, valuer.UUID, valuer.UUID) error
+ DeleteServiceAccountRolesByServiceAccountID(context.Context, valuer.UUID) error
// Service Account Factor API Key
CreateFactorAPIKey(context.Context, *FactorAPIKey) error
diff --git a/tests/integration/tests/role/02_crud.py b/tests/integration/tests/role/02_crud.py
index 8543ab0e25..fee1eb429c 100644
--- a/tests/integration/tests/role/02_crud.py
+++ b/tests/integration/tests/role/02_crud.py
@@ -13,6 +13,7 @@ from fixtures.auth import (
find_user_by_email,
)
from fixtures.role import find_role_by_name, flatten_transaction_groups, transaction_group
+from fixtures.serviceaccount import create_service_account, delete_service_account
CRUD_ROLE_NAME = "crud-test-role"
CRUD_ASSIGNEE_ROLE_NAME = "crud-assignee-role"
@@ -301,6 +302,24 @@ def test_delete_role_after_deleting_assigned_user(
assert resp.status_code == HTTPStatus.NO_CONTENT, f"delete role after deleting its only assignee: {resp.text}"
+def test_delete_role_after_deleting_assigned_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ create_role: Callable[..., str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ role_id = create_role(admin_token, "crud-deleted-sa-assignee-role", [transaction_group("read", "metaresource", "dashboard", ["*"])])
+
+ service_account_id = create_service_account(signoz, admin_token, "crud-deleted-sa-assignee", role="crud-deleted-sa-assignee-role")
+
+ delete_service_account(signoz, admin_token, service_account_id)
+
+ resp = requests.delete(signoz.self.host_configs["8080"].get(f"/api/v1/roles/{role_id}"), headers={"Authorization": f"Bearer {admin_token}"}, timeout=5)
+ assert resp.status_code == HTTPStatus.NO_CONTENT, f"delete role after deleting its only service account assignee: {resp.text}"
+
+
def test_delete_removes_role(
signoz: types.SigNoz,
create_user_admin: types.Operation, # pylint: disable=unused-argument