signal-desktop/ts/services/groupCredentialFetcher.ts

251 lines
7.2 KiB
TypeScript
Raw Normal View History

2020-10-30 20:34:04 +00:00
// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2023-11-13 22:33:43 +00:00
import { first, last, sortBy } from 'lodash';
2022-07-08 20:46:25 +00:00
import { AuthCredentialWithPniResponse } from '@signalapp/libsignal-client/zkgroup';
2020-09-09 02:25:05 +00:00
import { getClientZkAuthOperations } from '../util/zkgroup';
2020-09-09 02:25:05 +00:00
import type { GroupCredentialType } from '../textsecure/WebAPI';
2022-07-08 20:46:25 +00:00
import { strictAssert } from '../util/assert';
import * as durations from '../util/durations';
2021-06-09 22:28:54 +00:00
import { BackOff } from '../util/BackOff';
import { sleep } from '../util/sleep';
2022-07-08 20:46:25 +00:00
import { toDayMillis } from '../util/timestamp';
import { toTaggedPni } from '../types/ServiceId';
import { toPniObject, toAciObject } from '../util/ServiceId';
import * as log from '../logging/log';
2020-09-09 02:25:05 +00:00
export const GROUP_CREDENTIALS_KEY = 'groupCredentials';
2022-07-28 16:35:29 +00:00
type CredentialsDataType = ReadonlyArray<GroupCredentialType>;
2020-09-09 02:25:05 +00:00
type RequestDatesType = {
2022-07-08 20:46:25 +00:00
startDayInMs: number;
endDayInMs: number;
2020-09-09 02:25:05 +00:00
};
type NextCredentialsType = {
today: GroupCredentialType;
tomorrow: GroupCredentialType;
};
let started = false;
2022-07-08 20:46:25 +00:00
function getCheckedCredentials(reason: string): CredentialsDataType {
const result = window.storage.get('groupCredentials');
strictAssert(
result !== undefined,
`getCheckedCredentials: no credentials found, ${reason}`
);
return result;
}
2020-09-09 02:25:05 +00:00
export async function initializeGroupCredentialFetcher(): Promise<void> {
if (started) {
return;
}
log.info('initializeGroupCredentialFetcher: starting...');
2020-09-09 02:25:05 +00:00
started = true;
// Because we fetch eight days of credentials at a time, we really only need to run
// this about once a week. But there's no problem running it more often; it will do
// nothing if no new credentials are needed, and will only request needed credentials.
await runWithRetry(maybeFetchNewCredentials, {
scheduleAnother: 4 * durations.HOUR,
});
2020-09-09 02:25:05 +00:00
}
2021-06-09 22:28:54 +00:00
const BACKOFF_TIMEOUTS = [
durations.SECOND,
5 * durations.SECOND,
30 * durations.SECOND,
2 * durations.MINUTE,
5 * durations.MINUTE,
2021-06-09 22:28:54 +00:00
];
2020-09-09 02:25:05 +00:00
export async function runWithRetry(
fn: () => Promise<void>,
options: { scheduleAnother?: number } = {}
): Promise<void> {
2021-06-09 22:28:54 +00:00
const backOff = new BackOff(BACKOFF_TIMEOUTS);
2020-09-09 02:25:05 +00:00
// eslint-disable-next-line no-constant-condition
while (true) {
try {
// eslint-disable-next-line no-await-in-loop
await fn();
return;
} catch (error) {
2021-06-09 22:28:54 +00:00
const wait = backOff.getAndIncrement();
log.info(
2020-09-09 02:25:05 +00:00
`runWithRetry: ${fn.name} failed. Waiting ${wait}ms for retry. Error: ${error.stack}`
);
// eslint-disable-next-line no-await-in-loop
await sleep(wait);
}
}
// It's important to schedule our next run here instead of the level above; otherwise we
// could end up with multiple endlessly-retrying runs.
// eslint-disable-next-line no-unreachable -- Why is this here, its unreachable
2020-09-09 02:25:05 +00:00
const duration = options.scheduleAnother;
if (duration) {
log.info(
2020-09-09 02:25:05 +00:00
`runWithRetry: scheduling another run with a setTimeout duration of ${duration}ms`
);
setTimeout(async () => runWithRetry(fn, options), duration);
}
}
// In cases where we are at a day boundary, we might need to use tomorrow in a retry
2022-07-08 20:46:25 +00:00
export function getCheckedCredentialsForToday(
reason: string
2020-09-09 02:25:05 +00:00
): NextCredentialsType {
2022-07-08 20:46:25 +00:00
const data = getCheckedCredentials(reason);
2020-09-09 02:25:05 +00:00
2022-07-08 20:46:25 +00:00
const today = toDayMillis(Date.now());
2020-09-09 02:25:05 +00:00
const todayIndex = data.findIndex(
2022-07-08 20:46:25 +00:00
(item: GroupCredentialType) => item.redemptionTime === today
2020-09-09 02:25:05 +00:00
);
if (todayIndex < 0) {
throw new Error(
2023-11-13 22:33:43 +00:00
'getCredentialsForToday: Cannot find credentials for today. ' +
`First: ${first(data)?.redemptionTime}, ` +
`last: ${last(data)?.redemptionTime}`
2020-09-09 02:25:05 +00:00
);
}
return {
today: data[todayIndex],
tomorrow: data[todayIndex + 1],
};
}
export async function maybeFetchNewCredentials(): Promise<void> {
2022-07-08 20:46:25 +00:00
const logId = 'maybeFetchNewCredentials';
const aci = window.textsecure.storage.user.getAci();
2022-07-08 20:46:25 +00:00
if (!aci) {
log.info(`${logId}: no ACI, returning early`);
2020-09-09 02:25:05 +00:00
return;
}
2022-07-08 20:46:25 +00:00
2023-11-13 22:33:43 +00:00
const previous: CredentialsDataType =
window.storage.get('groupCredentials') ?? [];
2020-09-09 02:25:05 +00:00
const requestDates = getDatesForRequest(previous);
if (!requestDates) {
2022-07-08 20:46:25 +00:00
log.info(`${logId}: no new credentials needed`);
2020-09-09 02:25:05 +00:00
return;
}
2022-07-08 20:46:25 +00:00
const { server } = window.textsecure;
if (!server) {
log.error(`${logId}: unable to get server`);
2020-09-09 02:25:05 +00:00
return;
}
2022-07-08 20:46:25 +00:00
const { startDayInMs, endDayInMs } = requestDates;
log.info(
2022-07-08 20:46:25 +00:00
`${logId}: fetching credentials for ${startDayInMs} through ${endDayInMs}`
2020-09-09 02:25:05 +00:00
);
const serverPublicParamsBase64 = window.getServerPublicParams();
const clientZKAuthOperations = getClientZkAuthOperations(
serverPublicParamsBase64
);
2023-08-16 20:54:39 +00:00
// Received credentials depend on us knowing up-to-date PNI. Use the latest
// value from the server and log error on mismatch.
const { pni: untaggedPni, credentials: rawCredentials } =
await server.getGroupCredentials({ startDayInMs, endDayInMs });
strictAssert(
untaggedPni,
'Server must give pni along with group credentials'
2022-07-28 16:35:29 +00:00
);
2023-08-16 20:54:39 +00:00
const pni = toTaggedPni(untaggedPni);
2022-07-28 16:35:29 +00:00
const localPni = window.storage.user.getPni();
if (pni !== localPni) {
2022-07-28 16:35:29 +00:00
log.error(`${logId}: local PNI ${localPni}, does not match remote ${pni}`);
}
const newCredentials = sortCredentials(rawCredentials).map(
(item: GroupCredentialType) => {
const authCredential =
2023-08-16 20:54:39 +00:00
clientZKAuthOperations.receiveAuthCredentialWithPniAsServiceId(
toAciObject(aci),
toPniObject(pni),
2022-07-28 16:35:29 +00:00
item.redemptionTime,
new AuthCredentialWithPniResponse(
Buffer.from(item.credential, 'base64')
)
);
const credential = authCredential.serialize().toString('base64');
return {
redemptionTime: item.redemptionTime * durations.SECOND,
credential,
};
}
);
2020-09-09 02:25:05 +00:00
2022-07-08 20:46:25 +00:00
const today = toDayMillis(Date.now());
2020-09-09 02:25:05 +00:00
const previousCleaned = previous
? previous.filter(
2022-07-08 20:46:25 +00:00
(item: GroupCredentialType) => item.redemptionTime >= today
2020-09-09 02:25:05 +00:00
)
: [];
const finalCredentials = [...previousCleaned, ...newCredentials];
2023-11-13 22:33:43 +00:00
log.info(
`${logId}: saving ${newCredentials.length} new credentials, ` +
`cleaning up ${previous.length - previousCleaned.length} old ` +
`credentials, haveToday=${haveToday(finalCredentials)}`
);
2020-09-09 02:25:05 +00:00
// Note: we don't wait for this to finish
await window.storage.put('groupCredentials', finalCredentials);
2022-07-08 20:46:25 +00:00
log.info(`${logId}: Save complete.`);
2020-09-09 02:25:05 +00:00
}
2023-11-13 22:33:43 +00:00
function haveToday(
data: CredentialsDataType,
today = toDayMillis(Date.now())
): boolean {
return data?.some(({ redemptionTime }) => redemptionTime === today);
}
2020-09-09 02:25:05 +00:00
export function getDatesForRequest(
2023-11-13 22:33:43 +00:00
data: CredentialsDataType
2020-09-09 02:25:05 +00:00
): RequestDatesType | undefined {
2022-07-08 20:46:25 +00:00
const today = toDayMillis(Date.now());
const sixDaysOut = today + 6 * durations.DAY;
2020-09-09 02:25:05 +00:00
const lastCredential = last(data);
2023-11-13 22:33:43 +00:00
if (
!haveToday(data, today) ||
!lastCredential ||
lastCredential.redemptionTime < today
) {
2020-09-09 02:25:05 +00:00
return {
2022-07-08 20:46:25 +00:00
startDayInMs: today,
endDayInMs: sixDaysOut,
2020-09-09 02:25:05 +00:00
};
}
if (lastCredential.redemptionTime >= sixDaysOut) {
2020-09-09 02:25:05 +00:00
return undefined;
}
return {
2022-07-08 20:46:25 +00:00
startDayInMs: lastCredential.redemptionTime + durations.DAY,
endDayInMs: sixDaysOut,
2020-09-09 02:25:05 +00:00
};
}
export function sortCredentials(
data: CredentialsDataType
): CredentialsDataType {
return sortBy(data, (item: GroupCredentialType) => item.redemptionTime);
}