Skip to content

[FEAT] Restrict Firestore Doc/QuerySnapshot toJSON on client. #9048

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
fdaa937
Draft of synchronized bundle reader
DellaBitta Apr 18, 2025
a888667
Sync bundle reader stands alone
DellaBitta Apr 20, 2025
ab90498
docsnapshot.FromJSON prototype
DellaBitta Apr 22, 2025
5df33ec
Lint fixes.
DellaBitta Apr 22, 2025
7c8ef87
Put more logic into bundle_impl.
DellaBitta Apr 23, 2025
f0d3304
Templated converter DocSnapshot.fromJSON
DellaBitta Apr 23, 2025
f80c49d
Update bundleReader to be multi use utility
DellaBitta Apr 30, 2025
be5aee8
Update sync engine use of bundle loader.
DellaBitta Apr 30, 2025
ad2f0ac
typo fix
DellaBitta Apr 30, 2025
5ea4ea5
initial QuerySnapshot fromJSON impl
DellaBitta Apr 30, 2025
95b69f6
docgen
DellaBitta Apr 30, 2025
011ac37
Merge branch 'ddb-firestore-result-serialization' into ddb-sync-bundl…
DellaBitta Apr 30, 2025
fccd633
QuerySnapshot jsonSchema
DellaBitta Apr 30, 2025
51bc4bc
Use jsonSchemas
DellaBitta Apr 30, 2025
019aa4d
Remove need for toDocumentSnapshotData impl
DellaBitta Apr 30, 2025
52bc217
Revised comments.
DellaBitta May 1, 2025
90ade11
Add QuerySnapshot.fromJSON converter variant.
DellaBitta May 2, 2025
7ec7a0c
DocumentSet fix.
DellaBitta May 6, 2025
d97009e
Unit tests.
DellaBitta May 6, 2025
8a942f1
Non templated DocumentSnapshot.fromJSON
DellaBitta May 6, 2025
78626ef
fromJSON integration tests
DellaBitta May 6, 2025
5bf5767
remove fromJSONUsingConverter, user override.
DellaBitta May 6, 2025
4f27dc4
DocumentReference fromJSON overload
DellaBitta May 7, 2025
2840bb3
Created onSnapshotResume variant.
DellaBitta May 12, 2025
96a49f7
Move doc / querysnapshot fromJSON to func impl.
DellaBitta May 12, 2025
df70734
Implementation. Test fails client side.
DellaBitta May 15, 2025
8e1e51a
Remove tests on client side. Lint / format.
DellaBitta May 15, 2025
8359b95
converter feedback
DellaBitta May 15, 2025
2fb5df3
Test for specific exception text.
DellaBitta May 15, 2025
04620bc
format
DellaBitta May 15, 2025
fbd59e1
Merge branch 'ddb-sync-bundle-parse' into ddb-no-client-origin-bundles
DellaBitta May 15, 2025
3c91ad4
format
DellaBitta May 15, 2025
1615df9
merge main
DellaBitta May 16, 2025
618e3c2
format
DellaBitta May 16, 2025
158b491
merged console logging
DellaBitta May 16, 2025
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
124 changes: 54 additions & 70 deletions packages/firestore/src/api/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,12 @@ import { DocumentKey } from '../model/document_key';
import { DocumentSet } from '../model/document_set';
import { ResourcePath } from '../model/path';
import { newSerializer } from '../platform/serializer';
import {
buildQuerySnapshotJsonBundle,
buildDocumentSnapshotJsonBundle
} from '../platform/snapshot_to_json';
import { fromDocument } from '../remote/serializer';
import { debugAssert, fail } from '../util/assert';
import {
BundleBuilder,
DocumentSnapshotBundleData,
QuerySnapshotBundleData
} from '../util/bundle_builder_impl';
import { Code, FirestoreError } from '../util/error';
// API extractor fails importing 'property' unless we also explicitly import 'Property'.
// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts
Expand Down Expand Up @@ -529,6 +528,13 @@ export class DocumentSnapshot<
* @returns a JSON representation of this object.
*/
toJSON(): object {
if (this.metadata.hasPendingWrites) {
throw new FirestoreError(
Code.FAILED_PRECONDITION,
'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +
'Await waitForPendingWrites() before invoking toJSON().'
);
}
const document = this._document;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: any = {};
Expand All @@ -544,29 +550,16 @@ export class DocumentSnapshot<
) {
return result;
}
const builder: BundleBuilder = new BundleBuilder(
this._firestore,
AutoId.newId()
);
const documentData = this._userDataWriter.convertObjectMap(
document.data.value.mapValue.fields,
'previous'
);
if (this.metadata.hasPendingWrites) {
throw new FirestoreError(
Code.FAILED_PRECONDITION,
'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +
'Await waitForPendingWrites() before invoking toJSON().'
);
}
builder.addBundleDocument(
documentToDocumentSnapshotBundleData(
this.ref.path,
documentData,
document
)
result['bundle'] = buildDocumentSnapshotJsonBundle(
this._firestore,
document,
documentData,
this.ref.path
);
result['bundle'] = builder.build();
return result;
}
}
Expand Down Expand Up @@ -611,6 +604,12 @@ export function documentSnapshotFromJSON<
converter?: FirestoreDataConverter<AppModelType, DbModelType>
): DocumentSnapshot<AppModelType, DbModelType> {
if (validateJSON(json, DocumentSnapshot._jsonSchema)) {
if (json.bundle === 'NOT SUPPORTED') {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'The provided JSON object was created in a client environment, which is not supported.'
);
}
// Parse the bundle data.
const serializer = newSerializer(db._databaseId);
const bundleReader = createBundleReaderSync(json.bundle, serializer);
Expand Down Expand Up @@ -825,52 +824,48 @@ export class QuerySnapshot<
* @returns a JSON representation of this object.
*/
toJSON(): object {
if (this.metadata.hasPendingWrites) {
throw new FirestoreError(
Code.FAILED_PRECONDITION,
'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +
'Await waitForPendingWrites() before invoking toJSON().'
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: any = {};
result['type'] = QuerySnapshot._jsonSchemaVersion;
result['bundleSource'] = 'QuerySnapshot';
result['bundleName'] = AutoId.newId();

const builder: BundleBuilder = new BundleBuilder(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The bundle code is now moved into a platform specific file so only for node environments. The other platforms produce a bundle string that simply reads NOT SUPPORTED.

this._firestore,
result['bundleName']
);
const databaseId = this._firestore._databaseId.database;
const projectId = this._firestore._databaseId.projectId;
const parent = `projects/${projectId}/databases/${databaseId}/documents`;
const docBundleDataArray: DocumentSnapshotBundleData[] = [];
const docArray = this.docs;
docArray.forEach(doc => {
const documents: Document[] = [];
const documentData: DocumentData[] = [];
const paths: string[] = [];

this.docs.forEach(doc => {
if (doc._document === null) {
return;
}
const documentData = this._userDataWriter.convertObjectMap(
doc._document.data.value.mapValue.fields,
'previous'
);
if (this.metadata.hasPendingWrites) {
throw new FirestoreError(
Code.FAILED_PRECONDITION,
'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +
'Await waitForPendingWrites() before invoking toJSON().'
);
}
docBundleDataArray.push(
documentToDocumentSnapshotBundleData(
doc.ref.path,
documentData,
doc._document
documents.push(doc._document);
documentData.push(
this._userDataWriter.convertObjectMap(
doc._document.data.value.mapValue.fields,
'previous'
)
);
paths.push(doc.ref.path);
});
const bundleData: QuerySnapshotBundleData = {
name: result['bundleName'],
query: this.query._query,
result['bundle'] = buildQuerySnapshotJsonBundle(
this._firestore,
this.query._query,
result['bundleName'],
parent,
docBundleDataArray
};
builder.addBundleQuery(bundleData);
result['bundle'] = builder.build();
paths,
documents,
documentData
);
return result;
}
}
Expand Down Expand Up @@ -915,6 +910,12 @@ export function querySnapshotFromJSON<
converter?: FirestoreDataConverter<AppModelType, DbModelType>
): QuerySnapshot<AppModelType, DbModelType> {
if (validateJSON(json, QuerySnapshot._jsonSchema)) {
if (json.bundle === 'NOT SUPPORTED') {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'The provided JSON object was created in a client environment, which is not supported.'
);
}
// Parse the bundle data.
const serializer = newSerializer(db._databaseId);
const bundleReader = createBundleReaderSync(json.bundle, serializer);
Expand Down Expand Up @@ -1111,20 +1112,3 @@ export function snapshotEqual<AppModelType, DbModelType extends DocumentData>(

return false;
}

// Formats Document data for bundling a DocumentSnapshot.
function documentToDocumentSnapshotBundleData(
path: string,
documentData: DocumentData,
document: Document
): DocumentSnapshotBundleData {
return {
documentData,
documentKey: document.mutableCopy().key,
documentPath: path,
documentExists: true,
createdTime: document.createTime.toTimestamp(),
readTime: document.readTime.toTimestamp(),
versionTime: document.version.toTimestamp()
};
}
43 changes: 43 additions & 0 deletions packages/firestore/src/platform/browser/snapshot_to_json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* @license
* Copyright 2025 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
*
* http://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.
*/

/** Return the Platform-specific build JSON bundle implementations. */
import { Firestore } from '../../api/database';
import { Query } from '../../core/query';
import { DocumentData } from '../../lite-api/reference';
import { Document } from '../../model/document';

export function buildDocumentSnapshotJsonBundle(
db: Firestore,
document: Document,
docData: DocumentData,
path: string
): string {
return 'NOT SUPPORTED';
}

export function buildQuerySnapshotJsonBundle(
db: Firestore,
query: Query,
bundleName: string,
parent: string,
paths: string[],
docs: Document[],
documentData: DocumentData[]
): string {
return 'NOT SUPPORTED';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @license
* Copyright 2025 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
*
* http://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.
*/

export * from '../browser/snapshot_to_json';
84 changes: 84 additions & 0 deletions packages/firestore/src/platform/node/snapshot_to_json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* @license
* Copyright 2025 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
*
* http://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.
*/

/** Return the Platform-specific build JSON bundle implementations. */
import { Firestore } from '../../api/database';
import { Query } from '../../core/query';
import { DocumentData } from '../../lite-api/reference';
import { Document } from '../../model/document';
import {
BundleBuilder,
DocumentSnapshotBundleData,
QuerySnapshotBundleData
} from '../../util/bundle_builder_impl';
import { AutoId } from '../../util/misc';

export function buildDocumentSnapshotJsonBundle(
db: Firestore,
document: Document,
docData: DocumentData,
path: string
): string {
const builder: BundleBuilder = new BundleBuilder(db, AutoId.newId());
builder.addBundleDocument(
documentToDocumentSnapshotBundleData(path, docData, document)
);
return builder.build();
}

export function buildQuerySnapshotJsonBundle(
db: Firestore,
query: Query,
bundleName: string,
parent: string,
paths: string[],
docs: Document[],
documentData: DocumentData[]
): string {
const docBundleDataArray: DocumentSnapshotBundleData[] = [];
for (let i = 0; i < docs.length; i++) {
docBundleDataArray.push(
documentToDocumentSnapshotBundleData(paths[i], documentData[i], docs[i])
);
}
const bundleData: QuerySnapshotBundleData = {
name: bundleName,
query,
parent,
docBundleDataArray
};
const builder: BundleBuilder = new BundleBuilder(db, bundleName);
builder.addBundleQuery(bundleData);
return builder.build();
}

// Formats Document data for bundling a DocumentSnapshot.
function documentToDocumentSnapshotBundleData(
path: string,
documentData: DocumentData,
document: Document
): DocumentSnapshotBundleData {
return {
documentData,
documentKey: document.mutableCopy().key,
documentPath: path,
documentExists: true,
createdTime: document.createTime.toTimestamp(),
readTime: document.readTime.toTimestamp(),
versionTime: document.version.toTimestamp()
};
}
18 changes: 18 additions & 0 deletions packages/firestore/src/platform/node_lite/snapshot_to_json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @license
* Copyright 2025 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
*
* http://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.
*/

export * from '../node/snapshot_to_json';
21 changes: 21 additions & 0 deletions packages/firestore/src/platform/rn/snapshot_to_json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @license
* Copyright 2025 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
*
* http://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.
*/

export {
buildDocumentSnapshotJsonBundle,
buildQuerySnapshotJsonBundle
} from '../browser/snapshot_to_json';
Loading
Loading