fix(security): harden auth and secret handling (HH-444) (#101)
* fix(security): harden auth and credential handling (HH-444) * fix(security): address HH-444 review blockers * fix(security): close remaining HH-444 review blockers --------- Co-authored-by: Rogee <rogee@ipao.vip>
This commit is contained in:
@@ -14,29 +14,13 @@ export default {
|
||||
},
|
||||
logout() {
|
||||
const urlData = endPoints('logout');
|
||||
const fetchPromise = new Promise((resolve, reject) => {
|
||||
axios
|
||||
.delete(urlData.url)
|
||||
.then(response => {
|
||||
deleteIndexedDBOnLogout();
|
||||
clearCookiesOnLogout();
|
||||
resolve(response);
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error);
|
||||
});
|
||||
return axios.delete(urlData.url).finally(() => {
|
||||
deleteIndexedDBOnLogout();
|
||||
clearCookiesOnLogout();
|
||||
});
|
||||
return fetchPromise;
|
||||
},
|
||||
hasAuthCookie() {
|
||||
return !!Cookies.get('cw_d_session_info');
|
||||
},
|
||||
getAuthData() {
|
||||
if (this.hasAuthCookie()) {
|
||||
const savedAuthInfo = Cookies.get('cw_d_session_info');
|
||||
return JSON.parse(savedAuthInfo || '{}');
|
||||
}
|
||||
return false;
|
||||
return !!Cookies.get('cw_d_session_state');
|
||||
},
|
||||
profileUpdate({ displayName, avatar, ...profileAttributes }) {
|
||||
const formData = new FormData();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as APIUtils from '../store/utils/api';
|
||||
import Auth from './auth';
|
||||
|
||||
vi.spyOn(APIUtils, 'clearCookiesOnLogout').mockImplementation(() => {});
|
||||
vi.spyOn(APIUtils, 'deleteIndexedDBOnLogout').mockResolvedValue();
|
||||
|
||||
describe('Auth.logout', () => {
|
||||
it('clears browser credentials even when the server rejects logout', async () => {
|
||||
globalThis.axios = {
|
||||
delete: vi.fn().mockRejectedValue({ response: { status: 401 } }),
|
||||
};
|
||||
|
||||
await expect(Auth.logout()).rejects.toEqual({ response: { status: 401 } });
|
||||
expect(APIUtils.deleteIndexedDBOnLogout).toHaveBeenCalledOnce();
|
||||
expect(APIUtils.clearCookiesOnLogout).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -1,31 +1,48 @@
|
||||
import Auth from '../api/auth';
|
||||
|
||||
const parseErrorCode = error => Promise.reject(error);
|
||||
const AUTH_HEADERS = ['access-token', 'token-type', 'client', 'expiry', 'uid'];
|
||||
|
||||
export default axios => {
|
||||
const { apiHost = '' } = window.chatwootConfig || {};
|
||||
const wootApi = axios.create({ baseURL: `${apiHost}/` });
|
||||
// Add Auth Headers to requests if logged in
|
||||
if (Auth.hasAuthCookie()) {
|
||||
const {
|
||||
'access-token': accessToken,
|
||||
'token-type': tokenType,
|
||||
client,
|
||||
expiry,
|
||||
uid,
|
||||
} = Auth.getAuthData();
|
||||
Object.assign(wootApi.defaults.headers.common, {
|
||||
'access-token': accessToken,
|
||||
'token-type': tokenType,
|
||||
client,
|
||||
expiry,
|
||||
uid,
|
||||
});
|
||||
}
|
||||
// Response parsing interceptor
|
||||
const wootApi = axios.create({
|
||||
baseURL: `${apiHost}/`,
|
||||
withCredentials: true,
|
||||
});
|
||||
const authHeaders = {};
|
||||
let refreshRequest;
|
||||
|
||||
wootApi.interceptors.request.use(config => {
|
||||
Object.assign(config.headers, authHeaders);
|
||||
return config;
|
||||
});
|
||||
wootApi.interceptors.response.use(
|
||||
response => response,
|
||||
error => parseErrorCode(error)
|
||||
response => {
|
||||
AUTH_HEADERS.forEach(header => {
|
||||
if (response.headers?.[header])
|
||||
authHeaders[header] = response.headers[header];
|
||||
});
|
||||
return response;
|
||||
},
|
||||
async error => {
|
||||
const request = error.config;
|
||||
if (
|
||||
error.response?.status !== 401 ||
|
||||
request?._retry ||
|
||||
request?._sessionRefresh ||
|
||||
!Auth.hasAuthCookie()
|
||||
) {
|
||||
return parseErrorCode(error);
|
||||
}
|
||||
request._retry = true;
|
||||
refreshRequest ||= wootApi
|
||||
.get('/auth/validate_token', { _sessionRefresh: true })
|
||||
.finally(() => {
|
||||
refreshRequest = null;
|
||||
});
|
||||
await refreshRequest;
|
||||
return wootApi(request);
|
||||
}
|
||||
);
|
||||
return wootApi;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import axios from 'axios';
|
||||
import Cookies from 'js-cookie';
|
||||
import createAPIClient from './APIHelper';
|
||||
|
||||
describe('APIHelper browser session exchange', () => {
|
||||
it('keeps the access token in memory across reload exchange and 401 refresh', async () => {
|
||||
vi.spyOn(Cookies, 'get').mockImplementation(name =>
|
||||
name === 'cw_d_session_state' ? '1' : undefined
|
||||
);
|
||||
const requests = [];
|
||||
let protectedCalls = 0;
|
||||
const client = createAPIClient(axios);
|
||||
client.defaults.adapter = config => {
|
||||
requests.push(config);
|
||||
if (config.url === '/auth/validate_token') {
|
||||
return Promise.resolve({
|
||||
data: {},
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: { 'access-token': 'short-lived', client: 'browser' },
|
||||
config,
|
||||
});
|
||||
}
|
||||
protectedCalls += 1;
|
||||
if (protectedCalls === 1) {
|
||||
return Promise.reject({ config, response: { status: 401 } });
|
||||
}
|
||||
return Promise.resolve({
|
||||
data: {},
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {},
|
||||
config,
|
||||
});
|
||||
};
|
||||
|
||||
await client.get('/auth/validate_token');
|
||||
await client.get('/api/v1/protected');
|
||||
|
||||
expect(requests.at(-1).headers['access-token']).toBe('short-lived');
|
||||
expect(localStorage.getItem('access-token')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import '../../../../routes';
|
||||
|
||||
vi.spyOn(APIHelpers, 'setUser');
|
||||
vi.spyOn(APIHelpers, 'clearCookiesOnLogout');
|
||||
vi.spyOn(APIHelpers, 'getHeaderExpiry');
|
||||
vi.spyOn(Cookies, 'get');
|
||||
|
||||
const commit = vi.fn();
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import fromUnixTime from 'date-fns/fromUnixTime';
|
||||
import differenceInDays from 'date-fns/differenceInDays';
|
||||
import Cookies from 'js-cookie';
|
||||
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
|
||||
import { SESSION_STORAGE_KEYS } from 'dashboard/constants/sessionStorage';
|
||||
@@ -25,21 +23,18 @@ export const setUser = user => {
|
||||
emitter.emit(ANALYTICS_IDENTITY, { user });
|
||||
};
|
||||
|
||||
export const getHeaderExpiry = response =>
|
||||
fromUnixTime(response.headers.expiry);
|
||||
|
||||
export const setAuthCredentials = response => {
|
||||
const expiryDate = getHeaderExpiry(response);
|
||||
Cookies.set('cw_d_session_info', JSON.stringify(response.headers), {
|
||||
expires: differenceInDays(expiryDate, new Date()),
|
||||
});
|
||||
setUser(response.data.data, expiryDate);
|
||||
setUser(response.data.data);
|
||||
};
|
||||
|
||||
export const clearBrowserSessionCookies = () => {
|
||||
Cookies.remove('cw_d_session_info');
|
||||
Cookies.remove('cw_d_session_state');
|
||||
Cookies.remove('auth_data');
|
||||
Cookies.remove('user');
|
||||
['access-token', 'client', 'uid', 'token-type', 'expiry'].forEach(key =>
|
||||
localStorage.removeItem(key)
|
||||
);
|
||||
};
|
||||
|
||||
export const clearLocalStorageOnLogout = () => {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import Cookies from 'js-cookie';
|
||||
import { clearBrowserSessionCookies, setAuthCredentials } from './api';
|
||||
|
||||
describe('browser auth storage', () => {
|
||||
it('never persists response auth headers in JavaScript-readable storage', () => {
|
||||
const cookie = vi.spyOn(Cookies, 'set');
|
||||
const storage = vi.spyOn(Storage.prototype, 'setItem');
|
||||
|
||||
setAuthCredentials({
|
||||
data: { data: { id: 1 } },
|
||||
headers: { 'access-token': 'xss-readable-token', client: 'browser' },
|
||||
});
|
||||
|
||||
expect(cookie).not.toHaveBeenCalled();
|
||||
expect(storage).not.toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.stringContaining('xss-readable-token')
|
||||
);
|
||||
});
|
||||
|
||||
it('removes legacy auth storage during logout', () => {
|
||||
const removeCookie = vi.spyOn(Cookies, 'remove');
|
||||
const removeStorage = vi.spyOn(Storage.prototype, 'removeItem');
|
||||
|
||||
clearBrowserSessionCookies();
|
||||
|
||||
expect(removeCookie).toHaveBeenCalledWith('cw_d_session_info');
|
||||
expect(removeCookie).toHaveBeenCalledWith('cw_d_session_state');
|
||||
expect(removeStorage).toHaveBeenCalledWith('access-token');
|
||||
expect(removeStorage).toHaveBeenCalledWith('client');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user