Skip to content

Commit

Permalink
pep8 reformatting
Browse files Browse the repository at this point in the history
  • Loading branch information
brondsem committed Oct 30, 2024
1 parent 8475df6 commit bce9a59
Show file tree
Hide file tree
Showing 105 changed files with 256 additions and 247 deletions.
1 change: 1 addition & 0 deletions Allura/allura/controllers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -1545,6 +1545,7 @@ def revoke_access_token2authcode(self, _id):
flash('Authorization revoked')
redirect('.')


class OAuth2AuthorizationController(BaseController):
def _check_security(self):
require_authenticated()
Expand Down
1 change: 1 addition & 0 deletions Allura/allura/controllers/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,7 @@ def token(self, **kwargs):
response.status_int = status
return body


def rest_has_access(obj, user, perm):
"""
Helper function that encapsulates common functionality for has_access API
Expand Down
4 changes: 2 additions & 2 deletions Allura/allura/lib/custom_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ def timers(self):
debug_each_call=False),
Timer('ming', ming.odm.odmsession.ODMSession,
'insert_now', 'update_now', 'delete_now',
'find', 'find_one_and_update', 'find_one_and_replace', 'find_one_and_delete',
'find', 'find_one_and_update', 'find_one_and_replace', 'find_one_and_delete',
'remove', 'update', 'update_if_not_modified',
'aggregate', 'distinct',
),
Expand Down Expand Up @@ -502,7 +502,7 @@ def __call__(self, environ, start_response):
srcs += ' ' + ' '.join(environ['csp_form_actions'])

oauth_endpoints = (
'/auth/oauth2/authorize', '/auth/oauth2/do_authorize', '/rest/oauth/authorize', '/rest/oauth/do_authorize')
'/auth/oauth2/authorize', '/auth/oauth2/do_authorize', '/rest/oauth/authorize', '/rest/oauth/do_authorize')
if not req.path.startswith(oauth_endpoints): # Do not enforce CSP for OAuth1 and OAuth2 authorization
if asbool(self.config.get('csp.form_actions_enforce', False)):
rules.add(f"form-action {srcs}")
Expand Down
2 changes: 2 additions & 0 deletions Allura/allura/lib/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,7 @@ def https_open(self, req):
validators.NonPrivateUrl().to_python(req.full_url, None)
return super().https_open(req)


class UseKnownIPHTTPConnection(http.client.HTTPConnection):
# only for http, since https requires a valid cert it should be ok
def __init__(self, *a, known_ip_to_use=None, **kw):
Expand All @@ -1073,6 +1074,7 @@ def http_open(self, req):
else:
return super().http_open(req)


urllib.request.install_opener(urllib.request.build_opener(NotInternalHTTPHandler, NoInternalHTTPSHandler))


Expand Down
2 changes: 2 additions & 0 deletions Allura/allura/lib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from allura.lib import helpers as h

_patched = False


def apply():
global _patched # noqa: PLW0603
if _patched:
Expand Down
1 change: 0 additions & 1 deletion Allura/allura/lib/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,6 @@ def _passlib_crypt_by_id(self, algorithm: str) -> passlib.ifc.PasswordHash:
raise ValueError(f'LDAP algorithms should always start with ldap_ (got {algorithm})')
return crypt


def set_password(self, user, old_password, new_password, set_timestamp=True):
dn = ldap_user_dn(user.username)
if old_password is not None:
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/lib/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def debug_obj(obj) -> str:
return str(obj)


def has_access(obj, permission: str, user: M.User | None = None, project: M.Project | None = None, roles = None) -> bool:
def has_access(obj, permission: str, user: M.User | None = None, project: M.Project | None = None, roles=None) -> bool:
'''Return whether the given user has the permission name on the given object.
- First, all the roles for a user in the given project context are computed.
Expand Down
4 changes: 2 additions & 2 deletions Allura/allura/lib/solr.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def escape_solr_arg(term):
return term


def make_solr_from_config(push_servers: Iterable[str], query_server: str|None=None,
def make_solr_from_config(push_servers: Iterable[str], query_server: str | None = None,
push_servers_auths: Iterable[tuple[str, str] | None] = (),
query_server_auth: tuple[str, str] | None = None,
**kwargs):
Expand Down Expand Up @@ -91,7 +91,7 @@ class Solr:
unless explicitly overridden.
"""

