Skip to content

Commit ce6deb5

Browse files
authored
feat(store): role delete keeps the row and refuses while a live policy uses it (#1964)
1 parent bb329ac commit ce6deb5

5 files changed

Lines changed: 154 additions & 19 deletions

File tree

‎core/role/service.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -299,16 +299,16 @@ func (s Service) Delete(ctx context.Context, id string) error {
299299
return err
300300
}
301301

302-
// Delete the row first. The policies.role_id foreign key rejects this while
303-
// any policy still references the role, surfaced as ErrRoleInUse — so a role that
304-
// is still in use is left fully intact (no SpiceDB tuples are touched below).
302+
// Mark the row deleted first. The repository refuses with ErrRoleInUse while
303+
// any live policy still references the role, so a role that is still in use
304+
// is left fully intact (no SpiceDB tuples are touched below).
305305
// This is intentionally a guard, not a cascade: removing a role would revoke
306306
// access for everyone granted it, so the caller must drop those policies first.
307307
if err := s.repository.Delete(ctx, roleToDelete.ID); err != nil {
308308
return err
309309
}
310310

311-
// row is gone → remove the role's permission tuples (app/role:<id>#<perm>@...)
311+
// row is marked deleted → remove the role's permission tuples (app/role:<id>#<perm>@...)
312312
return s.relationService.Delete(ctx, relation.Relation{Object: relation.Object{
313313
ID: roleToDelete.ID,
314314
Namespace: schema.RoleNamespace,

‎core/role/service_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ func Test_Delete(t *testing.T) {
7979

8080
mockID := uuid.New().String()
8181
mockRepository.On("Get", mock.Anything, mockID).Return(role.Role{ID: "role-1"}, nil).Once()
82-
// the policies.role_id FK rejects the row delete -> ErrRoleInUse
82+
// a live policy still references the role -> ErrRoleInUse
8383
mockRepository.On("Delete", mock.Anything, "role-1").Return(role.ErrRoleInUse).Once()
8484

8585
svc := role.NewService(mockRepository, mockRelationSvc, mockPermissionSvc, mockAuditRecordRepo, nil)

‎internal/store/postgres/role_repository.go‎

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package postgres
22

33
import (
44
"context"
5+
"database/sql"
56
"encoding/json"
67
"errors"
78
"fmt"
@@ -14,9 +15,9 @@ import (
1415

1516
"github.com/google/uuid"
1617

17-
"database/sql"
18-
1918
"github.com/doug-martin/goqu/v9"
19+
"github.com/doug-martin/goqu/v9/exp"
20+
"github.com/jmoiron/sqlx"
2021
"github.com/raystack/frontier/core/namespace"
2122
"github.com/raystack/frontier/core/role"
2223
"github.com/raystack/frontier/pkg/db"
@@ -259,27 +260,62 @@ func (r RoleRepository) Update(ctx context.Context, rl role.Role) (role.Role, er
259260
}
260261

261262
func (r RoleRepository) Delete(ctx context.Context, id string) error {
262-
query, params, err := dialect.Delete(TABLE_ROLES).Where(
263-
goqu.Ex{
264-
"id": id,
265-
},
266-
).Returning(&Role{}).ToSQL()
263+
lockQuery, lockParams, err := fromLive(TABLE_ROLES).
264+
Select("id").
265+
Where(goqu.Ex{"id": id}).
266+
ForUpdate(exp.Wait).
267+
ToSQL()
267268
if err != nil {
268269
return fmt.Errorf("%w: %s", errQuery, err)
269270
}
270271

271-
var roleModel Role
272-
if err = r.dbc.WithTimeout(ctx, TABLE_ROLES, "Delete", func(ctx context.Context) error {
273-
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&roleModel)
272+
livePolicy := fromLive(TABLE_POLICIES).
273+
Select(goqu.L("1")).
274+
Where(goqu.I(TABLE_POLICIES + ".role_id").Eq(goqu.I(TABLE_ROLES + ".id")))
275+
276+
deleteQuery, deleteParams, err := softDelete(TABLE_ROLES).Where(
277+
goqu.Ex{"id": id},
278+
goqu.L("NOT EXISTS ?", livePolicy),
279+
).ToSQL()
280+
if err != nil {
281+
return fmt.Errorf("%w: %s", errQuery, err)
282+
}
283+
284+
// One transaction, two statements. The first locks the live role row the
285+
// way a hard DELETE would. The second marks it deleted, unless a live
286+
// policy still points at it.
287+
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
288+
return r.dbc.WithTimeout(ctx, TABLE_ROLES, "Delete", func(ctx context.Context) error {
289+
// Lock the role row first. A policy insert holds a lock on the role
290+
// row until it commits, so this waits for it and the check below sees that policy.
291+
var lockedID string
292+
if err := tx.QueryRowContext(ctx, lockQuery, lockParams...).Scan(&lockedID); err != nil {
293+
return err
294+
}
295+
296+
result, err := tx.ExecContext(ctx, deleteQuery, deleteParams...)
297+
if err != nil {
298+
return err
299+
}
300+
deleted, err := result.RowsAffected()
301+
if err != nil {
302+
return err
303+
}
304+
if deleted == 0 {
305+
return role.ErrRoleInUse
306+
}
307+
return nil
308+
})
274309
}); err != nil {
310+
// WithTxn wraps every error it rolled back on as "rollback: ...". Here
311+
// the rollback is the normal path, so return the plain sentinel.
312+
if errors.Is(err, role.ErrRoleInUse) {
313+
return role.ErrRoleInUse
314+
}
275315
err = checkPostgresError(err)
276316
switch {
277317
case errors.Is(err, sql.ErrNoRows):
278318
return role.ErrNotExist
279-
case errors.Is(err, ErrForeignKeyViolation):
280-
// policies.role_id references roles(id) with no ON DELETE rule, so a
281-
// role still bound to any policy cannot be deleted.
282-
return role.ErrRoleInUse
283319
default:
284320
return err
285321
}

‎internal/store/postgres/role_repository_test.go‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"fmt"
77
"testing"
8+
"time"
89

910
"github.com/raystack/frontier/internal/bootstrap/schema"
1011

@@ -422,6 +423,71 @@ func (s *RoleRepositoryTestSuite) TestDelete() {
422423
}
423424
})
424425
}
426+
427+
s.Run("should keep the row and mark it deleted", func() {
428+
target := s.roles[1]
429+
s.Require().NoError(s.repository.Delete(s.ctx, target.ID))
430+
431+
var deleted bool
432+
err := s.client.QueryRowxContext(s.ctx, "SELECT deleted_at IS NOT NULL FROM roles WHERE id = $1", target.ID).Scan(&deleted)
433+
s.Require().NoError(err)
434+
s.Assert().True(deleted)
435+
})
436+
437+
s.Run("should return not found when the role is already deleted", func() {
438+
target := s.roles[2]
439+
_, err := s.client.ExecContext(s.ctx, "UPDATE roles SET deleted_at = now() WHERE id = $1", target.ID)
440+
s.Require().NoError(err)
441+
442+
s.Assert().ErrorIs(s.repository.Delete(s.ctx, target.ID), role.ErrNotExist)
443+
})
444+
445+
s.Run("should return in use and keep the role when a live policy uses it", func() {
446+
target := s.roles[3]
447+
_, err := bootstrapPolicy(s.client, s.orgID, target, uuid.NewString())
448+
s.Require().NoError(err)
449+
450+
s.Assert().ErrorIs(s.repository.Delete(s.ctx, target.ID), role.ErrRoleInUse)
451+
_, err = s.repository.Get(s.ctx, target.ID)
452+
s.Assert().NoError(err)
453+
})
454+
455+
s.Run("should delete the role when only deleted policies use it", func() {
456+
target := s.roles[4]
457+
_, err := bootstrapPolicy(s.client, s.orgID, target, uuid.NewString())
458+
s.Require().NoError(err)
459+
_, err = s.client.ExecContext(s.ctx, "UPDATE policies SET deleted_at = now() WHERE role_id = $1", target.ID)
460+
s.Require().NoError(err)
461+
462+
s.Assert().NoError(s.repository.Delete(s.ctx, target.ID))
463+
})
464+
465+
s.Run("should wait for a policy insert that has not committed and return in use", func() {
466+
target, err := s.repository.Upsert(s.ctx, role.Role{
467+
Name: "role with a running policy insert",
468+
OrgID: s.orgID,
469+
Metadata: metadata.Metadata{},
470+
})
471+
s.Require().NoError(err)
472+
tx, err := s.client.BeginTxx(s.ctx, nil)
473+
s.Require().NoError(err)
474+
defer tx.Rollback() // nolint
475+
_, err = tx.ExecContext(s.ctx, "INSERT INTO policies (role_id, resource_id, resource_type, principal_id, principal_type) VALUES ($1, $2, 'ns1', $3, 'app/user')",
476+
target.ID, s.orgID, uuid.NewString())
477+
s.Require().NoError(err)
478+
479+
done := make(chan error, 1)
480+
go func() { done <- s.repository.Delete(s.ctx, target.ID) }()
481+
482+
s.Require().Eventually(func() bool {
483+
var waiting int
484+
err := s.client.QueryRowxContext(s.ctx, "SELECT count(*) FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock'").Scan(&waiting)
485+
return err == nil && waiting == 1
486+
}, time.Second, 10*time.Millisecond, "the delete did not wait for the policy insert")
487+
488+
s.Require().NoError(tx.Commit())
489+
s.Assert().ErrorIs(<-done, role.ErrRoleInUse)
490+
})
425491
}
426492

427493
func (s *RoleRepositoryTestSuite) TestGetByName() {

‎test/e2e/regression/api_test.go‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3092,6 +3092,39 @@ func (s *APIRegressionTestSuite) TestOrganizationRoleDeleteInUse() {
30923092

30933093
// after a successful delete, no role->permission tuples should linger
30943094
s.Assert().False(roleHasPermTuples())
3095+
3096+
// the deleted role is hidden from reads and cannot be deleted twice
3097+
_, err = s.testBench.Client.GetOrganizationRole(ctxOrgAdminAuth, connect.NewRequest(&frontierv1beta1.GetOrganizationRoleRequest{
3098+
OrgId: orgID,
3099+
Id: roleID,
3100+
}))
3101+
s.Require().Error(err)
3102+
s.Assert().Equal(connect.CodeNotFound, connect.CodeOf(err))
3103+
_, err = s.testBench.Client.DeleteOrganizationRole(ctxOrgAdminAuth, connect.NewRequest(&frontierv1beta1.DeleteOrganizationRoleRequest{
3104+
OrgId: orgID,
3105+
Id: roleID,
3106+
}))
3107+
s.Require().Error(err)
3108+
s.Assert().Equal(connect.CodeNotFound, connect.CodeOf(err))
3109+
3110+
// the name is free again and lands on a new row
3111+
recreateResp, err := s.testBench.Client.CreateOrganizationRole(ctxOrgAdminAuth, connect.NewRequest(&frontierv1beta1.CreateOrganizationRoleRequest{
3112+
OrgId: orgID,
3113+
Body: &frontierv1beta1.RoleRequestBody{
3114+
Title: "in use role",
3115+
Name: "in_use_role",
3116+
Scopes: []string{"app/organization"},
3117+
Permissions: []string{"app.organization.grouplist"},
3118+
},
3119+
}))
3120+
s.Require().NoError(err)
3121+
s.Assert().NotEqual(roleID, recreateResp.Msg.GetRole().GetId())
3122+
3123+
// the org now holds a live role and a deleted one; the delete still goes through
3124+
_, err = s.testBench.Client.DeleteOrganization(ctxOrgAdminAuth, connect.NewRequest(&frontierv1beta1.DeleteOrganizationRequest{
3125+
Id: orgID,
3126+
}))
3127+
s.Require().NoError(err)
30953128
}
30963129

30973130
func TestEndToEndAPIRegressionTestSuite(t *testing.T) {

0 commit comments

Comments
 (0)