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

chore(auth): Move credentials encoding into one service #330

Merged
merged 1 commit into from
Oct 25, 2021
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
15 changes: 7 additions & 8 deletions src/app/AppLayout/AuthModal.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
/*
* 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
Expand All @@ -38,7 +38,6 @@
import * as React from 'react';
import { first } from 'rxjs/operators';
import { ActionGroup, Button, Form, FormGroup, Modal, ModalVariant, TextInput } from '@patternfly/react-core';
import { Base64 } from 'js-base64';
import { ServiceContext } from '@app/Shared/Services/Services';

export interface AuthModalProps {
Expand All @@ -61,7 +60,7 @@ export const AuthModal: React.FunctionComponent<AuthModalProps> = (props) => {

const handleSave = () => {
context.target.target().pipe(first()).subscribe(target => {
context.target.setCredentials(target.connectUrl, Base64.encodeURL(`${username}:${password}`));
context.target.setCredentials(target.connectUrl, `${username}:${password}`);
context.target.setAuthRetry();
clear();
props.onSave();
Expand Down
32 changes: 4 additions & 28 deletions src/app/Shared/Services/Api.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { combineLatest, from, Observable, ObservableInput, of, ReplaySubject, forkJoin, throwError, EMPTY } from 'rxjs';
import { from, Observable, ObservableInput, of, ReplaySubject, forkJoin, throwError, EMPTY } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
import { catchError, concatMap, first, map, mergeMap, tap } from 'rxjs/operators';
import { Target, TargetService } from './Target.service';
Expand Down Expand Up @@ -333,7 +333,7 @@ export class ApiService {
}

downloadReport(recording: SavedRecording): void {
this.getHeaders().subscribe(headers => {
this.login.getHeaders().subscribe(headers => {
const req = () =>
fromFetch(recording.reportUrl, {
credentials: 'include',
Expand All @@ -358,7 +358,7 @@ export class ApiService {
}

downloadRecording(recording: SavedRecording): void {
this.getHeaders().subscribe(headers => {
this.login.getHeaders().subscribe(headers => {
const req = () => fromFetch(recording.downloadUrl, {
credentials: 'include',
mode: 'cors',
Expand Down Expand Up @@ -430,32 +430,8 @@ export class ApiService {
);
}

getHeaders(): Observable<Headers> {
const authorization = combineLatest([this.login.getToken(), this.login.getAuthMethod()])
.pipe(
map((parts: [string, string]) => this.login.getAuthHeaders(parts[0], parts[1])),
first(),
);
return combineLatest([authorization, this.target.target()])
.pipe(
first(),
map(parts => {
const headers = parts[0];
const target = parts[1];
if (!!target && !!target.connectUrl && this.target.hasCredentials(target.connectUrl)) {
const credentials = this.target.getCredentials(target.connectUrl);
if (credentials) {
headers.set('X-JMX-Authorization', `Basic ${this.target.getCredentials(target.connectUrl)}`);
}
}
return headers;
})
);

}

private sendRequest(apiVersion: ApiVersion, path: string, config?: RequestInit): Observable<Response> {
const req = () => this.getHeaders().pipe(
const req = () => this.login.getHeaders().pipe(
concatMap(headers =>
fromFetch(`${this.login.authority}/api/${apiVersion}/${path}`, {
credentials: 'include',
Expand Down
43 changes: 31 additions & 12 deletions src/app/Shared/Services/Login.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@
* SOFTWARE.
*/
import { Base64 } from 'js-base64';
import { Observable, ObservableInput, of, ReplaySubject } from 'rxjs';
import { combineLatest, Observable, ObservableInput, of, ReplaySubject } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
import { catchError, concatMap, first, map, tap } from 'rxjs/operators';
import { TargetService } from './Target.service';

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

constructor() {
constructor(private readonly target: TargetService) {
let apiAuthority = process.env.CRYOSTAT_AUTHORITY;
if (!apiAuthority) {
apiAuthority = '';
Expand All @@ -76,11 +77,7 @@ export class LoginService {
}

checkAuth(token: string, method: string, rememberMe = false): Observable<boolean> {

if (method === 'Basic') {
token = Base64.encodeURL(token);
}

token = Base64.encodeURL(token);
andrewazores marked this conversation as resolved.
Show resolved Hide resolved
token = this.useCacheItemIfAvailable(this.TOKEN_KEY, token);

return fromFetch(`${this.authority}/api/v2.1/auth`, {
Expand Down Expand Up @@ -117,19 +114,41 @@ export class LoginService {
);
}

getToken(): Observable<string> {
return this.token.asObservable();
}

getAuthHeaders(token: string, method: string): Headers {
const headers = new window.Headers();
if (!!token && !!method) {
headers.set('Authorization', `${method} ${token}`)
}

return headers;
}

getHeaders(): Observable<Headers> {
const authorization = combineLatest([this.getToken(), this.getAuthMethod()])
.pipe(
map((parts: [string, string]) => this.getAuthHeaders(parts[0], parts[1])),
first(),
);
return combineLatest([authorization, this.target.target()])
.pipe(
first(),
map(parts => {
const headers = parts[0];
const target = parts[1];
if (!!target && !!target.connectUrl && this.target.hasCredentials(target.connectUrl)) {
const credentials = this.target.getCredentials(target.connectUrl);
if (credentials) {
headers.set('X-JMX-Authorization', `Basic ${Base64.encodeURL(credentials)}`);
}
}
return headers;
})
);
}

getToken(): Observable<string> {
return this.token.asObservable();
}

getAuthMethod(): Observable<string> {
return this.authMethod.asObservable();
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/Shared/Services/NotificationChannel.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export class NotificationChannel {
}

if (authMethod === 'Bearer') {
subprotocol = `base64url.bearer.authorization.cryostat.${Base64.encodeURL(token)}`;
subprotocol = `base64url.bearer.authorization.cryostat.${token}`;
} else if (authMethod === 'Basic') {
subprotocol = `basic.authorization.cryostat.${token}`;
}
Expand Down
7 changes: 4 additions & 3 deletions src/app/Shared/Services/Report.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,14 @@
import { Observable, from, of, throwError } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
import { concatMap, first, tap } from 'rxjs/operators';
import { ApiService, isActiveRecording, RecordingState, SavedRecording } from './Api.service';
import { isActiveRecording, RecordingState, SavedRecording } from './Api.service';
import { Notifications } from '@app/Notifications/Notifications';
import { Base64 } from 'js-base64';
import { LoginService } from './Login.service';

export class ReportService {

constructor(private api: ApiService, private notifications: Notifications) { }
constructor(private login: LoginService, private notifications: Notifications) { }

report(recording: SavedRecording): Observable<string> {
if (!recording?.reportUrl) {
Expand All @@ -54,7 +55,7 @@ export class ReportService {
if (!!stored) {
return of(stored);
}
return this.api.getHeaders().pipe(
return this.login.getHeaders().pipe(
concatMap(headers =>
fromFetch(recording.reportUrl, {
method: 'GET',
Expand Down
4 changes: 2 additions & 2 deletions src/app/Shared/Services/Services.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ export interface Services {
login: LoginService;
}

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

Expand Down