def __init__(self, push_servers: Iterable[str], query_server: str|None = None,
def __init__(self, push_servers: Iterable[str], query_server: str | None = None,
push_servers_auths: Iterable[tuple[str, str] | None] = (),
query_server_auth: tuple[str, str] | None = None,
commit=True, commitWithin=None, **kw):
Expand Down
1 change: 0 additions & 1 deletion Allura/allura/lib/widgets/oauth_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,3 @@ class fields(ew_core.NameList):
attrs=dict(type='url', style='min-width:25em; margin-left: 162px;', # match grid-4 label width
pattern='https://.*', title='must start with https://'),
)

6 changes: 3 additions & 3 deletions Allura/allura/lib/widgets/project_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class ProjectSummary(ew_core.Widget):
show_proj_icon=True,
show_download_button=True,
show_awards_banner=True,
)
)

def prepare_context(self, context):
response = super().prepare_context(context)
Expand Down Expand Up @@ -84,7 +84,7 @@ class ProjectList(ew_core.Widget):
show_proj_icon=True,
show_download_button=True,
show_awards_banner=True,
)
)

def prepare_context(self, context):
response = super().prepare_context(context)
Expand Down Expand Up @@ -121,4 +121,4 @@ class ProjectScreenshots(ew_core.Widget):
def resources(self):
yield ew.JSLink('allura/js/Sortable.min.js')
yield ew.JSLink('js/screenshots.js')
yield ew.CSSLink('css/screenshots.css')
yield ew.CSSLink('css/screenshots.css')
2 changes: 1 addition & 1 deletion Allura/allura/model/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def send_verification_link(self):
'''.format(self.email,
self.claimed_by_user(include_pending=True).username,
h.absurl(f'/auth/verify_addr?a={h.urlquote(self.nonce)}'),
)
)
log.info('Verification email:\n%s', text)
allura.tasks.mail_tasks.sendsimplemail.post(
fromaddr=g.noreply,
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/model/discuss.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ def notify_moderators(self, post):
if (has_access(self, 'moderate', u)
and Mailbox.subscribed(user_id=u._id,
app_config_id=post.app_config_id)):
n.send_direct(str(u._id))
n.send_direct(str(u._id))

def update_stats(self):
self.num_replies = self.post_class().query.find(
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/model/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def from_links(cls, *links):
result = {}
# Parse all the links
parsed_links = {link: cls._parse_link(link)
for link in links}
for link in links}
links_by_artifact = defaultdict(list)
project_ids = set()
for link, d in list(parsed_links.items()):
Expand Down
4 changes: 2 additions & 2 deletions Allura/allura/model/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def _make_notification(cls, artifact, topic, **kwargs):
but the notification still gets sent if there is an error
'''
log.warning('Could not render notification template %s' %
artifact.type_s, exc_info=True)
artifact.type_s, exc_info=True)

assert d['reply_to_address'] is not None
project = c.project
Expand Down Expand Up @@ -622,7 +622,7 @@ def find_and_modify_direct_mbox():
queue=[],
queue_empty=True,
)},
)
)
mbox.fire(now)

