Merge branch 'dev' into sqlalchemy

# Conflicts:
#	app/main.py
This commit is contained in:
Oscar Krause 2022-12-23 08:08:35 +01:00
commit d5b51bd83c
5 changed files with 95 additions and 43 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ venv/
.idea/ .idea/
app/*.sqlite* app/*.sqlite*
app/cert/*.* app/cert/*.*
.pytest_cache

View File

@ -16,9 +16,17 @@ build:
- docker push ${CI_REGISTRY}/${CI_PROJECT_PATH}/${CI_BUILD_REF_NAME}:${CI_BUILD_REF} - docker push ${CI_REGISTRY}/${CI_PROJECT_PATH}/${CI_BUILD_REF_NAME}:${CI_BUILD_REF}
test: test:
image: python:3.10-slim-bullseye
stage: test stage: test
before_script:
- pip install -r requirements.txt
- pip install pytest httpx
- mkdir -p app/cert
- openssl genrsa -out app/cert/instance.private.pem 2048
- openssl rsa -in app/cert/instance.private.pem -outform PEM -pubout -out app/cert/instance.public.pem
- cd test
script: script:
- echo "Nothing to do ..." - pytest main.py
deploy: deploy:
stage: deploy stage: deploy

View File

@ -207,17 +207,13 @@ async def auth_v1_code(request: Request):
'iat': timegm(cur_time.timetuple()), 'iat': timegm(cur_time.timetuple()),
'exp': timegm(expires.timetuple()), 'exp': timegm(expires.timetuple()),
'challenge': j['code_challenge'], 'challenge': j['code_challenge'],
'origin_ref': j['code_challenge'], 'origin_ref': j['origin_ref'],
'key_ref': SITE_KEY_XID, 'key_ref': SITE_KEY_XID,
'kid': SITE_KEY_XID 'kid': SITE_KEY_XID
} }
auth_code = jws.sign(payload, key=jwt_encode_key, headers={'kid': payload.get('kid')}, algorithm=ALGORITHMS.RS256) auth_code = jws.sign(payload, key=jwt_encode_key, headers={'kid': payload.get('kid')}, algorithm=ALGORITHMS.RS256)
Auth.cleanup(db, origin_ref, cur_time - delta)
data = Auth(origin_ref=origin_ref, code_challenge=j['code_challenge'], expires=expires)
Auth.create(db, data)
response = { response = {
"auth_code": auth_code, "auth_code": auth_code,
"sync_timestamp": cur_time.isoformat(), "sync_timestamp": cur_time.isoformat(),
@ -235,13 +231,8 @@ async def auth_v1_token(request: Request):
j = json.loads((await request.body()).decode('utf-8')) j = json.loads((await request.body()).decode('utf-8'))
payload = jwt.decode(token=j['auth_code'], key=jwt_decode_key) payload = jwt.decode(token=j['auth_code'], key=jwt_decode_key)
code_challenge = payload['origin_ref'] origin_ref = payload['origin_ref']
logging.info(f'> [ auth ]: {origin_ref}: {j}')
entity = Auth.find_by_code_challenge(db, code_challenge)
if entity is None:
raise HTTPException(status_code=400, detail='code challenge not found')
origin_ref = entity.origin_ref
logging.info(f'> [ auth ]: {origin_ref} ({code_challenge}): {j}')
# validate the code challenge # validate the code challenge
if payload['challenge'] != b64enc(sha256(j['code_verifier'].encode('utf-8')).digest()).rstrip(b'=').decode('utf-8'): if payload['challenge'] != b64enc(sha256(j['code_verifier'].encode('utf-8')).digest()).rstrip(b'=').decode('utf-8'):
@ -256,7 +247,7 @@ async def auth_v1_token(request: Request):
'iss': 'https://cls.nvidia.org', 'iss': 'https://cls.nvidia.org',
'aud': 'https://cls.nvidia.org', 'aud': 'https://cls.nvidia.org',
'exp': timegm(access_expires_on.timetuple()), 'exp': timegm(access_expires_on.timetuple()),
'origin_ref': payload['origin_ref'], 'origin_ref': origin_ref,
'key_ref': SITE_KEY_XID, 'key_ref': SITE_KEY_XID,
'kid': SITE_KEY_XID, 'kid': SITE_KEY_XID,
} }
@ -277,14 +268,9 @@ async def auth_v1_token(request: Request):
async def leasing_v1_lessor(request: Request): async def leasing_v1_lessor(request: Request):
j, token = json.loads((await request.body()).decode('utf-8')), get_token(request) j, token = json.loads((await request.body()).decode('utf-8')), get_token(request)
code_challenge = token['origin_ref'] origin_ref = token['origin_ref']
scope_ref_list = j['scope_ref_list'] scope_ref_list = j['scope_ref_list']
logging.info(f'> [ create ]: {origin_ref}: create leases for scope_ref_list {scope_ref_list}')
entity = Auth.find_by_code_challenge(db, code_challenge)
if entity is None:
raise HTTPException(status_code=400, detail='code challenge not found')
origin_ref = entity.origin_ref
logging.info(f'> [ create ]: {origin_ref} ({code_challenge}): create leases for scope_ref_list {scope_ref_list}')
cur_time = datetime.utcnow() cur_time = datetime.utcnow()
lease_result_list = [] lease_result_list = []
@ -323,14 +309,10 @@ async def leasing_v1_lessor(request: Request):
async def leasing_v1_lessor_lease(request: Request): async def leasing_v1_lessor_lease(request: Request):
token = get_token(request) token = get_token(request)
code_challenge = token['origin_ref'] origin_ref = token['origin_ref']
entity = Auth.find_by_code_challenge(db, code_challenge) active_lease_list = list(map(lambda x: x['lease_ref'], db['lease'].find(origin_ref=origin_ref)))
if entity is None: logging.info(f'> [ leases ]: {origin_ref}: found {len(active_lease_list)} active leases')
raise HTTPException(status_code=400, detail='code challenge not found')
origin_ref = entity.origin_ref
active_lease_list = list(map(lambda x: x.lease_ref, Lease.find_by_origin_ref(db, origin_ref)))
logging.info(f'> [ leases ]: {origin_ref} ({code_challenge}): found {len(active_lease_list)} active leases')
cur_time = datetime.utcnow() cur_time = datetime.utcnow()
response = { response = {
@ -347,13 +329,8 @@ async def leasing_v1_lessor_lease(request: Request):
async def leasing_v1_lease_renew(request: Request, lease_ref: str): async def leasing_v1_lease_renew(request: Request, lease_ref: str):
token = get_token(request) token = get_token(request)
code_challenge = token['origin_ref'] origin_ref = token['origin_ref']
logging.info(f'> [ renew ]: {origin_ref}: renew {lease_ref}')
entity = Auth.find_by_code_challenge(db, code_challenge)
if entity is None:
raise HTTPException(status_code=400, detail='code challenge not found')
origin_ref = entity.origin_ref
logging.info(f'> [ renew ]: {origin_ref} ({code_challenge}): renew {lease_ref}')
entity = Lease.find_by_origin_ref_and_lease_ref(db, origin_ref, lease_ref) entity = Lease.find_by_origin_ref_and_lease_ref(db, origin_ref, lease_ref)
if entity is None: if entity is None:
@ -379,16 +356,11 @@ async def leasing_v1_lease_renew(request: Request, lease_ref: str):
async def leasing_v1_lessor_lease_remove(request: Request): async def leasing_v1_lessor_lease_remove(request: Request):
token = get_token(request) token = get_token(request)
code_challenge = token['origin_ref'] origin_ref = token['origin_ref']
entity = Auth.find_by_code_challenge(db, code_challenge)
if entity is None:
raise HTTPException(status_code=400, detail='code challenge not found')
origin_ref = entity.origin_ref
released_lease_list = list(map(lambda x: x.lease_ref, Lease.find_by_origin_ref(db, origin_ref))) released_lease_list = list(map(lambda x: x.lease_ref, Lease.find_by_origin_ref(db, origin_ref)))
deletions = Lease.ceanup(db, origin_ref) deletions = Lease.ceanup(db, origin_ref)
logging.info(f'> [ remove ]: {origin_ref} ({code_challenge}): removed {deletions} leases') logging.info(f'> [ remove ]: {origin_ref}: removed {deletions} leases')
cur_time = datetime.utcnow() cur_time = datetime.utcnow()
response = { response = {

71
test/main.py Normal file
View File

@ -0,0 +1,71 @@
from starlette.testclient import TestClient
import importlib.util
import sys
MODULE, PATH = 'main.app', '../app/main.py'
spec = importlib.util.spec_from_file_location(MODULE, PATH)
main = importlib.util.module_from_spec(spec)
sys.modules[MODULE] = main
spec.loader.exec_module(main)
client = TestClient(main.app)
def test_index():
response = client.get('/')
assert response.status_code == 200
def test_status():
response = client.get('/status')
assert response.status_code == 200
assert response.json()['status'] == 'up'
def test_client_token():
response = client.get('/client-token')
assert response.status_code == 200
def test_auth_v1_origin():
payload = {
"registration_pending": False,
"environment": {
"guest_driver_version": "guest_driver_version",
"hostname": "myhost",
"ip_address_list": ["192.168.1.123"],
"os_version": "os_version",
"os_platform": "os_platform",
"fingerprint": {"mac_address_list": ["ff:ff:ff:ff:ff:ff"]},
"host_driver_version": "host_driver_version"
},
"update_pending": False,
"candidate_origin_ref": "00112233-4455-6677-8899-aabbccddeeff"
}
response = client.post('/auth/v1/origin', json=payload)
assert response.status_code == 200
def test_auth_v1_code():
pass
def test_auth_v1_token():
pass
def test_leasing_v1_lessor():
pass
def test_leasing_v1_lessor_lease():
pass
def test_leasing_v1_lease_renew():
pass
def test_leasing_v1_lessor_lease_remove():
pass

View File

@ -1 +1 @@
VERSION=0.5 VERSION=0.6