Add scope ordinality and translations. Process oauth tokens and limit scopes accordingly.
This commit is contained in:
parent
25ceb90fc6
commit
e74eb3ee87
8 changed files with 137 additions and 31 deletions
56
auth/auth.py
56
auth/auth.py
|
@ -1,13 +1,16 @@
|
|||
import logging
|
||||
|
||||
from functools import wraps
|
||||
from datetime import datetime
|
||||
from flask import request, _request_ctx_stack, session
|
||||
from flask.ext.principal import identity_changed, Identity
|
||||
from base64 import b64decode
|
||||
|
||||
from data import model
|
||||
from data.model import oauth
|
||||
from app import app
|
||||
from permissions import QuayDeferredPermissionUser
|
||||
import scopes
|
||||
|
||||
from util.http import abort
|
||||
|
||||
|
@ -49,7 +52,8 @@ def process_basic_auth(auth):
|
|||
ctx = _request_ctx_stack.top
|
||||
ctx.authenticated_user = robot
|
||||
|
||||
identity_changed.send(app, identity=Identity(robot.username, 'username'))
|
||||
deferred_robot = QuayDeferredPermissionUser(robot.username, 'username')
|
||||
identity_changed.send(app, identity=deferred_robot)
|
||||
return
|
||||
except model.InvalidRobotException:
|
||||
logger.debug('Invalid robot or password for robot: %s' % credentials[0])
|
||||
|
@ -62,8 +66,7 @@ def process_basic_auth(auth):
|
|||
ctx = _request_ctx_stack.top
|
||||
ctx.authenticated_user = authenticated
|
||||
|
||||
new_identity = QuayDeferredPermissionUser(authenticated.username,
|
||||
'username')
|
||||
new_identity = QuayDeferredPermissionUser(authenticated.username, 'username')
|
||||
identity_changed.send(app, identity=new_identity)
|
||||
return
|
||||
|
||||
|
@ -94,18 +97,55 @@ def process_token(auth):
|
|||
token_data = model.load_token_data(token_vals['signature'])
|
||||
|
||||
except model.InvalidTokenException:
|
||||
logger.warning('Token could not be validated: %s' %
|
||||
token_vals['signature'])
|
||||
logger.warning('Token could not be validated: %s', token_vals['signature'])
|
||||
abort(401, message="Token could not be validated: %(auth)", issue='invalid-auth-token',
|
||||
auth=auth)
|
||||
|
||||
logger.debug('Successfully validated token: %s' % token_data.code)
|
||||
logger.debug('Successfully validated token: %s', token_data.code)
|
||||
ctx = _request_ctx_stack.top
|
||||
ctx.validated_token = token_data
|
||||
|
||||
identity_changed.send(app, identity=Identity(token_data.code, 'token'))
|
||||
|
||||
|
||||
def process_oauth(auth):
|
||||
normalized = [part.strip() for part in auth.split(' ') if part]
|
||||
if normalized[0].lower() != 'bearer' or len(normalized) != 2:
|
||||
logger.debug('Invalid oauth bearer token format.')
|
||||
return
|
||||
|
||||
token = normalized[1]
|
||||
validated = oauth.validate_access_token(token)
|
||||
if not validated:
|
||||
logger.warning('OAuth access token could not be validated: %s', token)
|
||||
authenticate_header = {
|
||||
'WWW-Authenticate': ('Bearer error="invalid_token", '
|
||||
'error_description="The access token is invalid"'),
|
||||
}
|
||||
abort(401, message="OAuth access token could not be validated: %(token)",
|
||||
issue='invalid-oauth-token', token=token, header=authenticate_header)
|
||||
elif validated.expires_at <= datetime.now():
|
||||
logger.info('OAuth access with an expired token: %s', token)
|
||||
authenticate_header = {
|
||||
'WWW-Authenticate': ('Bearer error="invalid_token", '
|
||||
'error_description="The access token expired"'),
|
||||
}
|
||||
abort(401, message="OAuth access token has expired: %(token)", issue='invalid-oauth-token',
|
||||
token=token, headers=authenticate_header)
|
||||
|
||||
# We have a valid token
|
||||
scope_set = scopes.scopes_from_scope_string(validated.scope)
|
||||
logger.debug('Successfully validated oauth access token: %s with scope: %s', token,
|
||||
scope_set)
|
||||
|
||||
ctx = _request_ctx_stack.top
|
||||
ctx.authenticated_user = validated.authorized_user
|
||||
|
||||
new_identity = QuayDeferredPermissionUser(validated.authorized_user.username, 'username',
|
||||
scope_set)
|
||||
identity_changed.send(app, identity=new_identity)
|
||||
|
||||
|
||||
def process_auth(f):
|
||||
@wraps(f)
|
||||
def wrapper(*args, **kwargs):
|
||||
|
@ -115,6 +155,7 @@ def process_auth(f):
|
|||
logger.debug('Validating auth header: %s' % auth)
|
||||
process_token(auth)
|
||||
process_basic_auth(auth)
|
||||
process_oauth(auth)
|
||||
else:
|
||||
logger.debug('No auth header.')
|
||||
|
||||
|
@ -126,8 +167,7 @@ def extract_namespace_repo_from_session(f):
|
|||
@wraps(f)
|
||||
def wrapper(*args, **kwargs):
|
||||
if 'namespace' not in session or 'repository' not in session:
|
||||
logger.error('Unable to load namespace or repository from session: %s' %
|
||||
session)
|
||||
logger.error('Unable to load namespace or repository from session: %s' % session)
|
||||
abort(400, message="Missing namespace in request")
|
||||
|
||||
return f(session['namespace'], session['repository'], *args, **kwargs)
|
||||
|
|
|
@ -18,40 +18,78 @@ _OrganizationNeed = namedtuple('organization', ['orgname', 'role'])
|
|||
_TeamNeed = namedtuple('orgteam', ['orgname', 'teamname', 'role'])
|
||||
|
||||
|
||||
REPO_ROLES = [None, 'read', 'write', 'admin']
|
||||
TEAM_ROLES = [None, 'member', 'creator', 'admin']
|
||||
|
||||
SCOPE_MAX_REPO_ROLES = {
|
||||
'repo:read': 'read',
|
||||
'repo:write': 'write',
|
||||
'repo:admin': 'admin',
|
||||
'repo:create': None,
|
||||
}
|
||||
|
||||
SCOPE_MAX_TEAM_ROLES = {
|
||||
'repo:read': None,
|
||||
'repo:write': None,
|
||||
'repo:admin': None,
|
||||
'repo:create': 'creator',
|
||||
}
|
||||
|
||||
class QuayDeferredPermissionUser(Identity):
|
||||
def __init__(self, id, auth_type=None):
|
||||
def __init__(self, id, auth_type=None, scopes=None):
|
||||
super(QuayDeferredPermissionUser, self).__init__(id, auth_type)
|
||||
|
||||
self._permissions_loaded = False
|
||||
self._scope_set = scopes
|
||||
|
||||
def _translate_role_for_scopes(self, cardinality, max_roles, role):
|
||||
if self._scope_set is None:
|
||||
return role
|
||||
|
||||
max_for_scopes = max({cardinality.index(max_roles[scope]) for scope in self._scope_set})
|
||||
|
||||
if max_for_scopes < cardinality.index(role):
|
||||
logger.debug('Translated permission %s -> %s', role, cardinality[max_for_scopes])
|
||||
return cardinality[max_for_scopes]
|
||||
else:
|
||||
return role
|
||||
|
||||
def _team_role_for_scopes(self, role):
|
||||
return self._translate_role_for_scopes(TEAM_ROLES, SCOPE_MAX_TEAM_ROLES, role)
|
||||
|
||||
def _repo_role_for_scopes(self, role):
|
||||
return self._translate_role_for_scopes(REPO_ROLES, SCOPE_MAX_REPO_ROLES, role)
|
||||
|
||||
def can(self, permission):
|
||||
if not self._permissions_loaded:
|
||||
logger.debug('Loading user permissions after deferring.')
|
||||
user_object = model.get_user(self.id)
|
||||
|
||||
# Add the user specific permissions
|
||||
user_grant = UserNeed(user_object.username)
|
||||
self.provides.add(user_grant)
|
||||
# Add the user specific permissions, only for non-oauth permission
|
||||
if self._scope_set is None:
|
||||
user_grant = UserNeed(user_object.username)
|
||||
self.provides.add(user_grant)
|
||||
|
||||
# Every user is the admin of their own 'org'
|
||||
user_namespace = _OrganizationNeed(user_object.username, 'admin')
|
||||
user_namespace = _OrganizationNeed(user_object.username, self._team_role_for_scopes('admin'))
|
||||
self.provides.add(user_namespace)
|
||||
|
||||
# Add repository permissions
|
||||
for perm in model.get_all_user_permissions(user_object):
|
||||
grant = _RepositoryNeed(perm.repository.namespace,
|
||||
perm.repository.name, perm.role.name)
|
||||
grant = _RepositoryNeed(perm.repository.namespace, perm.repository.name,
|
||||
self._repo_role_for_scopes(perm.role.name))
|
||||
logger.debug('User added permission: {0}'.format(grant))
|
||||
self.provides.add(grant)
|
||||
|
||||
# Add namespace permissions derived
|
||||
for team in model.get_org_wide_permissions(user_object):
|
||||
grant = _OrganizationNeed(team.organization.username, team.role.name)
|
||||
grant = _OrganizationNeed(team.organization.username,
|
||||
self._team_role_for_scopes(team.role.name))
|
||||
logger.debug('Organization team added permission: {0}'.format(grant))
|
||||
self.provides.add(grant)
|
||||
|
||||
team_grant = _TeamNeed(team.organization.username, team.name,
|
||||
team.role.name)
|
||||
self._team_role_for_scopes(team.role.name))
|
||||
logger.debug('Team added permission: {0}'.format(team_grant))
|
||||
self.provides.add(team_grant)
|
||||
|
||||
|
|
|
@ -23,3 +23,12 @@ CREATE_REPO = {
|
|||
}
|
||||
|
||||
ALL_SCOPES = {scope['scope']:scope for scope in (READ_REPO, WRITE_REPO, ADMIN_REPO, CREATE_REPO)}
|
||||
|
||||
|
||||
def scopes_from_scope_string(scopes):
|
||||
return {ALL_SCOPES.get(scope, {}).get('scope', None) for scope in scopes.split(',')}
|
||||
|
||||
|
||||
def validate_scope_string(scopes):
|
||||
decoded = scopes_from_scope_string(scopes)
|
||||
return None not in decoded and len(decoded) > 0
|
||||
|
|
Reference in a new issue