@@ -36,6 +36,9 @@ import { TaskContext } from "./tasks";
3636
3737const JWT_REGEX = / ^ [ a - z A - Z 0 - 9 \- _ = ] + ?\. [ a - z A - Z 0 - 9 \- _ = ] + ?\. ( [ a - z A - Z 0 - 9 \- _ = ] + ) ? $ / ;
3838
39+ const CALLABLE_AUTH_HEADER = "x-callable-context-auth" ;
40+ const ORIGINAL_AUTH_HEADER = "x-original-auth" ;
41+
3942/** An express request with the wire format representation of the request body. */
4043export interface Request extends express . Request {
4144 /** The wire format representation of the request body. */
@@ -661,6 +664,32 @@ function wrapOnCallHandler<Req = any, Res = any>(
661664 }
662665
663666 const context : CallableContext = { rawRequest : req } ;
667+
668+ // TODO(colerogers): yank this when we release a breaking change of the CLI that removes
669+ // our monkey-patching code referenced below and increases the minimum supported SDK version.
670+ //
671+ // Note: This code is needed to fix v1 callable functions in the emulator with a monorepo setup.
672+ // The original monkey-patched code lived in the functionsEmulatorRuntime
673+ // (link: https://github.com/firebase/firebase-tools/blob/accea7abda3cc9fa6bb91368e4895faf95281c60/src/emulator/functionsEmulatorRuntime.ts#L480)
674+ // and was not compatible with how monorepos separate out packages (see https://github.com/firebase/firebase-tools/issues/5210).
675+ if ( isDebugFeatureEnabled ( "skipTokenVerification" ) && handler . length === 2 ) {
676+ const authContext = context . rawRequest . header ( CALLABLE_AUTH_HEADER ) ;
677+ if ( authContext ) {
678+ logger . debug ( "Callable functions auth override" , {
679+ key : CALLABLE_AUTH_HEADER ,
680+ value : authContext ,
681+ } ) ;
682+ context . auth = JSON . parse ( decodeURIComponent ( authContext ) ) ;
683+ delete context . rawRequest . headers [ CALLABLE_AUTH_HEADER ] ;
684+ }
685+
686+ const originalAuth = context . rawRequest . header ( ORIGINAL_AUTH_HEADER ) ;
687+ if ( originalAuth ) {
688+ context . rawRequest . headers [ "authorization" ] = originalAuth ;
689+ delete context . rawRequest . headers [ ORIGINAL_AUTH_HEADER ] ;
690+ }
691+ }
692+
664693 const tokenStatus = await checkTokens ( req , context ) ;
665694 if ( tokenStatus . auth === "INVALID" ) {
666695 throw new HttpsError ( "unauthenticated" , "Unauthenticated" ) ;
0 commit comments