CVE-2022-23510: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') (CWE-89)
value: cube-js is a headless business intelligence platform. In version 0.31.23 all authenticated Cube clients could bypass SQL row-level security and run arbitrary SQL via the newly introduced /v1/sql-runner endpoint. This issue has been resolved in version 0.31.24. Users are advised to either upgrade to 0.31.24 or to downgrade to 0.31.22. There are no known workarounds for this vulnerability.
CWE description: The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.
CVSS v3 base score: 8.8
Published: 2022-12-09T23:15Z
Repository: https://github.com/cube-js/cube.js
Language: TypeScript
Files changed: packages/cubejs-api-gateway/src/gateway.ts, packages/cubejs-api-gateway/test/index.test.ts
Commit date: 2022-12-09 10:48:41 -0800
Commit message: Revert "chore(cubejs-api-gateway): added endpoint to run sql query directly (#5723)" (#5784)

This reverts commit f1e25bb50323c0b99f3891d349467e7b637baeea.
Diff: diff --git a/packages/cubejs-api-gateway/src/gateway.ts b/packages/cubejs-api-gateway/src/gateway.ts
index 32698dd9f..56caf82fd 100644
--- a/packages/cubejs-api-gateway/src/gateway.ts
+++ b/packages/cubejs-api-gateway/src/gateway.ts
@@ -249,23 +249,10 @@ class ApiGateway {
           res: this.resToResultFn(res),
         });
       }
     }));
 
