From f50c4b0c740e9f1ecd41d4062db838a9dcdcdc1a Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 1 Sep 2026 08:51:05 +0400 Subject: [PATCH] Add DeleteOrganizationResources Step 3 of the organization teardown: installations into the organization, the apps it published, and those apps' installations in other organizations. This is the one step that reaches outside the organization. Publishing an app is a commitment that outlives the publisher's own use of it, and deleting the publisher ends it. The organizations that installed those apps get no notice, which is a product question this does not answer. Installations go before apps because DeleteApp refuses while any remain -- that invariant is honoured rather than worked around. The uninstall path is the one UninstallApp already used, tuples included. The installation walk re-lists from the first page after each batch rather than carrying a cursor, because the deletes shrink the collection underneath it. --- charts/apps/Chart.yaml | 4 +- .../apps/templates/authorization-policy.yaml | 31 +++++ charts/apps/values.yaml | 6 + internal/server/organization_teardown.go | 104 +++++++++++++++++ internal/server/server_test.go | 107 ++++++++++++++++++ 5 files changed, 250 insertions(+), 2 deletions(-) create mode 100644 charts/apps/templates/authorization-policy.yaml create mode 100644 internal/server/organization_teardown.go diff --git a/charts/apps/Chart.yaml b/charts/apps/Chart.yaml index 4a32a10..5727b38 100644 --- a/charts/apps/Chart.yaml +++ b/charts/apps/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: apps description: Helm chart for deploying the AppsService gRPC server. type: application -version: 0.1.0 -appVersion: 0.1.0 +version: 0.2.0 +appVersion: 0.2.0 home: https://github.com/agynio/apps sources: - https://github.com/agynio/apps diff --git a/charts/apps/templates/authorization-policy.yaml b/charts/apps/templates/authorization-policy.yaml new file mode 100644 index 0000000..f670f1a --- /dev/null +++ b/charts/apps/templates/authorization-policy.yaml @@ -0,0 +1,31 @@ +{{- if .Values.internalAuthorizationPolicy.enabled }} +{{- $namespace := .Release.Namespace }} +# DeleteOrganizationResources is one step of the organization teardown. It has +# no caller identity to authorize, so who may reach it at all is settled here. +apiVersion: security.istio.io/v1beta1 +kind: AuthorizationPolicy +metadata: + name: {{ .Release.Name }}-internal-apps + labels: + app.kubernetes.io/name: {{ include "service-base.name" . }} + app.kubernetes.io/instance: {{ .Release.Name }} +spec: + selector: + matchLabels: + app.kubernetes.io/name: {{ include "service-base.name" . }} + app.kubernetes.io/instance: {{ .Release.Name }} + action: DENY + rules: + - from: + - source: + notPrincipals: +{{- range .Values.internalAuthorizationPolicy.serviceAccounts }} + - "cluster.local/ns/{{ .namespace | default $namespace }}/sa/{{ .name }}" +{{- end }} + to: + - operation: + methods: + - POST + paths: + - /agynio.api.apps.v1.AppsService/DeleteOrganizationResources +{{- end }} diff --git a/charts/apps/values.yaml b/charts/apps/values.yaml index 14662bc..b2a6f00 100644 --- a/charts/apps/values.yaml +++ b/charts/apps/values.yaml @@ -173,3 +173,9 @@ metrics: path: /metrics interval: "" scrapeTimeout: "" + +internalAuthorizationPolicy: + enabled: true + serviceAccounts: + - name: organizations + namespace: "" diff --git a/internal/server/organization_teardown.go b/internal/server/organization_teardown.go new file mode 100644 index 0000000..01a870c --- /dev/null +++ b/internal/server/organization_teardown.go @@ -0,0 +1,104 @@ +package server + +import ( + "context" + + appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" + "github.com/agynio/apps/internal/store" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// teardownPageSize drains the paginated list endpoints a page at a time. The +// listing shrinks as the loop deletes, so each pass re-reads from the start +// rather than carrying a cursor across a mutating walk. +const teardownPageSize = 100 + +// DeleteOrganizationResources removes the organization's app installations, the +// apps it published, and those apps' installations in *other* organizations. It +// is internal: Istio settles who may call it, so there is no permission check +// and no caller identity to check against. Step 3 of the organization teardown, +// after the agents those installations could reach. +// +// This is the one step that reaches outside the organization. Publishing an app +// is a commitment that outlives the publisher's own use of it, and deleting the +// publisher ends it -- so a public app's installations elsewhere are uninstalled +// too. The organizations that installed them get no notice; that is a product +// question this does not answer. +// +// Idempotent by construction: a retried step lists nothing and deletes nothing. +func (s *Server) DeleteOrganizationResources(ctx context.Context, req *appsv1.DeleteOrganizationResourcesRequest) (*appsv1.DeleteOrganizationResourcesResponse, error) { + organizationID, err := parseUUID(req.GetOrganizationId()) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "organization_id: %v", err) + } + + // Installations into this organization, whoever published the app. + if err := s.uninstallAll(ctx, store.ListInstallationsFilter{OrganizationID: &organizationID}); err != nil { + return nil, err + } + + apps, err := s.listAllApps(ctx, store.ListAppsFilter{OrganizationID: &organizationID}) + if err != nil { + return nil, err + } + for _, app := range apps { + appID := app.Meta.ID + // Installations of this app anywhere, including other organizations. + // DeleteApp refuses while any remain, and that invariant is honoured + // rather than worked around. + if err := s.uninstallAll(ctx, store.ListInstallationsFilter{AppID: &appID}); err != nil { + return nil, err + } + if app.ZitiServiceID != "" { + if err := s.deleteZitiIdentity(ctx, app.IdentityID, app.ZitiServiceID); err != nil { + return nil, status.Errorf(codes.Internal, "delete ziti identity: %v", err) + } + } + if err := s.store.DeleteApp(ctx, appID); err != nil { + return nil, toStatusError(err) + } + } + return &appsv1.DeleteOrganizationResourcesResponse{}, nil +} + +// uninstallAll removes every installation matching the filter, taking the +// installation's tuples off with each. It re-lists from the first page after +// every batch because the deletes shrink the collection under a cursor. +func (s *Server) uninstallAll(ctx context.Context, filter store.ListInstallationsFilter) error { + for { + installations, _, err := s.store.ListInstallations(ctx, teardownPageSize, "", filter) + if err != nil { + return toStatusError(err) + } + if len(installations) == 0 { + return nil + } + for _, installation := range installations { + app, err := s.store.GetApp(ctx, installation.AppID) + if err != nil { + return toStatusError(err) + } + s.deleteInstallationTuples(ctx, app, installation.OrganizationID) + if err := s.store.DeleteInstallation(ctx, installation.Meta.ID); err != nil { + return toStatusError(err) + } + } + } +} + +func (s *Server) listAllApps(ctx context.Context, filter store.ListAppsFilter) ([]store.App, error) { + apps := []store.App{} + pageToken := "" + for { + page, next, err := s.store.ListApps(ctx, teardownPageSize, pageToken, filter) + if err != nil { + return nil, toStatusError(err) + } + apps = append(apps, page...) + if next == "" { + return apps, nil + } + pageToken = next + } +} diff --git a/internal/server/server_test.go b/internal/server/server_test.go index e0a7809..30aa465 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -301,6 +301,10 @@ type fakeIdentityClient struct { registerRequests []*identityv1.RegisterIdentityRequest } +func (f *fakeIdentityClient) DeleteOrganizationResources(context.Context, *identityv1.DeleteOrganizationResourcesRequest, ...grpc.CallOption) (*identityv1.DeleteOrganizationResourcesResponse, error) { + return &identityv1.DeleteOrganizationResourcesResponse{}, nil +} + func (f *fakeIdentityClient) RegisterIdentity(ctx context.Context, req *identityv1.RegisterIdentityRequest, _ ...grpc.CallOption) (*identityv1.RegisterIdentityResponse, error) { f.registerRequests = append(f.registerRequests, req) if f.registerFn != nil { @@ -2892,3 +2896,106 @@ func TestInstallWritesNothingWhenEverythingExists(t *testing.T) { t.Fatalf("expected no write, got %d", len(authorizationClient.writeRequests)) } } + +func TestDeleteOrganizationResourcesUninstallsAndDeletesPublishedApps(t *testing.T) { + organizationID := uuid.New() + otherOrganizationID := uuid.New() + publishedAppID, foreignAppID := uuid.New(), uuid.New() + inboundInstallID, outboundInstallID := uuid.New(), uuid.New() + + apps := map[uuid.UUID]storepkg.App{ + publishedAppID: {Meta: storepkg.EntityMeta{ID: publishedAppID}, OrganizationID: organizationID, IdentityID: uuid.New()}, + foreignAppID: {Meta: storepkg.EntityMeta{ID: foreignAppID}, OrganizationID: otherOrganizationID, IdentityID: uuid.New()}, + } + installations := map[uuid.UUID]storepkg.Installation{ + // A foreign app installed into the organization being torn down. + inboundInstallID: {Meta: storepkg.EntityMeta{ID: inboundInstallID}, AppID: foreignAppID, OrganizationID: organizationID}, + // This organization's published app, installed somewhere else. + outboundInstallID: {Meta: storepkg.EntityMeta{ID: outboundInstallID}, AppID: publishedAppID, OrganizationID: otherOrganizationID}, + } + + var deletedApps []uuid.UUID + store := &fakeStore{ + getFn: func(_ context.Context, id uuid.UUID) (storepkg.App, error) { return apps[id], nil }, + listFn: func(_ context.Context, _ int, _ string, filter storepkg.ListAppsFilter) ([]storepkg.App, string, error) { + result := []storepkg.App{} + for _, app := range apps { + if filter.OrganizationID != nil && app.OrganizationID == *filter.OrganizationID { + result = append(result, app) + } + } + return result, "", nil + }, + listInstallationsFn: func(_ context.Context, _ int, _ string, filter storepkg.ListInstallationsFilter) ([]storepkg.Installation, string, error) { + result := []storepkg.Installation{} + for _, installation := range installations { + switch { + case filter.OrganizationID != nil && installation.OrganizationID == *filter.OrganizationID: + result = append(result, installation) + case filter.AppID != nil && installation.AppID == *filter.AppID: + result = append(result, installation) + } + } + return result, "", nil + }, + deleteInstallationFn: func(_ context.Context, id uuid.UUID) error { + delete(installations, id) + return nil + }, + deleteFn: func(_ context.Context, id uuid.UUID) error { + deletedApps = append(deletedApps, id) + delete(apps, id) + return nil + }, + } + + srv := New(store, &fakeIdentityClient{}, &fakeAuthorizationClient{}, &fakeZitiManagementClient{}) + // Internal RPC: no identity in the context, and none required. + _, err := srv.DeleteOrganizationResources(context.Background(), &appsv1.DeleteOrganizationResourcesRequest{ + OrganizationId: organizationID.String(), + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + // Both installations are gone: the inbound one because it was into this + // organization, the outbound one because deleting the publisher ends the + // commitment publishing made. + if len(installations) != 0 { + t.Fatalf("expected every installation removed, got %v", installations) + } + // Only the published app is deleted; the foreign app itself survives. + if len(deletedApps) != 1 || deletedApps[0] != publishedAppID { + t.Fatalf("expected only the published app deleted, got %v", deletedApps) + } +} + +func TestDeleteOrganizationResourcesIsIdempotent(t *testing.T) { + store := &fakeStore{ + listFn: func(context.Context, int, string, storepkg.ListAppsFilter) ([]storepkg.App, string, error) { + return nil, "", nil + }, + listInstallationsFn: func(context.Context, int, string, storepkg.ListInstallationsFilter) ([]storepkg.Installation, string, error) { + return nil, "", nil + }, + } + srv := New(store, &fakeIdentityClient{}, &fakeAuthorizationClient{}, &fakeZitiManagementClient{}) + + // The cascade retries a step it is unsure finished, so an organization with + // nothing left has to succeed rather than fail. + if _, err := srv.DeleteOrganizationResources(context.Background(), &appsv1.DeleteOrganizationResourcesRequest{ + OrganizationId: uuid.New().String(), + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestDeleteOrganizationResourcesRejectsInvalidOrganizationID(t *testing.T) { + srv := New(&fakeStore{}, &fakeIdentityClient{}, &fakeAuthorizationClient{}, &fakeZitiManagementClient{}) + _, err := srv.DeleteOrganizationResources(context.Background(), &appsv1.DeleteOrganizationResourcesRequest{ + OrganizationId: "not-a-uuid", + }) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("expected InvalidArgument, got %v", err) + } +}