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

JQ filtering in client #20

Merged
merged 9 commits into from
Oct 27, 2023
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
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn run lint-staged
114 changes: 114 additions & 0 deletions client/__tests__/__snapshots__/filter.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`json path filter returns only selected fields 1`] = `
{
"data": {
"items": [
{
"metadata": {
"name": "admin",
},
},
{
"metadata": {
"name": "aws-node",
},
},
],
"kind": "ClusterRoleList",
},
"status": 200,
}
`;

exports[`json path filter returns original input data on error 1`] = `
{
"data": {
"apiVersion": "rbac.authorization.k8s.io/v1",
"items": [
{
"metadata": {
"managedFields": [
{
"manager": "clusterrole-aggregation-controller",
"operation": "Apply",
},
{
"manager": "kube-apiserver",
"operation": "Update",
},
],
"name": "admin",
"resourceVersion": "345",
"uid": "4251609f-b3ca-4875-8ec6-76b40ab62748",
},
},
{
"metadata": {
"managedFields": [
{
"manager": "kubectl-client-side-apply",
"operation": "Update",
},
],
"name": "aws-node",
"resourceVersion": "273",
"uid": "63a3bed8-a750-440d-bca9-b5f41c8786c2",
},
},
],
"kind": "ClusterRoleList",
"metadata": {
"resourceVersion": "4423772",
},
},
"status": 200,
"statusText": "OK",
}
`;

exports[`json path filter returns original input data when no filter supplied 1`] = `
{
"data": {
"apiVersion": "rbac.authorization.k8s.io/v1",
"items": [
{
"metadata": {
"managedFields": [
{
"manager": "clusterrole-aggregation-controller",
"operation": "Apply",
},
{
"manager": "kube-apiserver",
"operation": "Update",
},
],
"name": "admin",
"resourceVersion": "345",
"uid": "4251609f-b3ca-4875-8ec6-76b40ab62748",
},
},
{
"metadata": {
"managedFields": [
{
"manager": "kubectl-client-side-apply",
"operation": "Update",
},
],
"name": "aws-node",
"resourceVersion": "273",
"uid": "63a3bed8-a750-440d-bca9-b5f41c8786c2",
},
},
],
"kind": "ClusterRoleList",
"metadata": {
"resourceVersion": "4423772",
},
},
"status": 200,
"statusText": "OK",
}
`;
70 changes: 70 additions & 0 deletions client/__tests__/filter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { jqTransform } from "../filter";

const exampleResponse = {
status: 200,
statusText: "OK",
data: {
kind: "ClusterRoleList",
apiVersion: "rbac.authorization.k8s.io/v1",
metadata: {
resourceVersion: "4423772",
},
items: [
{
metadata: {
name: "admin",
uid: "4251609f-b3ca-4875-8ec6-76b40ab62748",
resourceVersion: "345",
managedFields: [
{
manager: "clusterrole-aggregation-controller",
operation: "Apply",
},
{
manager: "kube-apiserver",
operation: "Update",
},
],
},
},
{
metadata: {
name: "aws-node",
uid: "63a3bed8-a750-440d-bca9-b5f41c8786c2",
resourceVersion: "273",
managedFields: [
{
manager: "kubectl-client-side-apply",
operation: "Update",
},
],
},
},
],
},
};

describe("json path filter", () => {
it("returns only selected fields", async () => {
const result = await jqTransform(
exampleResponse,
"{ status: .status, data: { kind: .data.kind, items: [.data.items[] | { metadata: { name: .metadata.name } }] } }"
);

expect(result).toMatchSnapshot();
});

describe("returns original input data", () => {
it("on error", async () => {
const result = await jqTransform(exampleResponse, "{ { }");

expect(result).toMatchSnapshot();
});

it("when no filter supplied", async () => {
const result = await jqTransform(exampleResponse, undefined);

expect(result).toMatchSnapshot();
});
});
});
30 changes: 30 additions & 0 deletions client/filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { isArray } from "lodash";

import { createLogger } from "../log";

const logger = createLogger({ name: "filter" });

// import { jq } from "node-jq";
// TODO fix node config because jq-node cannot be imported with the `import` syntax above
// Error:
// Module '"node-jq"' has no exported member 'jq'.
const jq = require("node-jq");

