-
Notifications
You must be signed in to change notification settings - Fork 516
/
Copy pathroutes.py
1731 lines (1450 loc) · 54.4 KB
/
routes.py
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Credential exchange admin routes."""
import logging
from json.decoder import JSONDecodeError
from typing import Mapping
from aiohttp import web
from aiohttp_apispec import (
docs,
match_info_schema,
querystring_schema,
request_schema,
response_schema,
)
from marshmallow import ValidationError, fields, validate, validates_schema
from ....admin.request_context import AdminRequestContext
from ....anoncreds.holder import AnonCredsHolderError
from ....anoncreds.issuer import AnonCredsIssuerError
from ....connections.models.conn_record import ConnRecord
from ....core.profile import Profile
from ....indy.holder import IndyHolderError
from ....indy.issuer import IndyIssuerError
from ....ledger.error import LedgerError
from ....messaging.decorators.attach_decorator import AttachDecorator
from ....messaging.models.base import BaseModelError
from ....messaging.models.openapi import OpenAPISchema
from ....messaging.valid import (
INDY_CRED_DEF_ID_EXAMPLE,
INDY_CRED_DEF_ID_VALIDATE,
INDY_DID_EXAMPLE,
INDY_DID_VALIDATE,
INDY_SCHEMA_ID_EXAMPLE,
INDY_SCHEMA_ID_VALIDATE,
INDY_VERSION_EXAMPLE,
INDY_VERSION_VALIDATE,
UUID4_EXAMPLE,
UUID4_VALIDATE,
)
from ....storage.error import StorageError, StorageNotFoundError
from ....utils.tracing import AdminAPIMessageTracingSchema, get_timer, trace_event
from ....vc.ld_proofs.error import LinkedDataProofException
from ....wallet.util import default_did_from_verkey
from ...out_of_band.v1_0.models.oob_record import OobRecord
from . import problem_report_for_record, report_problem
from .formats.handler import V20CredFormatError
from .formats.ld_proof.models.cred_detail import LDProofVCDetailSchema
from .manager import V20CredManager, V20CredManagerError
from .message_types import ATTACHMENT_FORMAT, CRED_20_PROPOSAL, SPEC_URI
from .messages.cred_format import V20CredFormat
from .messages.cred_problem_report import ProblemReportReason
from .messages.cred_proposal import V20CredProposal
from .messages.inner.cred_preview import V20CredPreview, V20CredPreviewSchema
from .models.cred_ex_record import V20CredExRecord, V20CredExRecordSchema
from .models.detail.indy import V20CredExRecordIndySchema
from .models.detail.ld_proof import V20CredExRecordLDProofSchema
LOGGER = logging.getLogger(__name__)
class V20IssueCredentialModuleResponseSchema(OpenAPISchema):
"""Response schema for v2.0 Issue Credential Module."""
class V20CredExRecordListQueryStringSchema(OpenAPISchema):
"""Parameters and validators for credential exchange record list query."""
connection_id = fields.Str(
required=False,
metadata={"description": "Connection identifier", "example": UUID4_EXAMPLE},
)
thread_id = fields.Str(
required=False,
metadata={"description": "Thread identifier", "example": UUID4_EXAMPLE},
)
role = fields.Str(
required=False,
validate=validate.OneOf(
[
getattr(V20CredExRecord, m)
for m in vars(V20CredExRecord)
if m.startswith("ROLE_")
]
),
metadata={"description": "Role assigned in credential exchange"},
)
state = fields.Str(
required=False,
validate=validate.OneOf(
[
getattr(V20CredExRecord, m)
for m in vars(V20CredExRecord)
if m.startswith("STATE_")
]
),
metadata={"description": "Credential exchange state"},
)
class V20CredExRecordDetailSchema(OpenAPISchema):
"""Credential exchange record and any per-format details."""
cred_ex_record = fields.Nested(
V20CredExRecordSchema,
required=False,
metadata={"description": "Credential exchange record"},
)
indy = fields.Nested(V20CredExRecordIndySchema, required=False)
ld_proof = fields.Nested(V20CredExRecordLDProofSchema, required=False)
class V20CredExRecordListResultSchema(OpenAPISchema):
"""Result schema for credential exchange record list query."""
results = fields.List(
fields.Nested(V20CredExRecordDetailSchema),
metadata={
"description": (
"Credential exchange records and corresponding detail records"
)
},
)
class V20CredStoreRequestSchema(OpenAPISchema):
"""Request schema for sending a credential store admin message."""
credential_id = fields.Str(required=False)
class V20CredFilterIndySchema(OpenAPISchema):
"""Indy credential filtration criteria."""
cred_def_id = fields.Str(
required=False,
validate=INDY_CRED_DEF_ID_VALIDATE,
metadata={
"description": "Credential definition identifier",
"example": INDY_CRED_DEF_ID_EXAMPLE,
},
)
schema_id = fields.Str(
required=False,
validate=INDY_SCHEMA_ID_VALIDATE,
metadata={
"description": "Schema identifier",
"example": INDY_SCHEMA_ID_EXAMPLE,
},
)
schema_issuer_did = fields.Str(
required=False,
validate=INDY_DID_VALIDATE,
metadata={"description": "Schema issuer DID", "example": INDY_DID_EXAMPLE},
)
schema_name = fields.Str(
required=False,
metadata={"description": "Schema name", "example": "preferences"},
)
schema_version = fields.Str(
required=False,
validate=INDY_VERSION_VALIDATE,
metadata={"description": "Schema version", "example": INDY_VERSION_EXAMPLE},
)
issuer_did = fields.Str(
required=False,
validate=INDY_DID_VALIDATE,
metadata={"description": "Credential issuer DID", "example": INDY_DID_EXAMPLE},
)
class V20CredFilterSchema(OpenAPISchema):
"""Credential filtration criteria."""
indy = fields.Nested(
V20CredFilterIndySchema,
required=False,
metadata={"description": "Credential filter for indy"},
)
ld_proof = fields.Nested(
LDProofVCDetailSchema,
required=False,
metadata={"description": "Credential filter for linked data proof"},
)
@validates_schema
def validate_fields(self, data, **kwargs):
"""Validate schema fields.
Data must have indy, ld_proof, or both.
Args:
data: The data to validate
Raises:
ValidationError: if data has neither indy nor ld_proof
"""
if not any(f.api in data for f in V20CredFormat.Format):
raise ValidationError(
"V20CredFilterSchema requires indy, ld_proof, or both"
)
class V20IssueCredSchemaCore(AdminAPIMessageTracingSchema):
"""Filter, auto-remove, comment, trace."""
filter_ = fields.Nested(
V20CredFilterSchema,
required=True,
data_key="filter",
metadata={"description": "Credential specification criteria by format"},
)
auto_remove = fields.Bool(
required=False,
metadata={
"description": (
"Whether to remove the credential exchange record on completion"
" (overrides --preserve-exchange-records configuration setting)"
)
},
)
comment = fields.Str(
required=False,
allow_none=True,
metadata={"description": "Human-readable comment"},
)
credential_preview = fields.Nested(V20CredPreviewSchema, required=False)
replacement_id = fields.Str(
required=False,
allow_none=True,
metadata={
"description": "Optional identifier used to manage credential replacement",
"example": UUID4_EXAMPLE,
},
)
@validates_schema
def validate(self, data, **kwargs):
"""Make sure preview is present when indy format is present."""
if data.get("filter", {}).get("indy") and not data.get("credential_preview"):
raise ValidationError(
"Credential preview is required if indy filter is present"
)
class V20CredFilterLDProofSchema(OpenAPISchema):
"""Credential filtration criteria."""
ld_proof = fields.Nested(
LDProofVCDetailSchema,
required=True,
metadata={"description": "Credential filter for linked data proof"},
)
class V20CredRequestFreeSchema(AdminAPIMessageTracingSchema):
"""Filter, auto-remove, comment, trace."""
connection_id = fields.Str(
required=True,
metadata={"description": "Connection identifier", "example": UUID4_EXAMPLE},
)
# Request can only start with LD Proof
filter_ = fields.Nested(
V20CredFilterLDProofSchema,
required=True,
data_key="filter",
metadata={"description": "Credential specification criteria by format"},
)
auto_remove = fields.Bool(
required=False,
metadata={
"description": (
"Whether to remove the credential exchange record on completion"
" (overrides --preserve-exchange-records configuration setting)"
)
},
)
comment = fields.Str(
required=False,
allow_none=True,
metadata={"description": "Human-readable comment"},
)
trace = fields.Bool(
required=False,
metadata={
"description": "Whether to trace event (default false)",
"example": False,
},
)
holder_did = fields.Str(
required=False,
allow_none=True,
metadata={
"description": "Holder DID to substitute for the credentialSubject.id",
"example": "did:key:ahsdkjahsdkjhaskjdhakjshdkajhsdkjahs",
},
)
class V20CredExFreeSchema(V20IssueCredSchemaCore):
"""Request schema for sending credential admin message."""
connection_id = fields.Str(
required=True,
metadata={"description": "Connection identifier", "example": UUID4_EXAMPLE},
)
verification_method = fields.Str(
required=False,
dump_default=None,
allow_none=True,
metadata={"description": "For ld-proofs. Verification method for signing."},
)
class V20CredBoundOfferRequestSchema(OpenAPISchema):
"""Request schema for sending bound credential offer admin message."""
filter_ = fields.Nested(
V20CredFilterSchema,
required=False,
data_key="filter",
metadata={"description": "Credential specification criteria by format"},
)
counter_preview = fields.Nested(
V20CredPreviewSchema,
required=False,
metadata={"description": "Optional content for counter-proposal"},
)
@validates_schema
def validate_fields(self, data, **kwargs):
"""Validate schema fields: need both filter and counter_preview or neither."""
if (
"filter_" in data
and ("indy" in data["filter_"] or "ld_proof" in data["filter_"])
) ^ ("counter_preview" in data):
raise ValidationError(
f"V20CredBoundOfferRequestSchema\n{data}\nrequires "
"both indy/ld_proof filter and counter_preview or neither"
)
class V20CredOfferRequestSchema(V20IssueCredSchemaCore):
"""Request schema for sending credential offer admin message."""
connection_id = fields.Str(
required=True,
metadata={"description": "Connection identifier", "example": UUID4_EXAMPLE},
)
auto_issue = fields.Bool(
required=False,
metadata={
"description": (
"Whether to respond automatically to credential requests, creating and"
" issuing requested credentials"
)
},
)
class V20CredOfferConnFreeRequestSchema(V20IssueCredSchemaCore):
"""Request schema for creating credential offer free from connection."""
auto_issue = fields.Bool(
required=False,
metadata={
"description": (
"Whether to respond automatically to credential requests, creating and"
" issuing requested credentials"
)
},
)
class V20CredRequestRequestSchema(OpenAPISchema):
"""Request schema for sending credential request message."""
holder_did = fields.Str(
required=False,
allow_none=True,
metadata={
"description": "Holder DID to substitute for the credentialSubject.id",
"example": "did:key:ahsdkjahsdkjhaskjdhakjshdkajhsdkjahs",
},
)
auto_remove = fields.Bool(
required=False,
dump_default=False,
metadata={
"description": (
"Whether to remove the credential exchange record on completion"
" (overrides --preserve-exchange-records configuration setting)"
)
},
)
class V20CredIssueRequestSchema(OpenAPISchema):
"""Request schema for sending credential issue admin message."""
comment = fields.Str(
required=False,
allow_none=True,
metadata={"description": "Human-readable comment"},
)
class V20CredIssueProblemReportRequestSchema(OpenAPISchema):
"""Request schema for sending problem report."""
description = fields.Str(required=True)
class V20CredIdMatchInfoSchema(OpenAPISchema):
"""Path parameters and validators for request taking credential id."""
credential_id = fields.Str(
required=True,
metadata={"description": "Credential identifier", "example": UUID4_EXAMPLE},
)
class V20CredExIdMatchInfoSchema(OpenAPISchema):
"""Path parameters and validators for request taking credential exchange id."""
cred_ex_id = fields.Str(
required=True,
validate=UUID4_VALIDATE,
metadata={
"description": "Credential exchange identifier",
"example": UUID4_EXAMPLE,
},
)
def _formats_filters(filt_spec: Mapping) -> Mapping:
"""Break out formats and filters for v2.0 cred proposal messages."""
return (
{
"formats": [
V20CredFormat(
attach_id=fmt_api,
format_=ATTACHMENT_FORMAT[CRED_20_PROPOSAL][fmt_api],
)
for fmt_api in filt_spec
],
"filters_attach": [
AttachDecorator.data_base64(filt_by_fmt, ident=fmt_api)
for (fmt_api, filt_by_fmt) in filt_spec.items()
],
}
if filt_spec
else {}
)
async def _get_attached_credentials(
profile: Profile, cred_ex_record: V20CredExRecord
) -> Mapping:
"""Fetch the detail records attached to a credential exchange."""
result = {}
for fmt in V20CredFormat.Format:
detail_record = await fmt.handler(profile).get_detail_record(
cred_ex_record.cred_ex_id
)
if detail_record:
result[fmt.api] = detail_record
return result
def _format_result_with_details(
cred_ex_record: V20CredExRecord, details: Mapping
) -> Mapping:
"""Get credential exchange result with detail records."""
result = {"cred_ex_record": cred_ex_record.serialize()}
for fmt in V20CredFormat.Format:
ident = fmt.api
detail_record = details.get(ident)
result[ident] = detail_record.serialize() if detail_record else None
return result
@docs(
tags=["issue-credential v2.0"],
summary="Fetch all credential exchange records",
)
@querystring_schema(V20CredExRecordListQueryStringSchema)
@response_schema(V20CredExRecordListResultSchema(), 200, description="")
async def credential_exchange_list(request: web.BaseRequest):
"""Request handler for searching credential exchange records.
Args:
request: aiohttp request object
Returns:
The connection list response
"""
context: AdminRequestContext = request["context"]
profile = context.profile
tag_filter = {}
if "thread_id" in request.query and request.query["thread_id"] != "":
tag_filter["thread_id"] = request.query["thread_id"]
post_filter = {
k: request.query[k]
for k in ("connection_id", "role", "state")
if request.query.get(k, "") != ""
}
try:
async with profile.session() as session:
cred_ex_records = await V20CredExRecord.query(
session=session,
tag_filter=tag_filter,
post_filter_positive=post_filter,
)
results = []
for cxr in cred_ex_records:
details = await _get_attached_credentials(profile, cxr)
result = _format_result_with_details(cxr, details)
results.append(result)
except (StorageError, BaseModelError) as err:
raise web.HTTPBadRequest(reason=err.roll_up) from err
return web.json_response({"results": results})
@docs(
tags=["issue-credential v2.0"],
summary="Fetch a single credential exchange record",
)
@match_info_schema(V20CredExIdMatchInfoSchema())
@response_schema(V20CredExRecordDetailSchema(), 200, description="")
async def credential_exchange_retrieve(request: web.BaseRequest):
"""Request handler for fetching single credential exchange record.
Args:
request: aiohttp request object
Returns:
The credential exchange record
"""
context: AdminRequestContext = request["context"]
profile = context.profile
outbound_handler = request["outbound_message_router"]
cred_ex_id = request.match_info["cred_ex_id"]
cred_ex_record = None
try:
async with profile.session() as session:
cred_ex_record = await V20CredExRecord.retrieve_by_id(session, cred_ex_id)
details = await _get_attached_credentials(profile, cred_ex_record)
result = _format_result_with_details(cred_ex_record, details)
except StorageNotFoundError as err:
# no such cred ex record: not protocol error, user fat-fingered id
raise web.HTTPNotFound(reason=err.roll_up) from err
except (BaseModelError, StorageError) as err:
# present but broken or hopeless: protocol error
await report_problem(
err,
ProblemReportReason.ISSUANCE_ABANDONED.value,
web.HTTPBadRequest,
cred_ex_record,
outbound_handler,
)
return web.json_response(result)
@docs(
tags=["issue-credential v2.0"],
summary=(
"Create a credential record without "
"sending (generally for use with Out-Of-Band)"
),
)
@request_schema(V20IssueCredSchemaCore())
@response_schema(V20CredExRecordSchema(), 200, description="")
async def credential_exchange_create(request: web.BaseRequest):
"""Request handler for creating a credential from attr values.
The internal credential record will be created without the credential
being sent to any connection. This can be used in conjunction with
the `oob` protocols to bind messages to an out of band message.
Args:
request: aiohttp request object
Returns:
The credential exchange record
"""
r_time = get_timer()
context: AdminRequestContext = request["context"]
profile = context.profile
body = await request.json()
comment = body.get("comment")
preview_spec = body.get("credential_preview")
filt_spec = body.get("filter")
auto_remove = body.get(
"auto_remove", not profile.settings.get("preserve_exchange_records")
)
if not filt_spec:
raise web.HTTPBadRequest(reason="Missing filter")
trace_msg = body.get("trace")
try:
# Not all formats use credential preview
cred_preview = (
V20CredPreview.deserialize(preview_spec) if preview_spec else None
)
cred_proposal = V20CredProposal(
comment=comment,
credential_preview=cred_preview,
**_formats_filters(filt_spec),
)
cred_proposal.assign_trace_decorator(
context.settings,
trace_msg,
)
trace_event(
context.settings,
cred_proposal,
outcome="credential_exchange_create.START",
)
cred_manager = V20CredManager(context.profile)
(cred_ex_record, cred_offer_message) = await cred_manager.prepare_send(
connection_id=None,
cred_proposal=cred_proposal,
auto_remove=auto_remove,
)
except (StorageError, BaseModelError) as err:
raise web.HTTPBadRequest(reason=err.roll_up) from err
trace_event(
context.settings,
cred_offer_message,
outcome="credential_exchange_create.END",
perf_counter=r_time,
)
return web.json_response(cred_ex_record.serialize())
@docs(
tags=["issue-credential v2.0"],
summary="Send holder a credential, automating entire flow",
)
@request_schema(V20CredExFreeSchema())
@response_schema(V20CredExRecordSchema(), 200, description="")
async def credential_exchange_send(request: web.BaseRequest):
"""Request handler for sending credential from issuer to holder from attr values.
If both issuer and holder are configured for automatic responses, the operation
ultimately results in credential issue; otherwise, the result waits on the first
response not automated; the credential exchange record retains state regardless.
Args:
request: aiohttp request object
Returns:
The credential exchange record
"""
r_time = get_timer()
context: AdminRequestContext = request["context"]
profile = context.profile
outbound_handler = request["outbound_message_router"]
body = await request.json()
comment = body.get("comment")
connection_id = body.get("connection_id")
verification_method = body.get("verification_method")
filt_spec = body.get("filter")
if not filt_spec:
raise web.HTTPBadRequest(reason="Missing filter")
preview_spec = body.get("credential_preview")
auto_remove = body.get(
"auto_remove", not profile.settings.get("preserve_exchange_records")
)
replacement_id = body.get("replacement_id")
trace_msg = body.get("trace")
conn_record = None
cred_ex_record = None
try:
# Not all formats use credential preview
cred_preview = (
V20CredPreview.deserialize(preview_spec) if preview_spec else None
)
async with profile.session() as session:
conn_record = await ConnRecord.retrieve_by_id(session, connection_id)
if not conn_record.is_ready:
raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")
# TODO: why do we create a proposal and then use that to create an offer.
# Seems easier to just pass the proposal data to the format specific handler
cred_proposal = V20CredProposal(
comment=comment,
credential_preview=cred_preview,
**_formats_filters(filt_spec),
)
cred_proposal.assign_trace_decorator(
context.settings,
trace_msg,
)
trace_event(
context.settings,
cred_proposal,
outcome="credential_exchange_send.START",
)
cred_manager = V20CredManager(profile)
(cred_ex_record, cred_offer_message) = await cred_manager.prepare_send(
connection_id,
verification_method=verification_method,
cred_proposal=cred_proposal,
auto_remove=auto_remove,
replacement_id=replacement_id,
)
result = cred_ex_record.serialize()
except (
BaseModelError,
LedgerError,
StorageError,
V20CredManagerError,
V20CredFormatError,
) as err:
LOGGER.exception("Error preparing credential offer")
if cred_ex_record:
async with profile.session() as session:
await cred_ex_record.save_error_state(session, reason=err.roll_up)
await report_problem(
err,
ProblemReportReason.ISSUANCE_ABANDONED.value,
web.HTTPBadRequest,
cred_ex_record or conn_record,
outbound_handler,
)
await outbound_handler(
cred_offer_message,
connection_id=cred_ex_record.connection_id,
)
trace_event(
context.settings,
cred_offer_message,
outcome="credential_exchange_send.END",
perf_counter=r_time,
)
return web.json_response(result)
@docs(
tags=["issue-credential v2.0"],
summary="Send issuer a credential proposal",
)
@request_schema(V20CredExFreeSchema())
@response_schema(V20CredExRecordSchema(), 200, description="")
async def credential_exchange_send_proposal(request: web.BaseRequest):
"""Request handler for sending credential proposal.
Args:
request: aiohttp request object
Returns:
The credential exchange record
"""
r_time = get_timer()
context: AdminRequestContext = request["context"]
profile = context.profile
outbound_handler = request["outbound_message_router"]
body = await request.json()
connection_id = body.get("connection_id")
comment = body.get("comment")
preview_spec = body.get("credential_preview")
filt_spec = body.get("filter")
if not filt_spec:
raise web.HTTPBadRequest(reason="Missing filter")
auto_remove = body.get(
"auto_remove", not profile.settings.get("preserve_exchange_records")
)
trace_msg = body.get("trace")
conn_record = None
cred_ex_record = None
try:
cred_preview = (
V20CredPreview.deserialize(preview_spec) if preview_spec else None
)
async with profile.session() as session:
conn_record = await ConnRecord.retrieve_by_id(session, connection_id)
if not conn_record.is_ready:
raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")
cred_manager = V20CredManager(profile)
cred_ex_record = await cred_manager.create_proposal(
connection_id=connection_id,
auto_remove=auto_remove,
comment=comment,
cred_preview=cred_preview,
trace=trace_msg,
fmt2filter={
V20CredFormat.Format.get(fmt_api): filt_by_fmt
for (fmt_api, filt_by_fmt) in filt_spec.items()
},
)
cred_proposal_message = cred_ex_record.cred_proposal
result = cred_ex_record.serialize()
except (BaseModelError, StorageError) as err:
LOGGER.exception("Error preparing credential proposal")
if cred_ex_record:
async with profile.session() as session:
await cred_ex_record.save_error_state(session, reason=err.roll_up)
# other party cannot yet receive a problem report about our failed protocol start
raise web.HTTPBadRequest(reason=err.roll_up)
await outbound_handler(cred_proposal_message, connection_id=connection_id)
trace_event(
context.settings,
cred_proposal_message,
outcome="credential_exchange_send_proposal.END",
perf_counter=r_time,
)
return web.json_response(result)
async def _create_free_offer(
profile: Profile,
filt_spec: Mapping = None,
connection_id: str = None,
auto_issue: bool = False,
auto_remove: bool = False,
replacement_id: str = None,
preview_spec: dict = None,
comment: str = None,
trace_msg: bool = None,
):
"""Create a credential offer and related exchange record."""
cred_preview = V20CredPreview.deserialize(preview_spec) if preview_spec else None
cred_proposal = V20CredProposal(
comment=comment,
credential_preview=cred_preview,
**_formats_filters(filt_spec),
)
cred_proposal.assign_trace_decorator(
profile.settings,
trace_msg,
)
cred_ex_record = V20CredExRecord(
connection_id=connection_id,
initiator=V20CredExRecord.INITIATOR_SELF,
role=V20CredExRecord.ROLE_ISSUER,
cred_proposal=cred_proposal.serialize(),
auto_issue=auto_issue,
auto_remove=auto_remove,
trace=trace_msg,
)
cred_manager = V20CredManager(profile)
(cred_ex_record, cred_offer_message) = await cred_manager.create_offer(
cred_ex_record,
comment=comment,
replacement_id=replacement_id,
)
return (cred_ex_record, cred_offer_message)
@docs(
tags=["issue-credential v2.0"],
summary="Create a credential offer, independent of any proposal or connection",
)
@request_schema(V20CredOfferConnFreeRequestSchema())
@response_schema(V20CredExRecordSchema(), 200, description="")
async def credential_exchange_create_free_offer(request: web.BaseRequest):
"""Request handler for creating free credential offer.
Unlike with `send-offer`, this credential exchange is not tied to a specific
connection. It must be dispatched out-of-band by the controller.
Args:
request: aiohttp request object
Returns:
The credential exchange record
"""
r_time = get_timer()
context: AdminRequestContext = request["context"]
profile = context.profile
body = await request.json()
auto_issue = body.get(
"auto_issue", context.settings.get("debug.auto_respond_credential_request")
)
auto_remove = body.get(
"auto_remove", not profile.settings.get("preserve_exchange_records")
)
replacement_id = body.get("replacement_id")
comment = body.get("comment")
preview_spec = body.get("credential_preview")
filt_spec = body.get("filter")
if not filt_spec:
raise web.HTTPBadRequest(reason="Missing filter")
trace_msg = body.get("trace")
cred_ex_record = None
try:
(cred_ex_record, cred_offer_message) = await _create_free_offer(
profile=profile,
filt_spec=filt_spec,
auto_issue=auto_issue,
auto_remove=auto_remove,
replacement_id=replacement_id,
preview_spec=preview_spec,
comment=comment,
trace_msg=trace_msg,
)
result = cred_ex_record.serialize()
except (
BaseModelError,
LedgerError,
V20CredFormatError,
V20CredManagerError,
) as err:
LOGGER.exception("Error creating free credential offer")
if cred_ex_record:
async with profile.session() as session:
await cred_ex_record.save_error_state(session, reason=err.roll_up)
raise web.HTTPBadRequest(reason=err.roll_up)
trace_event(
context.settings,
cred_offer_message,
outcome="credential_exchange_create_free_offer.END",
perf_counter=r_time,
)
return web.json_response(result)
@docs(
tags=["issue-credential v2.0"],
summary="Send holder a credential offer, independent of any proposal",
)
@request_schema(V20CredOfferRequestSchema())
@response_schema(V20CredExRecordSchema(), 200, description="")
async def credential_exchange_send_free_offer(request: web.BaseRequest):
"""Request handler for sending free credential offer.
An issuer initiates a such a credential offer, free from any
holder-initiated corresponding credential proposal with preview.
Args:
request: aiohttp request object
Returns:
The credential exchange record
"""
r_time = get_timer()
context: AdminRequestContext = request["context"]
profile = context.profile
outbound_handler = request["outbound_message_router"]