jwt.py 15.8 KB
Newer Older
Simo Sorce's avatar
Simo Sorce committed
1 2
# Copyright (C) 2015  JWCrypto Project Contributors - see LICENSE file

3 4 5 6 7
import time
import uuid

from six import string_types

8
from jwcrypto.common import JWException, json_decode, json_encode
Simo Sorce's avatar
Simo Sorce committed
9
from jwcrypto.jwe import JWE
10
from jwcrypto.jwk import JWK, JWKSet
Simo Sorce's avatar
Simo Sorce committed
11
from jwcrypto.jws import JWS
Simo Sorce's avatar
Simo Sorce committed
12 13


14 15 16 17 18 19 20 21 22 23 24
# RFC 7519 - 4.1
# name: description
JWTClaimsRegistry = {'iss': 'Issuer',
                     'sub': 'Subject',
                     'aud': 'Audience',
                     'exp': 'Expiration Time',
                     'nbf': 'Not Before',
                     'iat': 'Issued At',
                     'jti': 'JWT ID'}


25
class JWTExpired(JWException):
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    """Json Web Token is expired.

    This exception is raised when a token is expired accoring to its claims.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Token expired'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTExpired, self).__init__(msg)


42
class JWTNotYetValid(JWException):
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    """Json Web Token is not yet valid.

    This exception is raised when a token is not valid yet according to its
    claims.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Token not yet valid'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTNotYetValid, self).__init__(msg)


60
class JWTMissingClaim(JWException):
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    """Json Web Token claim is invalid.

    This exception is raised when a claim does not match the expected value.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Invalid Claim Value'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTMissingClaim, self).__init__(msg)


77
class JWTInvalidClaimValue(JWException):
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    """Json Web Token claim is invalid.

    This exception is raised when a claim does not match the expected value.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Invalid Claim Value'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTInvalidClaimValue, self).__init__(msg)


94
class JWTInvalidClaimFormat(JWException):
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    """Json Web Token claim format is invalid.

    This exception is raised when a claim is not in a valid format.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Invalid Claim Format'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTInvalidClaimFormat, self).__init__(msg)


111
class JWTMissingKeyID(JWException):
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    """Json Web Token is missing key id.

    This exception is raised when trying to decode a JWT with a key set
    that does not have a kid value in its header.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Missing Key ID'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTMissingKeyID, self).__init__(msg)


129
class JWTMissingKey(JWException):
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    """Json Web Token is using a key not in the key set.

    This exception is raised if the key that was used is not available
    in the passed key set.
    """

    def __init__(self, message=None, exception=None):
        msg = None
        if message:
            msg = str(message)
        else:
            msg = 'Missing Key'
        if exception:
            msg += ' {%s}' % str(exception)
        super(JWTMissingKey, self).__init__(msg)


Simo Sorce's avatar
Simo Sorce committed
147
class JWT(object):
Simo Sorce's avatar
Simo Sorce committed
148 149 150 151
    """JSON Web token object

    This object represent a generic token.
    """
Simo Sorce's avatar
Simo Sorce committed
152

153
    def __init__(self, header=None, claims=None, jwt=None, key=None,
154
                 algs=None, default_claims=None, check_claims=None):
Simo Sorce's avatar
Simo Sorce committed
155 156 157 158 159 160
        """Creates a JWT object.

        :param header: A dict or a JSON string with the JWT Header data.
        :param claims: A dict or a string withthe JWT Claims data.
        :param jwt: a 'raw' JWT token
        :param key: A (:class:`jwcrypto.jwk.JWK`) key to deserialize
Michael Boulton's avatar
Michael Boulton committed
161
         the token. A (:class:`jwcrypto.jwk.JWKSet`) can also be used.
162
        :param algs: An optional list of allowed algorithms
163 164 165 166 167 168 169
        :param default_claims: An optional dict with default values for
         registred claims. A None value for NumericDate type claims
         will cause generation according to system time. Only the values
         fro RFC 7519 - 4.1 are evaluated.
        :param check_claims: An optional dict of claims that must be
         present in the token, if the value is not None the claim must
         match exactly.
Simo Sorce's avatar
Simo Sorce committed
170 171 172 173 174

        Note: either the header,claims or jwt,key parameters should be
        provided as a deserialization operation (which occurs if the jwt
        is provided will wipe any header os claim provided by setting
        those obtained from the deserialization of the jwt token.
175 176 177 178 179

        Note: if check_claims is not provided the 'exp' and 'nbf' claims
        are checked if they are set on the token but not enforced if not
        set. Any other RFC 7519 registered claims are checked only for
        format conformance.
Simo Sorce's avatar
Simo Sorce committed
180
        """
Simo Sorce's avatar
Simo Sorce committed
181 182 183 184

        self._header = None
        self._claims = None
        self._token = None
185
        self._algs = algs
186 187 188 189
        self._reg_claims = None
        self._check_claims = None
        self._leeway = 60  # 1 minute clock skew allowed
        self._validity = 600  # 10 minutes validity (up to 11 with leeway)
Simo Sorce's avatar
Simo Sorce committed
190 191 192 193

        if header:
            self.header = header

