aristanetworks / cloudvision-ztpaas-utils

Utilities for ZTP as a Service with CloudVision
Apache License 2.0
11 stars 14 forks source link

Syntax of getExpiryFromToken fails on EoS < 4.30.0 #16

Closed alexeygorbunov closed 6 months ago

alexeygorbunov commented 6 months ago

Faced exception

Apr 25 22:31:14 ztp-yr404 Could not parse the enrollment token. Continuing with ZTP.

How to recreate

Details

def getExpiryFromToken(token):
   try:
      # jwt token has 3 parts (header, payload, sign) seperated by a '.'
      # payload has 'exp' field which contains the token expiry time in epoch
      token_payload = token.split(".")[1]
      token_payload_decoded = str(base64.b64decode(token_payload + "=="), "utf-8")  #<<<<<<<<<<<<<<<<<<<<<<<<<<
      payload = json.loads(token_payload_decoded)
      return payload["exp"], True
   except:
      log("Could not parse the enrollment token. Continuing with ZTP.")
      return -1, False

Example:

[admin@ztp-yr404 ~]$ python
Python 2.7.18 (default, Apr 21 2020, 18:22:01) 
[GCC 8.4.0 20200304 (Red Hat 8.4.0-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version
'2.7.18 (default, Apr 21 2020, 18:22:01) \n[GCC 8.4.0 20200304 (Red Hat 8.4.0-4)]'
>>> import base64
>>> str(base64.b64decode("dGVzdGxpbmUK"), "utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: str() takes at most 1 argument (2 given)

Solution

Use decode method instead as It is compatible with both Python2 and 3

token_payload_decoded = str(base64.b64decode(token_payload + "==").decode("utf-8"))