Skip to content
This repository has been archived by the owner on Aug 4, 2021. It is now read-only.

Commit

Permalink
Merge pull request #53 from CSCfi/devel
Browse files Browse the repository at this point in the history
bump to 0.5.10
  • Loading branch information
blankdots authored Jan 27, 2021
2 parents 2688801 + 99e55fc commit 713551e
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/eslint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node: [ '12', '14' ]
node: ['14' ]
name: Node ${{ matrix.node }} eslint check
steps:
- uses: actions/checkout@v2
Expand Down
18 changes: 12 additions & 6 deletions bindings/python/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
import fire


logging.basicConfig()
logging.basicConfig(format='%(levelname)-8s %(asctime)s | %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.INFO)


class Publish():
class Publish:
"""Share and publish Openstack Swift containers."""

@staticmethod
Expand Down Expand Up @@ -51,8 +53,8 @@ async def _push_share(self, container, recipient, rights):

def share(self, container, recipient, *args):
"""Share an existing container."""
print("share called")
print(args)
logging.log(logging.INFO, "share called")
logging.log(logging.INFO, args)
tenant = os.environ.get("OS_PROJECT_ID", None)
if not tenant:
logging.log(
Expand All @@ -79,7 +81,8 @@ def share(self, container, recipient, *args):
command.append("--write-acl")
command.append(recipient + ":*")
rights.append("w")
print("Running POST: %s" % command)

logging.log(logging.INFO, f"Running POST: {command}")
subprocess.call(command) # nosec

asyncio.run(self._push_share(
Expand Down Expand Up @@ -121,4 +124,7 @@ def publish(self, path, recipient, *args):


if __name__ == "__main__":
fire.Fire(Publish)
try:
fire.Fire(Publish)
except Exception as e:
logging.log(logging.ERROR, f"An error ocurred{': ' if e else ''}{e}.")
2 changes: 1 addition & 1 deletion swift_x_account_sharing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@


__name__ = "swift_x_account_sharing"
__version__ = "0.5.9"
__version__ = "0.5.10"
__author__ = "CSC Developers"
__license__ = "MIT License"
12 changes: 11 additions & 1 deletion swift_x_account_sharing/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@


import logging

import os
import aiohttp.web
from asyncpg import InterfaceError

from .db import handle_dropped_connection


MODULE_LOGGER = logging.getLogger("api")
MODULE_LOGGER.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))


async def has_access_handler(
Expand Down Expand Up @@ -214,6 +215,9 @@ async def handle_user_add_token(
formdata = await request.post()
token = str(formdata["token"])
except KeyError:
MODULE_LOGGER.log(
logging.ERROR, "No token present"
)
raise aiohttp.web.HTTPBadRequest(
reason="No token present"
)
Expand Down Expand Up @@ -273,13 +277,19 @@ async def handle_health_check(
# Case degraded
try:
if request.app["db_conn"].conn.is_closed():
MODULE_LOGGER.log(
logging.DEBUG, "Database closed"
)
return aiohttp.web.json_response({
"status": "Degraded",
"degraded": [
"database"
]
})
except AttributeError:
MODULE_LOGGER.log(
logging.ERROR, "Degraded Database"
)
return aiohttp.web.json_response({
"status": "Degraded",
"degraded": [
Expand Down
8 changes: 6 additions & 2 deletions swift_x_account_sharing/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@


LOGGER = logging.getLogger("swift_x_account_sharing.auth")
LOGGER.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))


async def read_in_keys(
Expand All @@ -55,8 +56,9 @@ async def test_signature(
"""Validate signature against the given tokens."""
# Check signature expiration
if int(validity) < time.time():
LOGGER.debug(f"Signature validity expired: {validity}")
raise aiohttp.web.HTTPUnauthorized(
reason="Signature expired"
reason="Signature validity expired"
)
byte_message = message.encode("utf-8")
for token in tokens:
Expand All @@ -67,6 +69,7 @@ async def test_signature(
).hexdigest()
if secrets.compare_digest(digest, signature):
return
LOGGER.debug(f"Missing valid query signature for signature {signature}")
raise aiohttp.web.HTTPUnauthorized(
reason="Missing valid query signature"
)
Expand All @@ -83,8 +86,9 @@ async def handle_validate_authentication(
validity = request.query["valid"]
path = request.url.path
except KeyError:
LOGGER.debug("Query string missing validity or signature")
raise aiohttp.web.HTTPClientError(
reason="Query string missing validity or signature."
reason="Query string missing validity or signature"
)

project: typing.Union[None, str]
Expand Down
20 changes: 13 additions & 7 deletions swift_x_account_sharing/bindings/bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ async def _handler_response(
try:
return json.loads(await resp.text())
except json.decoder.JSONDecodeError:
logging.error("Decoding JSON error \
response was not possible.")
logging.error("Decoding JSON error, "
"response was not possible.")
raise
except Exception as e:
logging.error(f"Unknown exception \
occured with content: {e}.")
logging.error("Unknown exception "
f"occured with content: {e}.")
raise
else:
logging.error(f"response status: {resp.status}.")
raise Exception(f"response status: {resp.status}.")
logging.error(f"API call {resp.url} responded with "
f"status {resp.status} and reason {resp.reason}.")
raise Exception

@staticmethod
def parse_list_to_string(
Expand Down Expand Up @@ -195,4 +196,9 @@ async def share_delete_access(
async with self.session.delete(url,
params=params,
ssl=ssl_context) as resp:
return bool(resp.status == 204)
if resp.status == 204:
return True
else:
logging.error(f"API call {resp.url} responded with status "
f"{resp.status} and reason {resp.reason}.")
raise Exception
2 changes: 1 addition & 1 deletion swift_x_account_sharing/bindings/signature.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def sign_api_request(
path: str
) -> dict:
"""Handle authentication with a signature."""
valid_until = str(int(time.time() + 10))
valid_until = str(int(time.time() + (60 * 61)))
to_sign = (valid_until + path).encode("utf-8")

digest = hmac.new(
Expand Down
1 change: 1 addition & 0 deletions swift_x_account_sharing/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@


MODULE_LOGGER = logging.getLogger("db")
MODULE_LOGGER.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))


def handle_dropped_connection(
Expand Down
19 changes: 12 additions & 7 deletions tests/test_bindings_bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def __init__(self, *args, **kwargs):
"text": asynctest.CoroutineMock(
return_value="[]"
),
"status": 200
"status": 200,
"url": "http://example",
})

async def __aenter__(self, *args, **kwargs):
Expand All @@ -47,16 +48,20 @@ async def __aexit__(self, *excinfo):
# Delete method mock context manager won't have any assertions in the
# __aexit__ method, since there's no real assertable functionality.
# Functionality will be tested in integration testing.
class MockDeleteContextManager(MockRequestContextManager):
class MockDeleteContextManager(asynctest.TestCase):
"""Mock class for aiohttp delete context manager."""

def __init__(self, *args, **kwargs):
"""."""
super(MockDeleteContextManager, self).__init__(
self,
*args,
**kwargs
)
self.resp = SimpleNamespace(**{
"status": 204,
"url": "http://example",
"reason": "reason"
})

async def __aenter__(self, *args, **kwargs):
"""."""
return self.resp

async def __aexit__(self, *excinfo):
"""."""
Expand Down

0 comments on commit 713551e

Please sign in to comment.