Skip to content

Commit 7d790e4

Browse files
committed
Make D1 binding fields private
The D1 wrapper kept the inner service stub in TypeScript `protected` and `private` fields. At runtime, these are plain properties. User code could get the stub and call any public method on the platform worker's entrypoint, not only `query()`. Use `#` private fields in `D1Database`, `D1DatabaseSession`, and `D1PreparedStatement`. Wrapped binding serialization does not read these fields. Compatibility: `env.DB.fetcher` and the related properties become `undefined`. These properties are not documented. We accept this risk without a compatibility flag.
1 parent 08157bd commit 7d790e4

2 files changed

Lines changed: 61 additions & 50 deletions

File tree

‎src/cloudflare/internal/d1-api.ts‎

Lines changed: 46 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -158,31 +158,29 @@ const D1_SESSION_CONSTRAINT_FIRST_UNCONSTRAINED = 'first-unconstrained';
158158
const D1_SESSION_COMMIT_TOKEN_HTTP_HEADER = 'x-cf-d1-session-commit-token';
159159

160160
class D1Database extends wrappedBinding.WrappedBinding {
161-
// TODO(soon): Can we use the # syntax here?
162-
// eslint-disable-next-line no-restricted-syntax
163-
private readonly alwaysPrimarySession: D1DatabaseSessionAlwaysPrimary;
164-
protected readonly fetcher: Fetcher;
161+
readonly #alwaysPrimarySession: D1DatabaseSessionAlwaysPrimary;
162+
readonly #fetcher: Fetcher;
165163

166164
constructor(fetcher: Fetcher) {
167165
super(fetcher);
168-
this.fetcher = fetcher;
169-
this.alwaysPrimarySession = new D1DatabaseSessionAlwaysPrimary(
170-
this.fetcher
166+
this.#fetcher = fetcher;
167+
this.#alwaysPrimarySession = new D1DatabaseSessionAlwaysPrimary(
168+
this.#fetcher
171169
);
172170
}
173171

174172
prepare(query: string): D1PreparedStatement {
175-
return new D1PreparedStatement(this.alwaysPrimarySession, query);
173+
return new D1PreparedStatement(this.#alwaysPrimarySession, query);
176174
}
177175

178176
async batch<T = unknown>(
179177
statements: D1PreparedStatement[]
180178
): Promise<D1Result<T>[]> {
181-
return this.alwaysPrimarySession.batch(statements);
179+
return this.#alwaysPrimarySession.batch(statements);
182180
}
183181

184182
async exec(query: string): Promise<D1ExecResult> {
185-
return this.alwaysPrimarySession.exec(query);
183+
return this.#alwaysPrimarySession.exec(query);
186184
}
187185

188186
withSession(
@@ -192,7 +190,7 @@ class D1Database extends wrappedBinding.WrappedBinding {
192190
if (constraintOrBookmark == null || constraintOrBookmark === '') {
193191
constraintOrBookmark = D1_SESSION_CONSTRAINT_FIRST_UNCONSTRAINED;
194192
}
195-
return new D1DatabaseSession(this.fetcher, constraintOrBookmark);
193+
return new D1DatabaseSession(this.#fetcher, constraintOrBookmark);
196194
}
197195

198196
/**
@@ -224,33 +222,33 @@ class D1Database extends wrappedBinding.WrappedBinding {
224222
throw new Error(`D1_ERROR: ${message}`);
225223
}
226224

227-
return await fetcherQuery(this.fetcher, request);
225+
return await fetcherQuery(this.#fetcher, request);
228226
}
229227

230228
/**
231229
* @deprecated
232230
*/
233231
async dump(): Promise<ArrayBuffer> {
234-
return this.alwaysPrimarySession.dump();
232+
return this.#alwaysPrimarySession.dump();
235233
}
236234
}
237235

238236
class D1DatabaseSession {
239-
protected fetcher: Fetcher;
240-
protected bookmarkOrConstraint: D1SessionBookmarkOrConstraint | null;
237+
readonly #fetcher: Fetcher;
238+
#bookmarkOrConstraint: D1SessionBookmarkOrConstraint | null;
241239

242240
constructor(
243241
fetcher: Fetcher,
244242
bookmarkOrConstraint: D1SessionBookmarkOrConstraint | null
245243
) {
246-
this.fetcher = fetcher;
244+
this.#fetcher = fetcher;
247245
// We should neve have received an empty string as a bookmark or constraint, but just be defensive.
248246
// `null` values are special indicating not to send any bookmark or constraint to the D1 eyeball worker.
249247
if (bookmarkOrConstraint == null) {
250-
this.bookmarkOrConstraint = null;
248+
this.#bookmarkOrConstraint = null;
251249
} else {
252-
this.bookmarkOrConstraint = bookmarkOrConstraint.trim();
253-
if (!this.bookmarkOrConstraint) {
250+
this.#bookmarkOrConstraint = bookmarkOrConstraint.trim();
251+
if (!this.#bookmarkOrConstraint) {
254252
throw new Error('D1_SESSION_ERROR: invalid bookmark or constraint');
255253
}
256254
}
@@ -275,7 +273,7 @@ class D1DatabaseSession {
275273
currentBookmark === null ||
276274
currentBookmark.localeCompare(newBookmark) < 0
277275
) {
278-
this.bookmarkOrConstraint = newBookmark;
276+
this.#bookmarkOrConstraint = newBookmark;
279277
}
280278
return this.getBookmark();
281279
}
@@ -336,15 +334,15 @@ class D1DatabaseSession {
336334
// Returns the latest bookmark we received from all responses processed so far.
337335
// It does not return constraints that might have be passed during the session creation.
338336
getBookmark(): D1SessionBookmark | null {
339-
switch (this.bookmarkOrConstraint) {
337+
switch (this.#bookmarkOrConstraint) {
340338
// First to any replica, and then anywhere that satisfies the bookmark.
341339
case D1_SESSION_CONSTRAINT_FIRST_UNCONSTRAINED:
342340
return null;
343341
// First to primary, and then anywhere that satisfies the bookmark.
344342
case D1_SESSION_CONSTRAINT_FIRST_PRIMARY:
345343
return null;
346344
default:
347-
return this.bookmarkOrConstraint;
345+
return this.#bookmarkOrConstraint;
348346
}
349347
}
350348

@@ -359,16 +357,16 @@ class D1DatabaseSession {
359357

360358
// We send either a constraint, or a bookmark, and the eyeball worker will figure out
361359
// what to do based on the value. This simulates the same flow as the REST API would behave too.
362-
if (this.bookmarkOrConstraint) {
363-
h.set(D1_SESSION_COMMIT_TOKEN_HTTP_HEADER, this.bookmarkOrConstraint);
360+
if (this.#bookmarkOrConstraint) {
361+
h.set(D1_SESSION_COMMIT_TOKEN_HTTP_HEADER, this.#bookmarkOrConstraint);
364362
}
365363

366364
if (!init) {
367365
init = { headers: h };
368366
} else {
369367
init.headers = h;
370368
}
371-
return this.fetcher.fetch(input, init).then((resp) => {
369+
return this.#fetcher.fetch(input, init).then((resp) => {
372370
const newBookmark = resp.headers.get(D1_SESSION_COMMIT_TOKEN_HTTP_HEADER);
373371
if (newBookmark) {
374372
this._updateBookmark(newBookmark);
@@ -460,10 +458,10 @@ class D1DatabaseSession {
460458
errorPrefix: 'D1_ERROR' | 'D1_EXEC_ERROR' = 'D1_ERROR'
461459
): Promise<D1RowsColumns[]> {
462460
try {
463-
const queryParams: QueryRequest = this.bookmarkOrConstraint
464-
? { ...request, bookmark: this.bookmarkOrConstraint }
461+
const queryParams: QueryRequest = this.#bookmarkOrConstraint
462+
? { ...request, bookmark: this.#bookmarkOrConstraint }
465463
: request;
466-
const response = await fetcherQuery(this.fetcher, queryParams);
464+
const response = await fetcherQuery(this.#fetcher, queryParams);
467465
if (response.bookmark) {
468466
this._updateBookmark(response.bookmark);
469467
}
@@ -593,9 +591,7 @@ class D1DatabaseSessionAlwaysPrimary extends D1DatabaseSession {
593591
}
594592

595593
class D1PreparedStatement {
596-
// TODO(soon): Can we use the # syntax here?
597-
// eslint-disable-next-line no-restricted-syntax
598-
private readonly dbSession: D1DatabaseSession;
594+
readonly #dbSession: D1DatabaseSession;
599595
readonly statement: string;
600596
readonly params: unknown[];
601597

@@ -604,7 +600,7 @@ class D1PreparedStatement {
604600
statement: string,
605601
values?: unknown[]
606602
) {
607-
this.dbSession = dbSession;
603+
this.#dbSession = dbSession;
608604
this.statement = statement;
609605
this.params = values || [];
610606
}
@@ -647,7 +643,7 @@ class D1PreparedStatement {
647643
);
648644
});
649645
return new D1PreparedStatement(
650-
this.dbSession,
646+
this.#dbSession,
651647
this.statement,
652648
transformedValues
653649
);
@@ -665,16 +661,16 @@ class D1PreparedStatement {
665661
'db.query.text': this.statement,
666662
'cloudflare.binding.type': 'D1',
667663
'cloudflare.d1.query.bookmark':
668-
this.dbSession.getBookmark() ?? undefined,
664+
this.#dbSession.getBookmark() ?? undefined,
669665
});
670666

671667
const info = firstIfArray(
672668
d1BindingJsrpc
673-
? await this.dbSession._queryOrThrow(
669+
? await this.#dbSession._queryOrThrow(
674670
{ queries: [{ sql: this.statement, params: this.params }] },
675671
span
676672
)
677-
: await this.dbSession._sendOrThrow<Record<string, T>>(
673+
: await this.#dbSession._sendOrThrow<Record<string, T>>(
678674
'/query',
679675
this.statement,
680676
this.params,
@@ -685,7 +681,7 @@ class D1PreparedStatement {
685681

686682
span.setAttributes({
687683
'cloudflare.d1.response.bookmark':
688-
this.dbSession.getBookmark() ?? undefined,
684+
this.#dbSession.getBookmark() ?? undefined,
689685
});
690686
addD1MetaToSpan(span, info.meta);
691687

@@ -719,16 +715,16 @@ class D1PreparedStatement {
719715
'db.query.text': this.statement,
720716
'cloudflare.binding.type': 'D1',
721717
'cloudflare.d1.query.bookmark':
722-
this.dbSession.getBookmark() ?? undefined,
718+
this.#dbSession.getBookmark() ?? undefined,
723719
});
724720

725721
const result = firstIfArray(
726722
d1BindingJsrpc
727-
? await this.dbSession._queryOrThrow(
723+
? await this.#dbSession._queryOrThrow(
728724
{ queries: [{ sql: this.statement, params: this.params }] },
729725
span
730726
)
731-
: await this.dbSession._sendOrThrow<T>(
727+
: await this.#dbSession._sendOrThrow<T>(
732728
'/execute',
733729
this.statement,
734730
this.params,
@@ -739,7 +735,7 @@ class D1PreparedStatement {
739735

740736
span.setAttributes({
741737
'cloudflare.d1.response.bookmark':
742-
this.dbSession.getBookmark() ?? undefined,
738+
this.#dbSession.getBookmark() ?? undefined,
743739
});
744740
addD1MetaToSpan(span, result.meta);
745741
return d1BindingJsrpc ? toArrayOfObjects(result) : result;
@@ -754,16 +750,16 @@ class D1PreparedStatement {
754750
'db.query.text': this.statement,
755751
'cloudflare.binding.type': 'D1',
756752
'cloudflare.d1.query.bookmark':
757-
this.dbSession.getBookmark() ?? undefined,
753+
this.#dbSession.getBookmark() ?? undefined,
758754
});
759755

760756
const result = firstIfArray(
761757
d1BindingJsrpc
762-
? await this.dbSession._queryOrThrow(
758+
? await this.#dbSession._queryOrThrow(
763759
{ queries: [{ sql: this.statement, params: this.params }] },
764760
span
765761
)
766-
: await this.dbSession._sendOrThrow<T[]>(
762+
: await this.#dbSession._sendOrThrow<T[]>(
767763
'/query',
768764
this.statement,
769765
this.params,
@@ -774,7 +770,7 @@ class D1PreparedStatement {
774770

775771
span.setAttributes({
776772
'cloudflare.d1.response.bookmark':
777-
this.dbSession.getBookmark() ?? undefined,
773+
this.#dbSession.getBookmark() ?? undefined,
778774
});
779775
addD1MetaToSpan(span, result.meta);
780776

@@ -790,20 +786,20 @@ class D1PreparedStatement {
790786
'db.query.text': this.statement,
791787
'cloudflare.binding.type': 'D1',
792788
'cloudflare.d1.query.bookmark':
793-
this.dbSession.getBookmark() ?? undefined,
789+
this.#dbSession.getBookmark() ?? undefined,
794790
});
795791

796792
if (d1BindingJsrpc) {
797793
const s = firstIfArray(
798-
await this.dbSession._queryOrThrow(
794+
await this.#dbSession._queryOrThrow(
799795
{ queries: [{ sql: this.statement, params: this.params }] },
800796
span
801797
)
802798
);
803799

804800
span.setAttributes({
805801
'cloudflare.d1.response.bookmark':
806-
this.dbSession.getBookmark() ?? undefined,
802+
this.#dbSession.getBookmark() ?? undefined,
807803
});
808804
addD1MetaToSpan(span, s.meta);
809805

@@ -814,7 +810,7 @@ class D1PreparedStatement {
814810
}
815811

816812
const s = firstIfArray(
817-
await this.dbSession._sendOrThrow<Record<string, unknown>>(
813+
await this.#dbSession._sendOrThrow<Record<string, unknown>>(
818814
'/query',
819815
this.statement,
820816
this.params,
@@ -825,7 +821,7 @@ class D1PreparedStatement {
825821

826822
span.setAttributes({
827823
'cloudflare.d1.response.bookmark':
828-
this.dbSession.getBookmark() ?? undefined,
824+
this.#dbSession.getBookmark() ?? undefined,
829825
});
830826
addD1MetaToSpan(span, s.meta);
831827

‎src/cloudflare/internal/test/d1/d1-api-test.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,21 @@ export const testExec = {
1818
},
1919
};
2020

21+
export const testInnerFetcherIsPrivate = {
22+
test(_ctr, env) {
23+
// User code must reach the inner service stub only through the D1 API.
24+
const session = env.d1.withSession();
25+
const statement = env.d1.prepare('select 1');
26+
assert.deepStrictEqual(Object.keys(env.d1), []);
27+
assert.deepStrictEqual(Object.keys(session), []);
28+
assert.deepStrictEqual(Object.keys(statement), ['statement', 'params']);
29+
assert.strictEqual(env.d1.fetcher, undefined);
30+
assert.strictEqual(env.d1.alwaysPrimarySession, undefined);
31+
assert.strictEqual(session.fetcher, undefined);
32+
assert.strictEqual(statement.dbSession, undefined);
33+
},
34+
};
35+
2136
export const testDirectQuery = {
2237
async test(_ctr, env) {
2338
if (!Cloudflare.compatibilityFlags['d1_binding_jsrpc']) {

0 commit comments

Comments
 (0)