-
Notifications
You must be signed in to change notification settings - Fork 6
/
interface.py
573 lines (470 loc) · 20.1 KB
/
interface.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
"""
Copyright 2022 Ledger SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from abc import ABC, abstractmethod
from contextlib import contextmanager
from enum import Enum, auto
from pathlib import Path
from types import TracebackType
from typing import Optional, Type, Generator, Any, Iterable
from ragger.firmware import Firmware
from ragger.utils import pack_APDU, RAPDU, Crop
from ragger.logger import get_default_logger, get_apdu_logger, set_apdu_logger_file
class RaisePolicy(Enum):
RAISE_NOTHING = auto()
RAISE_ALL_BUT_0x9000 = auto()
RAISE_ALL = auto()
RAISE_CUSTOM = auto()
class BackendInterface(ABC):
def __init__(self,
firmware: Firmware,
log_apdu_file: Optional[Path] = None,
whitelisted_status: Iterable = ()):
"""Initializes the Backend
:param firmware: Which Firmware will be managed
:type firmware: Firmware
"""
self._firmware = firmware
self._last_async_response: Optional[RAPDU] = None
self.raise_policy = RaisePolicy.RAISE_ALL_BUT_0x9000
if log_apdu_file:
set_apdu_logger_file(log_apdu_file=log_apdu_file)
self.logger = get_default_logger()
self.apdu_logger = get_apdu_logger()
self.whitelisted_status = whitelisted_status
@property
def firmware(self) -> Firmware:
"""
:return: The currently managed Firmware.
:rtype: Firmware
"""
return self._firmware
@property
def last_async_response(self) -> Optional[RAPDU]:
"""
:return: The last RAPDU received after a call to `exchange_async` or
`exchange_async_raw`. `None` if no called was made, or if it
resulted into an exception throw.
:rtype: RAPDU
"""
return self._last_async_response
@abstractmethod
def __enter__(self) -> "BackendInterface":
raise NotImplementedError
@abstractmethod
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]):
raise NotImplementedError
def handle_usb_reset(self) -> None:
"""
Inform the backend that it should handle an USB reset.
This happen when an app is called as a lib and have to reinit the USB stack.
:return: None
:rtype: NoneType
"""
raise NotImplementedError
def is_raise_required(self, rapdu: RAPDU) -> bool:
"""
:return: If the given status is considered valid or not
:rtype: bool
"""
return ((self.raise_policy == RaisePolicy.RAISE_ALL)
or ((self.raise_policy == RaisePolicy.RAISE_ALL_BUT_0x9000) and
(rapdu.status != 0x9000))
or ((self.raise_policy == RaisePolicy.RAISE_CUSTOM) and
(rapdu.status not in self.whitelisted_status)))
def send(self, cla: int, ins: int, p1: int = 0, p2: int = 0, data: bytes = b"") -> None:
"""
Formats then sends an APDU to the backend.
:param cla: The application ID
:type cla: int
:param ins: The command ID
:type ins: int
:param p1: First instruction parameter, defaults to 0
:type p1: int
:param p1: Second instruction parameter, defaults to 0
:type p1: int
:param data: Command data
:type data: bytes
:return: None
:rtype: NoneType
"""
return self.send_raw(pack_APDU(cla, ins, p1, p2, data))
@abstractmethod
def send_raw(self, data: bytes = b"") -> None:
"""
Sends the given APDU to the backend.
Every part of the APDU (including length) are the caller's
responsibility
:param data: The APDU message
:type data: bytes
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def receive(self) -> RAPDU:
"""
Receives a response APDU from the backend.
Calling this method implies a command APDU has been previously sent
to the backend, and a response is expected.
:raises ExceptionRAPDU: If the `raises` attribute is True, this method
will raise if the backend returns a status code
not registered as a `valid_statuses`
:return: The APDU response
:rtype: RAPDU
"""
raise NotImplementedError
def exchange(self,
cla: int,
ins: int,
p1: int = 0,
p2: int = 0,
data: bytes = b"",
tick_timeout: int = 5 * 60 * 10) -> RAPDU:
"""
Formats and sends an APDU to the backend, then receives its response.
The length is automatically added to the APDU message.
:param cla: The application ID
:type cla: int
:param ins: The command ID
:type ins: int
:param p1: First instruction parameter, defaults to 0
:type p1: int
:param p1: Second instruction parameter, defaults to 0
:type p1: int
:param data: Command data
:type data: bytes
:raises ExceptionRAPDU: If the `raises` attribute is True, this method
will raise if the backend returns a status code
not registered as a `valid_statuses`
:return: The APDU response
:rtype: RAPDU
"""
return self.exchange_raw(pack_APDU(cla, ins, p1, p2, data), tick_timeout=tick_timeout)
@abstractmethod
def exchange_raw(self, data: bytes = b"", tick_timeout: int = 5 * 60 * 10) -> RAPDU:
"""
Sends the given APDU to the backend, then receives its response.
Every part of the APDU (including length) are the caller's
responsibility
:param data: The APDU message
:type data: bytes
:raises ExceptionRAPDU: If the `raises` attribute is True, this method
will raise if the backend returns a status code
not registered as a `valid_statuses`
:return: The APDU response
:rtype: RAPDU
"""
raise NotImplementedError
@contextmanager
def exchange_async(self,
cla: int,
ins: int,
p1: int = 0,
p2: int = 0,
data: bytes = b"") -> Generator[None, None, None]:
"""
Formats and sends an APDU to the backend, then gives the control back to
the caller.
This can be useful to still control a device when it has not responded
yet, for instance when a UI validation is requested.
The context manager does not yield anything. Interaction through the
backend instance is still possible.
:param cla: The application ID
:type cla: int
:param ins: The command ID
:type ins: int
:param p1: First instruction parameter, defaults to 0
:type p1: int
:param p1: Second instruction parameter, defaults to 0
:type p1: int
:param data: Command data
:type data: bytes
:raises ExceptionRAPDU: If the `raises` attribute is True, this method
will raise if the backend returns a status code
not registered as a `valid_statuses`
:return: None
:rtype: NoneType
"""
with self.exchange_async_raw(pack_APDU(cla, ins, p1, p2, data)):
yield
@contextmanager
@abstractmethod
def exchange_async_raw(self, data: bytes = b"") -> Generator[None, None, None]:
"""
Sends the given APDU to the backend, then gives the control back to the
caller.
Every part of the APDU (including length) are the caller's
responsibility
:param data: The APDU message
:type data: bytes
:raises ExceptionRAPDU: If the `raises` attribute is True, this method
will raise if the backend returns a status code
not registered a a `valid_statuses`
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def right_click(self) -> None:
"""
Performs a right click on the device.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def left_click(self) -> None:
"""
Performs a left click on the device.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def both_click(self) -> None:
"""
Performs a click on both buttons of the device.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def finger_touch(self, x: int = 0, y: int = 0, delay: float = 0.5) -> None:
"""
Performs a finger touch on the device screen.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param x: The x coordinate of the finger touch.
:type x: int
:param y: The y coordinate of the finger touch.
:type y: int
:param delay: Delay between finger touch press and release actions.
:type delay: float
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def finger_swipe(self,
x: int = 0,
y: int = 0,
direction: str = "left",
delay: float = 0.5) -> None:
"""
Performs a finger swipe on the device screen.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param x: The x coordinate of the initial finger touch.
:type x: int
:param y: The y coordinate of the initial finger touch.
:type y: int
:param direction: The direction where to orientate the swipe. Must be in: ['up', 'down',
'left', 'right]
:type direction: str
:param delay: Delay between finger touch press and release actions.
:type delay: float
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def compare_screen_with_snapshot(self,
golden_snap_path: Path,
crop: Optional[Crop] = None,
tmp_snap_path: Optional[Path] = None,
golden_run: bool = False) -> bool:
"""
Compare the current device screen with the provided snapshot.
:param golden_snap_path: The path to the snap to compare the screen
device with
:type golden_snap_path: Path
:param crop: Optional crop options to use for the comparison
:type crop: Crop
:param tmp_snap_path: Optional path where to store the screen snap used
for the comparison
:type tmp_snap_path: Path
:param golden_run: Optional option to save the current screen as golden
instead of comparing it.
:type golden_run: bool
:return: True if matches else False
:rtype: bool
"""
raise NotImplementedError
@abstractmethod
def wait_for_screen_change(self, timeout: float = 10.0) -> None:
"""
Wait until the screen content changes compared to the last
reference stored internally by the backend.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param timeout: Maximum time to wait for a screen change before an
exception is raised.
:type timeout: float
:return: None
:rtype: NoneType
"""
raise NotImplementedError
def wait_for_home_screen(self, timeout: float = 10.0) -> None:
"""
Wait until the screen content is equal to the app home screen.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param timeout: Maximum time to wait for a screen change before an
exception is raised.
:type timeout: float
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def compare_screen_with_text(self, text: str) -> bool:
"""
Checks if the current screen content contains the text
string provided.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param text:
:type text: str
:return: True if the content contains the string, False
otherwise.
:rtype: bool
"""
raise NotImplementedError
@abstractmethod
def wait_for_text_on_screen(self, text: str, timeout: float = 10.0) -> None:
"""
Wait until the screen content contains the text string provider.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param text:
:type text: str
:param timeout: Maximum time to wait for a screen change before an
exception is raised.
:type timeout: float
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def wait_for_text_not_on_screen(self, text: str, timeout: float = 10.0) -> None:
"""
Wait until the screen content does not contains the text string provider.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:param text:
:type text: str
:param timeout: Maximum time to wait for a screen change before an
exception is raised.
:type timeout: float
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def get_current_screen_content(self) -> Any:
"""
Returns the current screen content.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`), but the instrumentation flow will probably
get stuck (on further call to `receive` for instance) until the expected
action is performed on the device.
:return: Current screen content as an opaque type depending on backend
implem.
:rtype: Any
"""
raise NotImplementedError
@abstractmethod
def pause_ticker(self) -> None:
"""
Pause the backend time.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`).
:return: None
:rtype: NoneType
"""
raise NotImplementedError
@abstractmethod
def resume_ticker(self) -> None:
"""
Resume the backend time.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`).
:return: None
:rtype: NoneType
"""
pass
@abstractmethod
def send_tick(self) -> None:
"""
Request the backend to increase time by a single step.
This method may be left void on backends connecting to physical devices,
where a physical interaction must be performed instead.
This will prevent the instrumentation to fail (the void method won't
raise `NotImplementedError`).
:return: None
:rtype: NoneType
"""
pass