Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
qn895 committed Apr 10, 2023
1 parent 59b7541 commit 605b27b
Show file tree
Hide file tree
Showing 22 changed files with 303 additions and 117 deletions.
49 changes: 49 additions & 0 deletions x-pack/plugins/fleet/common/http_authorization_header.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { KibanaRequest } from '@kbn/core/server';

// Duplicate of x-pack/plugins/security/server/authentication/http_authentication/http_authorization_header.ts
// to prevent bundle being required in security_solution
// FIXME: Put this in a package
export class HTTPAuthorizationHeader {
/**
* The authentication scheme. Should be consumed in a case-insensitive manner.
* https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes
*/
readonly scheme: string;

/**
* The authentication credentials for the scheme.
*/
readonly credentials: string;

constructor(scheme: string, credentials: string) {
this.scheme = scheme;
this.credentials = credentials;
}

/**
* Parses request's `Authorization` HTTP header if present.
* @param request Request instance to extract the authorization header from.
*/
static parseFromRequest(request: KibanaRequest) {
const authorizationHeaderValue = request.headers.authorization;
if (!authorizationHeaderValue || typeof authorizationHeaderValue !== 'string') {
return null;
}

const [scheme] = authorizationHeaderValue.split(/\s+/);
const credentials = authorizationHeaderValue.substring(scheme.length + 1);

return new HTTPAuthorizationHeader(scheme, credentials);
}

toString() {
return `${this.scheme} ${this.credentials}`;
}
}
8 changes: 8 additions & 0 deletions x-pack/plugins/fleet/common/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ export const createFleetAuthzMock = (): FleetAuthz => {
endpoint: {
actions: endpointActions,
},
transform: {
actions: {
canCreateTransform: { executePackageAction: true },
canDeleteTransform: { executePackageAction: true },
canGetTransform: { executePackageAction: true },
canStartStopTransform: { executePackageAction: true },
},
},
},
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,19 @@ describe('when on the package policy create page', () => {
fireEvent.click(renderResult.getByText(/Save and continue/).closest('button')!);
});

jest.setTimeout(100000);
renderResult.debug(undefined, 3000000);
await waitFor(
async () => {
expect(
await renderResult.findByText(/Add Elastic Agent to your hosts/)
).toBeInTheDocument();
},
{ timeout: 10000 }
);

renderResult.debug(undefined, 3000000);

