-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservices.py
More file actions
593 lines (514 loc) · 21.1 KB
/
services.py
File metadata and controls
593 lines (514 loc) · 21.1 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# api/features/vault/services.py
"""
Vault Service Layer
Business logic for vault operations (categories, organizations, profiles).
Views handle HTTP only; Services handle business logic.
"""
from django.utils import timezone
from api.models import UserProfile, Category, Organization, Profile, DuressSession, CuratedOrganization
import secrets
class VaultService:
"""Service layer for vault operations."""
@staticmethod
def is_duress_session(request) -> bool:
"""Check if the current request is from a duress token."""
if hasattr(request, "auth") and hasattr(request.auth, "key"):
return DuressSession.is_duress_token(request.auth.key)
return False
@staticmethod
def get_fake_vault_data():
"""
Generate fake vault data for duress mode.
Returns hardcoded low-value credentials to maintain the illusion.
"""
return [
{
"id": 99901,
"name": "Entertainment",
"description": "Streaming and entertainment services",
"organizations": [
{
"id": 99901,
"name": "Netflix",
"logo_url": "https://cdn.iconscout.com/icon/free/png-256/netflix-2296042-1912001.png",
"profile_count": 1,
"profiles": [
{
"id": 99901,
"title": "Personal Account",
"username_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"username_iv": "duress_fake_iv_1",
"password_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"password_iv": "duress_fake_iv_2",
"email_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"email_iv": "duress_fake_iv_3",
"password_strength": 2,
"is_breached": False,
}
],
},
{
"id": 99902,
"name": "Spotify",
"logo_url": "https://cdn.iconscout.com/icon/free/png-256/spotify-11-432546.png",
"profile_count": 1,
"profiles": [
{
"id": 99902,
"title": "Music Account",
"username_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"username_iv": "duress_fake_iv_4",
"password_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"password_iv": "duress_fake_iv_5",
"email_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"email_iv": "duress_fake_iv_6",
"password_strength": 2,
"is_breached": False,
}
],
},
],
},
{
"id": 99902,
"name": "Social Media",
"description": "Social networking accounts",
"organizations": [
{
"id": 99903,
"name": "Twitter/X",
"logo_url": "https://cdn.iconscout.com/icon/free/png-256/twitter-241-721979.png",
"profile_count": 1,
"profiles": [
{
"id": 99903,
"title": "Personal Twitter",
"username_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"username_iv": "duress_fake_iv_7",
"password_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"password_iv": "duress_fake_iv_8",
"email_encrypted": "ZHVyZXNzX2Zha2VfZGF0YQ==",
"email_iv": "duress_fake_iv_9",
"password_strength": 2,
"is_breached": False,
}
],
}
],
},
]
# ===========================
# CATEGORY OPERATIONS
# ===========================
@staticmethod
def list_categories(user, is_duress: bool = False):
"""List all categories for a user."""
if is_duress:
return VaultService.get_fake_vault_data()
return Category.objects.filter(user=user)
@staticmethod
def create_category(user, name: str, description: str = None, is_duress: bool = False):
"""Create a new category."""
if is_duress:
return {"id": 99999, "name": name, "description": description or "", "organizations": []}
return Category.objects.create(user=user, name=name, description=description)
@staticmethod
def get_category(pk: int, user, is_duress: bool = False):
"""Get a specific category."""
if is_duress:
fake_data = VaultService.get_fake_vault_data()
for cat in fake_data:
if cat["id"] == pk:
return cat
return None
try:
return Category.objects.get(pk=pk, user=user)
except Category.DoesNotExist:
return None
@staticmethod
def update_category(pk: int, user, data: dict, is_duress: bool = False):
"""Update a category."""
if is_duress:
return {
"id": pk,
"name": data.get("name", "Updated Category"),
"description": data.get("description", ""),
"organizations": [],
}
try:
category = Category.objects.get(pk=pk, user=user)
for key, value in data.items():
if hasattr(category, key):
setattr(category, key, value)
category.save()
return category
except Category.DoesNotExist:
return None
@staticmethod
def delete_category(pk: int, user, is_duress: bool = False) -> bool:
"""Delete a category."""
if is_duress:
return True
try:
category = Category.objects.get(pk=pk, user=user)
category.delete()
return True
except Category.DoesNotExist:
return False
# ===========================
# ORGANIZATION OPERATIONS
# ===========================
@staticmethod
def list_organizations(category_id: int, user, is_duress: bool = False):
"""List all organizations for a category."""
if is_duress:
fake_data = VaultService.get_fake_vault_data()
for cat in fake_data:
if cat["id"] == category_id:
return cat.get("organizations", [])
return []
try:
category = Category.objects.get(pk=category_id, user=user)
return category.organizations.all()
except Category.DoesNotExist:
return None
@staticmethod
def create_organization(category_id: int, user, data: dict, is_duress: bool = False):
"""Create a new organization."""
if is_duress:
return {
"id": secrets.randbelow(900000) + 100000,
"name": data.get("name", "New Organization"),
"logo_url": data.get("logo_url"),
"logo_image": None,
"profile_count": 0,
"profiles": [],
}
try:
category = Category.objects.get(pk=category_id, user=user)
return Organization.objects.create(
category=category,
name=data.get("name", ""),
logo_url=data.get("logo_url"),
website_link=data.get("website_link"),
logo_image=data.get("logo_image"),
)
except Category.DoesNotExist:
return None
@staticmethod
def get_organization(pk: int, user, is_duress: bool = False):
"""Get a specific organization."""
if is_duress:
fake_data = VaultService.get_fake_vault_data()
for cat in fake_data:
for org in cat.get("organizations", []):
if org["id"] == pk:
return org
return None
try:
return Organization.objects.get(pk=pk, category__user=user)
except Organization.DoesNotExist:
return None
@staticmethod
def update_organization(pk: int, user, data: dict, is_duress: bool = False):
"""Update an organization."""
if is_duress:
return {
"id": pk,
"name": data.get("name", "Updated Organization"),
"logo_url": data.get("logo_url"),
"logo_image": None,
"profile_count": 1,
"profiles": [],
}
try:
organization = Organization.objects.get(pk=pk, category__user=user)
for key, value in data.items():
if hasattr(organization, key):
setattr(organization, key, value)
organization.save()
return organization
except Organization.DoesNotExist:
return None
@staticmethod
def delete_organization(pk: int, user, is_duress: bool = False) -> bool:
"""Delete an organization."""
if is_duress:
return True
try:
organization = Organization.objects.get(pk=pk, category__user=user)
organization.delete()
return True
except Organization.DoesNotExist:
return False
# ===========================
# PROFILE OPERATIONS
# ===========================
@staticmethod
def list_profiles(organization_id: int, user, is_duress: bool = False):
"""
List all active profiles for an organization.
Excludes profiles in trash (where deleted_at is set).
"""
if is_duress:
fake_data = VaultService.get_fake_vault_data()
for cat in fake_data:
for org in cat.get("organizations", []):
if org["id"] == organization_id:
return org.get("profiles", [])
return []
try:
organization = Organization.objects.get(pk=organization_id, category__user=user)
# Filter out trashed profiles
return Profile.objects.filter(organization=organization, deleted_at__isnull=True)
except Organization.DoesNotExist:
return None
@staticmethod
def create_profile(organization_id: int, user, data: dict, is_duress: bool = False):
"""Create a new profile."""
if is_duress:
return {
"id": secrets.randbelow(900000) + 100000,
"title": data.get("title", "New Profile"),
"username_encrypted": data.get("username_encrypted"),
"username_iv": data.get("username_iv"),
"password_encrypted": data.get("password_encrypted"),
"password_iv": data.get("password_iv"),
"email_encrypted": data.get("email_encrypted"),
"email_iv": data.get("email_iv"),
"notes_encrypted": data.get("notes_encrypted"),
"notes_iv": data.get("notes_iv"),
"password_strength": data.get("password_strength", 0),
"is_breached": False,
}
try:
organization = Organization.objects.get(pk=organization_id, category__user=user)
return Profile.objects.create(organization=organization, **data)
except Organization.DoesNotExist:
return None
@staticmethod
def get_profile(pk: int, user, is_duress: bool = False):
"""
Get a specific active profile.
Excludes profiles in trash.
"""
if is_duress:
fake_data = VaultService.get_fake_vault_data()
for cat in fake_data:
for org in cat.get("organizations", []):
for profile in org.get("profiles", []):
if profile["id"] == pk:
return profile
return None
try:
return Profile.objects.get(
pk=pk, organization__category__user=user, deleted_at__isnull=True # Exclude trashed profiles
)
except Profile.DoesNotExist:
return None
@staticmethod
def update_profile(pk: int, user, data: dict, is_duress: bool = False):
"""Update a profile."""
if is_duress:
return {"id": pk, "title": data.get("title", "Updated Profile"), **data}
try:
profile = Profile.objects.get(pk=pk, organization__category__user=user)
for key, value in data.items():
if hasattr(profile, key):
setattr(profile, key, value)
profile.save()
return profile
except Profile.DoesNotExist:
return None
@staticmethod
def delete_profile(pk: int, user, is_duress: bool = False) -> bool:
"""Hard delete a profile (used internally)."""
if is_duress:
return True
try:
profile = Profile.objects.get(pk=pk, organization__category__user=user)
profile.delete()
return True
except Profile.DoesNotExist:
return False
@staticmethod
def soft_delete_profile(pk: int, user, is_duress: bool = False) -> bool:
"""
Soft delete a profile - moves it to trash.
Profile will be permanently deleted after 30 days.
"""
if is_duress:
return True
try:
# Only soft-delete profiles that are NOT already in trash
profile = Profile.objects.get(pk=pk, organization__category__user=user, deleted_at__isnull=True)
profile.deleted_at = timezone.now()
profile.save()
return True
except Profile.DoesNotExist:
return False
@staticmethod
def list_trash_profiles(user):
"""
List all profiles in trash (soft-deleted) for a user.
Returns only profiles where deleted_at is NOT null.
"""
return (
Profile.objects.filter(organization__category__user=user, deleted_at__isnull=False)
.select_related("organization", "organization__category")
.order_by("-deleted_at")
)
@staticmethod
def restore_profile(pk: int, user) -> bool:
"""
Restore a profile from trash.
Sets deleted_at back to None.
"""
try:
profile = Profile.objects.get(
pk=pk, organization__category__user=user, deleted_at__isnull=False # Must be in trash
)
profile.deleted_at = None
profile.save()
return True
except Profile.DoesNotExist:
return False
@staticmethod
def shred_profile(pk: int, user) -> bool:
"""
Permanently delete a profile with crypto-shredding.
SECURITY: Before deletion, all encrypted fields are overwritten
with random data to prevent disk recovery attacks.
"""
import os
try:
# Can shred both active and trashed profiles
profile = Profile.objects.get(pk=pk, organization__category__user=user)
# Crypto-shred: Overwrite all encrypted fields with random bytes
# This prevents recovery of deleted data from disk sectors
random_data = os.urandom(32).hex()
profile.username_encrypted = random_data
profile.username_iv = random_data[:24]
profile.password_encrypted = random_data
profile.password_iv = random_data[:24]
profile.email_encrypted = random_data
profile.email_iv = random_data[:24]
profile.notes_encrypted = random_data
profile.notes_iv = random_data[:24]
profile.recovery_codes_encrypted = random_data
profile.recovery_codes_iv = random_data[:24]
profile.password_hash = random_data[:64]
# Save the shredded data first (overwrites disk sectors)
profile.save()
# Delete any associated documents
if profile.document:
profile.document.delete(save=False)
# Now delete the record
profile.delete()
return True
except Profile.DoesNotExist:
return False
class ZeroKnowledgeVaultService:
"""Service layer for zero-knowledge vault blob operations."""
@staticmethod
def get_vault(user, is_duress: bool = False) -> dict:
"""Get user's encrypted vault blob."""
try:
profile = user.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile.objects.create(user=user)
response = {
"encryption_salt": profile.encryption_salt,
"vault_version": profile.vault_version,
"last_sync": profile.last_vault_sync,
}
if is_duress:
response["vault_blob"] = profile.decoy_vault_blob
response["encryption_salt"] = profile.duress_salt
else:
response["vault_blob"] = profile.vault_blob
if profile.decoy_vault_blob:
response["has_duress_vault"] = True
response["duress_salt"] = profile.duress_salt
return response
@staticmethod
def update_vault(
user, vault_blob: str = None, decoy_vault_blob: str = None, duress_salt: str = None, is_duress: bool = False
) -> dict:
"""Update user's encrypted vault blob."""
try:
profile = user.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile.objects.create(user=user)
if not vault_blob and not decoy_vault_blob:
return {"error": "Either vault_blob or decoy_vault_blob is required", "status": 400}
if is_duress:
# Pretend to save but don't modify real vault
return {
"message": "Vault updated successfully",
"last_sync": timezone.now().isoformat(),
}
if vault_blob:
profile.vault_blob = vault_blob
profile.last_vault_sync = timezone.now()
if decoy_vault_blob:
profile.decoy_vault_blob = decoy_vault_blob
if duress_salt:
profile.duress_salt = duress_salt
profile.save()
return {
"message": "Vault updated successfully",
"last_sync": profile.last_vault_sync.isoformat() if profile.last_vault_sync else None,
}
@staticmethod
def delete_vault(user, is_duress: bool = False) -> dict:
"""Delete user's vault."""
try:
profile = user.userprofile
except UserProfile.DoesNotExist:
return {"error": "No vault found", "status": 404}
if is_duress:
return {"message": "Vault deleted successfully"}
profile.vault_blob = None
profile.decoy_vault_blob = None
profile.duress_salt = None
profile.last_vault_sync = None
profile.save()
return {"message": "Vault deleted successfully"}
@staticmethod
def export_vault(user, is_duress: bool = False) -> dict:
"""Export vault for backup."""
try:
profile = user.userprofile
except UserProfile.DoesNotExist:
return {"error": "No vault found", "status": 404}
vault_blob = profile.decoy_vault_blob if is_duress else profile.vault_blob
if not vault_blob:
return {"error": "No vault to export", "status": 404}
return {
"vault_blob": vault_blob,
"encryption_salt": profile.encryption_salt,
"vault_version": profile.vault_version,
"exported_at": timezone.now().isoformat(),
"username": user.username,
}
@staticmethod
def import_vault(user, vault_blob: str, encryption_salt: str = None, is_duress: bool = False) -> dict:
"""Import vault from backup."""
try:
profile = user.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile.objects.create(user=user)
if not vault_blob:
return {"error": "vault_blob is required", "status": 400}
if is_duress:
return {"message": "Vault imported successfully"}
if encryption_salt and encryption_salt != profile.encryption_salt:
profile.encryption_salt = encryption_salt
profile.vault_blob = vault_blob
profile.last_vault_sync = timezone.now()
profile.save()
return {
"message": "Vault imported successfully",
"last_sync": profile.last_vault_sync.isoformat() if profile.last_vault_sync else None,
}