Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions delete-user-data/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## Version 0.1.32

fix: enforce exact file and directory path boundaries on Cloud Storage deletion

## Version 0.1.31

fix: update dependencies to address security vulnerabilities
Expand Down
2 changes: 1 addition & 1 deletion delete-user-data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ For example: `users/{UID},admins/{UID}`.

* Cloud Storage paths: Where in Google Cloud Storage do you store data keyed on a user ID? Leave empty if you don't use Cloud Storage.
Enter the full paths to files or directories in your Storage buckets, separated by commas. Use `{UID}` to represent the User ID of the deleted user, and use `{DEFAULT}` to represent your default Storage bucket.
Here's a series of examples. To delete all the files in your default bucket with the file naming scheme `{UID}-pic.png`, enter `{DEFAULT}/{UID}-pic.png`. To also delete all the files in another bucket called my-app-logs with the file naming scheme `{UID}-logs.txt`, enter `{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt`. To *also* delete a User ID-labeled directory and all its files (like `media/{UID}`), enter `{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt,{DEFAULT}/media/{UID}`.
Here's a series of examples. To delete all the files in your default bucket with the file naming scheme `{UID}-pic.png`, enter `{DEFAULT}/{UID}-pic.png`. To also delete all the files in another bucket called my-app-logs with the file naming scheme `{UID}-logs.txt`, enter `{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt`. To *also* delete a User ID-labeled directory and all its files (like `media/{UID}`), enter `{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt,{DEFAULT}/media/{UID}/`. Use trailing slashes for directories, and avoid custom UIDs containing `/`.

* Enable auto discovery: Enable the extension to automatically discover Firestore collections and documents to delete.

Expand Down
6 changes: 4 additions & 2 deletions delete-user-data/extension.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

name: delete-user-data
version: 0.1.31
version: 0.1.32
specVersion: v1beta

displayName: Delete User Data
Expand Down Expand Up @@ -199,7 +199,9 @@ params:
called my-app-logs with the file naming scheme `{UID}-logs.txt`, enter
`{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt`. To *also* delete a
User ID-labeled directory and all its files (like `media/{UID}`), enter
`{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt,{DEFAULT}/media/{UID}`.
`{DEFAULT}/{UID}-pic.png,my-app-logs/{UID}-logs.txt,{DEFAULT}/media/{UID}/`.
Use trailing slashes for directories, and avoid custom UIDs containing
`/`.
type: string
example: "{DEFAULT}/{UID}-pic.png,my-awesome-app-logs/{UID}-logs.txt"
required: false
Expand Down
261 changes: 261 additions & 0 deletions delete-user-data/functions/__tests__/clearStorageData.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as admin from "firebase-admin";
import firebaseFunctionsTest from "firebase-functions-test";

interface MockConfig {
location: string;
firestorePaths: string | undefined;
firestoreDeleteMode: string;
rtdbPaths: string | undefined;
storagePaths: string;
enableSearch: boolean;
storageBucketDefault: string;
selectedDatabaseInstance: string | undefined;
selectedDatabaseLocation: string | undefined;
searchFields: string;
searchFunction: string | undefined;
discoveryTopic: string;
deletionTopic: string;
searchDepth: number;
databaseId: string;
}

const mockConfig: MockConfig = {
location: "us-central1",
firestorePaths: undefined,
firestoreDeleteMode: "shallow",
rtdbPaths: undefined,
storagePaths: "",
enableSearch: false,
storageBucketDefault: "default-bucket",
selectedDatabaseInstance: undefined,
selectedDatabaseLocation: undefined,
searchFields: "uid",
searchFunction: undefined,
discoveryTopic: "ext-test-discovery",
deletionTopic: "ext-test-deletion",
searchDepth: 3,
databaseId: "(default)",
};

jest.mock("../src/config", () => ({
__esModule: true,
default: mockConfig,
}));

import { clearData } from "../src";
import * as logs from "../src/logs";

