-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtask.ts
327 lines (288 loc) · 9.88 KB
/
task.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { Buffer } from "buffer";
import { TaskId } from "./taskId.js";
import { ReportId } from "./reportId.js";
import {
Report,
ReportMetadata,
InputShareAad,
PlaintextInputShare,
} from "./report.js";
import { HpkeConfigList } from "./hpkeConfig.js";
import type { ClientVdaf } from "@divviup/vdaf";
import { Extension } from "./extension.js";
import { DAPError } from "./errors.js";
import { CONTENT_TYPES, DAP_VERSION } from "./constants.js";
import { Aggregator } from "./aggregator.js";
import {
Prio3Count,
Prio3Histogram,
Prio3Sum,
Prio3SumVec,
} from "@divviup/prio3";
import { randomBytes } from "@divviup/common";
export { TaskId } from "./taskId.js";
export interface ReportOptions {
timestamp?: Date;
}
/**
Parameters from which to build a Task
@typeParam Measurement The Measurement for the provided vdaf, usually inferred from the vdaf.
*/
export interface ClientParameters {
/**
The task identifier for this {@linkcode Task}. This can be specified
either as a Buffer, a {@linkcode TaskId} or a base64url-encoded
string
**/
id: TaskId | Buffer | string;
/**
the url of the leader aggregator, specified as either a string
or a {@linkcode URL}
*/
leader: string | URL;
/**
the url of the helper aggregator, specified as either a string or
{@linkcode URL}s.
*/
helper: string | URL;
/**
The task's minimum batch duration, in seconds. Report timestamps will be
rounded down to a multiple of this.
*/
timePrecisionSeconds: number;
}
type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
export interface KnownVdafs {
sum: typeof Prio3Sum;
count: typeof Prio3Count;
histogram: typeof Prio3Histogram;
sumVec: typeof Prio3SumVec;
}
type KnownVdafNames = keyof KnownVdafs;
export type KnownVdafSpec = {
[Key in KnownVdafNames]: Omit<
{ type: Key } & ConstructorParameters<KnownVdafs[Key]>[0],
"shares"
>;
}[KnownVdafNames];
type KnownVdaf<Spec extends KnownVdafSpec> = KnownVdafs[Spec["type"]];
type VdafInstance<Spec extends KnownVdafSpec> = InstanceType<KnownVdaf<Spec>>;
export type VdafMeasurement<Spec extends KnownVdafSpec> = Parameters<
VdafInstance<Spec>["shard"]
>[0];
function vdafFromSpec<Spec extends KnownVdafSpec>(
spec: Spec,
shares = 2,
): VdafInstance<Spec> {
switch (spec.type) {
case "count":
return new Prio3Count({ ...spec, shares }) as VdafInstance<Spec>;
case "histogram":
return new Prio3Histogram({
...spec,
shares,
}) as VdafInstance<Spec>;
case "sum":
return new Prio3Sum({ ...spec, shares }) as VdafInstance<Spec>;
case "sumVec":
return new Prio3SumVec({ ...spec, shares }) as VdafInstance<Spec>;
}
}
/**
A client for interacting with DAP servers, as specified by
[draft-ietf-ppm-dap-02](https://datatracker.ietf.org/doc/html/draft-ietf-ppm-dap/02/). Instances
of this class contain all of the necessary functionality to
generate a privacy-preserving measurement report for the provided
{@linkcode ClientVdaf}, such as an implementation of Prio3, as specified by
[draft-irtf-cfrg-vdaf-03](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vdaf/03/).
*/
export class Task<
Spec extends KnownVdafSpec,
Measurement extends VdafMeasurement<Spec>,
> {
#vdaf: ClientVdaf<Measurement>;
#id: TaskId;
#leader: Aggregator;
#helper: Aggregator;
#timePrecisionSeconds: number;
#extensions: Extension[] = [];
#fetch: Fetch = globalThis.fetch.bind(globalThis);
#hpkeConfigsWereInvalid = false;
/** the protocol version for this task, usually in the form `dap-{nn}` */
static readonly protocolVersion = DAP_VERSION;
/**
Builds a new Task from the {@linkcode ClientParameters} provided.
*/
constructor(parameters: ClientParameters & Spec) {
this.#vdaf = vdafFromSpec(parameters) as ClientVdaf<Measurement>;
this.#id = idFromDefinition(parameters.id);
this.#leader = Aggregator.leader(parameters.leader);
this.#helper = Aggregator.helper(parameters.helper);
if (typeof parameters.timePrecisionSeconds !== "number") {
throw new Error("timePrecisionSeconds must be a number");
}
this.#timePrecisionSeconds = parameters.timePrecisionSeconds;
}
/** @internal */
//this exists for testing, and should not be considered part of the public api.
get aggregators(): Aggregator[] {
return [this.#leader, this.#helper];
}
/** @internal */
//this exists for testing, and should not be considered part of the public api.
get vdaf(): ClientVdaf<Measurement> {
return this.#vdaf;
}
/** @internal */
//this exists for testing, and should not be considered part of the public api.
set fetch(fetch: Fetch) {
this.#fetch = fetch;
}
/** @internal */
//this exists for testing, and should not be considered part of the public api.
get id(): TaskId {
return this.#id;
}
/**
Produce a {@linkcode Report} from the supplied Measurement
This may make network requests to fetch key configuration from the
leader and helper, if needed.
@param measurement The type of this argument will be determined
by the Vdaf that this task is constructed for.
@throws `Error` if there is any issue in generating the report
*/
async generateReport(
measurement: Measurement,
options?: ReportOptions,
): Promise<Report> {
await this.fetchKeyConfiguration();
const reportId = ReportId.random();
const rand = Buffer.from(randomBytes(this.#vdaf.randSize));
const {
publicShare,
inputShares: [leaderShare, helperShare],
} = await this.#vdaf.shardEncoded(measurement, reportId.encode(), rand);
const time = roundedTime(this.#timePrecisionSeconds, options?.timestamp);
const metadata = new ReportMetadata(reportId, time);
const aad = new InputShareAad(this.id, metadata, publicShare);
const leaderCiphertext = await this.#leader.seal(
new PlaintextInputShare(this.#extensions, leaderShare),
aad,
);
const helperCiphertext = await this.#helper.seal(
new PlaintextInputShare(this.#extensions, helperShare),
aad,
);
return new Report(
metadata,
publicShare,
leaderCiphertext,
helperCiphertext,
);
}
/**
Sends a pregenerated {@linkcode Report} to the leader aggregator.
@param report The {@linkcode Report} to send.
@throws {@linkcode DAPError} if the response is not Ok.
*/
async sendReport(report: Report) {
const body = report.encode();
const leader = this.#leader;
const id = this.#id.toString();
const response = await this.#fetch(
new URL(`tasks/${id}/reports`, leader.url).toString(),
{
method: "PUT",
headers: { "Content-Type": CONTENT_TYPES.REPORT },
body,
},
);
if (!response.ok) {
throw await DAPError.fromResponse(response, "report upload failed");
}
}
private hasKeyConfiguration(): boolean {
return !!this.#leader.hpkeConfigList && !!this.#helper.hpkeConfigList;
}
/**
A convenience function to fetch the key configuration (if
needed), generate a report from the provided measurement and send
that report to the leader aggregator.
This will call {@linkcode Task.generateReport} and
{@linkcode Task.sendReport}, while automatically handling
any errors due to server key rotation with re-encryption and a
retry.
@throws {@linkcode DAPError} if any http response is not Ok or
`Error` if there is an issue generating the report
*/
async sendMeasurement(
measurement: Measurement,
options?: ReportOptions,
): Promise<void> {
const report = await this.generateReport(measurement, options);
try {
await this.sendReport(report);
this.#hpkeConfigsWereInvalid = false;
} catch (error) {
if (
error instanceof DAPError &&
error.shortType === "outdatedConfig" &&
!this.#hpkeConfigsWereInvalid // only retry once
) {
this.invalidateHpkeConfig();
await this.sendMeasurement(measurement);
} else {
throw error;
}
}
}
invalidateHpkeConfig() {
this.#hpkeConfigsWereInvalid = true;
delete this.#leader.hpkeConfigList;
delete this.#helper.hpkeConfigList;
}
/**
Fetches hpke configuration from the configured aggregators over
the network. This will make one http/https request for each
aggregator (leader and helper).
@throws {@linkcode DAPError} if any response is not Ok.
*/
async fetchKeyConfiguration(): Promise<void> {
if (this.hasKeyConfiguration()) return;
await Promise.all(
this.aggregators.map(async (aggregator) => {
const url = new URL("hpke_config", aggregator.url);
url.searchParams.append("task_id", this.#id.toString());
const response = await this.#fetch(url.toString(), {
headers: { Accept: CONTENT_TYPES.HPKE_CONFIG_LIST },
});
if (!response.ok) {
throw await DAPError.fromResponse(
response,
`fetchKeyConfiguration received a ${response.status} response, aborting`,
);
}
const blob = await response.blob();
if (blob.type !== CONTENT_TYPES.HPKE_CONFIG_LIST) {
throw new Error(
`expected ${CONTENT_TYPES.HPKE_CONFIG_LIST} content-type header, aborting`,
);
}
aggregator.hpkeConfigList = HpkeConfigList.parse(
await blob.arrayBuffer(),
);
aggregator.hpkeConfigList.selectConfig();
}),
);
}
}
function idFromDefinition(idDefinition: Buffer | TaskId | string): TaskId {
if (idDefinition instanceof TaskId) return idDefinition;
else return new TaskId(idDefinition);
}
function roundedTime(timePrecisionSeconds: number, date?: Date): number {
const epochSeconds = (date ? date.getTime() : Date.now()) / 1000;
const roundedSeconds =
Math.floor(epochSeconds / timePrecisionSeconds) * timePrecisionSeconds;
return roundedSeconds;
}