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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
use crate::client::reqwest_generic::{get, post};
use crate::config::SmartIDConfig;
use crate::error::Result;
use crate::error::SmartIdClientError;
use crate::error::SmartIdClientError::NoSessionException;
use crate::models::api::authentication_session::{
AuthenticationDeviceLinkRequest, AuthenticationDeviceLinkResponse,
AuthenticationNotificationRequest, AuthenticationNotificationResponse,
};
use crate::models::api::certificate_choice_session::{CertificateChoiceDeviceLinkRequest, CertificateChoiceDeviceLinkResponse, CertificateChoiceNotificationRequest, CertificateChoiceNotificationResponse, SigningCertificate, SigningCertificateRequest, SigningCertificateResponse, SigningCertificateResponseState};
use crate::models::api::session_status::{
SessionCertificate, SessionResponse, SessionState, SessionStatusResponse,
};
use crate::models::api::signature_session::{
SignatureDeviceLinkRequest, SignatureDeviceLinkResponse, SignatureNotificationLinkedRequest,
SignatureNotificationLinkedResponse, SignatureNotificationRequest,
SignatureNotificationResponse,
};
use crate::models::common::{SessionConfig, VCCode};
use crate::models::device_link::DeviceLink::{CrossDeviceLink, SameDeviceLink};
use crate::models::device_link::{DeviceLinkType, SessionType};
use crate::models::signature::FlowType;
use crate::models::user_identity::UserIdentity;
use crate::utils::demo_certificates::{demo_intermediate_certificates, demo_root_certificates};
use crate::utils::production_certificates::{
production_intermediate_certificates, production_root_certificates,
};
use crate::utils::sec_x509::verify_certificate;
use std::sync::{Arc, Mutex};
use tracing::debug;
// region: Path definitions
// Copied from https://github.com/SK-EID/smart-id-java-client/blob/81e48f519bf882db8584a344b161db378b959093/src/main/java/ee/sk/smartid/v3/rest/SmartIdRestConnector.java#L79
const SESSION_STATUS_URI: &str = "/session";
const NOTIFICATION_CERTIFICATE_CHOICE_WITH_SEMANTIC_IDENTIFIER_PATH: &str = "/signature/certificate-choice/notification/etsi";
#[allow(dead_code)]
const NOTIFICATION_CERTIFICATE_CHOICE_WITH_DOCUMENT_NUMBER_PATH: &str = "/signature/certificate-choice/notification/document";
const ANONYMOUSE_DEVICE_LINK_CERTIFICATE_CHOICE_PATH: &str = "/signature/certificate-choice/device-link/anonymous";
const SIGNING_CERTIFICATE_WITH_DOCUMENT_NUMBER_PATH: &str = "/signature/certificate";
const DEVICE_LINK_SIGNATURE_WITH_SEMANTIC_IDENTIFIER_PATH: &str = "/signature/device-link/etsi";
const DEVICE_LINK_SIGNATURE_WITH_DOCUMENT_NUMBER_PATH: &str = "/signature/device-link/document";
const NOTIFICATION_SIGNATURE_WITH_SEMANTIC_IDENTIFIER_PATH: &str = "/signature/notification/etsi";
const NOTIFICATION_SIGNATURE_WITH_DOCUMENT_NUMBER_PATH: &str = "/signature/notification/document";
const NOTIFICATION_SIGNATURE_WITH_DOCUMENT_NUMBER_LINKED_PATH: &str = "/signature/notification/linked";
const ANONYMOUS_DEVICE_LINK_AUTHENTICATION_PATH: &str = "/authentication/device-link/anonymous";
const DEVICE_LINK_AUTHENTICATION_WITH_SEMANTIC_IDENTIFIER_PATH: &str =
"/authentication/device-link/etsi";
const DEVICE_LINK_AUTHENTICATION_WITH_DOCUMENT_NUMBER_PATH: &str =
"/authentication/device-link/document";
#[allow(dead_code)]
const NOTIFICATION_AUTHENTICATION_WITH_SEMANTIC_IDENTIFIER_PATH: &str =
"/authentication/notification/etsi";
#[allow(dead_code)]
const NOTIFICATION_AUTHENTICATION_WITH_DOCUMENT_NUMBER_PATH: &str =
"/authentication/notification/document";
// Currently only support for 1.0
const DEVICE_LINK_VERSION: &str = "1.0";
// endregion: Path definitions
/// Smart ID Client
///
/// This struct provides methods to interact with the Smart ID service, including starting authentication,
/// certificate choice, and signature sessions using device links. It also includes methods to generate
/// device links, retrieve session status, and validate session responses.
///
/// The client maintains session state and authenticated user identity to ensure the correct user is signing
/// and to validate session responses.
#[derive(Debug)]
pub struct SmartIdClient {
pub cfg: SmartIDConfig,
/// This tracks session state and is used to make subsequent requests
/// For example to generate QR codes or to poll for session status
pub(crate) session_config: Arc<Mutex<Option<SessionConfig>>>,
/// Is checked against returned certificates to ensure the correct user is signing
pub(crate) authenticated_identity: Arc<Mutex<Option<UserIdentity>>>,
/// List of root certificates used to validate the smart id certificates. If not provided, only the default root certificates will be used.
/// If you are using an older version of this library, you will need to provide the latest root certificates yourself.
pub(crate) root_certificates: Vec<String>,
/// List of intermediate certificates used to validate the smart id certificates. If not provided, only the default intermediate certificates will be used.
/// If you are using an older version of this library, you will need to provide the latest intermediate certificates yourself.
pub(crate) intermediate_certificates: Vec<String>,
}
impl SmartIdClient {
/// Creates a new SmartIdClient instance with the given configuration.
///
/// # Arguments
///
/// * `cfg` - A reference to the SmartIDConfig.
/// * `user_identity` - An optional UserIdentity. This will be compared with the certificate subject to ensure the correct user is signing. If not provided, the UserIdentity will be set from the certificate during the first successful authentication.
/// * `root_certificates` - A vector of base64 der encoded root certificates (not bundles), this is used to validate the smart id certificate chain. If not provided, only the default root certificates will be used. If you are using an older version of this library, you will need to provide the latest root certificates yourself.
/// * `intermediate_certificates` - A vector of base64 der encoded intermediate certificates (not bundles), this is used to validate the smart id certificate chain. If not provided, only the default intermediate certificates will be used. If you are using an older version of this library, you will need to provide the latest intermediate certificates yourself
///
/// # Returns
///
/// A new instance of SmartIdClient.
pub fn new(
cfg: &SmartIDConfig,
user_identity: Option<UserIdentity>,
root_certificates: Vec<String>,
intermediate_certificates: Vec<String>,
) -> Self {
SmartIdClient {
cfg: cfg.clone(),
session_config: Arc::new(Mutex::new(None)),
authenticated_identity: Arc::new(Mutex::new(user_identity)),
root_certificates,
intermediate_certificates,
}
}
/// Creates a new SmartIdClient instance with the given session configuration.
/// This should not be used to start a new session!
/// This should be used when you need to cache the session configuration in a serialized form between requests.
///
/// Example Use Case:
/// After starting an authentication session, you can cache the session_configuration (serialized).
/// Then, when you receive a request for session status, you rebuild the client. After you cache the session_configuration again.
/// Then, when you receive a request for a Device Link, you can rebuild the client from the session_configuration.
///
/// # Arguments
///
/// * `cfg` - A reference to the SmartIDConfig.
/// * `session_config` - The session configuration from a previous session.
/// * `user_identity` - An optional UserIdentity. This will be compared with the certificate subject to ensure the correct user is signing. If not provided, the UserIdentity will be set from the certificate during the first successful authentication.
/// * `root_certificates` - A vector of root certificates, this is used to validate the smart id certificate chain. If not provided, only the default root certificates will be used. If you are using an older version of this library, you will need to provide the latest root certificates yourself.
/// * `intermediate_certificates` - A vector of intermediate certificates, this is used to validate the smart id certificate chain. If not provided, only the default intermediate certificates will be used. If you are using an older version of this library, you will need to provide the latest intermediate certificates yourself
///
/// # Returns
///
/// A new instance of SmartIdClient.
pub fn from_session(
cfg: &SmartIDConfig,
session_config: SessionConfig,
user_identity: Option<UserIdentity>,
root_certificates: Vec<String>,
intermediate_certificates: Vec<String>,
) -> Self {
SmartIdClient {
cfg: cfg.clone(),
session_config: Arc::new(Mutex::new(Some(session_config))),
authenticated_identity: Arc::new(Mutex::new(user_identity)),
root_certificates,
intermediate_certificates,
}
}
// region: Session Status
/// Retrieves the session status with a specified timeout.
/// The session must first be started with one of the start session methods.
///
/// # Arguments
///
/// * `timeoutMs` - Timeout in milliseconds. The upper bound of timeout: 120000, minimum 1000.
///
/// # Returns
///
/// A Result containing the SessionStatus or an error.
///
/// # Errors
///
/// This function will return an error if:
/// - The session is not found or not running.
/// - The session status request fails.
/// - The session did not complete within the specified timeout.
/// - The session response endResult is not OK.
/// - The session response is missing a certificate.
/// - The session response is missing a signature.
/// - The session response certificate is invalid.
/// - The session response signature is invalid.
pub async fn get_session_status(&self) -> Result<SessionStatusResponse> {
let session_config = self.get_session()?;
let path = format!(
"{}{}/{}?timeoutMs={}",
self.cfg.api_url(),
SESSION_STATUS_URI,
session_config.session_id(),
self.cfg.long_polling_timeout,
);
let session_response =
get::<SessionResponse>(path.as_str(), Some(self.cfg.long_polling_timeout + 100))
.await?; // Add 100ms to allow SmartId to respond with a long polling timeout error instead of reqwest creating a connection error
let session_status = session_response.into_result()?;
match session_status.state {
SessionState::COMPLETE => {
self.validate_session_status(session_status.clone(), session_config)?;
Ok(session_status)
}
SessionState::RUNNING => {
Err(SmartIdClientError::StatusRequestLongPollingTimeoutException)
}
}
}
// endregion: Session Status
// region: Authentication
/// Starts an authentication session using a device link.
/// Use the create device link methods to generate the device link to send to the user to continue the authentication process.
/// Use the get_session_status method to poll for the result.
///
/// # Arguments
///
/// * `authentication_request` - The authentication request.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_authentication_device_link_anonymous_session(
&self,
authentication_request: AuthenticationDeviceLinkRequest,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}",
self.cfg.api_url(),
ANONYMOUS_DEVICE_LINK_AUTHENTICATION_PATH,
);
let authentication_response =
post::<AuthenticationDeviceLinkRequest, AuthenticationDeviceLinkResponse>(
path.as_str(),
&authentication_request,
self.cfg.client_request_timeout,
)
.await?;
let session = authentication_response.into_result()?;
self.set_session(SessionConfig::from_authentication_device_link_response(
session,
authentication_request,
&self.cfg.scheme_name,
)?)
}
/// Starts an authentication session with a document using a device link.
/// Use the create device link methods to generate the device link to send to the user to continue the authentication process.
/// Use the get_session_status method to poll for the result.
///
/// # Arguments
///
/// * `authentication_request` - The authentication request.
/// * `document_number` - The document number.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_authentication_device_link_document_session(
&self,
authentication_request: AuthenticationDeviceLinkRequest,
document_number: String,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
DEVICE_LINK_AUTHENTICATION_WITH_DOCUMENT_NUMBER_PATH,
document_number,
);
let authentication_response =
post::<AuthenticationDeviceLinkRequest, AuthenticationDeviceLinkResponse>(
path.as_str(),
&authentication_request,
self.cfg.client_request_timeout,
)
.await?;
let session = authentication_response.into_result()?;
self.set_session(SessionConfig::from_authentication_device_link_response(
session,
authentication_request,
&self.cfg.scheme_name,
)?)
}
/// Starts an authentication session with an etsi using a device link.
/// Use the create device link methods to generate the device link to send to the user to continue the authentication process.
/// Use the get_session_status method to poll for the result.
///
/// # Arguments
///
/// * `authentication_request` - The authentication request.
/// * `etsi` - The ETSI semantic identifier.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_authentication_device_link_etsi_session(
&self,
authentication_request: AuthenticationDeviceLinkRequest,
etsi: String,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
DEVICE_LINK_AUTHENTICATION_WITH_SEMANTIC_IDENTIFIER_PATH,
etsi,
);
let authentication_response =
post::<AuthenticationDeviceLinkRequest, AuthenticationDeviceLinkResponse>(
path.as_str(),
&authentication_request,
self.cfg.client_request_timeout,
)
.await?;
let session = authentication_response.into_result()?;
self.set_session(SessionConfig::from_authentication_device_link_response(
session,
authentication_request,
&self.cfg.scheme_name,
)?)
}
/// Starts an authentication session using a notification.
/// Use the `get_session_status` method to poll for the result.
///
/// # Arguments
///
/// * `authentication_request` - The authentication request.
/// * `etsi` - The ETSI identifier of the user.
///
/// # Returns
///
/// A `Result` containing the verification code the user will see on screen.
pub async fn start_authentication_notification_etsi_session(
&self,
authentication_request: AuthenticationNotificationRequest,
etsi: String,
) -> Result<VCCode> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
NOTIFICATION_AUTHENTICATION_WITH_SEMANTIC_IDENTIFIER_PATH,
etsi,
);
let authentication_response =
post::<AuthenticationNotificationRequest, AuthenticationNotificationResponse>(
path.as_str(),
&authentication_request,
self.cfg.client_request_timeout,
)
.await?;
let session = authentication_response.into_result()?;
let session_config = SessionConfig::from_authentication_notification_response(
session.clone(),
authentication_request,
&self.cfg.scheme_name,
)?;
let vc_code = session_config.calculate_vc_code();
self.set_session(session_config)?;
vc_code
}
/// Starts an authentication session using a notification.
/// Use the `get_session_status` method to poll for the result.
///
/// # Arguments
///
/// * `authentication_request` - The authentication request.
/// * `document_number` - The document number.
///
/// # Returns
///
/// A `Result` containing the verification code the user will see on screen.
pub async fn start_authentication_notification_document_session(
&self,
authentication_request: AuthenticationNotificationRequest,
document_number: String,
) -> Result<VCCode> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
NOTIFICATION_AUTHENTICATION_WITH_DOCUMENT_NUMBER_PATH,
document_number,
);
let authentication_response =
post::<AuthenticationNotificationRequest, AuthenticationNotificationResponse>(
path.as_str(),
&authentication_request,
self.cfg.client_request_timeout,
)
.await?;
let session = authentication_response.into_result()?;
let session_config = SessionConfig::from_authentication_notification_response(
session.clone(),
authentication_request,
&self.cfg.scheme_name,
)?;
let vc_code = session_config.calculate_vc_code();
self.set_session(session_config)?;
vc_code
}
// endregion: Authentication
// region: Signature
/// Starts a signature session using a device link and an ETSI identifier.
/// Use the create device link methods to generate the device link to send to the user to continue the signature process.
/// Use the get_session_status method to poll for the result.
///
/// # Arguments
///
/// * `signature_request` - The signature request.
/// * `etsi` - The ETSI identifier.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_signature_device_link_etsi_session(
&self,
signature_request: SignatureDeviceLinkRequest,
etsi: String,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
DEVICE_LINK_SIGNATURE_WITH_SEMANTIC_IDENTIFIER_PATH,
etsi,
);
let signature_response = post::<SignatureDeviceLinkRequest, SignatureDeviceLinkResponse>(
path.as_str(),
&signature_request,
self.cfg.client_request_timeout,
)
.await?;
let session = signature_response.into_result()?;
self.set_session(SessionConfig::from_signature_device_link_request_response(
session,
signature_request,
&self.cfg.scheme_name,
)?)
}
/// Starts a signature session using a device link and a document number.
/// Use the create device link methods to generate the device link to send to the user to continue the signature process.
/// Use the get_session_status method to poll for the result.
///
/// # Arguments
///
/// * `signature_request` - The signature request.
/// * `document_number` - The document number.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_signature_device_link_document_session(
&self,
signature_request: SignatureDeviceLinkRequest,
document_number: String,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
DEVICE_LINK_SIGNATURE_WITH_DOCUMENT_NUMBER_PATH,
document_number,
);
let signature_response = post::<SignatureDeviceLinkRequest, SignatureDeviceLinkResponse>(
path.as_str(),
&signature_request,
self.cfg.client_request_timeout,
)
.await?;
let session = signature_response.into_result()?;
self.set_session(SessionConfig::from_signature_device_link_request_response(
session,
signature_request,
&self.cfg.scheme_name,
)?)
}
/// Starts a signature session using a notification.
/// Use the `get_session_status` method to poll for the result.
///
/// # Arguments
///
/// * `signature_request` - The signature request.
/// * `etsi` - The ETSI identifier.
///
/// # Returns
///
/// A `Result` containing the verification code the user will see on screen.
pub async fn start_signature_notification_etsi_session(
&self,
signature_request: SignatureNotificationRequest,
etsi: String,
) -> Result<VCCode> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
NOTIFICATION_SIGNATURE_WITH_SEMANTIC_IDENTIFIER_PATH,
etsi,
);
let signature_response =
post::<SignatureNotificationRequest, SignatureNotificationResponse>(
path.as_str(),
&signature_request,
self.cfg.client_request_timeout,
)
.await?;
let session = signature_response.into_result()?;
self.set_session(SessionConfig::from_signature_notification_response(
session.clone(),
signature_request,
&self.cfg.scheme_name,
)?)?;
Ok(session.vc)
}
/// Starts a signature session using a notification.
/// Use the `get_session_status` method to poll for the result.
///
/// # Arguments
///
/// * `signature_request` - The signature request.
/// * `document_number` - The document number.
///
/// # Returns
///
/// A `Result` containing the verification code the user will see on screen.
pub async fn start_signature_notification_document_session(
&self,
signature_request: SignatureNotificationRequest,
document_number: String,
) -> Result<VCCode> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
NOTIFICATION_SIGNATURE_WITH_DOCUMENT_NUMBER_PATH,
document_number,
);
let signature_response =
post::<SignatureNotificationRequest, SignatureNotificationResponse>(
path.as_str(),
&signature_request,
self.cfg.client_request_timeout,
)
.await?;
let session = signature_response.into_result()?;
self.set_session(SessionConfig::from_signature_notification_response(
session.clone(),
signature_request,
&self.cfg.scheme_name,
)?)?;
Ok(session.vc)
}
/// Starts a linked signature session using a notification.
/// This is the same as the start_signature_notification_document_session method, but can be linked to a previous certificate choice session.
/// Use the `get_session_status` method to poll for the result.
///
/// # Arguments
///
/// * `signature_request` - The signature request.
/// * `document_number` - The document number.
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_signature_notification_document_linked_session(
&self,
signature_request: SignatureNotificationLinkedRequest,
document_number: String,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
NOTIFICATION_SIGNATURE_WITH_DOCUMENT_NUMBER_LINKED_PATH,
document_number,
);
let signature_response =
post::<SignatureNotificationLinkedRequest, SignatureNotificationLinkedResponse>(
path.as_str(),
&signature_request,
self.cfg.client_request_timeout,
)
.await?;
let session = signature_response.into_result()?;
self.set_session(SessionConfig::from_signature_notification_linked_response(
session.clone(),
signature_request,
&self.cfg.scheme_name,
)?)?;
Ok(())
}
// endregion: Signature
// region: Certificate Choice
/// Starts a certificate choice session using a notification and an ETSI identifier.
/// Use the get_session_status method to poll for the result.
///
/// # Arguments
///
/// * `certificate_choice_request` - The certificate choice request.
/// * `etsi` - The ETSI identifier.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_certificate_choice_notification_etsi_session(
&self,
certificate_choice_request: CertificateChoiceNotificationRequest,
etsi: String,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
NOTIFICATION_CERTIFICATE_CHOICE_WITH_SEMANTIC_IDENTIFIER_PATH,
etsi,
);
let certificate_choice_response =
post::<CertificateChoiceNotificationRequest, CertificateChoiceNotificationResponse>(
path.as_str(),
&certificate_choice_request,
self.cfg.client_request_timeout,
)
.await?;
let session = certificate_choice_response.into_result()?;
self.set_session(
SessionConfig::from_certificate_choice_notification_response(
session,
certificate_choice_request,
&self.cfg.scheme_name,
),
)
}
/// Starts an anonymous certificate choice session using a ge link
/// Use the get_session_status method to poll for the result.
/// This should be proceeded by a signature session.
///
/// # Arguments
///
/// * `certificate_choice_request` - The certificate choice request.
///
/// # Returns
///
/// A Result indicating success or failure.
pub async fn start_certificate_choice_anonymous_session(
&self,
certificate_choice_request: CertificateChoiceDeviceLinkRequest,
) -> Result<()> {
self.clear_session();
let path = format!(
"{}{}",
self.cfg.api_url(),
ANONYMOUSE_DEVICE_LINK_CERTIFICATE_CHOICE_PATH,
);
let certificate_choice_response =
post::<CertificateChoiceDeviceLinkRequest, CertificateChoiceDeviceLinkResponse>(
path.as_str(),
&certificate_choice_request,
self.cfg.client_request_timeout,
)
.await?;
let session = certificate_choice_response.into_result()?;
self.set_session(
SessionConfig::from_certificate_choice_device_link_response(
session,
certificate_choice_request,
&self.cfg.scheme_name,
),
)
}
/// Get the signing certificate of the requested document number.
/// If the document number has been previously aquired via the certificate choice session or authentication session, this can be used to get the signing certificate.
/// This does not require a session.
///
/// # Arguments
/// * `document_number` - The document number.
/// * `signing_certificate_request` - The signing certificate request.
///
/// # Returns
/// A `Result` containing a SigningCertificateResult or an error.
pub async fn get_signing_certificate(
&self,
document_number: String,
signing_certificate_request: SigningCertificateRequest,
) -> Result<SigningCertificate> {
self.clear_session();
let path = format!(
"{}{}/{}",
self.cfg.api_url(),
SIGNING_CERTIFICATE_WITH_DOCUMENT_NUMBER_PATH,
document_number,
);
let certificate_choice_response =
post::<SigningCertificateRequest, SigningCertificateResponse>(
path.as_str(),
&signing_certificate_request,
self.cfg.client_request_timeout,
)
.await?;
match certificate_choice_response {
SigningCertificateResponse::Success(signing_certificate_result) => {
match signing_certificate_result.state {
SigningCertificateResponseState::OK => Ok(signing_certificate_result.cert),
SigningCertificateResponseState::DOCUMENT_UNUSABLE => {
Err(SmartIdClientError::GetSigningCertificateException(
"Document is unusable".to_string(),
))
}
}
}
SigningCertificateResponse::Error(e) => Err(
SmartIdClientError::GetSigningCertificateException(e.error_type),
),
}
}
// endregion: Certificate Choice
// region: Device Link
/// Generates a device link for the current session.
/// The link will redirect the device to the Smart-ID app.
/// The link must be refreshed every 1 second.
///
/// # Arguments
///
/// * `device_link_type` - This can be a QR, Web2App or App2App link.
/// * `language_code` - The language code (3-letter ISO 639-2 code).
///
/// # Returns
///
/// A `Result` containing the generated device link as a `String` or an error.
///
/// # Errors
///
/// This function will return an error if:
/// - There is no running session.
/// - The session type is `CertificateChoice`.
pub fn generate_device_link(
&self,
device_link_type: DeviceLinkType,
language_code: &str,
) -> Result<String> {
let session: SessionConfig = self.get_session()?;
match session {
SessionConfig::AuthenticationDeviceLink {
session_secret,
session_token,
device_link_base,
relying_party_name,
initial_callback_url,
signature_protocol,
interactions,
rp_challenge,
session_start_time,
..
} => {
let device_link = match device_link_type {
DeviceLinkType::Web2App | DeviceLinkType::App2App => {
if let Some(initial_callback_url) = initial_callback_url {
SameDeviceLink {
device_link_base,
device_link_type,
session_token,
session_type: SessionType::auth,
version: DEVICE_LINK_VERSION.to_string(),
language_code: language_code.to_string(),
session_secret,
scheme_name: self.cfg.scheme_name.clone(),
signature_protocol: Some(signature_protocol),
rp_challenge_or_digest: rp_challenge,
relying_party_name,
brokered_rp_name: "".to_string(),
interactions,
initial_callback_url,
}
} else {
return Err(SmartIdClientError::GenerateDeviceLinkException(
"Initial callback URL is required for Web2App or App2App device links",
));
}
}
DeviceLinkType::QR => {
CrossDeviceLink {
device_link_base,
device_link_type,
session_start_time,
session_token,
session_type: SessionType::auth,
version: DEVICE_LINK_VERSION.to_string(),
language_code: language_code.to_string(),
session_secret,
scheme_name: self.cfg.scheme_name.clone(),
signature_protocol: Some(signature_protocol),
rp_challenge_or_digest: rp_challenge,
relying_party_name,
brokered_rp_name: "".to_string(),
interactions,
initial_callback_url,
}
}
};
Ok(device_link.generate_device_link())
}
SessionConfig::SignatureDeviceLink {
session_secret,
session_token,
device_link_base,
relying_party_name,
initial_callback_url,
signature_protocol,
interactions,
digest,
session_start_time,
..
} => {
let device_link = match device_link_type {
DeviceLinkType::Web2App | DeviceLinkType::App2App => {
if let Some(initial_callback_url) = initial_callback_url {
SameDeviceLink {
device_link_base,
device_link_type,
session_token,
session_type: SessionType::sign,
version: DEVICE_LINK_VERSION.to_string(),
language_code: language_code.to_string(),
session_secret,
scheme_name: self.cfg.scheme_name.clone(),
signature_protocol: Some(signature_protocol),
rp_challenge_or_digest: digest,
relying_party_name,
brokered_rp_name: "".to_string(),
interactions,
initial_callback_url,
}
} else {
return Err(SmartIdClientError::GenerateDeviceLinkException(
"Initial callback URL is required for Web2App or App2App device links",
));
}
}
DeviceLinkType::QR => {
CrossDeviceLink {
device_link_base,
device_link_type,
session_start_time,
session_token,
session_type: SessionType::sign,
version: DEVICE_LINK_VERSION.to_string(),
language_code: language_code.to_string(),
session_secret,
scheme_name: self.cfg.scheme_name.clone(),
signature_protocol: Some(signature_protocol),
rp_challenge_or_digest: digest,
relying_party_name,
brokered_rp_name: "".to_string(),
interactions,
initial_callback_url,
}
}
};
Ok(device_link.generate_device_link())
}
SessionConfig::CertificateChoiceDeviceLink {
session_token,
session_secret,
device_link_base,
relying_party_name,
initial_callback_url,
session_start_time,
..
} => {
let device_link = match device_link_type {
DeviceLinkType::Web2App | DeviceLinkType::App2App => {
if let Some(initial_callback_url) = initial_callback_url {
SameDeviceLink {
device_link_base,
device_link_type,
session_token,
session_type: SessionType::cert,
version: DEVICE_LINK_VERSION.to_string(),
language_code: language_code.to_string(),
session_secret,
scheme_name: self.cfg.scheme_name.clone(),
signature_protocol: None,
rp_challenge_or_digest: "".to_string(),
relying_party_name,
brokered_rp_name: "".to_string(),
interactions: "".to_string(),
initial_callback_url,
}
} else {
return Err(SmartIdClientError::GenerateDeviceLinkException(
"Initial callback URL is required for Web2App or App2App device links",
));
}
}
DeviceLinkType::QR => {
CrossDeviceLink {
device_link_base,
device_link_type,
session_start_time,
session_token,
session_type: SessionType::cert,
version: DEVICE_LINK_VERSION.to_string(),
language_code: language_code.to_string(),
session_secret,
scheme_name: self.cfg.scheme_name.clone(),
signature_protocol: None,
rp_challenge_or_digest: "".to_string(),
relying_party_name,
brokered_rp_name: "".to_string(),
interactions: "".to_string(),
initial_callback_url,
}
}
};
Ok(device_link.generate_device_link())
}
_ => {
Err(SmartIdClientError::GenerateDeviceLinkException(
"Can only generate device links for authentication or signature device link sessions",
))
}
}
}
// endregion: Device Link
// region: Validation
/// Validates the session status and ensures that the session has completed successfully.
///
/// If the session is running returns Ok(()).
///
/// If the session is complete, this function performs several checks to validate the session status:
/// - Ensures that the session result is present.
/// - Validates the certificate chain and checks for expiration.
/// - Verifies the identity of the authenticated person using the subject field or subjectAltName extension of the X.509 certificate.
/// - Checks that the certificate level is high enough.
/// - Validates the signature using the public key from the certificate.
/// - Checks the session result is OK.
///
/// # Arguments
///
/// * `session_status` - The status of the session to be validated.
/// * `session_config` - The configuration of the session.
/// * `user_identity` - The subject of the certificate.
///
/// # Returns
///
/// A `Result` indicating success or failure. If the validation is successful, it returns `Ok(())`.
/// If any validation step fails, it returns an appropriate `SmartIdClientError`.
///
/// # Errors
///
/// This function will return an error if:
/// - The session result is missing.
/// - The certificate is missing or invalid.
/// - The signature is missing or invalid.
/// - The session did not complete successfully.
/// - The session result is not OK.
/// - The provided identity does not match the certificate.
fn validate_session_status(
&self,
session_status: SessionStatusResponse,
session_config: SessionConfig,
) -> Result<()> {
match session_status.result.clone() {
Some(session_result) => {
// Check the result is OK
session_result.end_result.is_ok()?;
// Validate the certificate is present (Required for OK status)
let cert = session_status
.cert
.clone()
.ok_or(SmartIdClientError::SessionResponseMissingCertificate)?;
// Verify the certificate chain
self.verify_certificate(cert.value.clone())?;
// Check certificate level is high enough
if &cert.certificate_level < session_config.requested_certificate_level() {
Err(
SmartIdClientError::FailedToValidateSessionResponseCertificate(format!(
"Certificate level is not high enough: {:?} < {:?}",
cert.certificate_level,
session_config.requested_certificate_level()
)),
)?
};
// Validate signature is correct
self.validate_signature(session_config, session_status, cert.clone())?;
// Check that the identity matches the certificate
if let Some(user_identity) = self.get_user_identity()? {
user_identity.identity_matches_certificate(cert.value)?
}
Ok(())
}
None => match session_status.state {
SessionState::RUNNING => Ok(()),
SessionState::COMPLETE => {
Err(SmartIdClientError::AuthenticationSessionCompletedWithoutResult)
}
},
}
}
/// Verifies a certificate chain using the root and intermediate certificates.
///
/// This is done automatically when validating the session response.
/// You only need to call this method if you want to validate a certificate that has not just been returned from a session.
/// Or if you want to get the certificate chain (Example: For PAdES-L/LTA signatures)
///
/// # Arguments
/// * `cert` - The base64 der encoded certificate to be validated.
/// # Returns
/// A valid certificate chain.
pub fn verify_certificate(&self, cert: String) -> Result<Vec<String>> {
if self.cfg.is_demo() {
let mut root_certs = demo_root_certificates();
root_certs.extend(self.root_certificates.clone());
let mut intermediate_certs = demo_intermediate_certificates();
intermediate_certs.extend(self.intermediate_certificates.clone());
verify_certificate(&cert, intermediate_certs, root_certs)
} else {
let mut root_certs = production_root_certificates();
root_certs.extend(self.root_certificates.clone());
let mut intermediate_certs = production_intermediate_certificates();
intermediate_certs.extend(self.intermediate_certificates.clone());
verify_certificate(
&cert,
production_root_certificates(),
production_intermediate_certificates(),
)
}
}
fn validate_signature(
&self,
session_config: SessionConfig,
session_status_response: SessionStatusResponse,
cert: SessionCertificate,
) -> Result<()> {
match session_config {
SessionConfig::AuthenticationDeviceLink {
relying_party_name,
initial_callback_url,
interactions,
rp_challenge,
scheme_name,
signature_protocol,
signature_protocol_parameters,
..
} => {
let signature = session_status_response
.signature
.ok_or(SmartIdClientError::SessionResponseMissingSignature)?;
if signature.get_flow_type() == FlowType::App2App
|| signature.get_flow_type() == FlowType::Web2App
{
debug!("When the user goes to the callback a secret is appended to the URL, this is needed to verify the signature for these flows");
return Ok(());
}
let used_interaction_type = session_status_response
.interaction_type_used
.ok_or(SmartIdClientError::SessionResponseMissingInteractionType)?;
signature.validate_acsp_v2(
scheme_name,
signature_protocol,
rp_challenge,
cert.value.clone(),
relying_party_name,
None,
interactions,
used_interaction_type,
initial_callback_url,
signature_protocol_parameters.get_hashing_algorithm(),
)?;
// If no user identity is set, set it from the certificate
// This happens during all anonymous sessions
if self.get_user_identity()?.is_none() {
self.set_user_identity(UserIdentity::from_certificate(cert.value.clone())?)?
};
Ok(())
}
SessionConfig::AuthenticationNotification {
relying_party_name,
interactions,
rp_challenge,
scheme_name,
signature_protocol,
signature_protocol_parameters,
..
} => {
let signature = session_status_response
.signature
.ok_or(SmartIdClientError::SessionResponseMissingSignature)?;
let used_interaction_type = session_status_response
.interaction_type_used
.ok_or(SmartIdClientError::SessionResponseMissingInteractionType)?;
signature.validate_acsp_v2(
scheme_name,
signature_protocol,
rp_challenge,
cert.value.clone(),
relying_party_name,
None,
interactions,
used_interaction_type,
None,
signature_protocol_parameters.get_hashing_algorithm(),
)?;
// If no user identity is set, set it from the certificate
// This happens during all anonymous sessions
if self.get_user_identity()?.is_none() {
self.set_user_identity(UserIdentity::from_certificate(cert.value.clone())?)?
};
Ok(())
}
SessionConfig::SignatureDeviceLink {
digest,
signature_protocol_parameters,
..
} => {
let signature = session_status_response
.signature
.ok_or(SmartIdClientError::SessionResponseMissingSignature)?;
let parameters = signature
.get_signature_algorithm_parameters()
.ok_or(SmartIdClientError::SessionResponseMissingSignature)?;
// TODO: CHeck this with prod
if self.cfg.is_demo() {
return Ok(());
}
signature.validate_raw_digest(
digest,
cert.value.clone(),
signature_protocol_parameters.get_hashing_algorithm(),
parameters.salt_length,
)
}
SessionConfig::SignatureNotification {
digest,
signature_protocol_parameters,
..
} => {
let signature = session_status_response
.signature
.ok_or(SmartIdClientError::SessionResponseMissingSignature)?;
let parameters = signature
.get_signature_algorithm_parameters()
.ok_or(SmartIdClientError::SessionResponseMissingSignature)?;
// TODO: CHeck this with prod
if self.cfg.is_demo() {
return Ok(());
}
signature.validate_raw_digest(
digest,
cert.value.clone(),
signature_protocol_parameters.get_hashing_algorithm(),
parameters.salt_length,
)
}
_ => {
debug!("Signature validation only needed for device link authentication and signature sessions");
Ok(())
}
}
}
// endregion: Validation
// region: Utility functions
/// Resets the current session by clearing the session configuration and the authenticated user identity.
///
/// If a different user wants to log in you must call this method to clear the current session identity.
pub fn reset_session(&self) {
self.clear_session();
self.clear_user_identity();
}
pub fn get_session(&self) -> Result<SessionConfig> {
match self.session_config.lock() {
Ok(guard) => match guard.clone() {
Some(s) => Ok(s),
None => {
debug!("Can't get session there is no running session");
Err(NoSessionException)
}
},
Err(e) => {
debug!("Failed to lock session config: {:?}", e);
Err(SmartIdClientError::GetSessionException)
}
}
}
fn set_session(&self, session: SessionConfig) -> Result<()> {
match self.session_config.lock() {
Ok(mut guard) => {
*guard = Some(session);
Ok(())
}
Err(e) => {
debug!("Failed to lock session config: {:?}", e);
Err(SmartIdClientError::SetSessionException)
}
}
}
fn clear_session(&self) {
match self.session_config.lock() {
Ok(mut guard) => {
*guard = None;
}
Err(e) => {
debug!("Failed to lock session config: {:?}", e);
}
}
}
pub fn get_user_identity(&self) -> Result<Option<UserIdentity>> {
match self.authenticated_identity.lock() {
Ok(guard) => match guard.clone() {
Some(s) => Ok(Some(s)),
None => Ok(None),
},
Err(e) => {
debug!("Failed to lock authenticated identity: {:?}", e);
Err(SmartIdClientError::GetUserIdentityException)
}
}
}
fn set_user_identity(&self, user_identity: UserIdentity) -> Result<()> {
match self.authenticated_identity.lock() {
Ok(mut guard) => {
*guard = Some(user_identity);
Ok(())
}
Err(e) => {
debug!("Failed to lock authenticated identity: {:?}", e);
Err(SmartIdClientError::SetUserIdentityException)
}
}
}
#[allow(dead_code)]
fn clear_user_identity(&self) {
match self.authenticated_identity.lock() {
Ok(mut guard) => {
*guard = None;
}
Err(e) => {
debug!("Failed to lock authenticated identity: {:?}", e);
}
}
}
// endregion: Utility functions
}