194 195 196 197 198 199
        if default_claims is not None:
            self._reg_claims = default_claims

        if check_claims is not None:
            self._check_claims = check_claims

200 201 202
        if claims:
            self.claims = claims

Simo Sorce's avatar
Simo Sorce committed
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
        if jwt is not None:
            self.deserialize(jwt, key)

    @property
    def header(self):
        if self._header is None:
            raise KeyError("'header' not set")
        return self._header

    @header.setter
    def header(self, h):
        if isinstance(h, dict):
            self._header = json_encode(h)
        else:
            self._header = h

    @property
    def claims(self):
        if self._claims is None:
            raise KeyError("'claims' not set")
        return self._claims

    @claims.setter
    def claims(self, c):
        if isinstance(c, dict):
228
            self._add_default_claims(c)
Simo Sorce's avatar
Simo Sorce committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            self._claims = json_encode(c)
        else:
            self._claims = c

    @property
    def token(self):
        return self._token

    @token.setter
    def token(self, t):
        if isinstance(t, JWS) or isinstance(t, JWE) or isinstance(t, JWT):
            self._token = t
        else:
            raise TypeError("Invalid token type, must be one of JWS,JWE,JWT")

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
    @property
    def leeway(self):
        return self._leeway

    @leeway.setter
    def leeway(self, l):
        self._leeway = int(l)

    @property
    def validity(self):
        return self._validity

    @validity.setter
    def validity(self, v):
        self._validity = int(v)

    def _add_optional_claim(self, name, claims):
        if name in claims:
            return
        val = self._reg_claims.get(name, None)
        if val is not None:
            claims[name] = val

    def _add_time_claim(self, name, claims, defval):
        if name in claims:
            return
        if name in self._reg_claims:
            if self._reg_claims[name] is None:
                claims[name] = defval
            else:
                claims[name] = self._reg_claims[name]

    def _add_jti_claim(self, claims):
        if 'jti' in claims or 'jti' not in self._reg_claims:
            return
        claims['jti'] = uuid.uuid4()

    def _add_default_claims(self, claims):
        if self._reg_claims is None:
            return

        now = int(time.time())
        self._add_optional_claim('iss', claims)
        self._add_optional_claim('sub', claims)
        self._add_optional_claim('aud', claims)
        self._add_time_claim('exp', claims, now + self.validity)
        self._add_time_claim('nbf', claims, now)
        self._add_time_claim('iat', claims, now)
        self._add_jti_claim(claims)

    def _check_string_claim(self, name, claims):
        if name not in claims:
            return
        if not isinstance(claims[name], string_types):
            raise JWTInvalidClaimFormat("Claim %s is not a StringOrURI type")

    def _check_array_or_string_claim(self, name, claims):
        if name not in claims:
            return
        if isinstance(claims[name], list):
            if any(not isinstance(claim, string_types) for claim in claims):
                raise JWTInvalidClaimFormat(
                    "Claim %s contains non StringOrURI types" % (name, ))
        elif not isinstance(claims[name], string_types):
            raise JWTInvalidClaimFormat(
                "Claim %s is not a StringOrURI type" % (name, ))

    def _check_integer_claim(self, name, claims):
        if name not in claims:
            return
        try:
            int(claims[name])
        except ValueError:
            raise JWTInvalidClaimFormat(
                "Claim %s is not an integer" % (name, ))

    def _check_exp(self, claim, limit, leeway):
        if claim < limit - leeway:
            raise JWTExpired('Expired at %d, time: %d(leeway: %d)' % (
                             claim, limit, leeway))

    def _check_nbf(self, claim, limit, leeway):
        if claim > limit + leeway:
            raise JWTNotYetValid('Valid from %d, time: %d(leeway: %d)' % (
                                 claim, limit, leeway))

    def _check_default_claims(self, claims):
        self._check_string_claim('iss', claims)
        self._check_string_claim('sub', claims)
        self._check_array_or_string_claim('aud', claims)
        self._check_integer_claim('exp', claims)
        self._check_integer_claim('nbf', claims)
        self._check_integer_claim('iat', claims)
        self._check_string_claim('jti', claims)

        if self._check_claims is None:
            if 'exp' in claims:
                self._check_exp(claims['exp'], time.time(), self._leeway)
            if 'nbf' in claims:
