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

[App Search] DRY helper for encoding/decoding routes that can have special characters in params #89811

Merged
merged 10 commits into from
Feb 2, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const ACTIONS_COLUMN = {
{ defaultMessage: 'View query analytics' }
),
type: 'icon',
icon: 'popout',
icon: 'eye',
Copy link
Member Author

Choose a reason for hiding this comment

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

This change has nothing to do with encoding/decoding, but Davey requested it recently (since the popout icon typically indicates a new tab/window, and that's not the case here) and I figure I'd shove it in this PR since it touches the 2 concerned views 😬 If you super hate that lmk and I can stop being lazy & pull it out to a separate PR haha

Copy link
Contributor

Choose a reason for hiding this comment

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

It's fine.........😒

color: 'primary',
onClick: (item: Query | RecentQuery) => {
const { navigateToUrl } = KibanaLogic.values;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
*/

import React from 'react';
import { useParams } from 'react-router-dom';
import { useValues } from 'kea';

import { i18n } from '@kbn/i18n';
import { EuiSpacer } from '@elastic/eui';

import { SetAppSearchChrome as SetPageChrome } from '../../../../shared/kibana_chrome';
import { BreadcrumbTrail } from '../../../../shared/kibana_chrome/generate_breadcrumbs';
import { useDecodedParams } from '../../../utils/encode_path_params';

import { AnalyticsLayout } from '../analytics_layout';
import { AnalyticsSection, QueryClicksTable } from '../components';
Expand All @@ -27,14 +27,15 @@ interface Props {
breadcrumbs: BreadcrumbTrail;
}
export const QueryDetail: React.FC<Props> = ({ breadcrumbs }) => {
const { query } = useParams() as { query: string };
const { query } = useDecodedParams();
const queryTitle = query === '""' ? query : `"${query}"`;

const { totalQueriesForQuery, queriesPerDayForQuery, startDate, topClicksForQuery } = useValues(
AnalyticsLogic
);

return (
<AnalyticsLayout isQueryView title={`"${query}"`}>
<AnalyticsLayout isQueryView title={queryTitle}>
<SetPageChrome trail={[...breadcrumbs, QUERY_DETAIL_TITLE, query]} />

<AnalyticsCards
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { i18n } from '@kbn/i18n';
import { Loading } from '../../../shared/loading';
import { SetAppSearchChrome as SetPageChrome } from '../../../shared/kibana_chrome';
import { FlashMessages } from '../../../shared/flash_messages';
import { useDecodedParams } from '../../utils/encode_path_params';
import { ResultFieldValue } from '../result';

import { DocumentDetailLogic } from './document_detail_logic';
Expand All @@ -43,6 +44,7 @@ export const DocumentDetail: React.FC<Props> = ({ engineBreadcrumb }) => {
const { deleteDocument, getDocumentDetails, setFields } = useActions(DocumentDetailLogic);

const { documentId } = useParams() as { documentId: string };
const { documentId: documentTitle } = useDecodedParams();

useEffect(() => {
getDocumentDetails(documentId);
Expand Down Expand Up @@ -74,13 +76,11 @@ export const DocumentDetail: React.FC<Props> = ({ engineBreadcrumb }) => {

return (
<>
<SetPageChrome
trail={[...engineBreadcrumb, DOCUMENTS_TITLE, decodeURIComponent(documentId)]}
/>
<SetPageChrome trail={[...engineBreadcrumb, DOCUMENTS_TITLE, documentTitle]} />
<EuiPageHeader>
<EuiPageHeaderSection>
<EuiTitle size="l">
<h1>{DOCUMENT_DETAIL_TITLE(decodeURIComponent(documentId))}</h1>
<h1>{DOCUMENT_DETAIL_TITLE(documentTitle)}</h1>
</EuiTitle>
</EuiPageHeaderSection>
<EuiPageHeaderSection>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

import { generatePath } from 'react-router-dom';

import { encodePathParams } from '../../utils/encode_path_params';

import { EngineLogic } from './';

/**
* Generate a path with engineName automatically filled from EngineLogic state
*/
export const generateEnginePath = (path: string, pathParams: object = {}) => {
const { engineName } = EngineLogic.values;
return generatePath(path, { engineName, ...pathParams });
return generatePath(path, encodePathParams({ engineName, ...pathParams }));
Copy link
Member Author

Choose a reason for hiding this comment

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

My hope is that by baking this into our new generateEnginePath helper that it'll "just work" going forward and at the very least we won't accidentally forget to encode user-generated IDs going forward.

Copy link
Member

@JasonStoltz JasonStoltz Feb 1, 2021

Choose a reason for hiding this comment

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

I think the problem I see here is that you are actually increasing the odds that someone will accidentally forget to encode user-generate ids, because as soon as you're in a place in the code you're not able to use generateEnginePath, then you won't be in the habit of encoding path params.

I really wish there was just one way to create paths that we could used everywhere, decoupled from state, that would handle encoding path params.

generateAppPath(ENGINE_DOCUMENT_DETAIL_PATH, {
  engineName: resultMeta.engine,
  documentId: resultMeta.id,
})

};
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { EuiPanel, EuiIcon } from '@elastic/eui';
import { i18n } from '@kbn/i18n';

import { ReactRouterHelper } from '../../../shared/react_router_helpers/eui_components';
import { encodePathParams } from '../../utils/encode_path_params';
import { ENGINE_DOCUMENT_DETAIL_PATH } from '../../routes';

import { Schema } from '../../../shared/types';
Expand Down Expand Up @@ -52,10 +53,13 @@ export const Result: React.FC<Props> = ({
if (schemaForTypeHighlights) return schemaForTypeHighlights[fieldName];
};

const documentLink = generatePath(ENGINE_DOCUMENT_DETAIL_PATH, {
engineName: resultMeta.engine,
documentId: resultMeta.id,
});
const documentLink = generatePath(
ENGINE_DOCUMENT_DETAIL_PATH,
encodePathParams({
engineName: resultMeta.engine,
documentId: resultMeta.id,
})
);
Copy link
Member Author

Choose a reason for hiding this comment

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

Instead of using the default RR generatePath, I'm tempted to convert this to

generateEnginePath(ENGINE_DOCUMENT_DETAIL_PATH, {
  engineName: resultMeta.engine,
  documentId: resultMeta.id,
})

Just so we get the encoding baked in without having to manually call it. I know Jason mentioned earlier that was maybe confusing though 🤷 What do you all think?

Copy link
Member

Choose a reason for hiding this comment

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

I left another comment about a more generic generateAppPath that I think applies here.

Copy link
Member

Choose a reason for hiding this comment

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

My objection still stands. It's like we're trying to force things through this state based helper that don't make sense to be part of a state based helper.

That being said, it's also inconsequential to me. It will be just fine if you choose to do this. I stated my objection, but either way will be just fine.

Copy link
Member Author

Choose a reason for hiding this comment

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

Ya I think you're right about that, I shouldn't be conflating the two different helpers. I'm good with a generic generateAppPath (or maybe generateEncodedPath if it should be specific to encoding?), will add that helper to this PR and have generateEnginePath call that helper.

Copy link
Member Author

Choose a reason for hiding this comment

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

68a3057 & a72aef2

const conditionallyLinkedArticle = (children: React.ReactNode) => {
return shouldLinkToDetailPage ? (
<ReactRouterHelper to={documentLink}>
Expand Down Expand Up @@ -135,7 +139,7 @@ export const Result: React.FC<Props> = ({
{ defaultMessage: 'Visit document details' }
)}
>
<EuiIcon type="popout" />
<EuiIcon type="eye" />
</a>
</ReactRouterHelper>
)}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import '../../../__mocks__/react_router_history.mock';
import { useParams } from 'react-router-dom';

import { encodePathParams, useDecodedParams } from './';

describe('encodePathParams', () => {
it('encodeURIComponent()s all object values', () => {
const params = {
someValue: 'hello world???',
anotherValue: 'test!@#$%^&*[]/|;:"<>~`',
};
expect(encodePathParams(params)).toEqual({
someValue: 'hello%20world%3F%3F%3F',
anotherValue: 'test!%40%23%24%25%5E%26*%5B%5D%2F%7C%3B%3A%22%3C%3E~%60',
});
});
});

describe('useDecodedParams', () => {
it('decodeURIComponent()s all object values from useParams()', () => {
(useParams as jest.Mock).mockReturnValue({
someValue: 'hello%20world%3F%3F%3F',
anotherValue: 'test!%40%23%24%25%5E%26*%5B%5D%2F%7C%3B%3A%22%3C%3E~%60',
});
expect(useDecodedParams()).toEqual({
someValue: 'hello world???',
anotherValue: 'test!@#$%^&*[]/|;:"<>~`',
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { useParams } from 'react-router-dom';

export const encodePathParams = (pathParams: Record<string, string | number>) => {
const encodedParams: Record<string, string> = {};

Object.entries(pathParams).map(([key, value]) => {
encodedParams[key] = encodeURIComponent(value);
});

return encodedParams;
};

export const useDecodedParams = () => {
const decodedParams: Record<string, string> = {};

const params = useParams();
Object.entries(params).map(([key, value]) => {
decodedParams[key] = decodeURIComponent(value as string);
});

return decodedParams;
};
Copy link
Member Author

Choose a reason for hiding this comment

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

Just want to note - on some reflection, it's maybe a little overkill to have a helper for 2 instances in our app, but I think it'll be worth it (from the perspective of future-proofing) that we have one documented and canonical place where we ensure our URLs are correctly encoded, vs. doing it manually and maybe slightly differently in multiple places in the future.

Copy link
Member

Choose a reason for hiding this comment

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

I agree.