Skip to content

Use crypo RNG for auto ID generation to reduce conflicts. #2764

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 4 commits into from
Mar 21, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
6 changes: 6 additions & 0 deletions packages/firestore/src/platform/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export interface Platform {
/** Converts a binary string to a Base64 encoded string. */
btoa(raw: string): string;

/**
* Generates `nBytes` of random bytes. If `nBytes` is negative, an empty array
* will be returned.
*/
randomBytes(nBytes: number): Uint8Array;

/** The Platform's 'window' implementation or null if not available. */
readonly window: Window | null;

Expand Down
10 changes: 10 additions & 0 deletions packages/firestore/src/platform_browser/browser_platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,14 @@ export class BrowserPlatform implements Platform {
btoa(raw: string): string {
return btoa(raw);
}

randomBytes(nBytes: number): Uint8Array {
if (nBytes <= 0) {
return new Uint8Array();
}

const v = new Uint8Array(nBytes);
crypto.getRandomValues(v);
return v;
}
}
9 changes: 9 additions & 0 deletions packages/firestore/src/platform_node/node_platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import { randomBytes } from 'crypto';
import * as util from 'util';

import { DatabaseId, DatabaseInfo } from '../core/database_info';
Expand Down Expand Up @@ -74,4 +75,12 @@ export class NodePlatform implements Platform {
btoa(raw: string): string {
return new Buffer(raw, 'binary').toString('base64');
}

randomBytes(nBytes: number): Uint8Array {
if (nBytes <= 0) {
return new Uint8Array();
}

return randomBytes(nBytes);
}
}
13 changes: 11 additions & 2 deletions packages/firestore/src/util/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

import { assert } from './assert';
import { PlatformSupport } from '../platform/platform';

export type EventHandler<E> = (value: E) => void;
export interface Indexable {
Expand All @@ -28,8 +29,16 @@ export class AutoId {
const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let autoId = '';
for (let i = 0; i < 20; i++) {
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
while (autoId.length < 20) {
const bytes = PlatformSupport.getPlatform().randomBytes(40);
bytes.forEach(b => {
Copy link
Contributor

Choose a reason for hiding this comment

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

You could rephrase this with a single for loop:

const numBytes = 40;
const maxValue = 62 * 4;
let bytes = PlatformSupport.getPlatform().randomBytes(numBytes);
let i = 0;
while (autoId.length < 20) {
  if (i >= numBytes) {
    bytes = PlatformSupport.getPlatform().randomBytes(numBytes);
    i = 0;
  }
  const b = bytes[i++];
  // Avoid modulus bias by discarding byte values greater than 247.
  if (b < maxValue) {
    autoId += chars.charAt(b % 62)
  }
}

Not sure this is necessarily better.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Right..it's hard to say which one is better. I'll stick to my version..

// Length of `chars` is 62. We only take bytes between 0 and 62*4-1
// (both inclusive). The value is then evenly mapped to indices of `char`
// via a modulo operation.
if (autoId.length < 20 && b <= 62 * 4 - 1) {
Copy link
Contributor

Choose a reason for hiding this comment

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

This magic number deserves a constant declaration.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done.

autoId += chars.charAt(b % 62);
}
});
}
assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);
return autoId;
Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/test/unit/generate_spec_json.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function main(args) {
var testName = specName.replace(/^specs\//, '');
var filename = testName.replace(/[^A-Za-z\d]/g, '_') + '.json';
var outputFile = outputPath + '/' + filename;
console.log("Generating " + outputFile);
console.log('Generating ' + outputFile);
writeToJSON(testFiles[i], outputFile);
}

Expand Down
4 changes: 3 additions & 1 deletion packages/firestore/test/unit/specs/spec_test_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,9 @@ abstract class TestRunner {
expect(actualTarget.query).to.deep.equal(expectedTarget.query);
expect(actualTarget.targetId).to.equal(expectedTarget.targetId);
expect(actualTarget.readTime).to.equal(expectedTarget.readTime);
expect(actualTarget.resumeToken || '').to.equal(expectedTarget.resumeToken || '');
expect(actualTarget.resumeToken || '').to.equal(
expectedTarget.resumeToken || ''
);
delete actualTargets[targetId];
});
expect(obj.size(actualTargets)).to.equal(
Expand Down
6 changes: 5 additions & 1 deletion packages/firestore/test/util/test_platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,14 @@ export class TestPlatform implements Platform {
btoa(raw: string): string {
return this.basePlatform.btoa(raw);
}

randomBytes(nBytes: number): Uint8Array {
return this.basePlatform.randomBytes(nBytes);
}
}

/** Returns true if we are running under Node. */
export function isNode() : boolean {
export function isNode(): boolean {
return (
typeof process !== 'undefined' &&
process.title !== undefined &&
Expand Down