await act(async () => {
fireEvent.click(
renderResult.getByText(/Add Elastic Agent to your hosts/).closest('button')!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { groupBy } from 'lodash';

import type { ResolvedSimpleSavedObject } from '@kbn/core/public';

import type { EsAssetReference } from '../../../../../../../../common';

import { Error, ExtensionWrapper, Loading } from '../../../../../components';

import type { PackageInfo } from '../../../../../types';
Expand All @@ -31,11 +33,7 @@ import type { AssetSavedObject } from './types';
import { allowedAssetTypes } from './constants';
import { AssetsAccordion } from './assets_accordion';

// @TODO
const allowedAssetTypesLookup = new Set<string>(allowedAssetTypes);
// const allowedAssetTypesLookup = new Set<string>(
// omit(allowedAssetTypes, ElasticsearchAssetType.transform)
// );

interface AssetsPanelProps {
packageInfo: PackageInfo;
Expand All @@ -57,7 +55,7 @@ export const AssetsPage = ({ packageInfo }: AssetsPanelProps) => {
// assume assets are installed in this space until we find otherwise
const [assetsInstalledInCurrentSpace, setAssetsInstalledInCurrentSpace] = useState<boolean>(true);
const [assetSavedObjects, setAssetsSavedObjects] = useState<undefined | AssetSavedObject[]>();
const [deferredInstallations, setDeferredInstallations] = useState<any[]>();
const [deferredInstallations, setDeferredInstallations] = useState<EsAssetReference[]>();

const [fetchError, setFetchError] = useState<undefined | Error>();
const [isLoading, setIsLoading] = useState<boolean>(true);
Expand Down Expand Up @@ -251,16 +249,15 @@ export const AssetsPage = ({ packageInfo }: AssetsPanelProps) => {
) : null,
];
}
const deferredInstallationsContent =
Array.isArray(deferredInstallations) && deferredInstallations.length > 0 ? (
<>
<DeferredAssetsSection
deferredInstallations={deferredInstallations}
packageInfo={packageInfo}
/>
<EuiSpacer size="m" />
</>
) : null;
const deferredInstallationsContent = showDeferredInstallations ? (
<>
<DeferredAssetsSection
deferredInstallations={deferredInstallations}
packageInfo={packageInfo}
/>
<EuiSpacer size="m" />
</>
) : null;

return (
<EuiFlexGroup alignItems="flexStart">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ import { i18n } from '@kbn/i18n';

import { FormattedMessage } from '@kbn/i18n-react';

import type { EsAssetReference } from '../../../../../../../../common';

import type { PackageInfo } from '../../../../../types';
import { ElasticsearchAssetType } from '../../../../../types';

import { DeferredTransformAccordion } from './deferred_transforms_accordion';

import type { AssetSavedObject } from './types';

interface Props {
packageInfo: PackageInfo;
deferredInstallations: AssetSavedObject[];
deferredInstallations: EsAssetReference[];
}

export const DeferredAssetsSection: FunctionComponent<Props> = ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import { i18n } from '@kbn/i18n';

import type { ElasticsearchErrorDetails } from '@kbn/es-errors';

import type { EsAssetReference } from '../../../../../../../../common';

import {
sendRequestReauthorizeTransforms,
useAuthz,
Expand All @@ -36,13 +38,10 @@ import { AssetTitleMap } from '../../../constants';
import type { PackageInfo } from '../../../../../types';
import { ElasticsearchAssetType } from '../../../../../types';

import type { AssetSavedObject } from './types';

interface Props {
packageInfo: PackageInfo;

type: ElasticsearchAssetType.transform;
deferredInstallations: AssetSavedObject[];
deferredInstallations: EsAssetReference[];
}

export const getDeferredAssetDescription = (assetType: string, assetCount: number) => {
Expand Down Expand Up @@ -79,7 +78,7 @@ export const DeferredTransformAccordion: FunctionComponent<Props> = ({
id: i.id,
attributes: {
title: i.id,
description: i._version,
description: i.type,
},
})),
[deferredInstallations]
Expand Down Expand Up @@ -203,9 +202,7 @@ export const DeferredTransformAccordion: FunctionComponent<Props> = ({
size={'m'}
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
setTransformsToAuthorize(
deferredTransforms.map((t) => ({ transformId: t.attributes.title }))
);
setTransformsToAuthorize(deferredTransforms.map((t) => ({ transformId: t.id })));
}}
aria-label={getDeferredAssetDescription(type, deferredInstallations.length)}
>
Expand All @@ -218,55 +215,45 @@ export const DeferredTransformAccordion: FunctionComponent<Props> = ({
<EuiSpacer size="m" />

<EuiSplitPanel.Outer hasBorder hasShadow={false}>
{deferredTransforms.map(
({ id: transformId, attributes: { title, description } }, idx) => {
return (
<>
<EuiSplitPanel.Inner grow={false} key={`${transformId}-${idx}`}>
<EuiFlexGroup>
<EuiFlexItem grow={8}>
<EuiText size="m">
<p>{title}</p>
</EuiText>
{description && (
<>
<EuiSpacer size="s" />
<EuiText size="s" color="subdued">
<p>{description}</p>
</EuiText>
</>
)}
</EuiFlexItem>
<EuiFlexItem>
<EuiToolTip
content={getDeferredAssetDescription(type, 1)}
data-test-subject={`fleetAssetsReauthorizeTooltip-${transformId}-${isLoading}`}
{deferredTransforms.map(({ id: transformId }, idx) => {
return (
<>
<EuiSplitPanel.Inner grow={false} key={`${transformId}-${idx}`}>
<EuiFlexGroup>
<EuiFlexItem grow={8}>
<EuiText size="m">
<p>{transformId}</p>
</EuiText>
</EuiFlexItem>
<EuiFlexItem>
<EuiToolTip
content={getDeferredAssetDescription(type, 1)}
data-test-subject={`fleetAssetsReauthorizeTooltip-${transformId}-${isLoading}`}
>
<EuiButton
isLoading={isLoading}
disabled={!canReauthorizeTransforms}
size={'s'}
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
setTransformsToAuthorize([{ transformId }]);
}}
>
<EuiButton
isLoading={isLoading}
disabled={!canReauthorizeTransforms}
size={'s'}
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
setTransformsToAuthorize([{ transformId }]);
}}
>
{i18n.translate(
'xpack.fleet.epm.packageDetails.assets.reauthorizeButton',
{
defaultMessage: 'Reauthorize',
}
)}
</EuiButton>
</EuiToolTip>
</EuiFlexItem>
</EuiFlexGroup>
</EuiSplitPanel.Inner>
{idx + 1 < deferredTransforms.length && <EuiHorizontalRule margin="none" />}
</>
);
}
)}
{i18n.translate(
'xpack.fleet.epm.packageDetails.assets.reauthorizeButton',
{
defaultMessage: 'Reauthorize',
}
)}
</EuiButton>
</EuiToolTip>
</EuiFlexItem>
</EuiFlexGroup>
</EuiSplitPanel.Inner>
{idx + 1 < deferredTransforms.length && <EuiHorizontalRule margin="none" />}
</>
);
})}
</EuiSplitPanel.Outer>
</>
</EuiAccordion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type {
import pMap from 'p-map';
import { safeDump } from 'js-yaml';

import { HTTPAuthorizationHeader } from '@kbn/security-plugin/server';
import { HTTPAuthorizationHeader } from '../../../common/http_authorization_header';

import { fullAgentPolicyToYaml } from '../../../common/services';
import { appContextService, agentPolicyService } from '../../services';
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/server/routes/epm/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import mime from 'mime-types';
import semverValid from 'semver/functions/valid';
import type { ResponseHeaders, KnownHeaders, HttpResponseOptions } from '@kbn/core/server';

import { HTTPAuthorizationHeader } from '@kbn/security-plugin/server';
import { HTTPAuthorizationHeader } from '../../../common/http_authorization_header';

import { generateTransformSecondaryAuthHeaders } from '../../services/api_keys/transform_api_keys';
import { handleTransformReauthorizeAndStart } from '../../services/epm/elasticsearch/transform/reauthorize';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { RequestHandler } from '@kbn/core/server';

import { groupBy, keyBy } from 'lodash';

import { HTTPAuthorizationHeader } from '@kbn/security-plugin/server';
import { HTTPAuthorizationHeader } from '../../../common/http_authorization_header';

import { populatePackagePolicyAssignedAgentsCount } from '../../services/package_policies/populate_package_policy_assigned_agents_count';

Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/server/services/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type { BulkResponseItem } from '@elastic/elasticsearch/lib/api/typesWithB

import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants';

import type { HTTPAuthorizationHeader } from '@kbn/security-plugin/server';
import type { HTTPAuthorizationHeader } from '../../common/http_authorization_header';

import {
AGENT_POLICY_SAVED_OBJECT_TYPE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/

import type { AuthenticatedUser } from '@kbn/security-plugin/common/model';

import type { HTTPAuthorizationHeader } from '@kbn/security-plugin/server';
import type { HTTPAuthorizationHeader } from '../../common/http_authorization_header';

import {
FLEET_ELASTIC_AGENT_PACKAGE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
import type { CreateAPIKeyParams } from '@kbn/security-plugin/server';
import type { FakeRawRequest, Headers } from '@kbn/core-http-server';
import { CoreKibanaRequest } from '@kbn/core-http-router-server-internal';
import type { HTTPAuthorizationHeader } from '@kbn/security-plugin/server';

import type { Logger } from '@kbn/logging';

import type { HTTPAuthorizationHeader } from '../../../common/http_authorization_header';

import type {
TransformAPIKey,
SecondaryAuthorizationHeader,
Expand Down Expand Up @@ -58,9 +59,7 @@ export async function generateTransformSecondaryAuthHeaders({
logger: Logger;
}): Promise<SecondaryAuthorizationHeader | undefined> {
if (!authorizationHeader) {
throw Error(
'Unable to generate secondary authorization if authorizationHeader is not provided.'
);
return;
}

const fakeKibanaRequest = createKibanaRequestFromAuth(authorizationHeader);
Expand Down
Loading

0 comments on commit 605b27b

Please sign in to comment.