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:
parent
8ba2e71fb1
commit
e220b50543
31 changed files with 822 additions and 436 deletions
|
@ -15,7 +15,8 @@ from auth.permissions import (ReadRepositoryPermission, ModifyRepositoryPermissi
|
|||
AdministerRepositoryPermission, UserReadPermission,
|
||||
UserAdminPermission)
|
||||
from auth import scopes
|
||||
from auth.auth_context import get_authenticated_user, get_validated_oauth_token
|
||||
from auth.auth_context import (get_authenticated_context, get_authenticated_user,
|
||||
get_validated_oauth_token)
|
||||
from auth.decorators import process_oauth
|
||||
from endpoints.csrf import csrf_protect
|
||||
from endpoints.exception import (Unauthorized, InvalidRequest, InvalidResponse,
|
||||
|
@ -291,8 +292,7 @@ def require_fresh_login(func):
|
|||
if not user:
|
||||
raise Unauthorized()
|
||||
|
||||
oauth_token = get_validated_oauth_token()
|
||||
if oauth_token:
|
||||
if get_validated_oauth_token():
|
||||
return func(*args, **kwargs)
|
||||
|
||||
logger.debug('Checking fresh login for user %s', user.username)
|
||||
|
|
|
@ -46,8 +46,7 @@ def csrf_protect(session_token_name=_QUAY_CSRF_TOKEN_NAME,
|
|||
def inner(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
oauth_token = get_validated_oauth_token()
|
||||
if oauth_token is None:
|
||||
if get_validated_oauth_token() is None:
|
||||
if all_methods or (request.method != "GET" and request.method != "HEAD"):
|
||||
verify_csrf(session_token_name, request_token_name)
|
||||
|
||||
|
|
|
@ -6,8 +6,7 @@ from flask import abort, request, make_response
|
|||
import features
|
||||
|
||||
from app import app
|
||||
from auth.auth_context import (
|
||||
get_validated_oauth_token, get_authenticated_user, get_validated_token, get_grant_context)
|
||||
from auth.auth_context import get_authenticated_context
|
||||
from util.names import parse_namespace_repository
|
||||
|
||||
|
||||
|
@ -73,8 +72,7 @@ def check_anon_protection(func):
|
|||
return func(*args, **kwargs)
|
||||
|
||||
# Check for validated context. If none exists, fail with a 401.
|
||||
if (get_authenticated_user() or get_validated_oauth_token() or get_validated_token() or
|
||||
get_grant_context()):
|
||||
if get_authenticated_context() and not get_authenticated_context().is_anonymous:
|
||||
return func(*args, **kwargs)
|
||||
|
||||
abort(401)
|
||||
|
|
|
@ -7,8 +7,7 @@ from functools import wraps
|
|||
from flask import request, make_response, jsonify, session
|
||||
|
||||
from app import userevents, metric_queue
|
||||
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.credentials import validate_credentials, CredentialKind
|
||||
from auth.decorators import process_auth
|
||||
from auth.permissions import (
|
||||
|
@ -106,7 +105,7 @@ def create_user():
|
|||
# Default case: Just fail.
|
||||
abort(400, result.error_message, issue='login-failure')
|
||||
|
||||
if result.has_user:
|
||||
if result.has_nonrobot_user:
|
||||
# Mark that the user was logged in.
|
||||
event = userevents.get_event(username)
|
||||
event.publish_event_data('docker-cli', {'action': 'login'})
|
||||
|
@ -119,27 +118,14 @@ def create_user():
|
|||
@process_auth
|
||||
@anon_allowed
|
||||
def get_user():
|
||||
if get_validated_oauth_token():
|
||||
return jsonify({
|
||||
'username': '$oauthtoken',
|
||||
'email': None,
|
||||
})
|
||||
elif get_validated_app_specific_token():
|
||||
return jsonify({
|
||||
'username': "$app",
|
||||
'email': None,
|
||||
})
|
||||
elif get_authenticated_user():
|
||||
return jsonify({
|
||||
'username': get_authenticated_user().username,
|
||||
'email': get_authenticated_user().email,
|
||||
})
|
||||
elif get_validated_token():
|
||||
return jsonify({
|
||||
'username': '$token',
|
||||
'email': None,
|
||||
})
|
||||
abort(404)
|
||||
context = get_authenticated_context()
|
||||
if not context or context.is_anonymous:
|
||||
abort(404)
|
||||
|
||||
return jsonify({
|
||||
'username': context.credential_username,
|
||||
'email': None,
|
||||
})
|
||||
|
||||
|
||||
@v1_bp.route('/users/<username>/', methods=['PUT'])
|
||||
|
|
|
@ -11,7 +11,6 @@ from app import storage as store, app, metric_queue
|
|||
from auth.auth_context import get_authenticated_user
|
||||
from auth.decorators import extract_namespace_repo_from_session, process_auth
|
||||
from auth.permissions import (ReadRepositoryPermission, ModifyRepositoryPermission)
|
||||
from auth.registry_jwt_auth import get_granted_username
|
||||
from data import model, database
|
||||
from digest import checksums
|
||||
from endpoints.v1 import v1_bp
|
||||
|
@ -433,9 +432,6 @@ def put_image_json(namespace, repository, image_id):
|
|||
v1_metadata = model.docker_v1_metadata(namespace, repository, image_id)
|
||||
if v1_metadata is None:
|
||||
username = get_authenticated_user() and get_authenticated_user().username
|
||||
if not username:
|
||||
username = get_granted_username()
|
||||
|
||||
logger.debug('Image not found, creating or linking image with initiating user context: %s',
|
||||
username)
|
||||
location_pref = store.preferred_locations[0]
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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})
|
||||
|
|
Reference in a new issue