generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 96
/
records-query.ts
261 lines (236 loc) · 10.6 KB
/
records-query.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
import type { DataStore } from '../types/data-store.js';
import type { DidResolver } from '@web5/dids';
import type { MessageStore } from '../types//message-store.js';
import type { MethodHandler } from '../types/method-handler.js';
import type { Filter, PaginationCursor } from '../types/query-types.js';
import type { GenericMessage, MessageSort } from '../types/message-types.js';
import type { RecordsQueryMessage, RecordsQueryReply, RecordsQueryReplyEntry } from '../types/records-types.js';
import { authenticate } from '../core/auth.js';
import { DateSort } from '../types/records-types.js';
import { Message } from '../core/message.js';
import { messageReplyFromError } from '../core/message-reply.js';
import { ProtocolAuthorization } from '../core/protocol-authorization.js';
import { Records } from '../utils/records.js';
import { RecordsQuery } from '../interfaces/records-query.js';
import { RecordsWrite } from '../interfaces/records-write.js';
import { SortDirection } from '../types/query-types.js';
import { DwnInterfaceName, DwnMethodName } from '../enums/dwn-interface-method.js';
export class RecordsQueryHandler implements MethodHandler {
constructor(private didResolver: DidResolver, private messageStore: MessageStore, private dataStore: DataStore) { }
public async handle({
tenant,
message
}: {tenant: string, message: RecordsQueryMessage}): Promise<RecordsQueryReply> {
let recordsQuery: RecordsQuery;
try {
recordsQuery = await RecordsQuery.parse(message);
} catch (e) {
return messageReplyFromError(e, 400);
}
let recordsWrites: RecordsQueryReplyEntry[];
let cursor: PaginationCursor | undefined;
// if this is an anonymous query and the filter supports published records, query only published records
if (Records.filterIncludesPublishedRecords(recordsQuery.message.descriptor.filter) && recordsQuery.author === undefined) {
const results = await this.fetchPublishedRecords(tenant, recordsQuery);
recordsWrites = results.messages as RecordsQueryReplyEntry[];
cursor = results.cursor;
} else {
// authentication and authorization
try {
await authenticate(message.authorization!, this.didResolver);
await RecordsQueryHandler.authorizeRecordsQuery(tenant, recordsQuery, this.messageStore);
} catch (e) {
return messageReplyFromError(e, 401);
}
if (recordsQuery.author === tenant) {
const results = await this.fetchRecordsAsOwner(tenant, recordsQuery);
recordsWrites = results.messages as RecordsQueryReplyEntry[];
cursor = results.cursor;
} else {
const results = await this.fetchRecordsAsNonOwner(tenant, recordsQuery);
recordsWrites = results.messages as RecordsQueryReplyEntry[];
cursor = results.cursor;
}
}
// attach initial write if returned RecordsWrite is not initial write
for (const recordsWrite of recordsWrites) {
if (!await RecordsWrite.isInitialWrite(recordsWrite)) {
const initialWriteQueryResult = await this.messageStore.query(
tenant,
[{ recordId: recordsWrite.recordId, isLatestBaseState: false, method: DwnMethodName.Write }]
);
const initialWrite = initialWriteQueryResult.messages[0] as RecordsQueryReplyEntry;
delete initialWrite.encodedData; // defensive measure but technically optional because we do this when an update RecordsWrite takes place
recordsWrite.initialWrite = initialWrite;
}
}
return {
status : { code: 200, detail: 'OK' },
entries : recordsWrites,
cursor
};
}
/**
* Convert an incoming DateSort to a sort type accepted by MessageStore
* Defaults to 'dateCreated' in Descending order if no sort is supplied.
*
* @param dateSort the optional DateSort from the RecordsQuery message descriptor.
* @returns {MessageSort} for MessageStore sorting.
*/
private convertDateSort(dateSort?: DateSort): MessageSort {
switch (dateSort) {
case DateSort.CreatedAscending:
return { dateCreated: SortDirection.Ascending };
case DateSort.CreatedDescending:
return { dateCreated: SortDirection.Descending };
case DateSort.PublishedAscending:
return { datePublished: SortDirection.Ascending };
case DateSort.PublishedDescending:
return { datePublished: SortDirection.Descending };
default:
return { dateCreated: SortDirection.Ascending };
}
}
/**
* Fetches the records as the owner of the DWN with no additional filtering.
*/
private async fetchRecordsAsOwner(
tenant: string,
recordsQuery: RecordsQuery
): Promise<{ messages: GenericMessage[], cursor?: PaginationCursor }> {
const { dateSort, filter, pagination } = recordsQuery.message.descriptor;
// fetch all published records matching the query
const queryFilter = {
...Records.convertFilter(filter, dateSort),
interface : DwnInterfaceName.Records,
method : DwnMethodName.Write,
isLatestBaseState : true
};
const messageSort = this.convertDateSort(dateSort);
return this.messageStore.query(tenant, [ queryFilter ], messageSort, pagination);
}
/**
* Fetches the records as a non-owner.
*
* Filters can support returning both published and unpublished records,
* as well as explicitly only published or only unpublished records.
*
* A) BOTH published and unpublished:
* 1. published records; and
* 2. unpublished records intended for the query author (where `recipient` is the query author); and
* 3. unpublished records authorized by a protocol rule.
*
* B) PUBLISHED:
* 1. only published records;
*
* C) UNPUBLISHED:
* 1. unpublished records intended for the query author (where `recipient` is the query author); and
* 2. unpublished records authorized by a protocol rule.
*
*/
private async fetchRecordsAsNonOwner(
tenant: string, recordsQuery: RecordsQuery
): Promise<{ messages: GenericMessage[], cursor?: PaginationCursor }> {
const { dateSort, pagination, filter } = recordsQuery.message.descriptor;
const filters = [];
if (Records.filterIncludesPublishedRecords(filter)) {
filters.push(RecordsQueryHandler.buildPublishedRecordsFilter(recordsQuery));
}
if (Records.filterIncludesUnpublishedRecords(filter)) {
filters.push(RecordsQueryHandler.buildUnpublishedRecordsByQueryAuthorFilter(recordsQuery));
const recipientFilter = recordsQuery.message.descriptor.filter.recipient;
if (recipientFilter === undefined || recipientFilter === recordsQuery.author) {
filters.push(RecordsQueryHandler.buildUnpublishedRecordsForQueryAuthorFilter(recordsQuery));
}
if (Records.shouldProtocolAuthorize(recordsQuery.signaturePayload!)) {
filters.push(RecordsQueryHandler.buildUnpublishedProtocolAuthorizedRecordsFilter(recordsQuery));
}
}
const messageSort = this.convertDateSort(dateSort);
return this.messageStore.query(tenant, filters, messageSort, pagination );
}
/**
* Fetches only published records.
*/
private async fetchPublishedRecords(
tenant: string, recordsQuery: RecordsQuery
): Promise<{ messages: GenericMessage[], cursor?: PaginationCursor }> {
const { dateSort, pagination } = recordsQuery.message.descriptor;
const filter = RecordsQueryHandler.buildPublishedRecordsFilter(recordsQuery);
const messageSort = this.convertDateSort(dateSort);
return this.messageStore.query(tenant, [ filter ], messageSort, pagination);
}
private static buildPublishedRecordsFilter(recordsQuery: RecordsQuery): Filter {
const { dateSort, filter } = recordsQuery.message.descriptor;
// fetch all published records matching the query
return {
...Records.convertFilter(filter, dateSort),
interface : DwnInterfaceName.Records,
method : DwnMethodName.Write,
published : true,
isLatestBaseState : true
};
}
/**
* Creates a filter for unpublished records that are intended for the query author (where `recipient` is the author).
*/
private static buildUnpublishedRecordsForQueryAuthorFilter(recordsQuery: RecordsQuery): Filter {
const { dateSort, filter } = recordsQuery.message.descriptor;
// include records where recipient is query author
return {
...Records.convertFilter(filter, dateSort),
interface : DwnInterfaceName.Records,
method : DwnMethodName.Write,
recipient : recordsQuery.author!,
isLatestBaseState : true,
published : false
};
}
/**
* Creates a filter for unpublished records that are within the specified protocol.
* Validation that `protocol` and other required protocol-related fields occurs before this method.
*/
private static buildUnpublishedProtocolAuthorizedRecordsFilter(recordsQuery: RecordsQuery): Filter {
const { dateSort, filter } = recordsQuery.message.descriptor;
return {
...Records.convertFilter(filter, dateSort),
interface : DwnInterfaceName.Records,
method : DwnMethodName.Write,
isLatestBaseState : true,
published : false
};
}
/**
* Creates a filter for only unpublished records where the author is the same as the query author.
*/
private static buildUnpublishedRecordsByQueryAuthorFilter(recordsQuery: RecordsQuery): Filter {
const { dateSort, filter } = recordsQuery.message.descriptor;
// include records where author is the same as the query author
return {
...Records.convertFilter(filter, dateSort),
author : recordsQuery.author!,
interface : DwnInterfaceName.Records,
method : DwnMethodName.Write,
isLatestBaseState : true,
published : false
};
}
/**
* @param messageStore Used to check if the grant has been revoked.
*/
private static async authorizeRecordsQuery(
tenant: string,
recordsQuery: RecordsQuery,
messageStore: MessageStore
): Promise<void> {
if (Message.isSignedByAuthorDelegate(recordsQuery.message)) {
await recordsQuery.authorizeDelegate(messageStore);
}
// NOTE: not all RecordsQuery messages require protocol authorization even if the filter includes protocol-related fields,
// this is because we dynamically filter out records that the caller is not authorized to see.
// Currently only run protocol authorization if message deliberately invokes a protocol role.
if (Records.shouldProtocolAuthorize(recordsQuery.signaturePayload!)) {
await ProtocolAuthorization.authorizeQueryOrSubscribe(tenant, recordsQuery, messageStore);
}
}
}