class FakeBucket {
public readonly objects: Set<string>;
private readonly errorToThrow?: Error & { code?: number };

constructor(
initialObjects: string[],
errorToThrow?: Error & { code?: number }
) {
this.objects = new Set(initialObjects);
this.errorToThrow = errorToThrow;
}

file(name: string) {
return {
delete: async (options?: { ignoreNotFound?: boolean }) => {
if (this.errorToThrow) {
throw this.errorToThrow;
}
if (this.objects.has(name)) {
this.objects.delete(name);
return;
}
if (!options?.ignoreNotFound) {
const err: Error & { code?: number } = new Error(
`No such object: ${name}`
);
err.code = 404;
throw err;
}
},
};
}

async deleteFiles(query: { prefix?: string } = {}) {
if (this.errorToThrow) {
throw this.errorToThrow;
}
const prefix = query.prefix ?? "";
for (const key of Array.from(this.objects)) {
if (key.startsWith(prefix)) {
this.objects.delete(key);
}
}
}
}

const testEnv = firebaseFunctionsTest();
const wrappedClearData = testEnv.wrap(clearData);

describe("clearStorageData boundary enforcement", () => {
let buckets: Record<string, FakeBucket>;
let storageSpy: jest.SpyInstance;

beforeEach(() => {
mockConfig.storagePaths = "";
buckets = {
"default-bucket": new FakeBucket([
"media/1/photo.jpg",
"media/1/nested/doc.pdf",
"media/12/photo.jpg",
"media/100/photo.jpg",
"media/1.png",
"1-pic.png",
"1-pic.png.bak",
"12-pic.png",
"secrets/1.json",
"secrets/12.json",
]),
"other-bucket": new FakeBucket([
"1-logs.txt",
"12-logs.txt",
"uploads/1/file.txt",
"uploads/12/file.txt",
]),
};

storageSpy = jest.spyOn(admin, "storage").mockReturnValue({
bucket: (name: string) => buckets[name],
} as unknown as admin.storage.Storage);
});

afterEach(() => {
storageSpy.mockRestore();
});

afterAll(() => {
testEnv.cleanup();
});

test("directory path without trailing slash does not delete other users sharing UID prefix", async () => {
mockConfig.storagePaths = "{DEFAULT}/media/{UID}";

await wrappedClearData(testEnv.auth.makeUserRecord({ uid: "1" }));

expect(buckets["default-bucket"].objects.has("media/1/photo.jpg")).toBe(
false
);
expect(
buckets["default-bucket"].objects.has("media/1/nested/doc.pdf")
).toBe(false);
expect(buckets["default-bucket"].objects.has("media/12/photo.jpg")).toBe(
true
);
expect(buckets["default-bucket"].objects.has("media/100/photo.jpg")).toBe(
true
);
expect(buckets["default-bucket"].objects.has("media/1.png")).toBe(true);
});

test("directory path with trailing slash deletes only the user directory", async () => {
mockConfig.storagePaths = "{DEFAULT}/media/{UID}/";

await wrappedClearData(testEnv.auth.makeUserRecord({ uid: "1" }));

expect(buckets["default-bucket"].objects.has("media/1/photo.jpg")).toBe(
false
);
expect(
buckets["default-bucket"].objects.has("media/1/nested/doc.pdf")
).toBe(false);
expect(buckets["default-bucket"].objects.has("media/12/photo.jpg")).toBe(
true
);
expect(buckets["default-bucket"].objects.has("media/1.png")).toBe(true);
});

test("flat file paths still delete exact user files without deleting sibling prefixes", async () => {
mockConfig.storagePaths =
"{DEFAULT}/{UID}-pic.png,{DEFAULT}/secrets/{UID}.json,other-bucket/{UID}-logs.txt";

await wrappedClearData(testEnv.auth.makeUserRecord({ uid: "1" }));

expect(buckets["default-bucket"].objects.has("1-pic.png")).toBe(false);
expect(buckets["default-bucket"].objects.has("1-pic.png.bak")).toBe(true);
expect(buckets["default-bucket"].objects.has("12-pic.png")).toBe(true);
expect(buckets["default-bucket"].objects.has("secrets/1.json")).toBe(false);
expect(buckets["default-bucket"].objects.has("secrets/12.json")).toBe(true);
expect(buckets["other-bucket"].objects.has("1-logs.txt")).toBe(false);
expect(buckets["other-bucket"].objects.has("12-logs.txt")).toBe(true);
});

test("empty bucket, empty prefix, or trailing comma does not throw or wipe the bucket", async () => {
mockConfig.storagePaths =
"/media/{UID},{DEFAULT}/,other-bucket/uploads/{UID},";

await wrappedClearData(testEnv.auth.makeUserRecord({ uid: "1" }));

expect(buckets["default-bucket"].objects.size).toBe(10);
expect(buckets["other-bucket"].objects.has("uploads/1/file.txt")).toBe(
false
);
expect(buckets["other-bucket"].objects.has("uploads/12/file.txt")).toBe(
true
);
});

test("empty uid warns and does not delete any objects", async () => {
mockConfig.storagePaths = "{DEFAULT}/media/{UID}";
const warnSpy = jest.spyOn(logs, "warnMissingUid");
const completeSpy = jest.spyOn(logs, "complete");

await wrappedClearData(testEnv.auth.makeUserRecord({ uid: "" }));

expect(warnSpy).toHaveBeenCalledTimes(1);
expect(completeSpy).not.toHaveBeenCalled();
expect(buckets["default-bucket"].objects.size).toBe(10);

warnSpy.mockRestore();
completeSpy.mockRestore();
});

test("logs 404 and non-404 storage errors without aborting other paths", async () => {
const notFoundErr: Error & { code?: number } = new Error("Bucket missing");
notFoundErr.code = 404;
const permErr: Error & { code?: number } = new Error("Permission denied");
permErr.code = 403;

buckets["missing-bucket"] = new FakeBucket([], notFoundErr);
buckets["forbidden-bucket"] = new FakeBucket([], permErr);

const log404Spy = jest.spyOn(logs, "storagePath404");
const logErrSpy = jest.spyOn(logs, "storagePathError");

mockConfig.storagePaths =
"missing-bucket/media/{UID},forbidden-bucket/media/{UID},other-bucket/uploads/{UID}";

await wrappedClearData(testEnv.auth.makeUserRecord({ uid: "1" }));

expect(log404Spy).toHaveBeenCalledWith("media/1");
expect(logErrSpy).toHaveBeenCalledWith("media/1", permErr);
expect(buckets["other-bucket"].objects.has("uploads/1/file.txt")).toBe(
false
);

log404Spy.mockRestore();
logErrSpy.mockRestore();
});
});
36 changes: 27 additions & 9 deletions delete-user-data/functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ export const clearData = functions.auth.user().onDelete(async (user) => {
const { firestorePaths, rtdbPaths, storagePaths, enableSearch } = config;

const { uid } = user;
if (!uid) {
logs.warnMissingUid();
return;
}

const promises = [];
if (firestorePaths) {
Expand Down Expand Up @@ -274,21 +278,35 @@ const clearStorageData = async (storagePaths: string, uid: string) => {

const paths = extractUserPaths(storagePaths, uid);
const promises = paths.map(async (path) => {
const parts = path.split("/");
const trimmedPath = path.trim();
if (!trimmedPath) {
return;
}
const parts = trimmedPath.split("/");
const bucketName = parts[0];
const bucket =
bucketName === "{DEFAULT}"
? admin.storage().bucket(config.storageBucketDefault)
: admin.storage().bucket(bucketName);
const prefix = parts.slice(1).join("/");
if (!bucketName || !prefix) {
return;
}
try {
Comment thread
avolkovi marked this conversation as resolved.
Resolved
const bucket =
bucketName === "{DEFAULT}"
? admin.storage().bucket(config.storageBucketDefault)
: admin.storage().bucket(bucketName);
logs.storagePathDeleting(prefix);
await bucket.deleteFiles({
prefix,
});
if (prefix.endsWith("/")) {
await bucket.deleteFiles({
prefix,
});
} else {
await bucket.file(prefix).delete({ ignoreNotFound: true });
await bucket.deleteFiles({
prefix: `${prefix}/`,
});
}
logs.storagePathDeleted(prefix);
} catch (err) {
if (err.code === 404) {
if ((err as { code?: number } | undefined)?.code === 404) {
logs.storagePath404(prefix);
} else {
logs.storagePathError(prefix, err);
Expand Down
4 changes: 4 additions & 0 deletions delete-user-data/functions/src/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,7 @@ export function warnInvalidPaths(invalidPathCount: number, uid: string) {
`Attempted to delete ${invalidPathCount} invalid paths for deleted user ${uid}`
);
}

export const warnMissingUid = () => {
logger.warn("User UID is missing or empty, skipping deletion");
};
Loading