Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
271 changes: 242 additions & 29 deletions cloudflare/packages/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ import {
scheduleAxiomSpanExport,
type MutableRequestTelemetryContext,
} from "./telemetry.ts"
import {
migrateLegacyTenant,
type LegacyMigrationAccount,
} from "./legacy-migration.ts"

export { TenantRegistryDurableObject }

Expand Down Expand Up @@ -111,6 +115,23 @@ interface CredentialLeaseEventInput {
readonly retryAt?: number
}

interface LegacyMigrationActor {
listMigrationAccounts(
orgId: string
): Promise<{ accounts: ReadonlyArray<LegacyMigrationAccount> }>
beginMigrationAccounts(
orgId: string
): Promise<{ accounts: ReadonlyArray<LegacyMigrationAccount> }>
completeMigrationAccounts(input: {
readonly orgId: string
readonly accounts: ReadonlyArray<LegacyMigrationAccount>
}): Promise<void>
restoreMigrationAccounts(input: {
readonly orgId: string
readonly accounts: ReadonlyArray<LegacyMigrationAccount>
}): Promise<void>
}

interface CredentialLeaseRow {
readonly [key: string]: SqlStorageValue
readonly id: string
Expand Down Expand Up @@ -436,6 +457,48 @@ const parseJsonRecord = async (
return body as Record<string, unknown>
}

const parseBoundedJsonRecord = async (
request: Request,
maxBytes: number
): Promise<Record<string, unknown> | Response> => {
const contentLength = Number(request.headers.get("content-length") ?? "0")
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
return json({ error: "Request body too large" }, { status: 413 })
}
if (!request.body) {
return json({ error: "Missing JSON body" }, { status: 400 })
}
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let total = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
total += value.byteLength
if (total > maxBytes) {
await reader.cancel().catch(() => {})
return json({ error: "Request body too large" }, { status: 413 })
}
chunks.push(value)
}
const body = new Uint8Array(total)
let offset = 0
for (const chunk of chunks) {
body.set(chunk, offset)
offset += chunk.byteLength
}
let decoded: unknown
try {
decoded = JSON.parse(new TextDecoder().decode(body))
} catch {
return json({ error: "Missing JSON body" }, { status: 400 })
}
if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) {
return json({ error: "Missing JSON body" }, { status: 400 })
}
return decoded as Record<string, unknown>
}

