Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add model for JWT refresh token #3268

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/3268.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add database model for JWT refresh tokens
32 changes: 32 additions & 0 deletions python/nav/models/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from nav.models.fields import VarcharField
from nav.models.profiles import Account
from nav.web.jwtgen import is_active


class APIToken(models.Model):
Expand Down Expand Up @@ -66,3 +67,34 @@ def get_absolute_url(self):

class Meta(object):
db_table = 'apitoken'


class JWTRefreshToken(models.Model):
"""Model representing a JWT refresh token. This model does not
contain the token itself, but a hash of the token that can be used
to validate the authenticity of the actual token when it is used to
generate an access token.
"""

name = VarcharField(unique=True)
description = models.TextField(null=True, blank=True)
expires = models.DateTimeField()
activates = models.DateTimeField()
last_used = models.DateTimeField(null=True, blank=True)
revoked = models.BooleanField(default=False)
hash = VarcharField()

def __str__(self):
return self.name

def is_active(self) -> bool:
"""Returns True if the token is active. A token is considered active when
`expires` is in the future and `activates` is in the past or matches
the current time.
"""
return is_active(self.expires.timestamp(), self.activates.timestamp())

class Meta(object):
"""Meta class"""

db_table = 'jwtrefreshtoken'
10 changes: 10 additions & 0 deletions python/nav/models/sql/changes/sc.05.13.0001.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE manage.jwtrefreshtoken (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL UNIQUE,
description VARCHAR,
expires TIMESTAMP NOT NULL,
activates TIMESTAMP NOT NULL,
last_used TIMESTAMP,
revoked BOOLEAN NOT NULL DEFAULT FALSE,
hash VARCHAR NOT NULL
);
20 changes: 19 additions & 1 deletion python/nav/web/jwtgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

from nav.jwtconf import JWTConf, ACCESS_TOKEN_EXPIRE_DELTA, REFRESH_TOKEN_EXPIRE_DELTA

# Alias for datetime.now for mocking purposes
get_now = datetime.now


def generate_access_token(token_data: Optional[dict[str, Any]] = None) -> str:
"""Generates and returns an access token in JWT format.
Expand Down Expand Up @@ -34,7 +37,7 @@ def _generate_token(
else:
new_token = dict(token_data)

now = datetime.now(timezone.utc)
now = get_now(timezone.utc)
name = JWTConf().get_nav_name()
updated_claims = {
'exp': (now + expiry_delta).timestamp(),
Expand All @@ -49,3 +52,18 @@ def _generate_token(
new_token, JWTConf().get_nav_private_key(), algorithm="RS256"
)
return encoded_token


def is_active(exp: float, nbf: float) -> bool:
"""
Takes `exp` (expiration time) and `nbf` (not before time) as POSIX timestamps.
These represent the claims of a JWT token. `exp` should be the expiration
time of the token and `nbf` should be the time when the token becomes active.

Returns True if `exp` is in the future and `nbf` is in the past or matches
the current time.
"""
now = get_now()
expires = datetime.fromtimestamp(exp)
activates = datetime.fromtimestamp(nbf)
return now >= activates and now < expires
64 changes: 64 additions & 0 deletions tests/unittests/models/jwtrefreshtoken_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from datetime import datetime, timedelta
from unittest.mock import patch

from nav.models.api import JWTRefreshToken


class TestIsActive:
def test_when_token_activates_in_the_future_it_should_return_false(self):
now = datetime.now()
token = JWTRefreshToken(
name="testtoken",
hash="dummyhash",
expires=now + timedelta(hours=1),
activates=now + timedelta(hours=1),
)
assert not token.is_active()

def test_when_token_expired_in_the_past_it_should_return_false(self):
now = datetime.now()
token = JWTRefreshToken(
name="testtoken",
hash="dummyhash",
expires=now - timedelta(hours=1),
activates=now - timedelta(hours=1),
)
assert not token.is_active()

def test_when_token_activated_in_the_past_and_expires_in_the_future_it_should_return_true(
self,
):
now = datetime.now()
token = JWTRefreshToken(
name="testtoken",
hash="dummyhash",
expires=now + timedelta(hours=1),
activates=now - timedelta(hours=1),
)
assert token.is_active()

def test_when_token_activates_now_and_expires_in_the_future_it_should_return_true(
self,
):
now = datetime.now()
token = JWTRefreshToken(
name="testtoken",
hash="dummyhash",
expires=now + timedelta(hours=1),
activates=now,
)
# Make sure the value we use for `activates` here matches
# the `now` value in jwtgen.is_active
with patch('nav.web.jwtgen.get_now', return_value=now):
assert token.is_active()


def test_string_representation_should_match_name():
now = datetime.now()
token = JWTRefreshToken(
name="testtoken",
hash="dummyhash",
expires=now + timedelta(hours=1),
activates=now - timedelta(hours=1),
)
assert str(token) == token.name
33 changes: 31 additions & 2 deletions tests/unittests/web/jwtgen_test.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import pytest
from unittest.mock import Mock, patch
from datetime import datetime
from datetime import datetime, timedelta

import jwt

from nav.web.jwtgen import generate_access_token, generate_refresh_token
from nav.web.jwtgen import generate_access_token, generate_refresh_token, is_active


class TestTokenGeneration:
Expand Down Expand Up @@ -55,6 +55,35 @@ def test_token_type_should_be_refresh_token(self):
assert data['token_type'] == "refresh_token"


class TestIsActive:
def test_when_nbf_is_in_the_future_it_should_return_false(self):
now = datetime.now()
nbf = now + timedelta(hours=1)
exp = now + timedelta(hours=1)
assert not is_active(exp.timestamp(), nbf.timestamp())

def test_when_exp_is_in_the_past_it_should_return_false(self):
now = datetime.now()
nbf = now - timedelta(hours=1)
exp = now - timedelta(hours=1)
assert not is_active(exp.timestamp(), nbf.timestamp())

def test_when_nbf_is_in_the_past_and_exp_is_in_the_future_it_should_return_true(
self,
):
now = datetime.now()
nbf = now - timedelta(hours=1)
exp = now + timedelta(hours=1)
assert is_active(exp.timestamp(), nbf.timestamp())

def test_when_nbf_is_now_and_exp_is_in_the_future_it_should_return_true(self):
now = datetime.now()
exp = now + timedelta(hours=1)
# Make sure the value we use for `nbf` here matches the `now` value in jwtgen.is_active
with patch('nav.web.jwtgen.get_now', return_value=now):
assert is_active(exp.timestamp(), now.timestamp())


@pytest.fixture(scope="module", autouse=True)
def jwtconf_mock(private_key, nav_name) -> str:
"""Mocks the get_nav_name and get_nav_private_key functions for
Expand Down
Loading