Skip to content

Commit

Permalink
feat(jmx): re-implement enhanced transient JMX credentials
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewazores committed Sep 27, 2022
1 parent 0c019a2 commit 77a0cf6
Show file tree
Hide file tree
Showing 10 changed files with 238 additions and 17 deletions.
5 changes: 3 additions & 2 deletions src/app/AppLayout/AuthModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ export const AuthModal: React.FunctionComponent<AuthModalProps> = (props) => {
first(),
filter(target => target !== NO_TARGET),
map(target => target.connectUrl),
map(connectUrl => `target.connectUrl == "${connectUrl}"`),
mergeMap(matchExpression => context.api.postCredentials(matchExpression, username, password))
mergeMap(connectUrl => context.jmxCredentials.setCredential(connectUrl, username, password))
).subscribe(result => {
if (result) {
props.onSave();
Expand All @@ -86,6 +85,8 @@ export const AuthModal: React.FunctionComponent<AuthModalProps> = (props) => {
<Text>
This target JVM requires authentication. The credentials you provide here will be passed from Cryostat to the target when establishing JMX connections.
Enter credentials specific to this target, or go to <Link onClick={props.onDismiss} to="/security">Security</Link> to add a credential matching multiple targets.
Visit <Link onClick={props.onDismiss} to="/settings">Settings</Link> to confirm and configure whether these credentials will be held only for this browser session
or stored encrypted in the Cryostat backend.
</Text>
}
>
Expand Down
8 changes: 6 additions & 2 deletions src/app/SecurityPanel/Credentials/StoreJmxCredentials.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ export const StoreJmxCredentials = () => {
for (let i = 0; i < matchExpressionRows.length; i++) {
rowPairs.push(matchExpressionRows[i]);
rowPairs.push(targetRows[i]);
}
}
return rowPairs;
}, [matchExpressionRows, targetRows]);

Expand Down Expand Up @@ -431,6 +431,10 @@ export const StoreJmxCredentials = () => {

export const StoreJmxCredentialsCard: SecurityCard = {
title: 'Store JMX Credentials',
description: `Credentials that Cryostat uses to connect to target JVMs over JMX are stored here.`,
description: `
Credentials that Cryostat uses to connect to target JVMs over JMX are stored here.
These are stored in encrypted storage managed by the Cryostat backend. Any locally-stored
client credentials held by your browser session are not displayed here.
`,
content: StoreJmxCredentials,
};
2 changes: 1 addition & 1 deletion src/app/Settings/AutoRefresh.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,6 @@ const Component = () => {

export const AutoRefresh: UserSetting = {
title: 'Auto-Refresh',
description: 'Set the refresh period for content views.',
description: 'Set the refresh period for content views. Views normally update dynamically via WebSocket notifications, so this should not be needed unless WebSockets are not working.',
content: Component,
}
120 changes: 120 additions & 0 deletions src/app/Settings/CredentialsStorage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import * as React from 'react';
import { Link } from 'react-router-dom';
import { Select, SelectOption, SelectVariant, Text } from '@patternfly/react-core';

import { UserSetting } from './Settings';
import { getFromLocalStorage, saveToLocalStorage } from "@app/utils/LocalStorage";

export interface Location {
key: string;
description: string;
}

export class Locations {
static readonly BROWSER_SESSION: Location = {
key: 'Session (Browser Memory)',
description: 'Keep credentials in browser memory for the current session only. When you close this browser tab the credentials will be forgotten.'
};
static readonly BACKEND: Location = {
key: 'Backend',
description: 'Keep credentials in encrypted Cryostat backend storage. These credentials will be available to other users and will be used for Automated Rules.'
};
}

const locations = [
Locations.BROWSER_SESSION,
Locations.BACKEND,
];

function getLocation(key: string): Location {
for (let l of locations) {
if (l.key === key) {
return l;
}
}
return Locations.BROWSER_SESSION;
}

const Component = () => {

const [isExpanded, setExpanded] = React.useState(false);
const [selection, setSelection] = React.useState(Locations.BROWSER_SESSION);

const handleSelect = React.useCallback((_, selection) => {
let location = getLocation(selection);
setSelection(location);
setExpanded(false);
saveToLocalStorage("JMX_CREDENTIAL_LOCATION", selection)
}, [getLocation, setSelection, setExpanded, saveToLocalStorage]);

React.useEffect(() => {
handleSelect(
undefined,
getFromLocalStorage("JMX_CREDENTIAL_LOCATION", Locations.BROWSER_SESSION)
);
}, [handleSelect, getLocation, getFromLocalStorage]);

return (<>
<Select
variant={SelectVariant.single}
onToggle={setExpanded}
onSelect={handleSelect}
isOpen={isExpanded}
selections={selection.key}
>
{
locations.map(location => <SelectOption key={location.key} value={location.key} description={location.description} />)
}
</Select>
</>);
}

export const CredentialsStorage: UserSetting = {
title: 'JMX Credentials Storage',
description: <Text>
When you attempt to connect to a target application which requires authentication
you will see a prompt for credentials to present to the application and complete the
connection. You can choose where to persist these credentials. Any credentials added
through the <Link to="/security">Security</Link> panel will always be stored in Cryostat
backend encrypted storage.
</Text>,
content: Component,
}
10 changes: 6 additions & 4 deletions src/app/Settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,21 @@ import * as React from 'react';
import { Card, CardBody, CardTitle, Text, TextVariants } from '@patternfly/react-core';
import { BreadcrumbPage } from '@app/BreadcrumbPage/BreadcrumbPage';

import { AutoRefresh } from './AutoRefresh';
import { NotificationControl } from './NotificationControl';
import { WebSocketDebounce } from './WebSocketDebounce';
import { CredentialsStorage } from './CredentialsStorage';
import { DeletionDialogControl } from './DeletionDialogControl';
import { WebSocketDebounce } from './WebSocketDebounce';
import { AutoRefresh } from './AutoRefresh';

export const Settings: React.FunctionComponent<{}> = () => {

const settings =
[
AutoRefresh,
NotificationControl,
CredentialsStorage,
DeletionDialogControl,
WebSocketDebounce,
AutoRefresh,
].map(c => ({
title: c.title,
description: c.description,
Expand Down Expand Up @@ -81,6 +83,6 @@ export const Settings: React.FunctionComponent<{}> = () => {

export interface UserSetting {
title: string;
description: string;
description: JSX.Element | string;
content: React.FunctionComponent;
}
2 changes: 1 addition & 1 deletion src/app/Settings/WebSocketDebounce.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
*/

import * as React from 'react';
import { NumberInput, Text, TextVariants } from '@patternfly/react-core';
import { NumberInput } from '@patternfly/react-core';
import { ServiceContext } from '@app/Shared/Services/Services';
import { UserSetting } from './Settings';

Expand Down
84 changes: 84 additions & 0 deletions src/app/Shared/Services/JmxCredentials.service.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { Observable, of } from 'rxjs';
import { getFromLocalStorage } from '@app/utils/LocalStorage';
import { Locations } from '@app/Settings/CredentialsStorage';
import { ApiService } from './Api.service';

export interface Credential {
username: string;
password: string;
}

export class JmxCredentials {

// TODO replace with Redux?
private readonly store = new Map<string, Credential>();

constructor(
private readonly api: () => ApiService
) { }

setCredential(targetId: string, username: string, password: string): Observable<boolean> {
let location = getFromLocalStorage('JMX_CREDENTIAL_LOCATION', Locations.BROWSER_SESSION);
switch (location) {
case Locations.BACKEND.key:
return this.api().postCredentials(`target.connectUrl == "${targetId}"`, username, password);
case Locations.BROWSER_SESSION.key:
this.store.set(targetId, { username, password });
return of(true);
default:
console.warn('Unknown storage location', location);
return of(true);
}
}

getCredential(targetId: string): Observable<Credential | undefined> {
let location = getFromLocalStorage('JMX_CREDENTIAL_LOCATION', Locations.BROWSER_SESSION);
switch (location) {
case Locations.BACKEND.key:
// if this is stored on the backend then Cryostat should be using those and not prompting us to request from the user
return of(undefined);
case Locations.BROWSER_SESSION.key:
return of(this.store.get(targetId));
default:
console.warn('Unknown storage location', location);
return of(undefined);
}
}
}
13 changes: 9 additions & 4 deletions src/app/Shared/Services/Login.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { catchError, concatMap, debounceTime, distinctUntilChanged, first, map,
import { SettingsService } from './Settings.service';
import { ApiV2Response, HttpError } from './Api.service';
import { TargetService } from './Target.service';
import { Credential, JmxCredentials } from './JmxCredentials.service';

export enum SessionState {
NO_USER_SESSION,
Expand All @@ -68,7 +69,7 @@ export class LoginService {
private readonly sessionState = new ReplaySubject<SessionState>(1);
readonly authority: string;

constructor(private readonly target: TargetService, private readonly settings: SettingsService) {
constructor(private readonly target: TargetService, private readonly jmxCredentials: JmxCredentials, private readonly settings: SettingsService) {
let apiAuthority = process.env.CRYOSTAT_AUTHORITY;
if (!apiAuthority) {
apiAuthority = '';
Expand Down Expand Up @@ -140,20 +141,24 @@ export class LoginService {
);
}

getAuthHeaders(token: string, method: string): Headers {
getAuthHeaders(token: string, method: string, jmxCredential?: Credential): Headers {
const headers = new window.Headers();
if (!!token && !!method) {
headers.set('Authorization', `${method} ${token}`)
} else if (method === AuthMethod.NONE) {
headers.set('Authorization', AuthMethod.NONE);
}
if (jmxCredential) {
let basic = `${jmxCredential.username}:${jmxCredential.password}`;
headers.set('X-JMX-Authorization', `Basic ${Base64.encode(basic)}`);
}
return headers;
}

getHeaders(): Observable<Headers> {
return combineLatest([this.getToken(), this.getAuthMethod()])
return combineLatest([this.getToken(), this.getAuthMethod(), this.target.target().pipe(map(target => target.connectUrl), concatMap(connect => this.jmxCredentials.getCredential(connect)))])
.pipe(
map((parts: [string, AuthMethod]) => this.getAuthHeaders(parts[0], parts[1])),
map((parts: [string, AuthMethod, Credential | undefined]) => this.getAuthHeaders(parts[0], parts[1], parts[2])),
first(),
);
}
Expand Down
7 changes: 5 additions & 2 deletions src/app/Shared/Services/Services.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,25 +44,28 @@ import { NotificationChannel } from './NotificationChannel.service';
import { ReportService } from './Report.service';
import { SettingsService } from './Settings.service';
import { LoginService } from './Login.service';
import { JmxCredentials } from './JmxCredentials.service';

export interface Services {
target: TargetService;
targets: TargetsService;
api: ApiService;
jmxCredentials: JmxCredentials;
notificationChannel: NotificationChannel;
reports: ReportService;
settings: SettingsService;
login: LoginService;
}

const settings = new SettingsService();
const login = new LoginService(TargetInstance, settings);
const jmxCredentials = new JmxCredentials(() => api);
const login = new LoginService(TargetInstance, jmxCredentials, settings);
const api = new ApiService(TargetInstance, NotificationsInstance, login);
const notificationChannel = new NotificationChannel(NotificationsInstance, login);
const reports = new ReportService(login, NotificationsInstance);
const targets = new TargetsService(api, NotificationsInstance, login, notificationChannel);

const defaultServices: Services = { target: TargetInstance, targets, api, notificationChannel, reports, settings, login };
const defaultServices: Services = { target: TargetInstance, targets, api, jmxCredentials, notificationChannel, reports, settings, login };

const ServiceContext: React.Context<Services> = React.createContext(defaultServices);

Expand Down
4 changes: 3 additions & 1 deletion src/app/utils/LocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
*/

export enum LocalStorageKey {
TARGET_RECORDING_FILTERS
TARGET_RECORDING_FILTERS,
JMX_CREDENTIAL_LOCATION,
JMX_CREDENTIALS,
}

/**
Expand Down

0 comments on commit 77a0cf6

Please sign in to comment.