Skip to content
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

fix: add more measures to prevent using data-cache for blob operations #2775

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions src/run/handlers/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ import {
setCacheTagsHeaders,
setVaryHeaders,
} from '../headers.js'
import { setFetchBeforeNextPatchedIt } from '../regional-blob-store.cjs'
import { nextResponseProxy } from '../revalidate.js'

import { getLogger, type RequestContext } from './request-context.cjs'
import { getTracer } from './tracer.cjs'
import { setupWaitUntil } from './wait-until.cjs'

setFetchBeforeNextPatchedIt(globalThis.fetch)

const nextImportPromise = import('../next.cjs')

setupWaitUntil()
Expand Down
55 changes: 53 additions & 2 deletions src/run/regional-blob-store.cts
Original file line number Diff line number Diff line change
@@ -1,11 +1,62 @@
import { getDeployStore, GetWithMetadataOptions, Store } from '@netlify/blobs'

const fetchBeforeNextPatchedIt = globalThis.fetch
const FETCH_BEFORE_NEXT_PATCHED_IT = Symbol.for('nf-not-patched-fetch')
const extendedGlobalThis = globalThis as typeof globalThis & {
[FETCH_BEFORE_NEXT_PATCHED_IT]?: typeof globalThis.fetch
}

/**
* Attempt to extract original fetch in case it was patched by Next.js already
*
* @see github.com/vercel/next.js/blob/fa214c74c1d8023098c0e94e57f917ef9f1afd1a/packages/next/src/server/lib/patch-fetch.ts#L986
*/
function attemptToGetOriginalFetch(
fetch: typeof globalThis.fetch & {
_nextOriginalFetch?: typeof globalThis.fetch
},
) {
return fetch._nextOriginalFetch ?? fetch
}

function forceOptOutOfUsingDataCache(fetch: typeof globalThis.fetch): typeof globalThis.fetch {
return (input, init) => {
return fetch(input, {
...init,
next: {
...init?.next,
// setting next.internal = true should prevent from trying to use data cache
// https://github.com/vercel/next.js/blob/fa214c74c1d8023098c0e94e57f917ef9f1afd1a/packages/next/src/server/lib/patch-fetch.ts#L174
// https://github.com/vercel/next.js/blob/fa214c74c1d8023098c0e94e57f917ef9f1afd1a/packages/next/src/server/lib/patch-fetch.ts#L210-L213
// this is last line of defense in case we didn't manage to get unpatched fetch that will not affect
// fetch if it's unpatched so it should be safe to apply always if we aren't sure if we use patched fetch

// @ts-expect-error - this is an internal field that Next.js doesn't add to its global
// type overrides for RequestInit type (like `next.revalidate` or `next.tags`)
internal: true,
},
})
}
}

export const setFetchBeforeNextPatchedIt = (fetch: typeof globalThis.fetch) => {
// we store in globalThis in case we have multiple copies of this module
// just as precaution

extendedGlobalThis[FETCH_BEFORE_NEXT_PATCHED_IT] = forceOptOutOfUsingDataCache(
attemptToGetOriginalFetch(fetch),
)
}

const fetchBeforeNextPatchedItFallback = forceOptOutOfUsingDataCache(
attemptToGetOriginalFetch(globalThis.fetch),
)
const getFetchBeforeNextPatchedIt = () =>
extendedGlobalThis[FETCH_BEFORE_NEXT_PATCHED_IT] ?? fetchBeforeNextPatchedItFallback
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this necessary? You're calling setFetchBeforeNextPatchedIt in the global scope of server.ts, so would the fallback ever be used?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It should not be needed when running full on server handler, no.

I did want to make this module to not necessarily rely on setup (might be useful for unit tests, tho not sure if we actually have any that would would fall into using this module today)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is also just using pattern of allowing few points of failure because of overall messiness with patched fetch - if for whatever reason we don't call setFetchBeforeNextPatchedIt before we execute getFetchBeforeNextPatchedIt - I do want to use rest of defensive measures (such as trying to grab _originalFetch first and ultimately adding next.internal = true param to fetch calls) and continue to have this fallback just fits the best here (IMO)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So I'll go ahead and merge as-is


export const getRegionalBlobStore = (args: GetWithMetadataOptions = {}): Store => {
return getDeployStore({
...args,
fetch: fetchBeforeNextPatchedIt,
fetch: getFetchBeforeNextPatchedIt(),
region: process.env.USE_REGIONAL_BLOBS?.toUpperCase() === 'TRUE' ? undefined : 'us-east-2',
})
}
Loading