export const jqTransform = async (
data: any,
jqHeader: string | string[] | undefined
): Promise<any> => {
const query = isArray(jqHeader) ? jqHeader[0] : jqHeader;
Copy link
Contributor

Choose a reason for hiding this comment

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

Wouldn't you want to run this multiple times if there are multiple headers?

Suggested change
const query = isArray(jqHeader) ? jqHeader[0] : jqHeader;
const query = isArray(jqHeader) ? jqHeader : [jqHeader];

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You mean chain the header jq commands? The output of the first is the input of the second?
I don't know if that's helpful, I think chains should be expressible in one query.

if (!query) {
return data;
}
try {
return await jq.run(query, data, { input: "json", output: "json" });
} catch (error: any) {
logger.error(
{ error, jpSelectQuery: query },
"Error running jq query, ignoring filters"
);
return data;
}
};
30 changes: 21 additions & 9 deletions client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import {
JSONRPCServer,
JSONRPCServerAndClient,
} from "json-rpc-2.0";
import { omit } from "lodash";
import { isArray, omit } from "lodash";
import { Logger } from "pino";
import WebSocket from "ws";

import { DEFAULT_FORWARDED_REQUEST_TIMEOUT_MILLIS } from "../common/constants";
import { createLogger } from "../log";
import { ForwardedRequest, ForwardedResponse } from "../types";
import { ForwardedRequest, ForwardedResponse, JQ_HEADER } from "../types";
import { deferral } from "../util/deferral";
import { Backoff } from "./backoff";
import { jqTransform } from "./filter";
import { jwt } from "./jwks";

/**
Expand Down Expand Up @@ -62,11 +63,7 @@ export class JsonRpcClient {
});

axios.interceptors.response.use((response) => {
// Do not log response object, it's lengthy and difficult to filter out the authorization header
this.#logger.debug(
{ response: omit(response, "request") },
"Axios response"
);
this.#logger.debug({ response }, "Axios response");
return response;
});
}
Expand Down Expand Up @@ -134,7 +131,15 @@ export class JsonRpcClient {
this.#webSocket = clientSocket;

client.addMethod("call", async (request: ForwardedRequest) => {
this.#logger.debug({ request }, "forwarded request");
this.#logger.debug(
{
request: {
...request,
headers: omit(request.headers, "authorization"),
},
},
"forwarded request"
);
// The headers are modified:
// 1. The Content-Length header may not be accurate for the forwarded request. By removing it, axios can recalculate the correct length.
// 2. The Host header should be switched out to the host this client is targeting.
Expand All @@ -153,11 +158,18 @@ export class JsonRpcClient {
request.options?.timeoutMillis ||
DEFAULT_FORWARDED_REQUEST_TIMEOUT_MILLIS,
});
const jpSelectHeader = request.headers[JQ_HEADER];
this.#logger.debug({ response }, "forwarded response before filters");
const data = await jqTransform(response.data, jpSelectHeader);
this.#logger.debug(
{ response: data },
"forwarded response data after filters"
);
return {
headers: response.headers,
status: response.status,
statusText: response.statusText,
data: response.data,
data,
} as ForwardedResponse;
});

Expand Down
2 changes: 2 additions & 0 deletions log/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ export const createLogger = <T extends LoggerOptions>(
// Redact the authorization header that may contain a secret token
redact: [
"response.config.headers.authorization", // Axios intercepted response object
"response.request.headers.authorization", // Axios intercepted response object contains the request as well
"request.headers.authorization", // Axios intercepted request object + forwarded request object (JSON RPC request)
Copy link
Contributor

Choose a reason for hiding this comment

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

Do you also want just headers? it looks like you manually assign request / response headers to a bare headers field in some logs.

"headers.authorization",
],
formatters: {
level: (label) => {
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-promise": "^6.0.0",
"husky": "^8.0.2",
"husky": "^8.0.3",
"jest": "29.2.1",
"jest-extended": "3.2.4",
"jest-mock": "29.2.1",
Expand All @@ -46,6 +46,7 @@
"json-rpc-2.0": "^1.6.0",
"json-stream-stringify": "^3.1.0",
"lodash": "^4.17.21",
"node-jq": "^4.2.2",
"path-to-regexp": "^6.2.1",
"pino": "^8.14.1",
"pino-http": "^8.3.3",
Expand All @@ -62,7 +63,7 @@
"start:prod:server": "NODE_PATH=dist node dist/cli server",
"start:dev:client": "NODE_ENV=development nodemon cli client",
"start:prod:client": "NODE_PATH=dist node dist/cli client",
"prepare": "cd .. && husky install ts/.husky",
"prepare": "husky install",
"format": "prettier --write '**/*.{html,js,ts,json,less,md}'",
"format:quick": "pretty-quick --branch origin/main"
},
Expand Down
5 changes: 5 additions & 0 deletions prettier.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
importOrder: ["^(cli|testing)([/]|$)", "^[.][.]?([/]|$)"],
importOrderSeparation: true,
importOrderSortSpecifiers: true,
};
2 changes: 2 additions & 0 deletions types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Request } from "express";
import core from "express-serve-static-core";
import { IncomingHttpHeaders } from "node:http";

export const JQ_HEADER = "braekhus-jq-response-transform";

export type IncomingRequest = Request<
core.ParamsDictionary,
any,
Expand Down
Loading