Refactor auth code to be cleaner and more extensible

We move all the auth handling, serialization and deserialization into a new AuthContext interface, and then standardize a registration model for handling of specific auth context types (user, robot, token, etc).
This commit is contained in:
Joseph Schorr 2018-01-05 16:27:03 -05:00
parent 8ba2e71fb1
commit e220b50543
31 changed files with 822 additions and 436 deletions

View file

@ -11,7 +11,7 @@ from semantic_version import Spec
import features
from app import app, metric_queue, get_app_url, license_validator
from auth.auth_context import get_grant_context
from auth.auth_context import get_authenticated_context
from auth.permissions import (
ReadRepositoryPermission, ModifyRepositoryPermission, AdministerRepositoryPermission)
from auth.registry_jwt_auth import process_registry_jwt_auth, get_auth_headers
@ -146,7 +146,7 @@ def v2_support_enabled():
response = make_response('true', 200)
if get_grant_context() is None:
if get_authenticated_context() is None:
response = make_response('true', 401)
response.headers.extend(get_auth_headers())

View file

@ -2,7 +2,8 @@ import features
from flask import jsonify
from auth.registry_jwt_auth import process_registry_jwt_auth, get_granted_entity
from auth.auth_context import get_authenticated_user
from auth.registry_jwt_auth import process_registry_jwt_auth
from endpoints.decorators import anon_protect
from endpoints.v2 import v2_bp, paginate
from endpoints.v2.models_pre_oci import data_model as model
@ -13,11 +14,7 @@ from endpoints.v2.models_pre_oci import data_model as model
@anon_protect
@paginate()
def catalog_search(limit, offset, pagination_callback):
username = None
entity = get_granted_entity()
if entity:
username = entity.user.username
username = get_authenticated_user().username if get_authenticated_user() else None
include_public = bool(features.PUBLIC_CATALOG)
visible_repositories = model.get_visible_repositories(username, limit + 1, offset,
include_public=include_public)

View file

@ -6,6 +6,7 @@ from flask import url_for
from playhouse.test_utils import assert_query_count
from app import instance_keys, app as realapp
from auth.auth_context_type import ValidatedAuthContext
from data import model
from data.cache import InMemoryDataModelCache
from data.database import ImageStorageLocation
@ -34,7 +35,7 @@ def test_blob_caching(method, endpoint, client, app):
'actions': ['pull'],
}]
context, subject = build_context_and_subject(user=user)
context, subject = build_context_and_subject(ValidatedAuthContext(user=user))
token = generate_bearer_token(realapp.config['SERVER_HOSTNAME'], subject, context, access, 600,
instance_keys)

View file

@ -8,6 +8,7 @@ from flask import url_for
from playhouse.test_utils import count_queries
from app import instance_keys, app as realapp
from auth.auth_context_type import ValidatedAuthContext
from data import model
from endpoints.test.shared import conduct_call
from util.security.registry_jwt import generate_bearer_token, build_context_and_subject
@ -28,7 +29,7 @@ def test_e2e_query_count_manifest_norewrite(client, app):
'actions': ['pull', 'push'],
}]
context, subject = build_context_and_subject(user=user)
context, subject = build_context_and_subject(ValidatedAuthContext(user=user))
token = generate_bearer_token(realapp.config['SERVER_HOSTNAME'], subject, context, access, 600,
instance_keys)

View file

@ -2,12 +2,11 @@ import logging
import re
from cachetools import lru_cache
from flask import request, jsonify, abort
from flask import request, jsonify
import features
from app import app, userevents, instance_keys
from auth.auth_context import (get_authenticated_user, get_validated_token,
get_validated_oauth_token, get_validated_app_specific_token)
from auth.auth_context import get_authenticated_context, get_authenticated_user
from auth.decorators import process_basic_auth
from auth.permissions import (ModifyRepositoryPermission, ReadRepositoryPermission,
CreateRepositoryPermission, AdministerRepositoryPermission)
@ -48,21 +47,14 @@ def generate_registry_jwt(auth_result):
scope_param = request.args.get('scope') or ''
logger.debug('Scope request: %s', scope_param)
user = get_authenticated_user()
logger.debug('Authenticated user: %s', user)
token = get_validated_token()
logger.debug('Authenticated token: %s', token)
oauthtoken = get_validated_oauth_token()
logger.debug('Authenticated OAuth token: %s', oauthtoken)
appspecifictoken = get_validated_app_specific_token()
logger.debug('Authenticated app specific token: %s', appspecifictoken)
auth_header = request.headers.get('authorization', '')
auth_credentials_sent = bool(auth_header)
if auth_credentials_sent and not user and not token:
has_valid_auth_context = False
if get_authenticated_context():
has_valid_auth_context = not get_authenticated_context().is_anonymous
if auth_credentials_sent and not has_valid_auth_context:
# The auth credentials sent for the user are invalid.
raise InvalidLogin(auth_result.error_message)
@ -109,9 +101,9 @@ def generate_registry_jwt(auth_result):
'This repository is for managing %s resources ' + 'and not container images.') % repo.kind)
if 'push' in actions:
# If there is no valid user or token, then the repository cannot be
# Check if there is a valid user or token, as otherwise the repository cannot be
# accessed.
if user is not None or token is not None:
if has_valid_auth_context:
# Lookup the repository. If it exists, make sure the entity has modify
# permission. Otherwise, make sure the entity has create permission.
if repo:
@ -123,6 +115,7 @@ def generate_registry_jwt(auth_result):
else:
logger.debug('No permission to modify repository %s/%s', namespace, reponame)
else:
user = get_authenticated_user()
if CreateRepositoryPermission(namespace).can() and user is not None:
logger.debug('Creating repository: %s/%s', namespace, reponame)
model.create_repository(namespace, reponame, user)
@ -172,19 +165,18 @@ def generate_registry_jwt(auth_result):
}
tuf_root = get_tuf_root(repo, namespace, reponame)
elif user is None and token is None:
elif not has_valid_auth_context:
# In this case, we are doing an auth flow, and it's not an anonymous pull
logger.debug('No user and no token sent for empty scope list')
raise Unauthorized()
# Send the user event.
if user is not None:
event = userevents.get_event(user.username)
if get_authenticated_user() is not None:
event = userevents.get_event(get_authenticated_user().username)
event.publish_event_data('docker-cli', user_event_data)
# Build the signed JWT.
context, subject = build_context_and_subject(user=user, token=token, oauthtoken=oauthtoken,
appspecifictoken=appspecifictoken, tuf_root=tuf_root)
# Build the signed JWT.
context, subject = build_context_and_subject(get_authenticated_context(), tuf_root=tuf_root)
token = generate_bearer_token(audience_param, subject, context, access,
TOKEN_VALIDITY_LIFETIME_S, instance_keys)
return jsonify({'token': token})