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:
Rogee
2026-08-22 15:45:06 +08:00
committed by GitHub
co-authored by rogee
parent e1557e7f21
commit f719529d66
81 changed files with 2149 additions and 474 deletions
@@ -13,34 +13,50 @@ class BaseActionCableConnector {
websocketHost = '',
presenceInterval = PRESENCE_INTERVAL
) {
// Read access-token for WebSocket auth from cookie
let accessToken = '';
try {
const raw = Cookies.get('cw_d_session_info');
if (raw) {
const parsed = JSON.parse(raw);
accessToken = parsed['access-token'] || '';
}
} catch (e) {
// Ignore cookie parse errors
}
this.consumer = null;
this.subscription = null;
this.websocketHost = websocketHost;
this.pubsubToken = pubsubToken;
this.app = app;
this.events = {};
this.reconnectTimer = null;
this.isAValidEvent = () => true;
this.connect();
this.triggerPresenceInterval = () => {
setTimeout(() => {
this.subscription?.updatePresence();
this.triggerPresenceInterval();
}, presenceInterval);
};
this.triggerPresenceInterval();
}
// Default to the page origin so the URL is never undefined.
const wsOrigin = websocketHost || window.location.origin;
async connect() {
const wsOrigin = this.websocketHost || window.location.origin;
let websocketURL = `${wsOrigin}/cable`;
if (accessToken) {
websocketURL += `?access-token=${encodeURIComponent(accessToken)}`;
} else if (pubsubToken) {
websocketURL += `?pubsub_token=${encodeURIComponent(pubsubToken)}`;
if (Cookies.get('cw_d_session_state')) {
try {
const response = await window.axios.post('/api/v1/auth/ws_ticket');
const ticket = response.data?.data?.ticket;
if (!ticket) throw new Error('missing websocket ticket');
websocketURL += `?ticket=${encodeURIComponent(ticket)}`;
this.usesWSTicket = true;
} catch (error) {
this.initReconnectTimer();
return;
}
} else if (this.pubsubToken) {
websocketURL += `?pubsub_token=${encodeURIComponent(this.pubsubToken)}`;
this.usesWSTicket = false;
}
this.consumer = createConsumer(websocketURL);
this.subscription = this.consumer.subscriptions.create(
{
channel: 'RoomChannel',
pubsub_token: pubsubToken,
account_id: app.$store.getters.getCurrentAccountId,
user_id: app.$store.getters.getCurrentUserID,
pubsub_token: this.pubsubToken,
account_id: this.app.$store.getters.getCurrentAccountId,
user_id: this.app.$store.getters.getCurrentUserID,
},
{
updatePresence() {
@@ -49,25 +65,23 @@ class BaseActionCableConnector {
received: this.onReceived,
disconnected: () => {
BaseActionCableConnector.isDisconnected = true;
if (this.usesWSTicket) {
this.consumer?.disconnect();
this.consumer = null;
this.subscription = null;
}
this.onDisconnected();
this.initReconnectTimer();
},
}
);
this.app = app;
this.events = {};
this.reconnectTimer = null;
this.isAValidEvent = () => true;
this.triggerPresenceInterval = () => {
setTimeout(() => {
this.subscription.updatePresence();
this.triggerPresenceInterval();
}, presenceInterval);
};
this.triggerPresenceInterval();
}
checkConnection() {
if (!this.consumer) {
this.connect();
return;
}
const isConnectionActive = this.consumer.connection.isOpen();
const isReconnected =
BaseActionCableConnector.isDisconnected && isConnectionActive;
@@ -101,7 +115,7 @@ class BaseActionCableConnector {
onDisconnected = () => {};
disconnect() {
this.consumer.disconnect();
this.consumer?.disconnect();
}
onReceived = ({ event, data } = {}) => {
@@ -1,25 +1,47 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { createConsumer, createSubscription, getCookie, subscriptionState } =
vi.hoisted(() => {
const subscriptionState = { callbacks: null };
return {
createConsumer: vi.fn(),
createSubscription: vi.fn((_identifier, callbacks) => {
subscriptionState.callbacks = callbacks;
return { updatePresence: vi.fn() };
}),
getCookie: vi.fn(),
subscriptionState,
};
});
const {
createConsumer,
createSubscription,
getCookie,
post,
subscriptionState,
} = vi.hoisted(() => {
const subscriptionState = { callbacks: null };
return {
createConsumer: vi.fn(),
createSubscription: vi.fn((_identifier, callbacks) => {
subscriptionState.callbacks = callbacks;
return { updatePresence: vi.fn() };
}),
getCookie: vi.fn(),
post: vi.fn(),
subscriptionState,
};
});
vi.mock('@rails/actioncable', () => ({ createConsumer }));
vi.mock('js-cookie', () => ({ default: { get: getCookie } }));
import BaseActionCableConnector from '../BaseActionCableConnector';
const app = {
$store: {
getters: { getCurrentAccountId: 3, getCurrentUserID: 7 },
},
};
describe('BaseActionCableConnector', () => {
beforeEach(() => {
vi.useFakeTimers();
createConsumer.mockReturnValue({
connection: { isOpen: vi.fn(() => true) },
disconnect: vi.fn(),
subscriptions: { create: createSubscription },
});
window.axios = { post };
});
afterEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
@@ -28,16 +50,9 @@ describe('BaseActionCableConnector', () => {
});
it('authenticates a widget socket and RoomChannel with its pubsub token', () => {
vi.useFakeTimers();
getCookie.mockReturnValue(undefined);
createConsumer.mockReturnValue({
subscriptions: { create: createSubscription },
});
new BaseActionCableConnector(
{ $store: { getters: {} } },
'visitor token'
);
new BaseActionCableConnector(app, 'visitor token');
expect(createConsumer).toHaveBeenCalledWith(
`${window.location.origin}/cable?pubsub_token=visitor%20token`
@@ -51,18 +66,9 @@ describe('BaseActionCableConnector', () => {
);
});
it('continues consuming widget events after ActionCable reconnects', () => {
vi.useFakeTimers();
it('continues consuming widget events after ActionCable reconnects', async () => {
getCookie.mockReturnValue(undefined);
const isOpen = vi.fn(() => true);
createConsumer.mockReturnValue({
connection: { isOpen },
subscriptions: { create: createSubscription },
});
const connector = new BaseActionCableConnector(
{ $store: { getters: {} } },
'visitor-token'
);
const connector = new BaseActionCableConnector(app, 'visitor-token');
const onMessage = vi.fn();
connector.events['message.created'] = onMessage;
connector.onDisconnected = vi.fn();
@@ -73,7 +79,7 @@ describe('BaseActionCableConnector', () => {
data: { id: 1, content: 'before reconnect' },
});
subscriptionState.callbacks.disconnected();
vi.advanceTimersByTime(1000);
await vi.advanceTimersByTimeAsync(1000);
subscriptionState.callbacks.received({
event: 'message.created',
data: { id: 2, content: 'after reconnect' },
@@ -90,4 +96,51 @@ describe('BaseActionCableConnector', () => {
content: 'after reconnect',
});
});
it('exchanges the dashboard session for a ticket without putting JWT in the URL', async () => {
getCookie.mockReturnValue('1');
post.mockResolvedValue({ data: { data: { ticket: 'one-time' } } });
const connector = new BaseActionCableConnector(
app,
'pubsub',
'wss://chat.test'
);
await vi.waitFor(() => expect(createConsumer).toHaveBeenCalledOnce());
expect(post).toHaveBeenCalledWith('/api/v1/auth/ws_ticket');
expect(createConsumer).toHaveBeenCalledWith(
'wss://chat.test/cable?ticket=one-time'
);
expect(createConsumer.mock.calls[0][0]).not.toContain('access-token');
connector.disconnect();
});
it('gets a fresh ticket after a dashboard disconnect', async () => {
getCookie.mockReturnValue('1');
post
.mockResolvedValueOnce({ data: { data: { ticket: 'first' } } })
.mockResolvedValueOnce({ data: { data: { ticket: 'second' } } });
const connector = new BaseActionCableConnector(app, 'pubsub');
await vi.waitFor(() => expect(createConsumer).toHaveBeenCalledOnce());
subscriptionState.callbacks.disconnected();
await vi.advanceTimersByTimeAsync(1000);
await vi.waitFor(() => expect(createConsumer).toHaveBeenCalledTimes(2));
expect(createConsumer).toHaveBeenLastCalledWith(
`${window.location.origin}/cable?ticket=second`
);
connector.disconnect();
});
it('does not open a dashboard socket when ticket exchange returns 401', async () => {
getCookie.mockReturnValue('1');
post.mockRejectedValue({ response: { status: 401 } });
new BaseActionCableConnector(app, 'pubsub');
await vi.waitFor(() => expect(post).toHaveBeenCalledOnce());
expect(createConsumer).not.toHaveBeenCalled();
});
});