-    app.post(
-      `${this.basePath}/v1/sql-runner`,
-      jsonParser,
-      userMiddlewares,
-      async (req: Request, res: Response) => {
-        await this.sqlRunner({
-          query: req.body.query,
-          context: req.context!,
-          res: this.resToResultFn(res),
-        });
-      }
-    );
-
     app.get(`${this.basePath}/v1/run-scheduled-refresh`, userMiddlewares, (async (req, res) => {
       await this.runScheduledRefresh({
         queryingOptions: req.query.queryingOptions,
         context: req.context,
         res: this.resToResultFn(res)
@@ -1081,58 +1068,10 @@ class ApiGateway {
         e, context, query, res, requestStarted
       });
     }
   }
 
-  public async sqlRunner({ query, context, res }: QueryRequest) {
-    const requestStarted = new Date();
-    try {
-      if (!query) {
-        throw new UserError(
-          'A user\'s query must contain a body'
-        );
-      }
-      
-      if (!(query as Record<string, any>).query) {
-        throw new UserError(
-          'A user\'s query must contain at least one query param.'
-        );
-      }
-
-      query = {
-        ...query,
-        requestId: context.requestId
-      };
-
-      this.log(
-        {
-          type: 'Load SQL Runner Request',
-          query,
-        },
-        context
-      );
-
-      const result = await this.getAdapterApi(context).executeQuery(query);
-
-      this.log(
-        {
-          type: 'Load SQL Runner Request Success',
-          query,
-          duration: this.duration(requestStarted),
-          dbType: result.dbType,
-        },
-        context
-      );
-
-      res(result);
-    } catch (e) {
-      this.handleError({
-        e, context, query, res, requestStarted
-      });
-    }
-  }
-
   protected createSecurityContextExtractor(options?: JWTOptions): SecurityContextExtractorFn {
     if (options?.claimsNamespace) {
       return (ctx: Readonly<RequestContext>) => {
         if (typeof ctx.securityContext === 'object' && ctx.securityContext !== null) {
           if (<string>options.claimsNamespace in ctx.securityContext) {
diff --git a/packages/cubejs-api-gateway/test/index.test.ts b/packages/cubejs-api-gateway/test/index.test.ts
index 32ff5bd73..d3cb48db2 100644
--- a/packages/cubejs-api-gateway/test/index.test.ts
+++ b/packages/cubejs-api-gateway/test/index.test.ts
@@ -337,62 +337,10 @@ describe('API Gateway', () => {
       { id: 'Foo.foo', desc: true },
     ]);
     expect(res.body.query.measures).toStrictEqual(['Foo.bar']);
   });
 
-  test('post http method for sql-runner route required params', async () => {
-    const { app } = createApiGateway();
-
-    const res = await request(app)
-      .post('/cubejs-api/v1/sql-runner')
-      .set('Content-type', 'application/json')
-      .set(
-        'Authorization',
-        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'
-      )
-      .send({})
-      .expect(400);
-
-    expect(res.body && res.body.error).toStrictEqual('A user\'s query must contain a body');
-
-    const res2 = await request(app)
-      .post('/cubejs-api/v1/sql-runner')
-      .set('Content-type', 'application/json')
-      .set(
-        'Authorization',
-        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'
-      )
-      .send({ query: { query: '' } })
-      .expect(400);
-
-    expect(res2.body && res2.body.error).toStrictEqual(
-      'A user\'s query must contain at least one query param.'
-    );
-  });
-
-  test('post http method for sql-runner route', async () => {
-    const { app } = createApiGateway();
-
-    const query = {
-      query: 'SELECT * FROM Foo',
-    };
-
-    const res = await request(app)
-      .post('/cubejs-api/v1/sql-runner')
-      .set('Content-type', 'application/json')
-      .set(
-        'Authorization',
-        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'
-      )
-      .send({ query })
-      .expect(200);
-
-    expect(res.body.data).toStrictEqual([
-      { foo__bar: 42 },
-    ]);
-  });
-
   test('meta endpoint to get schema information', async () => {
     const { app } = createApiGateway();
 
     const res = await request(app)
       .get('/cubejs-api/v1/meta')

Vulnerable code:     app.post(
      `${this.basePath}/v1/sql-runner`,
      jsonParser,
      userMiddlewares,
      async (req: Request, res: Response) => {
        await this.sqlRunner({
          query: req.body.query,
          context: req.context!,
          res: this.resToResultFn(res),
        });
      }
    );

  public async sqlRunner({ query, context, res }: QueryRequest) {
    const requestStarted = new Date();
    try {
      if (!query) {
        throw new UserError(
          'A user\'s query must contain a body'
        );
      }
      
      if (!(query as Record<string, any>).query) {
        throw new UserError(
          'A user\'s query must contain at least one query param.'
        );
      }

      query = {
        ...query,
        requestId: context.requestId
      };

      this.log(
        {
          type: 'Load SQL Runner Request',
          query,
        },
        context
      );

      const result = await this.getAdapterApi(context).executeQuery(query);

      this.log(
        {
          type: 'Load SQL Runner Request Success',
          query,
          duration: this.duration(requestStarted),
          dbType: result.dbType,
        },
        context
      );

      res(result);
    } catch (e) {
      this.handleError({
        e, context, query, res, requestStarted
      });
    }
  }

  test('post http method for sql-runner route required params', async () => {
    const { app } = createApiGateway();

    const res = await request(app)
      .post('/cubejs-api/v1/sql-runner')
      .set('Content-type', 'application/json')
      .set(
        'Authorization',
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'
      )
      .send({})
      .expect(400);

    expect(res.body && res.body.error).toStrictEqual('A user\'s query must contain a body');

    const res2 = await request(app)
      .post('/cubejs-api/v1/sql-runner')
      .set('Content-type', 'application/json')
      .set(
        'Authorization',
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'
      )
      .send({ query: { query: '' } })
      .expect(400);

    expect(res2.body && res2.body.error).toStrictEqual(
      'A user\'s query must contain at least one query param.'
    );
  });

  test('post http method for sql-runner route', async () => {
    const { app } = createApiGateway();

    const query = {
      query: 'SELECT * FROM Foo',
    };

    const res = await request(app)
      .post('/cubejs-api/v1/sql-runner')
      .set('Content-type', 'application/json')
      .set(
        'Authorization',
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'
      )
      .send({ query })
      .expect(200);

    expect(res.body.data).toStrictEqual([
      { foo__bar: 42 },
    ]);
  });