• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / storage / 30827295744

03 Aug 2026 03:23PM UTC coverage: 80.494% (+0.1%) from 80.366%
30827295744

push

github

web-flow
fix: hardening for non-json object reply (#1293)

Signed-off-by: ferhat elmas <elmas.ferhat@gmail.com>

5615 of 7504 branches covered (74.83%)

Branch coverage included in aggregate %.

28 of 32 new or added lines in 5 files covered. (87.5%)

10611 of 12654 relevant lines covered (83.85%)

433.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.09
/src/http/plugins/db.ts
1
import { createSingleFlightByKey } from '@internal/concurrency'
2
import {
3
  getPostgresConnection,
4
  getServiceKeyUser,
5
  getTenantConfig,
6
  type TenantConnection,
7
  TenantMigrationStatus,
8
} from '@internal/database'
9
import {
10
  areMigrationsUpToDate,
11
  DBMigration,
12
  lastLocalMigrationName,
13
  progressiveMigrations,
14
  runMigrationsOnTenant,
15
  updateTenantMigrationsState,
16
} from '@internal/database/migrations'
17
import { ERRORS } from '@internal/errors'
18
import type { FastifyInstance } from 'fastify'
19
import fastifyPlugin from 'fastify-plugin'
20
import { getConfig, MultitenantMigrationStrategy } from '../../config'
21

22
declare module 'fastify' {
23
  interface FastifyRequest {
24
    db: TenantConnection
25
    latestMigration?: keyof typeof DBMigration
26
  }
27
}
28

29
const { databaseEnableQueryCancellation, dbMigrationStrategy, isMultitenant, dbMigrationFreezeAt } =
30
  getConfig()
56✔
31

32
const migrationSingleFlight = createSingleFlightByKey<keyof typeof DBMigration>()
56✔
33

34
function resolveLatestMigration(
35
  localLatest: keyof typeof DBMigration,
36
  applied: keyof typeof DBMigration | undefined
37
): keyof typeof DBMigration {
38
  if (
30✔
39
    applied &&
61✔
40
    DBMigration[applied] !== undefined &&
41
    DBMigration[applied] > DBMigration[localLatest]
42
  ) {
43
    return applied
3✔
44
  }
45
  return localLatest
27✔
46
}
47

48
export const db = fastifyPlugin(
56✔
49
  async function db(fastify) {
50
    fastify.register(migrations)
4,753✔
51

52
    fastify.decorateRequest('db')
4,753✔
53

54
    fastify.addHook('preHandler', async (request) => {
4,753✔
55
      const adminUser = await getServiceKeyUser(request.tenantId)
1,097✔
56
      const userPayload = request.jwtPayload
1,097✔
57

58
      if (!userPayload) {
1,097!
59
        throw ERRORS.AccessDenied('JWT payload is missing')
×
60
      }
61

62
      request.db = await getPostgresConnection({
1,097✔
63
        user: {
64
          payload: userPayload,
65
          jwt: request.jwt,
66
        },
67
        superUser: adminUser,
68
        tenantId: request.tenantId,
69
        host: request.headers['x-forwarded-host'] as string,
70
        headers: request.headers,
71
        path: request.url,
72
        method: request.method,
73
        operation: () => request.operation,
2,413✔
74
      })
75

76
      // Connect abort signal to DB connection for query cancellation
77
      if (databaseEnableQueryCancellation && request.signals) {
1,095✔
78
        request.db.setAbortSignal(request.signals.disconnect.signal)
1✔
79
      }
80
    })
81

82
    registerConnectionCleanupHooks(fastify)
4,753✔
83
  },
84
  { name: 'db-init' }
85
)
86

87
interface DbSuperUserPluginOptions {
88
  disableHostCheck?: boolean
89
}
90

91
export const dbSuperUser = fastifyPlugin<DbSuperUserPluginOptions>(
56✔
92
  async function dbSuperUser(fastify, opts) {
93
    fastify.register(migrations)
1,832✔
94
    fastify.decorateRequest('db')
1,832✔
95

96
    fastify.addHook('preHandler', async (request) => {
1,832✔
97
      const adminUser = await getServiceKeyUser(request.tenantId)
220✔
98

99
      request.db = await getPostgresConnection({
220✔
100
        user: adminUser,
101
        superUser: adminUser,
102
        tenantId: request.tenantId,
103
        host: request.headers['x-forwarded-host'] as string,
104
        path: request.url,
105
        method: request.method,
106
        headers: request.headers,
107
        disableHostCheck: opts.disableHostCheck,
108
        operation: () => request.operation,
65✔
109
      })
110

111
      // Connect abort signal to DB connection for query cancellation
112
      if (databaseEnableQueryCancellation && request.signals) {
220✔
113
        request.db.setAbortSignal(request.signals.disconnect.signal)
1✔
114
      }
115
    })
116

117
    registerConnectionCleanupHooks(fastify)
1,832✔
118
  },
119
  { name: 'db-superuser-init' }
120
)
121

122
function registerConnectionCleanupHooks(fastify: FastifyInstance) {
123
  fastify.addHook('onSend', (request, _reply, payload, done) => {
6,585✔
124
    request.db?.dispose()
1,384✔
125
    done(null, payload)
1,384✔
126
  })
127

128
  fastify.addHook('onTimeout', (request, _reply, done) => {
6,585✔
NEW
129
    request.db?.dispose()
×
NEW
130
    done()
×
131
  })
132

133
  fastify.addHook('onRequestAbort', (request, done) => {
6,585✔
134
    request.db?.dispose()
2✔
135
    done()
2✔
136
  })
137
}
138

139
/**
140
 * Handle database migration for multitenant applications when a request is made
141
 */
142
export const migrations = fastifyPlugin(
56✔
143
  async function migrations(fastify) {
144
    fastify.addHook('preHandler', async (req) => {
6,585✔
145
      if (isMultitenant) {
1,319✔
146
        const { migrationVersion } = await getTenantConfig(req.tenantId)
22✔
147
        req.latestMigration = migrationVersion
22✔
148
        return
22✔
149
      }
150

151
      req.latestMigration = await lastLocalMigrationName()
1,297✔
152
    })
153

154
    if (dbMigrationStrategy === MultitenantMigrationStrategy.ON_REQUEST) {
6,585✔
155
      fastify.addHook('preHandler', async (request) => {
6,578✔
156
        // migrations are handled via async migrations
157
        if (!isMultitenant) {
1,312✔
158
          return
1,290✔
159
        }
160

161
        const tenant = await getTenantConfig(request.tenantId)
22✔
162
        if (tenant.syncMigrationsDone) {
22✔
163
          request.latestMigration = resolveLatestMigration(
4✔
164
            await lastLocalMigrationName(),
165
            tenant.migrationVersion
166
          )
167
          return
4✔
168
        }
169

170
        const latestMigration = await migrationSingleFlight(request.tenantId, async () => {
18✔
171
          const localLatest = await lastLocalMigrationName()
14✔
172
          const migrationsUpToDate = await areMigrationsUpToDate(request.tenantId)
14✔
173

174
          if (!migrationsUpToDate) {
14✔
175
            await runMigrationsOnTenant({
13✔
176
              databaseUrl: tenant.databaseUrl,
177
              tenantId: request.tenantId,
178
              upToMigration: dbMigrationFreezeAt,
179
            })
180
          }
181

182
          const refreshedTenant = await getTenantConfig(request.tenantId)
13✔
183
          const resolvedMigration = resolveLatestMigration(
13✔
184
            resolveLatestMigration(localLatest, tenant.migrationVersion),
185
            refreshedTenant.migrationVersion
186
          )
187

188
          if (!migrationsUpToDate) {
13✔
189
            await updateTenantMigrationsState(request.tenantId, {
12✔
190
              migration: resolvedMigration,
191
              state: TenantMigrationStatus.COMPLETED,
192
            })
193
          }
194

195
          refreshedTenant.migrationVersion = resolvedMigration
13✔
196
          refreshedTenant.migrationStatus = TenantMigrationStatus.COMPLETED
13✔
197
          refreshedTenant.syncMigrationsDone = true
13✔
198

199
          return resolvedMigration
13✔
200
        })
201

202
        tenant.migrationVersion = latestMigration
16✔
203
        tenant.migrationStatus = TenantMigrationStatus.COMPLETED
16✔
204
        tenant.syncMigrationsDone = true
16✔
205
        request.latestMigration = latestMigration
16✔
206
      })
207
    }
208

209
    if (dbMigrationStrategy === MultitenantMigrationStrategy.PROGRESSIVE) {
6,585✔
210
      fastify.addHook('preHandler', async (request) => {
7✔
211
        if (!isMultitenant) {
7!
212
          return
7✔
213
        }
214

215
        const tenant = await getTenantConfig(request.tenantId)
×
216
        if (tenant.syncMigrationsDone) {
×
217
          return
×
218
        }
219

220
        // migrations are up to date
221
        if (await areMigrationsUpToDate(request.tenantId)) {
×
222
          tenant.syncMigrationsDone = true
×
223
          return
×
224
        }
225

226
        progressiveMigrations.addTenant(request.tenantId)
×
227
      })
228
    }
229
  },
230
  { name: 'db-migrations' }
231
)
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc