Skip to content

Commit

Permalink
[ML] Adds secondary authorization header to Transforms in Fleet (#154665
Browse files Browse the repository at this point in the history
)

## Summary

The PR updates how credentials are created and managed for packages
including Transforms. Previously, everything will be installed as
`kibana_system` user, which has limited permissions to a specific set of
indices defined internally. This PR changes so that a secondary
authorization is passed to the creation of Transforms, making the
permissions/privileges dependent on the logged-in user.

### Installing a package containing transforms
- If the package has transforms assets to be installed, it will show
warning/info call out message indicating that the transforms will be
created and started with the current user's credentials/roles.
<img width="1226" alt="Screen Shot 2023-04-11 at 17 45 58"
src="https://user-images.githubusercontent.com/43350163/231305549-ad4c981c-e186-4431-8229-5083e9ed6fc3.png">
<img width="1226" alt="Screen Shot 2023-04-11 at 17 46 03"
src="https://user-images.githubusercontent.com/43350163/231305550-7b47e95d-f876-456a-beb4-d71336a3f2cf.png">

-It will parse the authorization header (schema and credentials) from
the Kibana request to the package handlers.
- If the package contains transforms, and if **run_as_kibana_system:
false in the any of the transform yml config** , then generate an API
key from the above credential (as that Kibana user with the roles and
permissions at the time of generation), and use it in `transform/_put`
requests.
- If user has **sufficient permissions**:
- Transforms will be successfully created and started. They will be
marked in the saved object reference with `deferred: false`
  - Transform `_meta` will have `installed_by: {username}`
<img width="582" alt="Screen Shot 2023-04-11 at 14 11 43"
src="https://user-images.githubusercontent.com/43350163/231305101-20a63860-6d0c-4324-ba49-bea116de1f96.png">

  - Package will be successfully installed
- If user has **insufficient permissions**:
- Transforms will be successfully created, but fail to start. They will
be marked in the saved object reference with `deferred: true`
- Package will still be successfully installed. It will show warning
that the package has some deferred installations.


### Deferred installations

If a package has deferred installations (a.k.a assets that were included
in the package, but require additional permissions to operate
correctly), it will:

- Show a warning on the `Installed integrations` page:
<img width="1216" alt="Screen Shot 2023-04-06 at 15 59 46"
src="https://user-images.githubusercontent.com/43350163/230955445-fcb575af-d02b-4b0f-96f7-7506fa4a8f02.png">


- Show a warning badge with explanation on the tab:
<img width="750" alt="Screen Shot 2023-04-10 at 12 17 26"
src="https://user-images.githubusercontent.com/43350163/230955055-2fa85f1f-b7f8-4473-997a-1e4fec5453b9.png">

- Show a new `Deferred installations` section as well as call out
message to prompt user to re-authorize inside the `Assets` tab:
<img width="1216" alt="Screen Shot 2023-04-06 at 15 59 09"
src="https://user-images.githubusercontent.com/43350163/230955326-457074da-9f04-4aa6-aa15-f2c7ff14c6f1.png">

If the currently logged-in user has sufficient permissions
(`manage_transform` ES cluster privilege/`transform_admin` Kibana role),
the Reauthorize buttons will be enabled:

<img width="1054" alt="Screen Shot 2023-04-10 at 12 24 18"
src="https://user-images.githubusercontent.com/43350163/230960881-aa122119-c408-41c9-ab0c-90c18f65205e.png">

### Reauthorizing installations

- For transforms:
- Clicking the `Reauthorize` button will send an `_transform/_update`
API request with a `headers: {es-secondary-authorization: 'ApiKey
{encoded_api}'` and then a `_transform/_start` to start operations.
- Transform `_meta` will be updated with addition of
`last_authorized_by: {username}`
<img width="593" alt="Screen Shot 2023-04-11 at 14 12 38"
src="https://user-images.githubusercontent.com/43350163/231305257-eb79cf47-dbc1-4d93-b47f-0ff698ba8e6d.png">

- If `order` is specified in `_meta` of the transform, they will be
updated and started sequentially. Else, they will be executed
concurrently.

## Reviewers note:
-For **kibana-core**: saved object for Fleet's EsAsset was extended with
`deferred: boolean`, thus changing the hash.

### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
qn895 and kibanamachine authored Apr 20, 2023
1 parent a33b6d0 commit 1fe26f3
Show file tree
Hide file tree
Showing 55 changed files with 1,936 additions and 289 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ describe('checking migration metadata changes on all registered SO types', () =>
"endpoint:user-artifact": "a5b154962fb6cdf5d9e7452e58690054c95cc72a",
"endpoint:user-artifact-manifest": "5989989c0f84dd2d02da1eb46b6254e334bd2ccd",
"enterprise_search_telemetry": "4b41830e3b28a16eb92dee0736b44ae6276ced9b",
"epm-packages": "83235af7c95fd9bfb1d70996a5511e05b3fcc9ef",
"epm-packages": "8755f947a00613f994b1bc5d5580e104043e27f6",
"epm-packages-assets": "00c8b5e5bf059627ffc9fbde920e1ac75926c5f6",
"event_loop_delays_daily": "ef49e7f15649b551b458c7ea170f3ed17f89abd0",
"exception-list": "38181294f64fc406c15f20d85ca306c8a4feb3c0",
Expand Down
29 changes: 29 additions & 0 deletions x-pack/plugins/fleet/common/authz.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import { DEFAULT_APP_CATEGORIES } from '@kbn/core-application-common';

import { TRANSFORM_PLUGIN_ID } from './constants/plugin';

import {
calculatePackagePrivilegesFromCapabilities,
calculatePackagePrivilegesFromKibanaPrivileges,
Expand Down Expand Up @@ -39,16 +41,33 @@ describe('fleet authz', () => {
writeHostIsolationExceptions: true,
writeHostIsolation: false,
};

const transformCapabilities = {
canCreateTransform: false,
canDeleteTransform: false,
canGetTransform: true,
canStartStopTransform: false,
};

const expected = {
endpoint: {
actions: generateActions(ENDPOINT_PRIVILEGES, endpointCapabilities),
},
transform: {
actions: {
canCreateTransform: { executePackageAction: false },
canDeleteTransform: { executePackageAction: false },
canGetTransform: { executePackageAction: true },
canStartStopTransform: { executePackageAction: false },
},
},
};
const actual = calculatePackagePrivilegesFromCapabilities({
navLinks: {},
management: {},
catalogue: {},
siem: endpointCapabilities,
transform: transformCapabilities,
});

expect(actual).toEqual(expected);
Expand All @@ -65,6 +84,8 @@ describe('fleet authz', () => {
{ privilege: `${SECURITY_SOLUTION_ID}-writeHostIsolationExceptions`, authorized: true },
{ privilege: `${SECURITY_SOLUTION_ID}-writeHostIsolation`, authorized: false },
{ privilege: `${SECURITY_SOLUTION_ID}-ignoreMe`, authorized: true },
{ privilege: `${TRANSFORM_PLUGIN_ID}-admin`, authorized: true },
{ privilege: `${TRANSFORM_PLUGIN_ID}-read`, authorized: true },
];
const expected = {
endpoint: {
Expand All @@ -77,6 +98,14 @@ describe('fleet authz', () => {
writeHostIsolation: false,
}),
},
transform: {
actions: {
canCreateTransform: { executePackageAction: true },
canDeleteTransform: { executePackageAction: true },
canGetTransform: { executePackageAction: true },
canStartStopTransform: { executePackageAction: true },
},
},
};
const actual = calculatePackagePrivilegesFromKibanaPrivileges(endpointPrivileges);
expect(actual).toEqual(expected);
Expand Down
51 changes: 51 additions & 0 deletions x-pack/plugins/fleet/common/authz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@

import type { Capabilities } from '@kbn/core-capabilities-common';

import { TRANSFORM_PLUGIN_ID } from './constants/plugin';

import { ENDPOINT_PRIVILEGES } from './constants';

export type TransformPrivilege =
| 'canGetTransform'
| 'canCreateTransform'
| 'canDeleteTransform'
| 'canStartStopTransform';

export interface FleetAuthz {
fleet: {
all: boolean;
Expand Down Expand Up @@ -106,10 +114,22 @@ export function calculatePackagePrivilegesFromCapabilities(
{}
);

const transformActions = Object.keys(capabilities.transform).reduce((acc, privilegeName) => {
return {
...acc,
[privilegeName]: {
executePackageAction: capabilities.transform[privilegeName] || false,
},
};
}, {});

return {
endpoint: {
actions: endpointActions,
},
transform: {
actions: transformActions,
},
};
}

Expand Down Expand Up @@ -158,9 +178,40 @@ export function calculatePackagePrivilegesFromKibanaPrivileges(
{}
);

const hasTransformAdmin = getAuthorizationFromPrivileges(
kibanaPrivileges,
`${TRANSFORM_PLUGIN_ID}-`,
`admin`
);
const transformActions: {
[key in TransformPrivilege]: {
executePackageAction: boolean;
};
} = {
canCreateTransform: {
executePackageAction: hasTransformAdmin,
},
canDeleteTransform: {
executePackageAction: hasTransformAdmin,
},
canStartStopTransform: {
executePackageAction: hasTransformAdmin,
},
canGetTransform: {
executePackageAction: getAuthorizationFromPrivileges(
kibanaPrivileges,
`${TRANSFORM_PLUGIN_ID}-`,
`read`
),
},
};

return {
endpoint: {
actions: endpointActions,
},
transform: {
actions: transformActions,
},
};
}
1 change: 1 addition & 0 deletions x-pack/plugins/fleet/common/constants/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@

export const PLUGIN_ID = 'fleet' as const;
export const INTEGRATIONS_PLUGIN_ID = 'integrations' as const;
export const TRANSFORM_PLUGIN_ID = 'transform' as const;
2 changes: 2 additions & 0 deletions x-pack/plugins/fleet/common/constants/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export const EPM_API_ROUTES = {
INFO_PATTERN_DEPRECATED: EPM_PACKAGES_ONE_DEPRECATED,
INSTALL_FROM_REGISTRY_PATTERN_DEPRECATED: EPM_PACKAGES_ONE_DEPRECATED,
DELETE_PATTERN_DEPRECATED: EPM_PACKAGES_ONE_DEPRECATED,

REAUTHORIZE_TRANSFORMS: `${EPM_PACKAGES_ONE}/transforms/authorize`,
};

// Data stream API routes
Expand Down
58 changes: 58 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,58 @@
/*
* 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';

// Extended version of x-pack/plugins/security/server/authentication/http_authentication/http_authorization_header.ts
// to prevent bundle being required in security_solution
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;

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

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

/**
* Parses request's `Authorization` HTTP header if present.
* @param request Request instance to extract the authorization header from.
*/
static parseFromRequest(request: KibanaRequest, username?: string) {
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, username);
}

toString() {
return `${this.scheme} ${this.credentials}`;
}

getUsername() {
return this.username;
}
}
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 },
},
},
},
};
};
6 changes: 6 additions & 0 deletions x-pack/plugins/fleet/common/services/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ export const epmRouteService = {
pkgVersion
);
},

getReauthorizeTransformsPath: (pkgName: string, pkgVersion: string) => {
return EPM_API_ROUTES.REAUTHORIZE_TRANSFORMS.replace('{pkgName}', pkgName)
.replace('{pkgVersion}', pkgVersion)
.replace(/\/$/, ''); // trim trailing slash
},
};

export const packagePolicyRouteService = {
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/fleet/common/types/models/epm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,7 @@ export interface IntegrationCardItem {
id: string;
categories: string[];
fromIntegrations?: string;
isReauthorizationRequired?: boolean;
isUnverified?: boolean;
isUpdateAvailable?: boolean;
showLabels?: boolean;
Expand Down Expand Up @@ -539,6 +540,7 @@ export type KibanaAssetReference = Pick<SavedObjectReference, 'id'> & {
};
export type EsAssetReference = Pick<SavedObjectReference, 'id'> & {
type: ElasticsearchAssetType;
deferred?: boolean;
};

export type PackageAssetReference = Pick<SavedObjectReference, 'id'> & {
Expand Down
19 changes: 19 additions & 0 deletions x-pack/plugins/fleet/common/types/models/transform_api_key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* 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 { GrantAPIKeyResult } from '@kbn/security-plugin/server';

export interface TransformAPIKey extends GrantAPIKeyResult {
/**
* Generated encoded API key used for headers
*/
encoded: string;
}

export interface SecondaryAuthorizationHeader {
headers?: { 'es-secondary-authorization': string | string[] };
}
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,15 @@ describe('when on the package policy create page', () => {
fireEvent.click(renderResult.getByText(/Save and continue/).closest('button')!);
});

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

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 @@ -22,6 +22,11 @@ import {
} from '@elastic/eui';
import type { EuiStepProps } from '@elastic/eui/src/components/steps/step';

import {
getNumTransformAssets,
TransformInstallWithCurrentUserPermissionCallout,
} from '../../../../../../components/transform_install_as_current_user_callout';

import { useCancelAddPackagePolicy } from '../hooks';

import { splitPkgKey } from '../../../../../../../common/services';
Expand Down Expand Up @@ -266,6 +271,11 @@ export const CreatePackagePolicySinglePage: CreatePackagePolicyParams = ({
]
);

const numTransformAssets = useMemo(
() => getNumTransformAssets(packageInfo?.assets),
[packageInfo?.assets]
);

const extensionView = useUIExtension(packagePolicy.package?.name ?? '', 'package-policy-create');
const replaceDefineStepView = useUIExtension(
packagePolicy.package?.name ?? '',
Expand Down Expand Up @@ -406,6 +416,12 @@ export const CreatePackagePolicySinglePage: CreatePackagePolicyParams = ({
integration={integrationInfo?.name}
/>
)}
{numTransformAssets > 0 ? (
<>
<TransformInstallWithCurrentUserPermissionCallout count={numTransformAssets} />
<EuiSpacer size="xl" />
</>
) : null}
<StepsWithLessPadding steps={steps} />
<EuiSpacer size="xl" />
<EuiSpacer size="xl" />
Expand Down
Loading

0 comments on commit 1fe26f3

Please sign in to comment.