-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathorganization.py
More file actions
434 lines (359 loc) · 14.7 KB
/
Copy pathorganization.py
File metadata and controls
434 lines (359 loc) · 14.7 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# Parsec Cloud (https://parsec.cloud) Copyright (c) BUSL-1.1 2016-present Scille SAS
from __future__ import annotations
from dataclasses import dataclass
from enum import auto
from parsec._parsec import (
AccessToken,
ActiveUsersLimit,
DateTime,
DeviceCertificate,
DeviceID,
OrganizationID,
SequesterAuthorityCertificate,
SequesterVerifyKeyDer,
UserCertificate,
UserProfile,
VerifyKey,
VlobID,
anonymous_cmds,
authenticated_cmds,
tos_cmds,
)
from parsec.api import api
from parsec.ballpark import TimestampOutOfBallpark, timestamps_in_the_ballpark
from parsec.client_context import AnonymousClientContext, AuthenticatedClientContext
from parsec.config import BackendConfig
from parsec.types import BadOutcomeEnum, Unset, UnsetType
from parsec.webhooks import WebhooksComponent
@dataclass(slots=True)
class OrganizationStatsProfileDetailItem:
profile: UserProfile
active: int
revoked: int
@dataclass(slots=True)
class OrganizationStats:
data_size: int
metadata_size: int
realms: int
users: int
active_users: int
users_per_profile_detail: tuple[OrganizationStatsProfileDetailItem, ...]
type TosLocale = str
type TosUrl = str
@dataclass(slots=True, frozen=True)
class TermsOfService:
updated_on: DateTime
# e.g. {"en_US": "https://example.com/tos_en.html", "fr_FR": "https://example.com/tos_fr.html"}
per_locale_urls: dict[TosLocale, TosUrl]
@dataclass(slots=True)
class OrganizationDump:
organization_id: OrganizationID
created_on: DateTime
bootstrap_token: AccessToken | None
bootstrapped_on: DateTime | None
is_bootstrapped: bool
expired_on: DateTime | None
is_expired: bool
active_users_limit: ActiveUsersLimit
user_profile_outsider_allowed: bool
realm_minimum_archiving_period_before_deletion: int
tos: TermsOfService | None
class OrganizationBootstrapValidateBadOutcome(BadOutcomeEnum):
INVALID_CERTIFICATE = auto()
TIMESTAMP_MISMATCH = auto()
INVALID_USER_PROFILE = auto()
USER_ID_MISMATCH = auto()
INVALID_REDACTED = auto()
REDACTED_MISMATCH = auto()
def organization_bootstrap_validate(
now: DateTime,
root_verify_key: VerifyKey,
user_certificate: bytes,
device_certificate: bytes,
redacted_user_certificate: bytes,
redacted_device_certificate: bytes,
sequester_authority_certificate: bytes | None,
) -> (
tuple[UserCertificate, DeviceCertificate, SequesterAuthorityCertificate | None]
| TimestampOutOfBallpark
| OrganizationBootstrapValidateBadOutcome
):
try:
u_data = UserCertificate.verify_and_load(
user_certificate,
author_verify_key=root_verify_key,
expected_author=None,
)
d_data = DeviceCertificate.verify_and_load(
device_certificate,
author_verify_key=root_verify_key,
expected_author=None,
)
ru_data = UserCertificate.verify_and_load(
redacted_user_certificate,
author_verify_key=root_verify_key,
expected_author=None,
)
rd_data = DeviceCertificate.verify_and_load(
redacted_device_certificate,
author_verify_key=root_verify_key,
expected_author=None,
)
except ValueError:
return OrganizationBootstrapValidateBadOutcome.INVALID_CERTIFICATE
if u_data.profile != UserProfile.ADMIN:
return OrganizationBootstrapValidateBadOutcome.INVALID_USER_PROFILE
if u_data.timestamp != d_data.timestamp:
return OrganizationBootstrapValidateBadOutcome.TIMESTAMP_MISMATCH
if u_data.user_id != d_data.user_id:
return OrganizationBootstrapValidateBadOutcome.USER_ID_MISMATCH
match timestamps_in_the_ballpark(u_data.timestamp, now):
case TimestampOutOfBallpark() as error:
return error
case _:
pass
if not ru_data.is_redacted:
return OrganizationBootstrapValidateBadOutcome.INVALID_REDACTED
if not u_data.redacted_compare(ru_data):
return OrganizationBootstrapValidateBadOutcome.REDACTED_MISMATCH
if not rd_data.is_redacted:
return OrganizationBootstrapValidateBadOutcome.INVALID_REDACTED
if not d_data.redacted_compare(rd_data):
return OrganizationBootstrapValidateBadOutcome.REDACTED_MISMATCH
if sequester_authority_certificate is None:
s_data = None
else:
try:
s_data = SequesterAuthorityCertificate.verify_and_load(
sequester_authority_certificate,
author_verify_key=root_verify_key,
)
except ValueError:
return OrganizationBootstrapValidateBadOutcome.INVALID_CERTIFICATE
match timestamps_in_the_ballpark(s_data.timestamp, now):
case TimestampOutOfBallpark() as error:
return error
case _:
pass
if s_data.timestamp != u_data.timestamp:
return OrganizationBootstrapValidateBadOutcome.TIMESTAMP_MISMATCH
return u_data, d_data, s_data
@dataclass(slots=True)
class Organization:
organization_id: OrganizationID
bootstrap_token: AccessToken | None
is_expired: bool
expired_on: DateTime | None
created_on: DateTime
realm_minimum_archiving_period_before_deletion: int
bootstrapped_on: DateTime | None
root_verify_key: VerifyKey | None
user_profile_outsider_allowed: bool
active_users_limit: ActiveUsersLimit
sequester_authority_certificate: bytes | None
sequester_authority_verify_key_der: SequesterVerifyKeyDer | None
sequester_services_certificates: tuple[bytes, ...] | None
tos: TermsOfService | None
@property
def is_bootstrapped(self) -> bool:
return self.root_verify_key is not None
@property
def is_sequestered(self) -> bool:
return self.sequester_authority_certificate is not None
class OrganizationCreateBadOutcome(BadOutcomeEnum):
ORGANIZATION_ALREADY_EXISTS = auto()
class OrganizationGetBadOutcome(BadOutcomeEnum):
ORGANIZATION_NOT_FOUND = auto()
class OrganizationBootstrapStoreBadOutcome(BadOutcomeEnum):
ORGANIZATION_NOT_FOUND = auto()
ORGANIZATION_EXPIRED = auto()
ORGANIZATION_ALREADY_BOOTSTRAPPED = auto()
INVALID_BOOTSTRAP_TOKEN = auto()
class OrganizationGetTosBadOutcome(BadOutcomeEnum):
ORGANIZATION_NOT_FOUND = auto()
ORGANIZATION_EXPIRED = auto()
class OrganizationStatsAsUserBadOutcome(BadOutcomeEnum):
ORGANIZATION_NOT_FOUND = auto()
ORGANIZATION_EXPIRED = auto()
AUTHOR_NOT_FOUND = auto()
AUTHOR_REVOKED = auto()
AUTHOR_NOT_ALLOWED = auto()
class OrganizationStatsBadOutcome(BadOutcomeEnum):
ORGANIZATION_NOT_FOUND = auto()
class OrganizationUpdateBadOutcome(BadOutcomeEnum):
ORGANIZATION_NOT_FOUND = auto()
@dataclass(slots=True)
class OrganizationDumpTopics:
common: DateTime
realms: dict[VlobID, DateTime]
sequester: DateTime | None
shamir_recovery: DateTime | None
class BaseOrganizationComponent:
def __init__(self, webhooks: WebhooksComponent, config: BackendConfig):
self.webhooks = webhooks
self._config = config
#
# Public methods
#
async def create(
self,
now: DateTime,
id: OrganizationID,
# `None` is a valid value for some of those params, hence it cannot be used
# as "param not set" marker and we use a custom `Unset` singleton instead.
# `None` stands for "no limit"
active_users_limit: UnsetType | ActiveUsersLimit = Unset,
user_profile_outsider_allowed: UnsetType | bool = Unset,
realm_minimum_archiving_period_before_deletion: UnsetType | int = Unset,
tos: UnsetType | dict[TosLocale, TosUrl] = Unset,
force_bootstrap_token: AccessToken | None = None,
) -> AccessToken | OrganizationCreateBadOutcome:
raise NotImplementedError
async def get(self, id: OrganizationID) -> Organization | OrganizationGetBadOutcome:
raise NotImplementedError
async def bootstrap(
self,
id: OrganizationID,
now: DateTime,
bootstrap_token: AccessToken | None,
root_verify_key: VerifyKey,
user_certificate: bytes,
device_certificate: bytes,
redacted_user_certificate: bytes,
redacted_device_certificate: bytes,
sequester_authority_certificate: bytes | None,
) -> (
tuple[UserCertificate, DeviceCertificate, SequesterAuthorityCertificate | None]
| OrganizationBootstrapValidateBadOutcome
| OrganizationBootstrapStoreBadOutcome
| TimestampOutOfBallpark
):
raise NotImplementedError
# TODO: This is intended for organization admins but is not currently exposed/used
async def stats(
self,
organization_id: OrganizationID,
author: DeviceID,
at: DateTime | None = None,
) -> OrganizationStats | OrganizationStatsAsUserBadOutcome:
raise NotImplementedError
async def organization_stats(
self,
organization_id: OrganizationID,
) -> OrganizationStats | OrganizationStatsBadOutcome:
raise NotImplementedError
async def server_stats(
self, at: DateTime | None = None
) -> dict[OrganizationID, OrganizationStats]:
raise NotImplementedError
async def update(
self,
now: DateTime,
id: OrganizationID,
# `None` is a valid value for some of those params, hence it cannot be used
# as "param not set" marker and we use a custom `Unset` singleton instead.
is_expired: UnsetType | bool = Unset,
# `None` stands for "no limit"
active_users_limit: UnsetType | ActiveUsersLimit = Unset,
user_profile_outsider_allowed: UnsetType | bool = Unset,
realm_minimum_archiving_period_before_deletion: UnsetType | int = Unset,
tos: UnsetType | dict[TosLocale, TosUrl] | None = Unset,
) -> OrganizationUpdateBadOutcome | None:
raise NotImplementedError
async def get_tos(
self, id: OrganizationID
) -> TermsOfService | OrganizationGetTosBadOutcome | None:
raise NotImplementedError
async def list_organizations(
self, skip_templates: bool = True
) -> dict[OrganizationID, OrganizationDump]:
raise NotImplementedError
async def test_dump_topics(self, id: OrganizationID) -> OrganizationDumpTopics:
raise NotImplementedError
async def test_drop_organization(self, id: OrganizationID) -> None:
raise NotImplementedError
async def test_duplicate_organization(
self, source_id: OrganizationID, target_id: OrganizationID
) -> None:
raise NotImplementedError
#
# API commands
#
@api
async def api_organization_bootstrap(
self,
client_ctx: AnonymousClientContext,
req: anonymous_cmds.latest.organization_bootstrap.Req,
) -> anonymous_cmds.latest.organization_bootstrap.Rep:
outcome = await self.bootstrap(
id=client_ctx.organization_id,
now=DateTime.now(),
bootstrap_token=req.bootstrap_token,
root_verify_key=req.root_verify_key,
user_certificate=req.user_certificate,
device_certificate=req.device_certificate,
redacted_user_certificate=req.redacted_user_certificate,
redacted_device_certificate=req.redacted_device_certificate,
sequester_authority_certificate=req.sequester_authority_certificate,
)
match outcome:
case (UserCertificate() as user, DeviceCertificate() as first_device, _):
# TODO: replace this by a background task listening for event
# Finally notify webhook
await self.webhooks.on_organization_bootstrap(
organization_id=client_ctx.organization_id,
device_id=first_device.device_id,
device_label=first_device.device_label,
human_email=user.human_handle.email,
human_label=user.human_handle.label,
)
return anonymous_cmds.latest.organization_bootstrap.RepOk()
case OrganizationBootstrapStoreBadOutcome.ORGANIZATION_ALREADY_BOOTSTRAPPED:
return anonymous_cmds.latest.organization_bootstrap.RepOrganizationAlreadyBootstrapped()
case OrganizationBootstrapStoreBadOutcome.INVALID_BOOTSTRAP_TOKEN:
return anonymous_cmds.latest.organization_bootstrap.RepInvalidBootstrapToken()
case TimestampOutOfBallpark() as error:
return anonymous_cmds.latest.organization_bootstrap.RepTimestampOutOfBallpark(
ballpark_client_early_offset=error.ballpark_client_early_offset,
ballpark_client_late_offset=error.ballpark_client_late_offset,
server_timestamp=error.server_timestamp,
client_timestamp=error.client_timestamp,
)
case OrganizationBootstrapValidateBadOutcome():
return anonymous_cmds.latest.organization_bootstrap.RepInvalidCertificate()
case OrganizationBootstrapStoreBadOutcome.ORGANIZATION_NOT_FOUND:
client_ctx.organization_not_found_abort()
case OrganizationBootstrapStoreBadOutcome.ORGANIZATION_EXPIRED:
client_ctx.organization_expired_abort()
@api
async def api_tos_get(
self, client_ctx: AuthenticatedClientContext, req: tos_cmds.latest.tos_get.Req
) -> tos_cmds.latest.tos_get.Rep:
outcome = await self.get_tos(
id=client_ctx.organization_id,
)
match outcome:
case None:
return tos_cmds.latest.tos_get.RepNoTos()
case TermsOfService() as tos:
return tos_cmds.latest.tos_get.RepOk(
per_locale_urls=tos.per_locale_urls, updated_on=tos.updated_on
)
case OrganizationGetTosBadOutcome.ORGANIZATION_NOT_FOUND:
client_ctx.organization_not_found_abort()
case OrganizationGetTosBadOutcome.ORGANIZATION_EXPIRED:
client_ctx.organization_expired_abort()
@api
async def api_organization_info(
self,
client_ctx: AuthenticatedClientContext,
req: authenticated_cmds.latest.organization_info.Req,
) -> authenticated_cmds.latest.organization_info.Rep:
outcome = await self.organization_stats(client_ctx.organization_id)
match outcome:
case OrganizationStats() as stats:
return authenticated_cmds.latest.organization_info.RepOk(
total_block_bytes=stats.data_size, total_metadata_bytes=stats.metadata_size
)
case OrganizationStatsBadOutcome.ORGANIZATION_NOT_FOUND:
client_ctx.organization_not_found_abort()