Skip to content

Commit

Permalink
Add an option to disable rejection of requests with invalid App Check…
Browse files Browse the repository at this point in the history
… token for callable functions. (#989)

Since releasing App Check integration for Callable Functions, we've received several requests from our users to make it possible turn  App Check enforcement off. By default, if a request includes an App Check token, callable functions will verify the token, and - if the token is invalid - reject the request. This makes it hard for developers to onboard to App Check, especially for developers that want to "soft launch" App Check integration to measure the App Check enforcement would have on its users.

The change here adds a `runWith` option to allow requests with invalid App check token to continue to user code execution, e.g.

```js
exports.yourCallableFunction = functions.
  .runWith({
    allowInvalidAppCheckToken: true  // Opt-out: Invalid App Check token cont. to user code.
  }).
  .https.onCall(
  (data, context) => {
    // Requests with an invalid App Check token are not rejected.
    //
    // context.app will be undefined if the request:
    //   1) Does not include an App Check token
    //   2) Includes an invalid App Check token
    if (context.app == undefined) {
      // Users can manually inspect raw request header to check whether an App Check
      // token was provided in the request.
      const rawToken = context.rawRequest.header['X-Firebase-AppCheck'];
      if (rawToken == undefined) {
        throw new functions.https.HttpsError(
            'failed-precondition',
            'The function must be called from an App Check verified app.'
        );
      } else {
        throw new functions.https.HttpsError(
            'unauthenticated',
            'Provided App Check token failed to validate.'
        );
      }
    },
  }
);
```
  • Loading branch information
taeold authored Oct 14, 2021
1 parent 0479817 commit 63bd14d
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
- GCS Enhancement
- Add option to allow callable functions to ignore invalid App Check tokens.
31 changes: 30 additions & 1 deletion spec/common/providers/https.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ interface CallTest {

callableFunction2: (request: https.CallableRequest<any>) => any;

callableOption?: https.CallableOptions;

// The expected shape of the http response returned to the callable SDK.
expectedHttpResponse: RunHandlerResult;
}
Expand Down Expand Up @@ -104,7 +106,10 @@ function runHandler(

// Runs a CallTest test.
async function runTest(test: CallTest): Promise<any> {
const opts = { origin: true, methods: 'POST' };
const opts = {
cors: { origin: true, methods: 'POST' },
...test.callableOption,
};
const callableFunctionV1 = https.onCallHandler(opts, (data, context) => {
expect(data).to.deep.equal(test.expectedData);
return test.callableFunction(data, context);
Expand Down Expand Up @@ -470,6 +475,30 @@ describe('onCallHandler', () => {
});
});

it('should handle bad AppCheck token with callable option', async () => {
await runTest({
httpRequest: mockRequest(null, 'application/json', {
appCheckToken: 'FAKE',
}),
expectedData: null,
callableFunction: (data, context) => {
return;
},
callableFunction2: (request) => {
return;
},
callableOption: {
cors: { origin: true, methods: 'POST' },
allowInvalidAppCheckToken: true,
},
expectedHttpResponse: {
status: 200,
headers: expectedResponseHeaders,
body: { result: null },
},
});
});

it('should handle instance id', async () => {
await runTest({
httpRequest: mockRequest(null, 'application/json', {
Expand Down
18 changes: 14 additions & 4 deletions src/common/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,16 +592,22 @@ async function checkTokens(
type v1Handler = (data: any, context: CallableContext) => any | Promise<any>;
type v2Handler<Req, Res> = (request: CallableRequest<Req>) => Res;

/** @hidden **/
export interface CallableOptions {
cors: cors.CorsOptions;
allowInvalidAppCheckToken?: boolean;
}

/** @hidden */
export function onCallHandler<Req = any, Res = any>(
options: cors.CorsOptions,
options: CallableOptions,
handler: v1Handler | v2Handler<Req, Res>
): (req: Request, res: express.Response) => Promise<void> {
const wrapped = wrapOnCallHandler(handler);
const wrapped = wrapOnCallHandler(options, handler);
return (req: Request, res: express.Response) => {
return new Promise((resolve) => {
res.on('finish', resolve);
cors(options)(req, res, () => {
cors(options.cors)(req, res, () => {
resolve(wrapped(req, res));
});
});
Expand All @@ -610,6 +616,7 @@ export function onCallHandler<Req = any, Res = any>(

/** @internal */
function wrapOnCallHandler<Req = any, Res = any>(
options: CallableOptions,
handler: v1Handler | v2Handler<Req, Res>
): (req: Request, res: express.Response) => Promise<void> {
return async (req: Request, res: express.Response): Promise<void> => {
Expand All @@ -621,7 +628,10 @@ function wrapOnCallHandler<Req = any, Res = any>(

const context: CallableContext = { rawRequest: req };
const tokenStatus = await checkTokens(req, context);
if (tokenStatus.app === 'INVALID' || tokenStatus.auth === 'INVALID') {
if (tokenStatus.auth === 'INVALID') {
throw new HttpsError('unauthenticated', 'Unauthenticated');
}
if (tokenStatus.app === 'INVALID' && !options.allowInvalidAppCheckToken) {
throw new HttpsError('unauthenticated', 'Unauthenticated');
}

Expand Down
5 changes: 5 additions & 0 deletions src/function-configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,11 @@ export interface RuntimeOptions {
* Invoker to set access control on https functions.
*/
invoker?: 'public' | 'private' | string | string[];

/*
* Allow requests with invalid App Check tokens on callable functions.
*/
allowInvalidAppCheckToken?: boolean;
}

export interface DeploymentOptions extends RuntimeOptions {
Expand Down
8 changes: 7 additions & 1 deletion src/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,13 @@ export function _onCallWithOptions(
// in another handler to avoid accidentally triggering the v2 API
const fixedLen = (data: any, context: CallableContext) =>
handler(data, context);
const func: any = onCallHandler({ origin: true, methods: 'POST' }, fixedLen);
const func: any = onCallHandler(
{
allowInvalidAppCheckToken: options.allowInvalidAppCheckToken,
cors: { origin: true, methods: 'POST' },
},
fixedLen
);

func.__trigger = {
labels: {},
Expand Down
5 changes: 4 additions & 1 deletion src/v2/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ export function onCall<T = any, Return = any | Promise<any>>(
// onCallHandler sniffs the function length to determine which API to present.
// fix the length to prevent api versions from being mismatched.
const fixedLen = (req: CallableRequest<T>) => handler(req);
const func: any = onCallHandler({ origin, methods: 'POST' }, fixedLen);
const func: any = onCallHandler(
{ cors: { origin, methods: 'POST' } },
fixedLen
);

Object.defineProperty(func, '__trigger', {
get: () => {
Expand Down

0 comments on commit 63bd14d

Please sign in to comment.