This repository has been archived on 2020-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
quay/endpoints/v2/__init__.py

164 lines
5.2 KiB
Python
Raw Normal View History

2015-06-22 21:37:13 +00:00
import logging
from functools import wraps
from urlparse import urlparse
2016-07-26 22:41:51 +00:00
from urllib import urlencode
from flask import Blueprint, make_response, url_for, request, jsonify
from semantic_version import Spec
import features
2015-06-22 21:37:13 +00:00
from app import app, metric_queue, get_app_url, license_validator
from auth.auth_context import get_grant_context
2015-06-22 21:37:13 +00:00
from auth.permissions import (ReadRepositoryPermission, ModifyRepositoryPermission,
AdministerRepositoryPermission)
from auth.registry_jwt_auth import process_registry_jwt_auth, get_auth_headers
2015-06-22 21:37:13 +00:00
from data import model
from endpoints.decorators import anon_protect, anon_allowed
from endpoints.v2.errors import V2RegistryException, Unauthorized
2015-06-22 21:37:13 +00:00
from util.http import abort
from util.metrics.metricqueue import time_blueprint
from util.registry.dockerver import docker_version
2016-07-26 22:41:51 +00:00
from util.pagination import encrypt_page_token, decrypt_page_token
2015-06-22 21:37:13 +00:00
2015-06-22 21:37:13 +00:00
logger = logging.getLogger(__name__)
v2_bp = Blueprint('v2', __name__)
license_validator.enforce_license_before_request(v2_bp)
time_blueprint(v2_bp, metric_queue)
2015-06-22 21:37:13 +00:00
2016-07-26 22:41:51 +00:00
2016-10-17 19:21:11 +00:00
@v2_bp.app_errorhandler(V2RegistryException)
def handle_registry_v2_exception(error):
response = jsonify({
'errors': [error.as_dict()]
})
response.status_code = error.http_status_code
if response.status_code == 401:
response.headers.extend(get_auth_headers(repository=error.repository, scopes=error.scopes))
logger.debug('sending response: %s', response.get_data())
return response
2016-07-26 22:41:51 +00:00
_MAX_RESULTS_PER_PAGE = 50
2016-08-02 00:48:00 +00:00
def paginate(limit_kwarg_name='limit', offset_kwarg_name='offset',
callback_kwarg_name='pagination_callback'):
2016-08-09 19:11:35 +00:00
"""
Decorates a handler adding a parsed pagination token and a callback to encode a response token.
"""
2016-07-26 22:41:51 +00:00
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
requested_limit = int(request.args.get('n', _MAX_RESULTS_PER_PAGE))
except ValueError:
requested_limit = 0
limit = max(min(requested_limit, _MAX_RESULTS_PER_PAGE), 1)
next_page_token = request.args.get('next_page', None)
# Decrypt the next page token, if any.
offset = 0
page_info = decrypt_page_token(next_page_token)
if page_info is not None:
# Note: we use offset here instead of ID >= n because one of the V2 queries is a UNION.
offset = page_info.get('offset', 0)
def callback(num_results, response):
2016-10-03 18:10:39 +00:00
if num_results < limit:
2016-07-26 22:41:51 +00:00
return
2016-10-03 18:10:39 +00:00
next_page_token = encrypt_page_token({'offset': limit + offset})
link_url = get_app_url() + url_for(request.endpoint, **request.view_args)
link_param = urlencode({'n': limit, 'next_page': next_page_token})
link = '<%s?%s>; rel="next"' % (link_url, link_param)
2016-07-26 22:41:51 +00:00
response.headers['Link'] = link
kwargs[limit_kwarg_name] = limit
kwargs[offset_kwarg_name] = offset
kwargs[callback_kwarg_name] = callback
return func(*args, **kwargs)
2016-07-26 22:41:51 +00:00
return wrapped
return wrapper
def _require_repo_permission(permission_class, scopes=None, allow_public=False):
2015-06-22 21:37:13 +00:00
def wrapper(func):
@wraps(func)
2016-03-09 21:20:28 +00:00
def wrapped(namespace_name, repo_name, *args, **kwargs):
logger.debug('Checking permission %s for repo: %s/%s', permission_class,
namespace_name, repo_name)
permission = permission_class(namespace_name, repo_name)
2015-06-22 21:37:13 +00:00
if (permission.can() or
(allow_public and
2016-03-09 21:20:28 +00:00
model.repository.repository_is_public(namespace_name, repo_name))):
return func(namespace_name, repo_name, *args, **kwargs)
repository = namespace_name + '/' + repo_name
raise Unauthorized(repository=repository, scopes=scopes)
2015-06-22 21:37:13 +00:00
return wrapped
return wrapper
require_repo_read = _require_repo_permission(ReadRepositoryPermission,
scopes=['pull'],
allow_public=True)
require_repo_write = _require_repo_permission(ModifyRepositoryPermission,
scopes=['pull', 'push'])
require_repo_admin = _require_repo_permission(AdministerRepositoryPermission,
scopes=['pull', 'push'])
2015-06-22 21:37:13 +00:00
def get_input_stream(flask_request):
if flask_request.headers.get('transfer-encoding') == 'chunked':
return flask_request.environ['wsgi.input']
return flask_request.stream
def route_show_if(value):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not value:
abort(404)
return f(*args, **kwargs)
return decorated_function
return decorator
2016-10-17 19:21:11 +00:00
2015-06-22 21:37:13 +00:00
@v2_bp.route('/')
@route_show_if(features.ADVERTISE_V2)
@process_registry_jwt_auth()
2015-06-22 21:37:13 +00:00
@anon_allowed
def v2_support_enabled():
docker_ver = docker_version(request.user_agent.string)
# Check if our version is one of the blacklisted versions, if we can't
# identify the version (None) we will fail open and assume that it is
# newer and therefore should not be blacklisted.
if Spec(app.config['BLACKLIST_V2_SPEC']).match(docker_ver) and docker_ver is not None:
abort(404)
2015-06-22 21:37:13 +00:00
response = make_response('true', 200)
if get_grant_context() is None:
2015-06-22 21:37:13 +00:00
response = make_response('true', 401)
response.headers.extend(get_auth_headers())
2015-06-22 21:37:13 +00:00
return response
2016-07-26 22:41:51 +00:00
from endpoints.v2 import (
blob,
catalog,
manifest,
tag,
v2auth,
)