def fire(self, now):
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/model/repo_refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def refresh_repo(repo, all_commits=False, notify=True, new_clone=False, commits_
if user is not None:
g.statsUpdater.newCommit(new, repo.app_config.project, user)
actor = user or TransientActor(
activity_name=new.committed.name or new.committed.email)
activity_name=new.committed.name or new.committed.email)
g.director.create_activity(actor, 'committed', new, target=repo.app,
related_nodes=[repo.app_config.project],
tags=['commit', repo.tool.lower()])
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/model/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ def substitute_extensions(session, extensions=None):
main_orm_session = ThreadLocalODMSession(
doc_session=main_doc_session,
extensions=[IndexerSessionExtension]
)
)
main_explicitflush_orm_session = ThreadLocalODMSession(
doc_session=main_doc_session,
extensions=[IndexerSessionExtension, ExplicitFlushOnlySessionExtension]
Expand Down
1 change: 1 addition & 0 deletions Allura/allura/model/timeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ class TransientActor(NodeBase, ActivityObjectBase):
"""An activity actor which is not a persistent Node in the network.
"""

def __init__(self, activity_name):
NodeBase.__init__(self)
ActivityObjectBase.__init__(self)
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/scripts/refreshrepo.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def repo_type_list(s):
parser.add_argument('--clean-after', metavar='DATETIME', dest='clean_after',
type=lambda d: datetime.strptime(d, date_format),
help='Like --clean but only docs for commits after date ({} format)'.format(
date_format.replace('%', '%%')
date_format.replace('%', '%%')
))
parser.add_argument(
'--all', action='store_true', dest='all', default=False,
Expand Down
1 change: 1 addition & 0 deletions Allura/allura/tasks/admin_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def install_app(*args, **kwargs):
"""
c.project.install_app(*args, **kwargs)


install_app.__doc__ += '''
Arguments::
Expand Down
1 change: 0 additions & 1 deletion Allura/allura/templates/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,3 @@
# under the License.

"""Templates package for the application."""

2 changes: 1 addition & 1 deletion Allura/allura/templates_responsive/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# under the License.
2 changes: 1 addition & 1 deletion Allura/allura/tests/exclude_from_rewrite_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ def raise_compound_exception():
assert False, 'assert %d' % x
except Exception:
errs.append(sys.exc_info())
raise CompoundError(*errs)
raise CompoundError(*errs)
1 change: 0 additions & 1 deletion Allura/allura/tests/functional/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,3 @@
# under the License.

"""Functional test suite for the controllers of the application."""

2 changes: 1 addition & 1 deletion Allura/allura/tests/functional/test_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ def test_project_screenshot(self, uuid1):
upload = ('screenshot', file_name, file_data)

self.app.get('/admin/')
e_filename, e_fileext = os.path.splitext(file_name)
e_filename, e_fileext = os.path.splitext(file_name)
with audits('screenshots: added screenshot {}'.format(f"{e_filename}-123{e_fileext}")):
self.app.post('/admin/add_screenshot', params=dict(
caption='test me'),
Expand Down
54 changes: 33 additions & 21 deletions Allura/allura/tests/functional/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2184,7 +2184,11 @@ def test_authorize(self):
redirect_uris=['https://localhost/']
)
ThreadLocalODMSession.flush_all()
r = self.app.get('/auth/oauth2/authorize', params={'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
r = self.app.get('/auth/oauth2/authorize', params={
'client_id': 'client_12345',
'response_type': 'code',
'redirect_uri': 'https://localhost/',
})
assert 'testoauth2' in r.text
assert 'client_12345' in r.text

Expand All @@ -2201,11 +2205,14 @@ def test_do_authorize_no(self):
redirect_uris=['https://localhost/']
)
ThreadLocalODMSession.flush_all()
r = self.app.get('/auth/oauth2/authorize', params={'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
r = self.app.get('/auth/oauth2/authorize', params={
'client_id': 'client_12345',
'response_type': 'code',
'redirect_uri': 'https://localhost/',
})
r = r.forms[0].submit('no')
assert M.OAuth2AuthorizationCode.query.get(client_id='client_12345') is None


@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_authorize_and_create_access_token(self):
# client owned by someone other than the test-admin user that self.app.get/post use
Expand All @@ -2225,7 +2232,11 @@ def test_authorize_and_create_access_token(self):
r.mustcontain(no='testoauth2')

# First navigate to the authorization page for the backend to validate the authorization request
r = self.app.get('/auth/oauth2/authorize', params={'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
r = self.app.get('/auth/oauth2/authorize', params={
'client_id': 'client_12345',
'response_type': 'code',
'redirect_uri': 'https://localhost/',
})
# The submit authorization for the authorization code to be created
r.forms[0].submit('yes')

Expand All @@ -2251,7 +2262,6 @@ def test_authorize_and_create_access_token(self):
r = self.app.get('/auth/oauth/')
r.mustcontain('testoauth2')


@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_revoke_auth_code(self):
# only the auth code is present, and it gets revoked
Expand Down Expand Up @@ -2287,7 +2297,6 @@ def test_revoke_auth_code(self):
r = self.app.get('/auth/oauth/')
r.mustcontain(no='testoauth2')


@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_revoke_access_token(self):
# both auth code and access token are present, both get revoked
Expand Down Expand Up @@ -2332,16 +2341,16 @@ def test_revoke_access_token(self):
r = self.app.get('/auth/oauth/')
r.mustcontain(no='testoauth2')


@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_pkce(self, mock_client, mock_credentials):
code_verifier = 'QkatVHgTq_cZj8tTKWPIe78fXpoeszhVq6kLIUxJj8g9tMmfi0XV4dfZHQBXwOiWsLihJotfrOGKR4nZSXA4mA'
code_challenge = 'BxGpJVKt_l6Srlq3uXPfpxge3TxtxetcWhGXq2958yU'
code_challenge_method = 'S256' # Must be uppercase
code_challenge_method = 'S256' # Must be uppercase

# Authorize the app by sending the code challenge and code challenge method as qs param
params = dict(client_id='client_12345', response_type='code', redirect_uri='https://localhost/', code_challenge=code_challenge,
code_challenge_method=code_challenge_method)
params = dict(client_id='client_12345', response_type='code', redirect_uri='https://localhost/',
code_challenge=code_challenge,
code_challenge_method=code_challenge_method)
r = self.app.get('/auth/oauth2/authorize', params=params)

# Authorize app
Expand All @@ -2352,7 +2361,8 @@ def test_pkce(self, mock_client, mock_credentials):
assert ac is not None

# Exchange the authorization code for an access token. It should fail if you do not provide the code verifier
body = dict(client_id='client_12345', client_secret='98765', code=ac.authorization_code, grant_type='authorization_code', redirect_uri='https://localhost/')
body = dict(client_id='client_12345', client_secret='98765', code=ac.authorization_code,
grant_type='authorization_code', redirect_uri='https://localhost/')

with pytest.raises(webtest.app.AppError) as ex:
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})
Expand All @@ -2368,15 +2378,17 @@ def test_pkce(self, mock_client, mock_credentials):
def test_refresh_token(self, mock_client, mock_valid_token):
token = M.OAuth2AccessToken.query.get(client_id='client_12345')

body = dict(client_id='client_12345', client_secret='98765', grant_type='refresh_token', refresh_token=token.refresh_token)
body = dict(client_id='client_12345', client_secret='98765', grant_type='refresh_token',
refresh_token=token.refresh_token)
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})
assert r.status_int == 200
assert r.json['access_token'] != token.access_token
assert r.json['refresh_token'] != token.refresh_token

@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_invalid_refresh_token(self, mock_client, mock_valid_token):
body = dict(client_id='client_12345', client_secret='98765', grant_type='refresh_token', refresh_token='invalid_token')
body = dict(client_id='client_12345', client_secret='98765', grant_type='refresh_token',
refresh_token='invalid_token')
with pytest.raises(webtest.app.AppError) as ex:
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})

Expand All @@ -2387,8 +2399,8 @@ def test_access_token_with_expired_code(self, mock_client, mock_expired_authoriz
c = M.OAuth2ClientApp.query.get(client_id='client_12345')
ac = M.OAuth2AuthorizationCode.query.get(client_id='client_12345')

body = dict(client_id=c.client_id, client_secret=c.client_secret, grant_type='authorization_code', code=ac.authorization_code,
redirect_uri=c.redirect_uris[0])
body = dict(client_id=c.client_id, client_secret=c.client_secret, grant_type='authorization_code',
code=ac.authorization_code, redirect_uri=c.redirect_uris[0])
with pytest.raises(webtest.app.AppError) as ex:
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})

Expand All @@ -2399,8 +2411,8 @@ def test_access_token_with_invalid_redirect_uri(self, mock_client, mock_valid_au
c = M.OAuth2ClientApp.query.get(client_id='client_12345')
ac = M.OAuth2AuthorizationCode.query.get(client_id='client_12345')

body = dict(client_id=c.client_id, client_secret=c.client_secret, grant_type='authorization_code', code=ac.authorization_code,
redirect_uri='https://invalid.com')
body = dict(client_id=c.client_id, client_secret=c.client_secret, grant_type='authorization_code',
code=ac.authorization_code, redirect_uri='https://invalid.com')
with pytest.raises(webtest.app.AppError) as ex:
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})

Expand All @@ -2412,17 +2424,17 @@ def test_access_token_with_invalid_credentials(self, mock_client, mock_valid_aut
ac = M.OAuth2AuthorizationCode.query.get(client_id='client_12345')

# First test passing an invalid client id
body = dict(client_id='invalid_client_id', client_secret=c.client_secret, grant_type='authorization_code', code=ac.authorization_code,
redirect_uri=c.redirect_uris[0])
body = dict(client_id='invalid_client_id', client_secret=c.client_secret, grant_type='authorization_code',
code=ac.authorization_code, redirect_uri=c.redirect_uris[0])

with pytest.raises(webtest.app.AppError) as ex:
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})

assert 'invalid_client' in str(ex.value)

# Now test passing an invalid client secret
body = dict(client_id=c.client_id, client_secret='invalid_secret', grant_type='authorization_code', code=ac.authorization_code,
redirect_uri=c.redirect_uris[0])
body = dict(client_id=c.client_id, client_secret='invalid_secret', grant_type='authorization_code',
code=ac.authorization_code, redirect_uri=c.redirect_uris[0])

with pytest.raises(webtest.app.AppError) as ex:
r = self.app.post_json('/rest/oauth2/token', body, extra_environ={'username': '*anonymous'})
Expand Down
Loading

0 comments on commit bce9a59

Please sign in to comment.