@pithy-sh/storage 0.2.10 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/capability.d.ts +12 -3
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +35 -9
- package/dist/config/config.d.ts +20 -4
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js +23 -6
- package/dist/data/storageObject.d.ts +12 -0
- package/dist/data/storageObject.d.ts.map +1 -1
- package/dist/data/storageObject.js +13 -2
- package/dist/data/tables.js +1 -1
- package/dist/error/errors.js +2 -2
- package/dist/http/handlers.d.ts +48 -16
- package/dist/http/handlers.d.ts.map +1 -1
- package/dist/http/handlers.js +169 -66
- package/dist/http/responses.d.ts +173 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +92 -0
- package/dist/http/routes.d.ts +13 -2
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +134 -22
- package/dist/http/schemas.d.ts +6 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +7 -6
- package/dist/http/scopes.d.ts +25 -0
- package/dist/http/scopes.d.ts.map +1 -0
- package/dist/http/scopes.js +32 -0
- package/dist/http/serve.d.ts +5 -2
- package/dist/http/serve.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/migrations/0002_ownership.d.ts +5 -0
- package/dist/migrations/0002_ownership.d.ts.map +1 -0
- package/dist/migrations/0002_ownership.js +114 -0
- package/dist/object/cloudflare.d.ts +3 -2
- package/dist/object/cloudflare.d.ts.map +1 -1
- package/dist/object/cloudflare.js +3 -3
- package/dist/object/store.d.ts +2 -7
- package/dist/object/store.d.ts.map +1 -1
- package/dist/object/store.js +1 -6
- package/dist/object/uploadedPart.d.ts +11 -0
- package/dist/object/uploadedPart.d.ts.map +1 -0
- package/dist/object/uploadedPart.js +12 -0
- package/dist/provision/provisionStorage.d.ts +14 -2
- package/dist/provision/provisionStorage.d.ts.map +1 -1
- package/dist/provision/provisionStorage.js +19 -4
- package/dist/provision/resolveStorageConfig.js +1 -1
- package/dist/quota/ceiling.d.ts +36 -0
- package/dist/quota/ceiling.d.ts.map +1 -0
- package/dist/quota/ceiling.js +31 -0
- package/dist/quota/quota.d.ts +24 -7
- package/dist/quota/quota.d.ts.map +1 -1
- package/dist/quota/quota.js +40 -12
- package/dist/secret/bundleToken.d.ts +24 -0
- package/dist/secret/bundleToken.d.ts.map +1 -0
- package/dist/secret/bundleToken.js +74 -0
- package/dist/secret/registry.d.ts +5 -1
- package/dist/secret/registry.d.ts.map +1 -1
- package/dist/secret/registry.js +7 -3
- package/dist/seeds/example.d.ts.map +1 -1
- package/dist/seeds/example.js +3 -0
- package/dist/test-utils/liveStorage.d.ts.map +1 -1
- package/dist/test-utils/liveStorage.js +5 -2
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +7 -7
- package/pithy.manifest.json +20 -10
- package/src/capability.ts +52 -8
- package/src/config/config.ts +24 -6
- package/src/data/storageObject.ts +22 -6
- package/src/error/errors.ts +2 -2
- package/src/http/handlers.ts +215 -81
- package/src/http/responses.ts +168 -0
- package/src/http/routes.ts +245 -46
- package/src/http/schemas.ts +11 -5
- package/src/http/scopes.ts +39 -0
- package/src/http/serve.ts +5 -2
- package/src/index.ts +2 -0
- package/src/migrations/0002_ownership.ts +176 -0
- package/src/object/cloudflare.ts +4 -3
- package/src/object/store.ts +6 -10
- package/src/object/uploadedPart.ts +17 -0
- package/src/provision/provisionStorage.ts +22 -3
- package/src/quota/ceiling.ts +44 -0
- package/src/quota/quota.ts +63 -20
- package/src/secret/bundleToken.ts +81 -0
- package/src/secret/registry.ts +6 -8
- package/src/seeds/example.ts +3 -0
- package/src/test-utils/liveStorage.ts +3 -6
- package/src/version.generated.ts +1 -1
package/src/http/handlers.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
+
import {
|
|
5
|
+
type AccessCaller,
|
|
6
|
+
type AccessLevel,
|
|
7
|
+
accessLevel,
|
|
8
|
+
disclosedTenancy,
|
|
9
|
+
keepReadable,
|
|
10
|
+
type PermissionHook,
|
|
11
|
+
readablePredicate,
|
|
12
|
+
} from "@pithy-sh/core/src/access/access";
|
|
13
|
+
import { resolveVisibility } from "@pithy-sh/core/src/access/visibility";
|
|
14
|
+
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
4
15
|
import type { StorageConfig } from "../config/config";
|
|
5
16
|
import { StorageShare } from "../data/share";
|
|
6
17
|
import { StorageObject } from "../data/storageObject";
|
|
@@ -14,8 +25,10 @@ import {
|
|
|
14
25
|
} from "../error/errors";
|
|
15
26
|
import { deriveObjectKey } from "../object/key";
|
|
16
27
|
import { collectParts, needsMultipart, planMultipart } from "../object/multipart";
|
|
17
|
-
import type { ObjectStore
|
|
18
|
-
import {
|
|
28
|
+
import type { ObjectStore } from "../object/store";
|
|
29
|
+
import type { UploadedPart } from "../object/uploadedPart";
|
|
30
|
+
import type { StorageCeiling } from "../quota/ceiling";
|
|
31
|
+
import { assertWithinQuota, insertReservingQuota, type QuotaCheck, updateSettlingQuota } from "../quota/quota";
|
|
19
32
|
import type {
|
|
20
33
|
CompleteUploadInput,
|
|
21
34
|
CopyObjectInput,
|
|
@@ -31,7 +44,7 @@ import type {
|
|
|
31
44
|
* these dependencies from the request env and maps their results onto responses.
|
|
32
45
|
*
|
|
33
46
|
* **Request shape is not validated here.** Each route declares its own schemas with
|
|
34
|
-
* `
|
|
47
|
+
* `validate(target, Schema)` and hands the handler the already-parsed value, so a
|
|
35
48
|
* malformed request is refused before a dependency is resolved or a row is read. What survives in
|
|
36
49
|
* these handlers is everything a request schema cannot express — ownership, quota, upload state —
|
|
37
50
|
* which is the whole of what they were ever really about.
|
|
@@ -41,28 +54,87 @@ import type {
|
|
|
41
54
|
* addresses, so a key in a response body is a capability leak waiting for the first adopter who logs
|
|
42
55
|
* their API responses.
|
|
43
56
|
*
|
|
44
|
-
* **
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
57
|
+
* **Whose a file is, and who may reach it.** Every file is written with its owner, the organization in
|
|
58
|
+
* force, and a visibility — `private`, `organization` or `public` — from the project's policy. Every route
|
|
59
|
+
* asks core's access rules, and the adopter's permission hook if they supplied one, before it acts:
|
|
60
|
+
* reading is the visibility's, and changing a file — completing, aborting, copying, renaming,
|
|
61
|
+
* re-scoping, sharing, deleting — is its owner's, acting for its organization, or a role holding
|
|
62
|
+
* `storage:manage` there.
|
|
63
|
+
*
|
|
64
|
+
* **A file you cannot see reads as missing.** A caller who may not read a file gets `storage/not_found`,
|
|
65
|
+
* and `storage/forbidden` only when they may read it but not change it — because a 403 on a file they
|
|
66
|
+
* cannot see confirms it exists, which is exactly the oracle an enumeration attack wants. A file they
|
|
67
|
+
* can already read has nothing left to hide, so there the honest answer is the useful one.
|
|
48
68
|
*/
|
|
49
69
|
|
|
70
|
+
/** The power a role holds to edit, delete and re-scope any file in its own organization. */
|
|
71
|
+
export const STORAGE_MANAGE_POWER = "storage:manage";
|
|
72
|
+
|
|
73
|
+
/** The capability's name, as the permission hook sees it. */
|
|
74
|
+
const CAPABILITY = "storage";
|
|
75
|
+
|
|
50
76
|
/** Everything a handler needs, all injectable. */
|
|
51
77
|
export interface HandlerDeps {
|
|
52
78
|
/** The storage database. */
|
|
53
79
|
db: StorageDatabase;
|
|
54
80
|
/** The object plane — presigning, the multipart lifecycle, and binding-backed reads. */
|
|
55
81
|
store: ObjectStore;
|
|
56
|
-
/** The resolved storage config: quota, multipart sizing,
|
|
82
|
+
/** The resolved storage config: quota, multipart sizing, the visibility policy. */
|
|
57
83
|
config: StorageConfig;
|
|
58
|
-
/**
|
|
59
|
-
|
|
84
|
+
/** Who is asking: the signed-in user from `AuthContext`, if any, and the organization they act for. */
|
|
85
|
+
caller: AccessCaller;
|
|
86
|
+
/** The adopter's permission hook, if they supplied one. */
|
|
87
|
+
permission?: PermissionHook;
|
|
88
|
+
/** The Worker env, handed to the permission hook. */
|
|
89
|
+
env: Record<string, unknown>;
|
|
60
90
|
/** Mints an object id. */
|
|
61
91
|
newId: () => string;
|
|
62
92
|
/** Mints a share token. */
|
|
63
93
|
newToken: () => string;
|
|
64
94
|
/** The current time. */
|
|
65
95
|
now: () => Date;
|
|
96
|
+
/**
|
|
97
|
+
* The byte ceiling for this request's writes, and whose bytes it covers.
|
|
98
|
+
*
|
|
99
|
+
* Absent means the configured `quota.bytesPerOwner`, per owner, which is what a project composing no
|
|
100
|
+
* entitlement provider has always had. The default resolver fills it from the `storageBytes` meter when the
|
|
101
|
+
* provider enforces one, so a plan's quota — or a subject's pinned one, or `unrestricted` — becomes the
|
|
102
|
+
* ceiling, summed across the organization when the plan is an organization's, and an advisory meter leaves
|
|
103
|
+
* the configured number in force.
|
|
104
|
+
*/
|
|
105
|
+
quotaLimit?: () => Promise<StorageCeiling>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The quota a write of a row held for `ownerId` in `organizationId` is checked against: the ceiling, and
|
|
110
|
+
* whose bytes it sums. The resolved ceiling where the request has one, the configured one otherwise.
|
|
111
|
+
*
|
|
112
|
+
* **A ceiling that covers an organization covers only that organization's rows**, so a row about to be held
|
|
113
|
+
* for a different one — or for none — would sit outside the very sum it is checked against, and never count.
|
|
114
|
+
* That is refused rather than written: it means the billing subject and the organization in force disagree,
|
|
115
|
+
* which is wiring for the adopter to fix, and under-counting has no recovery.
|
|
116
|
+
*/
|
|
117
|
+
async function quotaFor(
|
|
118
|
+
deps: HandlerDeps,
|
|
119
|
+
ownerId: string | null,
|
|
120
|
+
organizationId: string | null,
|
|
121
|
+
): Promise<Pick<QuotaCheck, "ownerId" | "organizationId" | "limitBytes" | "metered">> {
|
|
122
|
+
const ceiling = deps.quotaLimit
|
|
123
|
+
? await deps.quotaLimit()
|
|
124
|
+
: { limitBytes: deps.config.quota.bytesPerOwner, tenant: null, metered: false };
|
|
125
|
+
const { metered } = ceiling;
|
|
126
|
+
if (ceiling.tenant === null || ceiling.limitBytes === null || ownerId === null) {
|
|
127
|
+
return { ownerId, limitBytes: ceiling.limitBytes, metered };
|
|
128
|
+
}
|
|
129
|
+
if (organizationId !== ceiling.tenant) {
|
|
130
|
+
throw new InternalError({
|
|
131
|
+
message: "This file cannot be counted against the plan it is billed to, so nothing was written.",
|
|
132
|
+
action:
|
|
133
|
+
"Make the payments subject resolver and the organization in force agree — both should answer the organization the caller acts for.",
|
|
134
|
+
detail: `The storageBytes ceiling covers organization ${ceiling.tenant}; the file would be held for ${organizationId ?? "no organization"}.`,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return { ownerId, organizationId: ceiling.tenant, limitBytes: ceiling.limitBytes, metered };
|
|
66
138
|
}
|
|
67
139
|
|
|
68
140
|
/** The client-facing shape of a stored file. Deliberately without `key` and `uploadId`. */
|
|
@@ -70,9 +142,10 @@ export interface StorageObjectView {
|
|
|
70
142
|
id: string;
|
|
71
143
|
path: string;
|
|
72
144
|
ownerId: string | null;
|
|
145
|
+
organizationId: string | null;
|
|
73
146
|
contentType: string;
|
|
74
147
|
size: number | null;
|
|
75
|
-
visibility: "
|
|
148
|
+
visibility: StorageObject["visibility"];
|
|
76
149
|
checksum: string | null;
|
|
77
150
|
status: "pending" | "stored" | "failed";
|
|
78
151
|
createdAt: Date;
|
|
@@ -106,12 +179,20 @@ export interface ShareView {
|
|
|
106
179
|
createdAt: Date;
|
|
107
180
|
}
|
|
108
181
|
|
|
109
|
-
/**
|
|
110
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Drop the server-only fields. The single place a row becomes something a client may see.
|
|
184
|
+
*
|
|
185
|
+
* The owner and organization are the caller's to see only when they act for the file's organization
|
|
186
|
+
* ({@link disclosedTenancy}). A public file reached from anywhere else names neither: reading a file is not
|
|
187
|
+
* learning which organization its owner belongs to.
|
|
188
|
+
*/
|
|
189
|
+
function view(object: StorageObject, caller: AccessCaller): StorageObjectView {
|
|
190
|
+
const tenancy = disclosedTenancy(object, caller);
|
|
111
191
|
return {
|
|
112
192
|
id: object.id,
|
|
113
193
|
path: object.path,
|
|
114
|
-
ownerId:
|
|
194
|
+
ownerId: tenancy.ownerId,
|
|
195
|
+
organizationId: tenancy.organizationId,
|
|
115
196
|
contentType: object.contentType,
|
|
116
197
|
size: object.size,
|
|
117
198
|
visibility: object.visibility,
|
|
@@ -128,33 +209,56 @@ async function findObject(deps: HandlerDeps, id: string): Promise<StorageObject
|
|
|
128
209
|
return row ? StorageObject.parse(row) : null;
|
|
129
210
|
}
|
|
130
211
|
|
|
131
|
-
/**
|
|
212
|
+
/**
|
|
213
|
+
* Load one row or throw `storage/not_found`, asking nobody whether the caller may see it — for a share
|
|
214
|
+
* link, where the token is the credential and the rules have already been spent by whoever minted it.
|
|
215
|
+
*/
|
|
132
216
|
async function loadObject(deps: HandlerDeps, id: string): Promise<StorageObject> {
|
|
133
217
|
const object = await findObject(deps, id);
|
|
134
218
|
if (!object) throw new StorageNotFoundError({ detail: `no storage object ${id}` });
|
|
135
219
|
return object;
|
|
136
220
|
}
|
|
137
221
|
|
|
138
|
-
/**
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
222
|
+
/** What the caller may do with one file, asking the rules and the hook. */
|
|
223
|
+
function levelOf(deps: HandlerDeps, object: StorageObject): Promise<AccessLevel> {
|
|
224
|
+
return accessLevel({
|
|
225
|
+
record: object,
|
|
226
|
+
caller: deps.caller,
|
|
227
|
+
capability: CAPABILITY,
|
|
228
|
+
managePower: STORAGE_MANAGE_POWER,
|
|
229
|
+
hook: deps.permission,
|
|
230
|
+
env: deps.env,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Who is asking, for a log line. */
|
|
235
|
+
function callerName(deps: HandlerDeps): string {
|
|
236
|
+
return deps.caller.userId ?? "an anonymous caller";
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Load a file the caller may read, or answer not found — for a file that is absent and one they cannot see alike. */
|
|
240
|
+
async function loadReadable(deps: HandlerDeps, id: string): Promise<StorageObject> {
|
|
241
|
+
const object = await findObject(deps, id);
|
|
242
|
+
if (!object || (await levelOf(deps, object)) === "none") {
|
|
243
|
+
throw new StorageNotFoundError({ detail: `no storage object ${id} readable by ${callerName(deps)}` });
|
|
147
244
|
}
|
|
148
|
-
|
|
245
|
+
return object;
|
|
149
246
|
}
|
|
150
247
|
|
|
151
|
-
/**
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
248
|
+
/**
|
|
249
|
+
* Load a file the caller may change. Not found when they cannot read it; forbidden only when they can,
|
|
250
|
+
* because by then they already know it exists.
|
|
251
|
+
*/
|
|
252
|
+
async function loadWritable(deps: HandlerDeps, id: string): Promise<StorageObject> {
|
|
253
|
+
const object = await findObject(deps, id);
|
|
254
|
+
const level = object ? await levelOf(deps, object) : "none";
|
|
255
|
+
if (!object || level === "none") {
|
|
256
|
+
throw new StorageNotFoundError({ detail: `no storage object ${id} readable by ${callerName(deps)}` });
|
|
257
|
+
}
|
|
258
|
+
if (level !== "write") {
|
|
259
|
+
throw new StorageForbiddenError({ detail: `${callerName(deps)} may read object ${id} but not change it` });
|
|
260
|
+
}
|
|
261
|
+
return object;
|
|
158
262
|
}
|
|
159
263
|
|
|
160
264
|
/** Require the object's bytes to actually be there. A `pending` row has a record but no content. */
|
|
@@ -185,11 +289,14 @@ async function saveObject(deps: HandlerDeps, object: StorageObject): Promise<Sto
|
|
|
185
289
|
*/
|
|
186
290
|
export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): Promise<UploadInitResult> {
|
|
187
291
|
const now = deps.now();
|
|
292
|
+
// Whose it is comes from the request, never the body, and a level the policy does not allow is
|
|
293
|
+
// refused before a byte of R2 is reserved.
|
|
294
|
+
const organizationId = deps.caller.acting?.organizationId ?? null;
|
|
295
|
+
const visibility = resolveVisibility(deps.config.visibility, input.visibility, organizationId);
|
|
188
296
|
|
|
189
297
|
await assertWithinQuota({
|
|
190
298
|
db: deps.db,
|
|
191
|
-
|
|
192
|
-
limitBytes: deps.config.quota.bytesPerOwner,
|
|
299
|
+
...(await quotaFor(deps, deps.caller.userId, organizationId)),
|
|
193
300
|
additionalBytes: input.size,
|
|
194
301
|
});
|
|
195
302
|
|
|
@@ -219,10 +326,11 @@ export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): P
|
|
|
219
326
|
id: deps.newId(),
|
|
220
327
|
key,
|
|
221
328
|
path: input.path,
|
|
222
|
-
ownerId: deps.
|
|
329
|
+
ownerId: deps.caller.userId,
|
|
330
|
+
organizationId,
|
|
223
331
|
contentType: input.contentType,
|
|
224
332
|
size: input.size,
|
|
225
|
-
visibility
|
|
333
|
+
visibility,
|
|
226
334
|
checksum: null,
|
|
227
335
|
status: "pending",
|
|
228
336
|
uploadId,
|
|
@@ -232,8 +340,7 @@ export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): P
|
|
|
232
340
|
try {
|
|
233
341
|
await insertReservingQuota({
|
|
234
342
|
db: deps.db,
|
|
235
|
-
|
|
236
|
-
limitBytes: deps.config.quota.bytesPerOwner,
|
|
343
|
+
...(await quotaFor(deps, deps.caller.userId, organizationId)),
|
|
237
344
|
additionalBytes: input.size,
|
|
238
345
|
record: StorageObject.encode(object),
|
|
239
346
|
});
|
|
@@ -244,7 +351,7 @@ export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): P
|
|
|
244
351
|
throw error;
|
|
245
352
|
}
|
|
246
353
|
|
|
247
|
-
return { object: view(object), upload };
|
|
354
|
+
return { object: view(object, deps.caller), upload };
|
|
248
355
|
}
|
|
249
356
|
|
|
250
357
|
/**
|
|
@@ -274,11 +381,10 @@ export async function completeUpload(
|
|
|
274
381
|
id: string,
|
|
275
382
|
input: CompleteUploadInput,
|
|
276
383
|
): Promise<StorageObjectView> {
|
|
277
|
-
const object = await
|
|
278
|
-
assertOwner(object, deps.ownerId);
|
|
384
|
+
const object = await loadWritable(deps, id);
|
|
279
385
|
// Completing twice is a no-op rather than an error: a client that retried a dropped response gets
|
|
280
386
|
// the same answer, which is what makes the route safe to retry at all.
|
|
281
|
-
if (object.status === "stored") return view(object);
|
|
387
|
+
if (object.status === "stored") return view(object, deps.caller);
|
|
282
388
|
if (object.status !== "pending") {
|
|
283
389
|
throw new StorageUploadIncompleteError({ detail: `object ${id} is ${object.status} and cannot be completed` });
|
|
284
390
|
}
|
|
@@ -318,13 +424,15 @@ export async function completeUpload(
|
|
|
318
424
|
// An upload smaller than it declared claims nothing further, so it is written unconditionally. A
|
|
319
425
|
// quota an adopter lowered under an in-flight upload must not turn a shrinking completion into a
|
|
320
426
|
// deletion of bytes the owner was, at reservation time, granted.
|
|
321
|
-
if (overshoot <= 0) return view(await saveObject(deps, settled));
|
|
427
|
+
if (overshoot <= 0) return view(await saveObject(deps, settled), deps.caller);
|
|
322
428
|
|
|
429
|
+
// Resolved before the settlement's `try`: a ceiling that cannot be read, or that covers another
|
|
430
|
+
// organization, refuses this request — it is not a verdict on the bytes, so it must not discard them.
|
|
431
|
+
const quota = await quotaFor(deps, object.ownerId, object.organizationId);
|
|
323
432
|
try {
|
|
324
433
|
await updateSettlingQuota({
|
|
325
434
|
db: deps.db,
|
|
326
|
-
|
|
327
|
-
limitBytes: deps.config.quota.bytesPerOwner,
|
|
435
|
+
...quota,
|
|
328
436
|
additionalBytes: overshoot,
|
|
329
437
|
record: StorageObject.encode(settled),
|
|
330
438
|
});
|
|
@@ -337,7 +445,7 @@ export async function completeUpload(
|
|
|
337
445
|
await saveObject(deps, { ...object, status: "failed", uploadId: null, updatedAt: deps.now() });
|
|
338
446
|
throw error;
|
|
339
447
|
}
|
|
340
|
-
return view(settled);
|
|
448
|
+
return view(settled, deps.caller);
|
|
341
449
|
}
|
|
342
450
|
|
|
343
451
|
/**
|
|
@@ -355,8 +463,7 @@ export async function completeUpload(
|
|
|
355
463
|
* than sheltered forever by a row that counts toward no quota (`workflows/sweep.ts`).
|
|
356
464
|
*/
|
|
357
465
|
export async function abortUpload(deps: HandlerDeps, id: string): Promise<StorageObjectView> {
|
|
358
|
-
const object = await
|
|
359
|
-
assertOwner(object, deps.ownerId);
|
|
466
|
+
const object = await loadWritable(deps, id);
|
|
360
467
|
if (object.status === "stored") {
|
|
361
468
|
throw new StorageUploadIncompleteError({
|
|
362
469
|
message: "That upload already finished.",
|
|
@@ -369,7 +476,10 @@ export async function abortUpload(deps: HandlerDeps, id: string): Promise<Storag
|
|
|
369
476
|
// too, so aborting never leaves an object the sweep has to find later.
|
|
370
477
|
await deps.store.delete(object.key);
|
|
371
478
|
|
|
372
|
-
return view(
|
|
479
|
+
return view(
|
|
480
|
+
await saveObject(deps, { ...object, status: "failed", uploadId: null, updatedAt: deps.now() }),
|
|
481
|
+
deps.caller,
|
|
482
|
+
);
|
|
373
483
|
}
|
|
374
484
|
|
|
375
485
|
/** Where a resuming client stands: what R2 already holds, and a live URL for everything it does not. */
|
|
@@ -395,8 +505,7 @@ export interface UploadPartsResult {
|
|
|
395
505
|
* its parts discarded — re-presigning against either would hand out URLs addressing nothing.
|
|
396
506
|
*/
|
|
397
507
|
export async function listUploadParts(deps: HandlerDeps, id: string): Promise<UploadPartsResult> {
|
|
398
|
-
const object = await
|
|
399
|
-
assertOwner(object, deps.ownerId);
|
|
508
|
+
const object = await loadWritable(deps, id);
|
|
400
509
|
const uploadId = object.uploadId;
|
|
401
510
|
if (object.status !== "pending" || !uploadId) {
|
|
402
511
|
throw new StorageUploadIncompleteError({
|
|
@@ -460,8 +569,10 @@ function decodeCursor(value: string | undefined): ListCursor | null {
|
|
|
460
569
|
const DEFAULT_LIST_LIMIT = 50;
|
|
461
570
|
|
|
462
571
|
/**
|
|
463
|
-
* One page of the caller
|
|
464
|
-
*
|
|
572
|
+
* One page of the files the caller may see, ordered by logical path: their own, their organization's,
|
|
573
|
+
* and — only when `includePublic=true` — every public file. The rules run in SQL, so there is no
|
|
574
|
+
* parameter that lists anyone else's private files; the hook is asked about each row on the page and may
|
|
575
|
+
* remove one, so a page can come back short while its cursor still says there is more.
|
|
465
576
|
*/
|
|
466
577
|
export async function listObjects(
|
|
467
578
|
deps: HandlerDeps,
|
|
@@ -473,7 +584,12 @@ export async function listObjects(
|
|
|
473
584
|
let statement = deps.db
|
|
474
585
|
.selectFrom(STORAGE_OBJECTS_TABLE)
|
|
475
586
|
.selectAll()
|
|
476
|
-
.where(
|
|
587
|
+
.where(
|
|
588
|
+
readablePredicate(deps.caller, {
|
|
589
|
+
managePower: STORAGE_MANAGE_POWER,
|
|
590
|
+
includePublic: query.includePublic === "true",
|
|
591
|
+
}),
|
|
592
|
+
)
|
|
477
593
|
.orderBy("path", "asc")
|
|
478
594
|
.orderBy("id", "asc")
|
|
479
595
|
// One extra row is what distinguishes "this page is full" from "there is another page", without
|
|
@@ -494,16 +610,23 @@ export async function listObjects(
|
|
|
494
610
|
|
|
495
611
|
const rows = await statement.execute();
|
|
496
612
|
const page = rows.slice(0, limit).map((row) => StorageObject.parse(row));
|
|
497
|
-
|
|
613
|
+
// The cursor is the page's, computed before the hook runs: a row the hook removes is still a row the
|
|
614
|
+
// next page must start after.
|
|
615
|
+
const kept = await keepReadable(page, {
|
|
616
|
+
capability: CAPABILITY,
|
|
617
|
+
caller: deps.caller,
|
|
618
|
+
hook: deps.permission,
|
|
619
|
+
env: deps.env,
|
|
620
|
+
});
|
|
621
|
+
const objects = kept.map((object) => view(object, deps.caller));
|
|
498
622
|
if (rows.length <= limit) return { objects };
|
|
499
623
|
const last = page[page.length - 1];
|
|
500
624
|
return last ? { objects, cursor: encodeCursor({ path: last.path, id: last.id }) } : { objects };
|
|
501
625
|
}
|
|
502
626
|
|
|
503
|
-
/** Load an object for reading, enforcing
|
|
627
|
+
/** Load an object for reading, enforcing who may read it and that its bytes exist. */
|
|
504
628
|
export async function readableObject(deps: HandlerDeps, id: string): Promise<StorageObject> {
|
|
505
|
-
const object = await
|
|
506
|
-
assertReadable(object, deps.ownerId);
|
|
629
|
+
const object = await loadReadable(deps, id);
|
|
507
630
|
assertStored(object);
|
|
508
631
|
return object;
|
|
509
632
|
}
|
|
@@ -524,21 +647,28 @@ export async function presignObject(deps: HandlerDeps, id: string): Promise<{ ur
|
|
|
524
647
|
return { url, expiresInSeconds: PRESIGNED_URL_TTL_SECONDS };
|
|
525
648
|
}
|
|
526
649
|
|
|
527
|
-
/**
|
|
650
|
+
/**
|
|
651
|
+
* Rename a file, change who may read it, or both. The key never moves — only the row changes. A level the
|
|
652
|
+
* policy does not allow is refused, and `organization` on a file written with no organization is too.
|
|
653
|
+
*/
|
|
528
654
|
export async function updateObject(
|
|
529
655
|
deps: HandlerDeps,
|
|
530
656
|
id: string,
|
|
531
657
|
input: UpdateObjectInput,
|
|
532
658
|
): Promise<StorageObjectView> {
|
|
533
|
-
const object = await
|
|
534
|
-
|
|
659
|
+
const object = await loadWritable(deps, id);
|
|
660
|
+
const visibility =
|
|
661
|
+
input.visibility === undefined
|
|
662
|
+
? object.visibility
|
|
663
|
+
: resolveVisibility(deps.config.visibility, input.visibility, object.organizationId);
|
|
535
664
|
return view(
|
|
536
665
|
await saveObject(deps, {
|
|
537
666
|
...object,
|
|
538
667
|
path: input.path ?? object.path,
|
|
539
|
-
visibility
|
|
668
|
+
visibility,
|
|
540
669
|
updatedAt: deps.now(),
|
|
541
670
|
}),
|
|
671
|
+
deps.caller,
|
|
542
672
|
);
|
|
543
673
|
}
|
|
544
674
|
|
|
@@ -546,23 +676,32 @@ export async function updateObject(
|
|
|
546
676
|
* Copy a file server-side. The bytes are copied by R2 and never enter the Worker; the copy is a new
|
|
547
677
|
* object with its own id, its own key, and its own share links — it is not an alias.
|
|
548
678
|
*
|
|
549
|
-
*
|
|
679
|
+
* A change, like every other mutating route: you may copy a file you may change. Copying a *public* file
|
|
550
680
|
* you do not own is a plausible feature and deliberately not this one — it would let any reader
|
|
551
681
|
* duplicate bytes into their own quota on the owner's storage bill, which is a decision an adopter
|
|
552
|
-
* should make explicitly rather than inherit.
|
|
682
|
+
* should make explicitly rather than inherit. The copy is the caller's, in the organization they act for.
|
|
553
683
|
*/
|
|
554
684
|
export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjectInput): Promise<StorageObjectView> {
|
|
555
|
-
const source = await
|
|
556
|
-
assertOwner(source, deps.ownerId);
|
|
685
|
+
const source = await loadWritable(deps, id);
|
|
557
686
|
assertStored(source);
|
|
558
687
|
|
|
688
|
+
const organizationId = deps.caller.acting?.organizationId ?? null;
|
|
559
689
|
await assertWithinQuota({
|
|
560
690
|
db: deps.db,
|
|
561
|
-
|
|
562
|
-
limitBytes: deps.config.quota.bytesPerOwner,
|
|
691
|
+
...(await quotaFor(deps, deps.caller.userId, organizationId)),
|
|
563
692
|
additionalBytes: source.size ?? 0,
|
|
564
693
|
});
|
|
565
694
|
|
|
695
|
+
// A copy starts private even when the source was public. Republishing is a decision, and a copy made to
|
|
696
|
+
// take a private working copy of your own public file should not re-publish it by default. Where the policy
|
|
697
|
+
// allows no private file, it starts at the policy's default instead. Either way the level goes through the
|
|
698
|
+
// one check every write does, so the kit never writes a file outside its own policy.
|
|
699
|
+
const visibility = resolveVisibility(
|
|
700
|
+
deps.config.visibility,
|
|
701
|
+
deps.config.visibility.allowed.includes("private") ? "private" : undefined,
|
|
702
|
+
organizationId,
|
|
703
|
+
);
|
|
704
|
+
|
|
566
705
|
const key = deriveObjectKey();
|
|
567
706
|
await deps.store.copy(source.key, key);
|
|
568
707
|
const now = deps.now();
|
|
@@ -571,10 +710,9 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
|
|
|
571
710
|
id: deps.newId(),
|
|
572
711
|
key,
|
|
573
712
|
path: input.path,
|
|
574
|
-
ownerId: deps.
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
visibility: "private",
|
|
713
|
+
ownerId: deps.caller.userId,
|
|
714
|
+
organizationId,
|
|
715
|
+
visibility,
|
|
578
716
|
status: "stored",
|
|
579
717
|
uploadId: null,
|
|
580
718
|
createdAt: now,
|
|
@@ -585,8 +723,7 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
|
|
|
585
723
|
// owner, and concurrent copies of one 1 GiB file against a 1 GiB quota must not all pass.
|
|
586
724
|
await insertReservingQuota({
|
|
587
725
|
db: deps.db,
|
|
588
|
-
|
|
589
|
-
limitBytes: deps.config.quota.bytesPerOwner,
|
|
726
|
+
...(await quotaFor(deps, deps.caller.userId, organizationId)),
|
|
590
727
|
additionalBytes: source.size ?? 0,
|
|
591
728
|
record: StorageObject.encode(copy),
|
|
592
729
|
});
|
|
@@ -596,7 +733,7 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
|
|
|
596
733
|
await deps.store.delete(key).catch(() => {});
|
|
597
734
|
throw error;
|
|
598
735
|
}
|
|
599
|
-
return view(copy);
|
|
736
|
+
return view(copy, deps.caller);
|
|
600
737
|
}
|
|
601
738
|
|
|
602
739
|
/**
|
|
@@ -608,8 +745,7 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
|
|
|
608
745
|
* sweep collects an object whose row went first.
|
|
609
746
|
*/
|
|
610
747
|
export async function deleteObject(deps: HandlerDeps, id: string): Promise<{ id: string; deleted: true }> {
|
|
611
|
-
const object = await
|
|
612
|
-
assertOwner(object, deps.ownerId);
|
|
748
|
+
const object = await loadWritable(deps, id);
|
|
613
749
|
if (object.uploadId) await deps.store.abortMultipart(object.key, object.uploadId).catch(() => {});
|
|
614
750
|
await deps.store.delete(object.key).catch(() => {});
|
|
615
751
|
await deps.db.deleteFrom(STORAGE_OBJECTS_TABLE).where("id", "=", id).execute();
|
|
@@ -618,8 +754,7 @@ export async function deleteObject(deps: HandlerDeps, id: string): Promise<{ id:
|
|
|
618
754
|
|
|
619
755
|
/** Mint a revocable share link for one file. */
|
|
620
756
|
export async function createShare(deps: HandlerDeps, id: string, input: CreateShareInput): Promise<ShareView> {
|
|
621
|
-
const object = await
|
|
622
|
-
assertOwner(object, deps.ownerId);
|
|
757
|
+
const object = await loadWritable(deps, id);
|
|
623
758
|
assertStored(object);
|
|
624
759
|
|
|
625
760
|
const now = deps.now();
|
|
@@ -645,8 +780,7 @@ export async function revokeShare(deps: HandlerDeps, token: string): Promise<{ t
|
|
|
645
780
|
const row = await deps.db.selectFrom(STORAGE_SHARES_TABLE).selectAll().where("token", "=", token).executeTakeFirst();
|
|
646
781
|
if (!row) throw new StorageNotFoundError({ detail: `no share token ${token}` });
|
|
647
782
|
const share = StorageShare.parse(row);
|
|
648
|
-
|
|
649
|
-
assertOwner(object, deps.ownerId);
|
|
783
|
+
await loadWritable(deps, share.objectId);
|
|
650
784
|
if (share.revokedAt) return { token, revokedAt: share.revokedAt };
|
|
651
785
|
|
|
652
786
|
const revokedAt = deps.now();
|