-
Notifications
You must be signed in to change notification settings - Fork 44
/
auth.rs
1811 lines (1702 loc) · 69 KB
/
auth.rs
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
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use rand::Rng;
use soroban_env_common::xdr::{
ContractDataEntry, CreateContractArgs, HashIdPreimage, HashIdPreimageSorobanAuthorization,
InvokeContractArgs, LedgerEntry, LedgerEntryData, LedgerEntryExt, ScAddress, ScErrorCode,
ScErrorType, ScNonceKey, ScVal, SorobanAuthorizationEntry, SorobanAuthorizedFunction,
SorobanCredentials,
};
use soroban_env_common::{AddressObject, Compare, Symbol, TryFromVal, TryIntoVal, Val, VecObject};
use crate::budget::{AsBudget, Budget};
use crate::host::error::TryBorrowOrErr;
use crate::host::metered_clone::{MeteredAlloc, MeteredClone, MeteredContainer, MeteredIterator};
use crate::host::Frame;
use crate::host_object::HostVec;
use crate::native_contract::account_contract::{
check_account_authentication, check_account_contract_auth,
};
use crate::native_contract::invoker_contract_auth::invoker_contract_auth_to_authorized_invocation;
use crate::{Host, HostError};
use super::xdr;
use super::xdr::Hash;
// Authorization manager encapsulates host-based authentication & authorization
// framework.
// This supports enforcing authentication & authorization of the contract
// invocation trees as well as recording the authorization requirements in
// simulated environments (such as tests or preflight).
#[derive(Clone)]
pub struct AuthorizationManager {
// Mode of operation of this AuthorizationManager. This can't be changed; in
// order to switch the mode a new instance of AuthorizationManager has to
// be created.
mode: AuthorizationMode,
// Per-address trackers of authorized invocations.
// Every tracker takes care about a single rooted invocation tree for some
// address. There can be multiple trackers per address.
// The internal structure of this field is build in such a way that trackers
// can be borrowed mutably independently, while still allowing for
// modification of the `account_trackers` vec itself.
account_trackers: RefCell<Vec<RefCell<AccountAuthorizationTracker>>>,
// Per-address trackers for authorization performed by the contracts at
// execution time (as opposed to signature-based authorization for accounts).
// Contract authorizations are always enforced independently of the `mode`,
// as they are self-contained and fully defined by the contract logic.
invoker_contract_trackers: RefCell<Vec<InvokerContractAuthorizationTracker>>,
// Current call stack consisting only of the contract invocations (i.e. not
// the host functions).
call_stack: RefCell<Vec<AuthStackFrame>>,
}
macro_rules! impl_checked_borrow_helpers {
($field:ident, $t:ty, $borrow:ident, $borrow_mut:ident) => {
impl AuthorizationManager {
#[allow(dead_code)]
fn $borrow(&self, host: &Host) -> Result<std::cell::Ref<'_, $t>, HostError> {
use crate::host::error::TryBorrowOrErr;
self.$field.try_borrow_or_err_with(
host,
concat!(
"authorization_manager.",
stringify!($field),
".try_borrow failed"
),
)
}
fn $borrow_mut(&self, host: &Host) -> Result<std::cell::RefMut<'_, $t>, HostError> {
use crate::host::error::TryBorrowOrErr;
self.$field.try_borrow_mut_or_err_with(
host,
concat!(
"authorization_manager.",
stringify!($field),
".try_borrow_mut failed"
),
)
}
}
};
}
impl_checked_borrow_helpers!(
account_trackers,
Vec<RefCell<AccountAuthorizationTracker>>,
try_borrow_account_trackers,
try_borrow_account_trackers_mut
);
impl_checked_borrow_helpers!(
invoker_contract_trackers,
Vec<InvokerContractAuthorizationTracker>,
try_borrow_invoker_contract_trackers,
try_borrow_invoker_contract_trackers_mut
);
impl_checked_borrow_helpers!(
call_stack,
Vec<AuthStackFrame>,
try_borrow_call_stack,
try_borrow_call_stack_mut
);
// The authorization payload recorded for an address in the recording
// authorization mode.
#[derive(Debug)]
pub struct RecordedAuthPayload {
pub address: Option<ScAddress>,
pub nonce: Option<i64>,
pub invocation: xdr::SorobanAuthorizedInvocation,
}
// Snapshot of `AuthorizationManager` to use when performing the callstack
// rollbacks.
pub struct AuthorizationManagerSnapshot {
account_trackers_snapshot: AccountTrackersSnapshot,
invoker_contract_tracker_root_snapshots: Vec<AuthorizedInvocationSnapshot>,
// This is set only for the recording mode.
tracker_by_address_handle: Option<HashMap<u32, usize>>,
}
// Snapshot of the `account_trackers` in `AuthorizationManager`.
enum AccountTrackersSnapshot {
// In enforcing mode we only need to snapshot the mutable part of the
// trackers.
// `None` means that the tracker is currently in authentication process and
// shouldn't be modified (as the tracker can't be used to authenticate
// itself).
Enforcing(Vec<Option<AccountAuthorizationTrackerSnapshot>>),
// In recording mode snapshot the whole vector, as we create trackers
// lazily and hence the outer vector itself might change.
Recording(Vec<RefCell<AccountAuthorizationTracker>>),
}
#[derive(Clone)]
enum AuthorizationMode {
Enforcing,
Recording(RecordingAuthInfo),
}
// Additional AuthorizationManager fields needed only for the recording mode.
#[derive(Clone)]
struct RecordingAuthInfo {
// Maps the `Address` object identifiers to the respective tracker indices
// in `trackers`
// This allows to disambiguate between the addresses that have the same
// value, but are specified as two different objects (e.g. as two different
// contract function inputs).
tracker_by_address_handle: RefCell<HashMap<u32, usize>>,
// Whether to allow root authorized invocation to not match the root
// contract invocation.
disable_non_root_auth: bool,
}
impl RecordingAuthInfo {
fn try_borrow_tracker_by_address_handle(
&self,
host: &Host,
) -> Result<std::cell::Ref<'_, HashMap<u32, usize>>, HostError> {
self.tracker_by_address_handle.try_borrow_or_err_with(
host,
"recording_auth_info.tracker_by_address_handle.try_borrow failed",
)
}
fn try_borrow_tracker_by_address_handle_mut(
&self,
host: &Host,
) -> Result<std::cell::RefMut<'_, HashMap<u32, usize>>, HostError> {
self.tracker_by_address_handle.try_borrow_mut_or_err_with(
host,
"recording_auth_info.tracker_by_address_handle.try_borrow_mut failed",
)
}
}
// Helper for matching the 'sparse' tree of authorized invocations to the actual
// call tree.
#[derive(Clone)]
struct InvocationTracker {
// Root of the authorized invocation tree.
// The authorized invocation tree only contains the contract invocations
// that explicitly require authorization on behalf of the address.
root_authorized_invocation: AuthorizedInvocation,
// Call stack that tracks the current walk in the tree of authorized
// invocations.
// This is set to `None` if the invocation didn't require authorization on
// behalf of the address.
// When not `None` this is an index of the authorized invocation in the
// parent's `sub_invocations` vector or 0 for the
// `root_authorized_invocation`.
invocation_id_in_call_stack: Vec<Option<usize>>,
// If root invocation is exhuasted, the index of the stack frame where it
// was exhausted (i.e. index in `invocation_id_in_call_stack`).
root_exhausted_frame: Option<usize>,
// Indicates whether this tracker is fully processed, i.e. the authorized
// root frame has been exhausted and then popped from the stack.
is_fully_processed: bool,
}
// Stores all the authorizations that are authorized by an address.
// In the enforcing mode this performs authentication and makes sure that only
// pre-authorized invocations can happen on behalf of the `address`.
// In the recording mode this will record the invocations that are authorized
// on behalf of the address.
#[derive(Clone)]
pub(crate) struct AccountAuthorizationTracker {
// Tracked address.
address: AddressObject,
// Helper for matching the tree that address authorized to the invocation
// tree.
invocation_tracker: InvocationTracker,
// Value representing the signature created by the address to authorize
// the invocations tracked here.
signature: Val,
// Indicates whether this tracker is still valid. If invalidated once, this
// can't be used to authorize anything anymore
is_valid: bool,
// Indicates whether this is a tracker for the transaction invoker.
is_invoker: bool,
// Indicates whether authentication has already succesfully happened.
authenticated: bool,
// Indicates whether nonce still needs to be verified and consumed.
need_nonce: bool,
// The value of nonce authorized by the address with its expiration ledger.
// Must not exist in the ledger.
nonce: Option<(i64, u32)>,
}
pub(crate) struct AccountAuthorizationTrackerSnapshot {
invocation_tracker_root_snapshot: AuthorizedInvocationSnapshot,
authenticated: bool,
need_nonce: bool,
}
// Stores all the authorizations peformed by contracts at runtime.
#[derive(Clone)]
pub(crate) struct InvokerContractAuthorizationTracker {
contract_address: AddressObject,
invocation_tracker: InvocationTracker,
}
#[derive(Clone)]
pub(crate) enum AuthStackFrame {
Contract(ContractInvocation),
CreateContractHostFn(CreateContractArgs),
}
#[derive(Clone)]
pub(crate) struct ContractInvocation {
pub(crate) contract_address: AddressObject,
pub(crate) function_name: Symbol,
}
#[derive(Clone)]
pub(crate) struct ContractFunction {
pub(crate) contract_address: AddressObject,
pub(crate) function_name: Symbol,
pub(crate) args: Vec<Val>,
}
#[derive(Clone)]
pub(crate) enum AuthorizedFunction {
ContractFn(ContractFunction),
CreateContractHostFn(CreateContractArgs),
}
// A single node in the authorized invocation tree.
// This represents an invocation and all it's authorized sub-invocations.
#[derive(Clone)]
pub(crate) struct AuthorizedInvocation {
pub(crate) function: AuthorizedFunction,
pub(crate) sub_invocations: Vec<AuthorizedInvocation>,
// Indicates that this invocation has been already used in the
// enforcing mode. Exhausted authorizations can't be reused.
// In the recording mode this is immediately set to `true` (as the
// authorizations are recorded when they actually happen).
is_exhausted: bool,
}
// Snapshot of `AuthorizedInvocation` that contains only mutable fields.
pub(crate) struct AuthorizedInvocationSnapshot {
is_exhausted: bool,
sub_invocations: Vec<AuthorizedInvocationSnapshot>,
}
impl Compare<ContractFunction> for Host {
type Error = HostError;
// metering: covered by host
fn compare(
&self,
a: &ContractFunction,
b: &ContractFunction,
) -> Result<std::cmp::Ordering, Self::Error> {
let ord = self.compare(&a.contract_address, &b.contract_address)?;
if !ord.is_eq() {
return Ok(ord);
}
let ord = self.compare(&a.function_name, &b.function_name)?;
if !ord.is_eq() {
return Ok(ord);
}
self.compare(&a.args, &b.args)
}
}
impl Compare<AuthorizedFunction> for Host {
type Error = HostError;
// metering: covered by components
fn compare(
&self,
a: &AuthorizedFunction,
b: &AuthorizedFunction,
) -> Result<std::cmp::Ordering, Self::Error> {
match (a, b) {
(AuthorizedFunction::ContractFn(f1), AuthorizedFunction::ContractFn(f2)) => {
self.compare(f1, f2)
}
(
AuthorizedFunction::CreateContractHostFn(c1),
AuthorizedFunction::CreateContractHostFn(c2),
) => self.compare(c1, c2),
(AuthorizedFunction::ContractFn(_), AuthorizedFunction::CreateContractHostFn(_)) => {
Ok(std::cmp::Ordering::Less)
}
(AuthorizedFunction::CreateContractHostFn(_), AuthorizedFunction::ContractFn(_)) => {
Ok(std::cmp::Ordering::Greater)
}
}
}
}
impl AuthStackFrame {
// metering: covered
fn to_authorized_function(
&self,
host: &Host,
args: Vec<Val>,
) -> Result<AuthorizedFunction, HostError> {
match self {
AuthStackFrame::Contract(contract_frame) => {
Ok(AuthorizedFunction::ContractFn(ContractFunction {
contract_address: contract_frame.contract_address,
function_name: contract_frame.function_name.metered_clone(host)?,
args,
}))
}
AuthStackFrame::CreateContractHostFn(args) => Ok(
AuthorizedFunction::CreateContractHostFn(args.metered_clone(host)?),
),
}
}
}
impl AuthorizedFunction {
// metering: covered by the host
fn from_xdr(host: &Host, xdr_fn: SorobanAuthorizedFunction) -> Result<Self, HostError> {
Ok(match xdr_fn {
SorobanAuthorizedFunction::ContractFn(xdr_contract_fn) => {
AuthorizedFunction::ContractFn(ContractFunction {
contract_address: host.add_host_object(xdr_contract_fn.contract_address)?,
function_name: Symbol::try_from_val(host, &xdr_contract_fn.function_name)?,
args: host.scvals_to_rawvals(xdr_contract_fn.args.as_slice())?,
})
}
SorobanAuthorizedFunction::CreateContractHostFn(xdr_args) => {
AuthorizedFunction::CreateContractHostFn(xdr_args)
}
})
}
// metering: covered by the host
fn to_xdr(&self, host: &Host) -> Result<SorobanAuthorizedFunction, HostError> {
match self {
AuthorizedFunction::ContractFn(contract_fn) => {
let function_name_sc_val = host.from_host_val(contract_fn.function_name.into())?;
let function_name = if let ScVal::Symbol(s) = function_name_sc_val {
s
} else {
return Err(host.err(
ScErrorType::Object,
ScErrorCode::InternalError,
"unexpected non-symbol function name",
&[],
));
};
Ok(SorobanAuthorizedFunction::ContractFn(InvokeContractArgs {
contract_address: host.scaddress_from_address(contract_fn.contract_address)?,
function_name,
args: host.rawvals_to_sc_val_vec(contract_fn.args.as_slice())?,
}))
}
AuthorizedFunction::CreateContractHostFn(create_contract_args) => {
Ok(SorobanAuthorizedFunction::CreateContractHostFn(
create_contract_args.metered_clone(host)?,
))
}
}
}
// metering: free
fn to_xdr_non_metered(&self, host: &Host) -> Result<xdr::SorobanAuthorizedFunction, HostError> {
match self {
AuthorizedFunction::ContractFn(contract_fn) => {
Ok(SorobanAuthorizedFunction::ContractFn(InvokeContractArgs {
contract_address: host
.visit_obj(contract_fn.contract_address, |addr: &ScAddress| {
Ok(addr.clone())
})?,
function_name: contract_fn.function_name.try_into_val(host)?,
// why is this intentionally non-metered? the visit_obj above is metered.
args: host.rawvals_to_sc_val_vec_non_metered(contract_fn.args.as_slice())?,
}))
}
AuthorizedFunction::CreateContractHostFn(create_contract_args) => Ok(
SorobanAuthorizedFunction::CreateContractHostFn(create_contract_args.clone()),
),
}
}
}
impl AuthorizedInvocation {
// metering: covered
fn from_xdr(
host: &Host,
xdr_invocation: xdr::SorobanAuthorizedInvocation,
) -> Result<Self, HostError> {
let sub_invocations_xdr = xdr_invocation.sub_invocations.into_vec();
let sub_invocations = sub_invocations_xdr
.into_iter()
.map(|a| AuthorizedInvocation::from_xdr(host, a))
.metered_collect::<Result<Vec<_>, _>>(host)??;
Ok(Self {
function: AuthorizedFunction::from_xdr(host, xdr_invocation.function)?,
sub_invocations,
is_exhausted: false,
})
}
// metering: free
pub(crate) fn new(
function: AuthorizedFunction,
sub_invocations: Vec<AuthorizedInvocation>,
) -> Self {
Self {
function,
sub_invocations,
is_exhausted: false,
}
}
// metering: free
fn new_recording(function: AuthorizedFunction) -> Self {
Self {
function,
sub_invocations: vec![],
is_exhausted: true,
}
}
// metering: covered
fn to_xdr(&self, host: &Host) -> Result<xdr::SorobanAuthorizedInvocation, HostError> {
Ok(xdr::SorobanAuthorizedInvocation {
function: self.function.to_xdr(host)?,
sub_invocations: self
.sub_invocations
.iter()
.map(|i| i.to_xdr(host))
.metered_collect::<Result<Vec<xdr::SorobanAuthorizedInvocation>, HostError>>(host)??
.try_into()
.map_err(|_| HostError::from((ScErrorType::Auth, ScErrorCode::InternalError)))?,
})
}
// Non-metered conversion should only be used for the recording preflight
// runs or testing.
// metering: free
fn to_xdr_non_metered(
&self,
host: &Host,
exhausted_sub_invocations_only: bool,
) -> Result<xdr::SorobanAuthorizedInvocation, HostError> {
Ok(xdr::SorobanAuthorizedInvocation {
function: self.function.to_xdr_non_metered(host)?,
sub_invocations: self
.sub_invocations
.iter()
.filter(|i| i.is_exhausted || !exhausted_sub_invocations_only)
.map(|i| i.to_xdr_non_metered(host, exhausted_sub_invocations_only))
.collect::<Result<Vec<xdr::SorobanAuthorizedInvocation>, HostError>>()?
.try_into()
.map_err(|_| HostError::from((ScErrorType::Auth, ScErrorCode::InternalError)))?,
})
}
// Walks a path in the tree defined by `invocation_id_in_call_stack` and
// returns the last visited authorized node.
// metering: free
fn last_authorized_invocation_mut(
&mut self,
invocation_id_in_call_stack: &Vec<Option<usize>>,
call_stack_id: usize,
) -> &mut AuthorizedInvocation {
// Start walking the stack from `call_stack_id`. We trust the callers to
// hold the invariant that `invocation_id_in_call_stack[call_stack_id - 1]`
// corresponds to this invocation tree, so that the next non-`None` child
// corresponds to the child of the current tree.
for (i, id) in invocation_id_in_call_stack
.iter()
.enumerate()
.skip(call_stack_id)
{
if let Some(id) = id {
// We trust the caller to have the correct sub-invocation
// indices.
return self.sub_invocations[*id]
.last_authorized_invocation_mut(invocation_id_in_call_stack, i + 1);
}
// Skip `None` invocations as they don't require authorization.
}
self
}
// metering: covered
fn snapshot(&self, budget: &Budget) -> Result<AuthorizedInvocationSnapshot, HostError> {
Ok(AuthorizedInvocationSnapshot {
is_exhausted: self.is_exhausted,
sub_invocations: self
.sub_invocations
.iter()
.map(|i| i.snapshot(budget))
.metered_collect::<Result<Vec<AuthorizedInvocationSnapshot>, HostError>>(
budget,
)??,
})
}
// metering: free
fn rollback(&mut self, snapshot: &AuthorizedInvocationSnapshot) -> Result<(), HostError> {
self.is_exhausted = snapshot.is_exhausted;
if self.sub_invocations.len() != snapshot.sub_invocations.len() {
// This would be a bug.
return Err((ScErrorType::Auth, ScErrorCode::InternalError).into());
}
for (i, sub_invocation) in self.sub_invocations.iter_mut().enumerate() {
sub_invocation.rollback(&snapshot.sub_invocations[i])?;
}
Ok(())
}
}
impl Default for AuthorizationManager {
fn default() -> Self {
Self::new_enforcing_without_authorizations()
}
}
impl AuthorizationManager {
// Creates a new enforcing `AuthorizationManager` from the given
// authorization entries.
// This should be created once per top-level invocation.
// metering: covered
pub(crate) fn new_enforcing(
host: &Host,
auth_entries: Vec<SorobanAuthorizationEntry>,
) -> Result<Self, HostError> {
Vec::<AccountAuthorizationTracker>::charge_bulk_init_cpy(auth_entries.len() as u64, host)?;
let mut trackers = Vec::with_capacity(auth_entries.len());
for auth_entry in auth_entries {
trackers.push(RefCell::new(
AccountAuthorizationTracker::from_authorization_entry(host, auth_entry)?,
));
}
Ok(Self {
mode: AuthorizationMode::Enforcing,
call_stack: RefCell::new(vec![]),
account_trackers: RefCell::new(trackers),
invoker_contract_trackers: RefCell::new(vec![]),
})
}
// Creates a new enforcing `AuthorizationManager` that doesn't allow any
// authorizations.
// This is useful as a safe default mode.
// metering: free
pub(crate) fn new_enforcing_without_authorizations() -> Self {
Self {
mode: AuthorizationMode::Enforcing,
call_stack: RefCell::new(vec![]),
account_trackers: RefCell::new(vec![]),
invoker_contract_trackers: RefCell::new(vec![]),
}
}
// Creates a new recording `AuthorizationManager`.
// All the authorization requirements will be recorded and can then be
// retrieved using `get_recorded_auth_payloads`.
// metering: free
pub(crate) fn new_recording(disable_non_root_auth: bool) -> Self {
Self {
mode: AuthorizationMode::Recording(RecordingAuthInfo {
tracker_by_address_handle: Default::default(),
disable_non_root_auth,
}),
call_stack: RefCell::new(vec![]),
account_trackers: RefCell::new(vec![]),
invoker_contract_trackers: RefCell::new(vec![]),
}
}
// Require the `address` to have authorized the current contract invocation
// with provided args and within the current context (i.e. the current
// authorized call stack and for the current network).
// In the recording mode this stores the auth requirement instead of
// verifying it.
// metering: covered
pub(crate) fn require_auth(
&self,
host: &Host,
address: AddressObject,
args: Vec<Val>,
) -> Result<(), HostError> {
let _span = tracy_span!("require auth");
let authorized_function = self
.try_borrow_call_stack(host)?
.last()
.ok_or_else(|| {
host.err(
ScErrorType::Auth,
ScErrorCode::InternalError,
"unexpected require_auth outside of valid frame",
&[],
)
})?
.to_authorized_function(host, args)?;
self.require_auth_internal(host, address, authorized_function)
}
// metering: covered
pub(crate) fn add_invoker_contract_auth(
&self,
host: &Host,
auth_entries: VecObject,
) -> Result<(), HostError> {
let auth_entries =
host.visit_obj(auth_entries, |e: &HostVec| e.to_vec(host.budget_ref()))?;
let mut trackers = self.try_borrow_invoker_contract_trackers_mut(host)?;
Vec::<Val>::charge_bulk_init_cpy(auth_entries.len() as u64, host)?;
trackers.reserve(auth_entries.len());
for e in auth_entries {
trackers.push(InvokerContractAuthorizationTracker::new(host, e)?)
}
Ok(())
}
// metering: covered by components
fn verify_contract_invoker_auth(
&self,
host: &Host,
address: AddressObject,
function: &AuthorizedFunction,
) -> Result<bool, HostError> {
{
let call_stack = self.try_borrow_call_stack(host)?;
// If stack has just one call there can't be invoker.
if call_stack.len() < 2 {
return Ok(false);
}
// Try matching the direct invoker contract first. It is considered to
// have authorized any direct calls.
let invoker_frame = &call_stack[call_stack.len() - 2];
if let AuthStackFrame::Contract(invoker_contract) = invoker_frame {
if host
.compare(&invoker_contract.contract_address, &address)?
.is_eq()
{
return Ok(true);
}
}
}
let mut invoker_contract_trackers = self.try_borrow_invoker_contract_trackers_mut(host)?;
// If there is no direct invoker, there still might be a valid
// sub-contract call authorization from another invoker higher up the
// stack. Note, that invoker contract trackers consider the direct frame
// to never require auth (any `require_auth` calls would be matched by
// logic above).
for tracker in invoker_contract_trackers.iter_mut() {
if host.compare(&tracker.contract_address, &address)?.is_eq()
&& tracker.maybe_authorize_invocation(host, function)?
{
return Ok(true);
}
}
return Ok(false);
}
// metering: covered by components
fn require_auth_enforcing(
&self,
host: &Host,
address: AddressObject,
function: &AuthorizedFunction,
) -> Result<(), HostError> {
// Find if there is already an active tracker for this address that has
// not been matched for the current frame. If there is such tracker,
// this authorization has to be matched with an already active tracker.
// This prevents matching sets of disjoint authorization entries to
// a tree of calls.
let mut has_active_tracker = false;
for tracker in self.try_borrow_account_trackers(host)?.iter() {
if let Ok(tracker) = tracker.try_borrow() {
// If address doesn't match, just skip the tracker.
if host.compare(&tracker.address, &address)?.is_eq()
&& tracker.is_active()
&& !tracker.current_frame_is_already_matched()
{
has_active_tracker = true;
break;
}
}
}
// Iterate all the trackers and try to find one that
// fullfills the authorization requirement.
for tracker in self.try_borrow_account_trackers(host)?.iter() {
// Tracker can only be borrowed by the authorization manager itself.
// The only scenario in which re-borrow might occur is when
// `require_auth` is called within `__check_auth` call. The tracker
// that called `__check_auth` would be already borrowed in such
// scenario.
// We allow such call patterns in general, but we don't allow using
// tracker to verify auth for itself, i.e. we don't allow something
// like address.require_auth()->address_contract.__check_auth()
// ->address.require_auth(). Thus we simply skip the trackers that
// have already been borrowed.
if let Ok(mut tracker) = tracker.try_borrow_mut() {
// If address doesn't match, just skip the tracker.
if !host.compare(&tracker.address, &address)?.is_eq() {
continue;
}
match tracker.maybe_authorize_invocation(host, function, !has_active_tracker) {
// If tracker doesn't have a matching invocation,
// just skip it (there could still be another
// tracker that matches it).
Ok(false) => continue,
// Found a matching authorization.
Ok(true) => return Ok(()),
// Found a matching authorization, but another
// requirement hasn't been fullfilled (for
// example, incorrect authentication or nonce).
Err(e) => return Err(e),
}
}
}
// No matching tracker found, hence the invocation isn't
// authorized.
Err(host.err(
ScErrorType::Auth,
ScErrorCode::InvalidAction,
"Unauthorized function call for address",
&[address.to_val()],
))
}
// metering: covered
fn require_auth_internal(
&self,
host: &Host,
address: AddressObject,
function: AuthorizedFunction,
) -> Result<(), HostError> {
// For now we give a blanket approval of the invoker contract to any
// calls it made, but never to the deeper calls. It's possible
// to eventually add a capability to pre-authorize arbitrary call
// stacks on behalf of the contract.
if self.verify_contract_invoker_auth(host, address, &function)? {
return Ok(());
}
match &self.mode {
AuthorizationMode::Enforcing => self.require_auth_enforcing(host, address, &function),
// metering: free for recording
AuthorizationMode::Recording(recording_info) => {
let address_obj_handle = address.get_handle();
let existing_tracker_id = recording_info
.try_borrow_tracker_by_address_handle(host)?
.get(&address_obj_handle)
.copied();
if let Some(tracker_id) = existing_tracker_id {
// The tracker should not be borrowed recursively in
// recording mode, as we don't call `__check_auth` in this
// flow.
if let Ok(mut tracker) =
self.try_borrow_account_trackers(host)?[tracker_id].try_borrow_mut()
{
// The recording invariant is that trackers are created
// with the first authorized invocation, which means
// that when their stack no longer has authorized
// invocation, then we've popped frames past its root
// and hence need to create a new tracker.
if !tracker.has_authorized_invocations_in_stack() {
recording_info
.try_borrow_tracker_by_address_handle_mut(host)?
.remove(&address_obj_handle);
} else {
return tracker.record_invocation(host, function);
}
} else {
return Err(host.err(
ScErrorType::Auth,
ScErrorCode::InternalError,
"unexpected recursive tracker borrow in recording mode",
&[],
));
}
}
if recording_info.disable_non_root_auth
&& self.try_borrow_call_stack(host)?.len() != 1
{
return Err(host.err(
ScErrorType::Auth,
ScErrorCode::InvalidAction,
"[recording authorization only] encountered authorization not tied \
to the root contract invocation for an address. Use `require_auth()` \
in the top invocation or enable non-root authorization.",
&[address.into()],
));
}
// If a tracker for the new tree doesn't exist yet, create
// it and initialize with the current invocation.
self.try_borrow_account_trackers_mut(host)?
.push(RefCell::new(AccountAuthorizationTracker::new_recording(
host,
address,
function,
self.try_borrow_call_stack(host)?.len(),
)?));
recording_info
.try_borrow_tracker_by_address_handle_mut(host)?
.insert(
address_obj_handle,
self.try_borrow_account_trackers(host)?.len() - 1,
);
Ok(())
}
}
}
// Returns a snapshot of `AuthorizationManager` to use for rollback.
// metering: covered
pub(crate) fn snapshot(&self, host: &Host) -> Result<AuthorizationManagerSnapshot, HostError> {
let _span = tracy_span!("snapshot auth");
let account_trackers_snapshot = match &self.mode {
AuthorizationMode::Enforcing => {
let len = self.try_borrow_account_trackers(host)?.len();
let mut snapshots = Vec::with_capacity(len);
Vec::<Option<AccountAuthorizationTrackerSnapshot>>::charge_bulk_init_cpy(
len as u64, host,
)?;
for t in self.try_borrow_account_trackers(host)?.iter() {
let sp = if let Ok(tracker) = t.try_borrow() {
Some(tracker.snapshot(host.as_budget())?)
} else {
// If tracker is borrowed, snapshotting it is a no-op
// (it can't change until we release it higher up the
// stack).
None
};
snapshots.push(sp);
}
AccountTrackersSnapshot::Enforcing(snapshots)
}
AuthorizationMode::Recording(_) => {
// All trackers should be avaialable to borrow for copy as in
// recording mode we can't have recursive authorization.
// metering: free for recording
AccountTrackersSnapshot::Recording(self.try_borrow_account_trackers(host)?.clone())
}
};
let invoker_contract_tracker_root_snapshots = self
.try_borrow_invoker_contract_trackers(host)?
.iter()
.map(|t| {
t.invocation_tracker
.root_authorized_invocation
.snapshot(host.as_budget())
})
.metered_collect::<Result<Vec<AuthorizedInvocationSnapshot>, HostError>>(host)??;
let tracker_by_address_handle = match &self.mode {
AuthorizationMode::Enforcing => None,
AuthorizationMode::Recording(recording_info) => Some(
// metering: free for recording
recording_info
.try_borrow_tracker_by_address_handle(host)?
.clone(),
),
};
Ok(AuthorizationManagerSnapshot {
account_trackers_snapshot,
invoker_contract_tracker_root_snapshots,
tracker_by_address_handle,
})
}
// Rolls back this `AuthorizationManager` to the snapshot state.
// metering: covered
pub(crate) fn rollback(
&self,
host: &Host,
snapshot: AuthorizationManagerSnapshot,
) -> Result<(), HostError> {
let _span = tracy_span!("rollback auth");
match snapshot.account_trackers_snapshot {
AccountTrackersSnapshot::Enforcing(trackers_snapshot) => {
let trackers = self.try_borrow_account_trackers(host)?;
if trackers.len() != trackers_snapshot.len() {
return Err(host.err(
ScErrorType::Auth,
ScErrorCode::InternalError,
"unexpected bad auth snapshot",
&[],
));
}
for (i, tracker) in trackers.iter().enumerate() {
if let Some(tracker_snapshot) = &trackers_snapshot[i] {
tracker
.try_borrow_mut()
.map_err(|_| {
host.err(
ScErrorType::Auth,
ScErrorCode::InternalError,
"unexpected bad auth snapshot",
&[],
)
})?
.rollback(&tracker_snapshot)?;
}
}
}
AccountTrackersSnapshot::Recording(s) => {
*self.try_borrow_account_trackers_mut(host)? = s;
}
}
let invoker_trackers = self.try_borrow_invoker_contract_trackers_mut(host)?;
if invoker_trackers.len() != snapshot.invoker_contract_tracker_root_snapshots.len() {
return Err(host.err(
ScErrorType::Auth,
ScErrorCode::InternalError,
"unexpected bad auth snapshot",
&[],
));
}
if let Some(tracker_by_address_handle) = snapshot.tracker_by_address_handle {
match &self.mode {
AuthorizationMode::Recording(recording_info) => {
*recording_info.try_borrow_tracker_by_address_handle_mut(host)? =
tracker_by_address_handle;
}
AuthorizationMode::Enforcing => (),
}
}
Ok(())
}
// metering: covered
fn push_tracker_frame(&self, host: &Host) -> Result<(), HostError> {
for tracker in self.try_borrow_account_trackers(host)?.iter() {
// Skip already borrowed trackers, these must be in the middle of
// authentication and hence don't need stack to be updated.
if let Ok(mut tracker) = tracker.try_borrow_mut() {
tracker.push_frame(host.as_budget())?;
}
}
for tracker in self
.try_borrow_invoker_contract_trackers_mut(host)?
.iter_mut()
{
tracker.push_frame(host.as_budget())?;
}
Ok(())
}
// metering: covered
pub(crate) fn push_create_contract_host_fn_frame(
&self,
host: &Host,
args: CreateContractArgs,
) -> Result<(), HostError> {
Vec::<CreateContractArgs>::charge_bulk_init_cpy(1, host)?;
self.try_borrow_call_stack_mut(host)?
.push(AuthStackFrame::CreateContractHostFn(args));