const parseRouteInput = async (request: Request): Promise<RouteInput> => {
const body = await request.json().catch(() => ({}))
if (!body || typeof body !== "object" || Array.isArray(body)) {
Expand Down Expand Up @@ -2479,40 +2542,97 @@ export class SubrouterDurableObject extends DurableObject<Env> {
}
}

async listMigrationAccounts(
orgId: string
): Promise<{ accounts: ReadonlyArray<LegacyMigrationAccount> }> {
return {
accounts: this.ctx.storage.sql
.exec<AccountRow>(
`SELECT * FROM accounts
WHERE org_id = ?
ORDER BY id`,
orgId
)
.toArray()
.map((row) => ({
id: row.id,
kind: row.kind as AccountKind,
label: row.label,
enabled: row.enabled === 1,
hasTotp: row.totp_seed_base32 !== null,
...(row.credentials_json
? { credentials: JSON.parse(row.credentials_json) as AccountCredentials }
: {}),
})),
}
}

async beginMigrationAccounts(
orgId: string
): Promise<{ accounts: ReadonlyArray<LegacyMigrationAccount> }> {
return await this.ctx.blockConcurrencyWhile(async () => {
// A refresh token can be single-use. Let every refresh already holding
// one settle before snapshotting, then prevent later refreshes by
// disabling the source rows in the same concurrency barrier.
await Promise.allSettled([...this.refreshInFlight.values()])
const snapshot = await this.listMigrationAccounts(orgId)
this.ctx.storage.sql.exec(
"UPDATE accounts SET enabled = 0, updated_at = ? WHERE org_id = ?",
Date.now(),
orgId
)
await this.scheduleNextRefreshAlarm()
return snapshot
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

async restoreMigrationAccounts(input: {
readonly orgId: string
readonly accounts: ReadonlyArray<LegacyMigrationAccount>
}): Promise<void> {
this.ctx.storage.transactionSync(() => {
for (const account of input.accounts) {
this.ctx.storage.sql.exec(
"UPDATE accounts SET enabled = ?, updated_at = ? WHERE id = ? AND org_id = ?",
account.enabled ? 1 : 0,
Date.now(),
account.id,
input.orgId
)
}
})
await this.scheduleNextRefreshAlarm()
}

async completeMigrationAccounts(input: {
readonly orgId: string
readonly accounts: ReadonlyArray<LegacyMigrationAccount>
}): Promise<void> {
this.ctx.storage.transactionSync(() => {
const sql = this.ctx.storage.sql
for (const account of input.accounts) {
const row = this.getAccountRow(sql, input.orgId, account.id, false)
if (
!row ||
row.enabled !== 0 ||
row.credentials_json !== JSON.stringify(account.credentials)
) {
throw new Error("migration source changed during hosted upload")
}
}
for (const account of input.accounts) {
this.deleteAccountRows(sql, input.orgId, account.id)
}
})
await this.scheduleNextRefreshAlarm()
}

async deleteAccount(input: { readonly orgId?: string; readonly accountId: string }): Promise<{ ok: true }> {
const orgId = this.resolveOrgId(input.orgId)
const accountId = this.requireNonEmpty(input.accountId, "accountId")
const row = this.getAccountRow(this.ctx.storage.sql, orgId, accountId, false)
if (!row) throw new Error("account not found")
const sql = this.ctx.storage.sql
sql.exec("DELETE FROM accounts WHERE id = ? AND org_id = ?", accountId, orgId)
sql.exec("DELETE FROM account_model_quotas WHERE account_id = ?", accountId)
sql.exec("DELETE FROM account_usage WHERE account_id = ?", accountId)
sql.exec(
"DELETE FROM session_assignments WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM sticky_sessions WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM sticky_session_routes WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM credential_leases WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM credential_quota_cooldowns WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
this.deleteAccountRows(this.ctx.storage.sql, orgId, accountId)
await this.scheduleNextRefreshAlarm()
return { ok: true }
}
Expand Down Expand Up @@ -3133,6 +3253,41 @@ export class SubrouterDurableObject extends DurableObject<Env> {
)
}

private deleteAccountRows(
sql: SqlStorage,
orgId: string,
accountId: string
): void {
sql.exec("DELETE FROM accounts WHERE id = ? AND org_id = ?", accountId, orgId)
sql.exec("DELETE FROM account_model_quotas WHERE account_id = ?", accountId)
sql.exec("DELETE FROM account_usage WHERE account_id = ?", accountId)
sql.exec(
"DELETE FROM session_assignments WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM sticky_sessions WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM sticky_session_routes WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM credential_leases WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
sql.exec(
"DELETE FROM credential_quota_cooldowns WHERE org_id = ? AND account_id = ?",
orgId,
accountId
)
}

private async refreshAccountIfExpired(
orgId: string,
accountId: string,
Expand Down Expand Up @@ -4856,6 +5011,64 @@ const handleFetch = async (
return json(await registryActor(env).listTenants())
}

const tenantMigrationMatch = url.pathname.match(
/^\/admin\/tenants\/([^/]+)\/migrate-hosted$/
)
if (tenantMigrationMatch && request.method === "POST") {
const tenantId = decodeURIComponent(tenantMigrationMatch[1]!)
const record = await parseBoundedJsonRecord(request, 4 * 1024)
if (record instanceof Response) return record
Comment on lines +5275 to +5278

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Validate tenantId before you address the Durable Object.

Line 5018 passes the decoded path segment straight to adminActor at Line 5031. Other routes in this file normalize it first. /_subrouter/ready calls normalizeTenantId and returns 400 for an invalid value (Lines 4658-4661).

Without that check, a malformed tenant id addresses a new empty Durable Object. The migration then returns 200 with migrated: 0, and the operator believes an empty tenant was migrated.

🐛 Proposed fix
       if (tenantMigrationMatch && request.method === "POST") {
-        const tenantId = decodeURIComponent(tenantMigrationMatch[1]!)
+        const tenantId = normalizeTenantId(
+          decodeURIComponent(tenantMigrationMatch[1]!)
+        )
+        if (!tenantId) {
+          return json({ error: "Invalid tenant" }, { status: 400 })
+        }
         const record = await parseBoundedJsonRecord(request, 4 * 1024)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (tenantMigrationMatch && request.method === "POST") {
const tenantId = decodeURIComponent(tenantMigrationMatch[1]!)
const record = await parseBoundedJsonRecord(request, 4 * 1024)
if (record instanceof Response) return record
if (tenantMigrationMatch && request.method === "POST") {
const tenantId = normalizeTenantId(
decodeURIComponent(tenantMigrationMatch[1]!)
)
if (!tenantId) {
return json({ error: "Invalid tenant" }, { status: 400 })
}
const record = await parseBoundedJsonRecord(request, 4 * 1024)
if (record instanceof Response) return record
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cloudflare/packages/worker/src/index.ts` around lines 5017 - 5020, Validate
the decoded tenantId in the tenant migration POST handler before parsing the
request or calling adminActor. Use normalizeTenantId, return HTTP 400 for an
invalid value consistent with /_subrouter/ready, and pass the normalized tenant
ID to the Durable Object.

if (
record["finalizeSource"] !== undefined &&
typeof record["finalizeSource"] !== "boolean"
) {
return json({ error: "finalizeSource must be boolean" }, { status: 400 })
}
try {
// Cloudflare's generated RPC stub erases methods that carry the
// encrypted credential union. Keep the cast at this trusted DO
// boundary and validate the rows before any outbound upload.
const actor = adminActor(
env,
tenantId
) as unknown as LegacyMigrationActor
const requestHost = new URL(request.url).hostname
const finalizeSource = record["finalizeSource"] === true
const migrated = await migrateLegacyTenant({
destinationUrl: record["destinationUrl"],
tenantKey: record["tenantKey"],
finalizeSource,
allowLoopback:
requestHost === "localhost" ||
requestHost === "127.0.0.1" ||
requestHost === "[::1]",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
source: {
list: async () =>
(await actor.listMigrationAccounts(tenantId)).accounts,
begin: async () =>
(await actor.beginMigrationAccounts(tenantId)).accounts,
complete: async (accounts) =>
await actor.completeMigrationAccounts({
orgId: tenantId,
accounts,
}),
restore: async (accounts) =>
await actor.restoreMigrationAccounts({
orgId: tenantId,
accounts,
}),
},
})
return json(
{ ok: true, migrated, sourceFinalized: finalizeSource },
{ headers: { "Cache-Control": "no-store" } }
)
} catch (error) {
if (telemetry) telemetry.errorType = errorTypeFor(error)
return errorJson(error, 409)
}
}

const tenantRevokeMatch = url.pathname.match(/^\/admin\/tenants\/([^/]+)\/revoke$/)
if (tenantRevokeMatch && request.method === "POST") {
const tenantId = decodeURIComponent(tenantRevokeMatch[1]!)
Expand Down
Loading