343
                self._check_nbf(claims['nbf'], time.time(), self._leeway)
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

    def _check_provided_claims(self):
        # check_claims can be set to False to skip any check
        if self._check_claims is False:
            return

        try:
            claims = json_decode(self.claims)
            if not isinstance(claims, dict):
                raise ValueError()
        except ValueError:
            if self._check_claims is not None:
                raise JWTInvalidClaimFormat(
                    "Claims check requested but claims is not a json dict")
            return

        self._check_default_claims(claims)

        if self._check_claims is None:
            return

        for name, value in self._check_claims.items():
            if name not in claims:
                raise JWTMissingClaim("Claim %s is missing" % (name, ))

            if name in ['iss', 'sub', 'jti']:
                if value is not None and value != claims[name]:
                    raise JWTInvalidClaimValue(
                        "Invalid '%s' value. Expected '%s' got '%s'" % (
                            name, value, claims[name]))

            elif name == 'aud':
                if value is not None:
                    if value == claims[name]:
                        continue
                    if isinstance(claims[name], list):
                        if value in claims[name]:
                            continue
                    raise JWTInvalidClaimValue(
                        "Invalid '%s' value. Expected '%s' in '%s'" % (
                            name, value, claims[name]))

            elif name == 'exp':
                if value is not None:
                    self._check_exp(claims[name], value, 0)
                else:
                    self._check_exp(claims[name], time.time(), self._leeway)

            elif name == 'nbf':
                if value is not None:
                    self._check_nbf(claims[name], value, 0)
                else:
                    self._check_nbf(claims[name], time.time(), self._leeway)

            else:
                if value is not None and value != claims[name]:
                    raise JWTInvalidClaimValue(
401
                        "Invalid '%s' value. Expected '%s' got '%s'" % (
402 403
                            name, value, claims[name]))

Simo Sorce's avatar
Simo Sorce committed
404
    def make_signed_token(self, key):
Simo Sorce's avatar
Simo Sorce committed
405 406 407 408 409 410 411 412 413
        """Signs the payload.

        Creates a JWS token with the header as the JWS protected header and
        the claims as the payload. See (:class:`jwcrypto.jws.JWS`) for
        details on the exceptions that may be reaised.

        :param key: A (:class:`jwcrypto.jwk.JWK`) key.
        """

Simo Sorce's avatar
Simo Sorce committed
414 415 416 417 418
        t = JWS(self.claims)
        t.add_signature(key, protected=self.header)
        self.token = t

    def make_encrypted_token(self, key):
Simo Sorce's avatar
Simo Sorce committed
419 420 421 422 423 424 425 426 427
        """Encrypts the payload.

        Creates a JWE token with the header as the JWE protected header and
        the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for
        details on the exceptions that may be reaised.

        :param key: A (:class:`jwcrypto.jwk.JWK`) key.
        """

Simo Sorce's avatar
Simo Sorce committed
428 429 430 431 432
        t = JWE(self.claims, self.header)
        t.add_recipient(key)
        self.token = t

    def deserialize(self, jwt, key=None):
Simo Sorce's avatar
Simo Sorce committed
433 434 435 436 437 438 439
        """Deserialize a JWT token.

        NOTE: Destroys any current status and tries to import the raw
        token provided.

        :param jwt: a 'raw' JWT token.
        :param key: A (:class:`jwcrypto.jwk.JWK`) verification or
Michael Boulton's avatar
Michael Boulton committed
440
         decryption key, or a (:class:`jwcrypto.jwk.JWKSet`) that
441
         contains a key indexed by the 'kid' header.
Simo Sorce's avatar
Simo Sorce committed
442
        """
Simo Sorce's avatar
Simo Sorce committed
443 444 445 446 447 448 449 450
        c = jwt.count('.')
        if c == 2:
            self.token = JWS()
        elif c == 4:
            self.token = JWE()
        else:
            raise ValueError("Token format unrecognized")

451 452 453 454
        # Apply algs restrictions if any, before performing any operation
        if self._algs:
            self.token.allowed_algs = self._algs

Simo Sorce's avatar
Simo Sorce committed
455 456
        # now deserialize and also decrypt/verify (or raise) if we
        # have a key
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
        if key is None:
            self.token.deserialize(jwt, None)
        elif isinstance(key, JWK):
            self.token.deserialize(jwt, key)
        elif isinstance(key, JWKSet):
            self.token.deserialize(jwt, None)
            if 'kid' not in self.token.jose_header:
                raise JWTMissingKeyID('No key ID in JWT header')

            token_key = key.get_key(self.token.jose_header['kid'])
            if not token_key:
                raise JWTMissingKey('Key ID %s not in key set'
                                    % self.token.jose_header['kid'])

            if isinstance(self.token, JWE):
                self.token.decrypt(token_key)
            elif isinstance(self.token, JWS):
                self.token.verify(token_key)
            else:
                raise RuntimeError("Unknown Token Type")
        else:
            raise ValueError("Unrecognized Key Type")
Simo Sorce's avatar
Simo Sorce committed
479 480 481 482

        if key is not None:
            self.header = self.token.jose_header
            self.claims = self.token.payload.decode('utf-8')
483
            self._check_provided_claims()
Simo Sorce's avatar
Simo Sorce committed
484 485

    def serialize(self, compact=True):
Simo Sorce's avatar
Simo Sorce committed
486 487 488 489 490 491 492 493 494 495
        """Serializes the object into a JWS token.

        :param compact(boolean): must be True.

        Note: the compact parameter is provided for general compatibility
        with the serialize() functions of :class:`jwcrypto.jws.JWS` and
        :class:`jwcrypto.jwe.JWE` so that these objects can all be used
        interchangeably. However the only valid JWT representtion is the
        compact representation.
        """
Simo Sorce's avatar
Simo Sorce committed
496
        return self.token.serialize(compact)