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

Commit 713551e

Browse files
authored
Merge pull request #53 from CSCfi/devel
bump to 0.5.10
2 parents 2688801 + 99e55fc commit 713551e

File tree

9 files changed

+58
-26
lines changed

9 files changed

+58
-26
lines changed

.github/workflows/eslint.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ jobs:
88
runs-on: ubuntu-latest
99
strategy:
1010
matrix:
11-
node: [ '12', '14' ]
11+
node: ['14' ]
1212
name: Node ${{ matrix.node }} eslint check
1313
steps:
1414
- uses: actions/checkout@v2

bindings/python/publish.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@
1414
import fire
1515

1616

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

1921

20-
class Publish():
22+
class Publish:
2123
"""Share and publish Openstack Swift containers."""
2224

2325
@staticmethod
@@ -51,8 +53,8 @@ async def _push_share(self, container, recipient, rights):
5153

5254
def share(self, container, recipient, *args):
5355
"""Share an existing container."""
54-
print("share called")
55-
print(args)
56+
logging.log(logging.INFO, "share called")
57+
logging.log(logging.INFO, args)
5658
tenant = os.environ.get("OS_PROJECT_ID", None)
5759
if not tenant:
5860
logging.log(
@@ -79,7 +81,8 @@ def share(self, container, recipient, *args):
7981
command.append("--write-acl")
8082
command.append(recipient + ":*")
8183
rights.append("w")
82-
print("Running POST: %s" % command)
84+
85+
logging.log(logging.INFO, f"Running POST: {command}")
8386
subprocess.call(command) # nosec
8487

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

122125

123126
if __name__ == "__main__":
124-
fire.Fire(Publish)
127+
try:
128+
fire.Fire(Publish)
129+
except Exception as e:
130+
logging.log(logging.ERROR, f"An error ocurred{': ' if e else ''}{e}.")

swift_x_account_sharing/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33

44
__name__ = "swift_x_account_sharing"
5-
__version__ = "0.5.9"
5+
__version__ = "0.5.10"
66
__author__ = "CSC Developers"
77
__license__ = "MIT License"

swift_x_account_sharing/api.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22

33

44
import logging
5-
5+
import os
66
import aiohttp.web
77
from asyncpg import InterfaceError
88

99
from .db import handle_dropped_connection
1010

1111

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

1415

1516
async def has_access_handler(
@@ -214,6 +215,9 @@ async def handle_user_add_token(
214215
formdata = await request.post()
215216
token = str(formdata["token"])
216217
except KeyError:
218+
MODULE_LOGGER.log(
219+
logging.ERROR, "No token present"
220+
)
217221
raise aiohttp.web.HTTPBadRequest(
218222
reason="No token present"
219223
)
@@ -273,13 +277,19 @@ async def handle_health_check(
273277
# Case degraded
274278
try:
275279
if request.app["db_conn"].conn.is_closed():
280+
MODULE_LOGGER.log(
281+
logging.DEBUG, "Database closed"
282+
)
276283
return aiohttp.web.json_response({
277284
"status": "Degraded",
278285
"degraded": [
279286
"database"
280287
]
281288
})
282289
except AttributeError:
290+
MODULE_LOGGER.log(
291+
logging.ERROR, "Degraded Database"
292+
)
283293
return aiohttp.web.json_response({
284294
"status": "Degraded",
285295
"degraded": [

swift_x_account_sharing/auth.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333

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

3637

3738
async def read_in_keys(
@@ -55,8 +56,9 @@ async def test_signature(
5556
"""Validate signature against the given tokens."""
5657
# Check signature expiration
5758
if int(validity) < time.time():
59+
LOGGER.debug(f"Signature validity expired: {validity}")
5860
raise aiohttp.web.HTTPUnauthorized(
59-
reason="Signature expired"
61+
reason="Signature validity expired"
6062
)
6163
byte_message = message.encode("utf-8")
6264
for token in tokens:
@@ -67,6 +69,7 @@ async def test_signature(
6769
).hexdigest()
6870
if secrets.compare_digest(digest, signature):
6971
return
72+
LOGGER.debug(f"Missing valid query signature for signature {signature}")
7073
raise aiohttp.web.HTTPUnauthorized(
7174
reason="Missing valid query signature"
7275
)
@@ -83,8 +86,9 @@ async def handle_validate_authentication(
8386
validity = request.query["valid"]
8487
path = request.url.path
8588
except KeyError:
89+
LOGGER.debug("Query string missing validity or signature")
8690
raise aiohttp.web.HTTPClientError(
87-
reason="Query string missing validity or signature."
91+
reason="Query string missing validity or signature"
8892
)
8993

9094
project: typing.Union[None, str]

swift_x_account_sharing/bindings/bind.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,17 @@ async def _handler_response(
4444
try:
4545
return json.loads(await resp.text())
4646
except json.decoder.JSONDecodeError:
47-
logging.error("Decoding JSON error \
48-
response was not possible.")
47+
logging.error("Decoding JSON error, "
48+
"response was not possible.")
4949
raise
5050
except Exception as e:
51-
logging.error(f"Unknown exception \
52-
occured with content: {e}.")
51+
logging.error("Unknown exception "
52+
f"occured with content: {e}.")
5353
raise
5454
else:
55-
logging.error(f"response status: {resp.status}.")
56-
raise Exception(f"response status: {resp.status}.")
55+
logging.error(f"API call {resp.url} responded with "
56+
f"status {resp.status} and reason {resp.reason}.")
57+
raise Exception
5758

5859
@staticmethod
5960
def parse_list_to_string(
@@ -195,4 +196,9 @@ async def share_delete_access(
195196
async with self.session.delete(url,
196197
params=params,
197198
ssl=ssl_context) as resp:
198-
return bool(resp.status == 204)
199+
if resp.status == 204:
200+
return True
201+
else:
202+
logging.error(f"API call {resp.url} responded with status "
203+
f"{resp.status} and reason {resp.reason}.")
204+
raise Exception

swift_x_account_sharing/bindings/signature.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def sign_api_request(
1010
path: str
1111
) -> dict:
1212
"""Handle authentication with a signature."""
13-
valid_until = str(int(time.time() + 10))
13+
valid_until = str(int(time.time() + (60 * 61)))
1414
to_sign = (valid_until + path).encode("utf-8")
1515

1616
digest = hmac.new(

swift_x_account_sharing/db.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313

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

1617

1718
def handle_dropped_connection(

tests/test_bindings_bind.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ def __init__(self, *args, **kwargs):
2020
"text": asynctest.CoroutineMock(
2121
return_value="[]"
2222
),
23-
"status": 200
23+
"status": 200,
24+
"url": "http://example",
2425
})
2526

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

5354
def __init__(self, *args, **kwargs):
5455
"""."""
55-
super(MockDeleteContextManager, self).__init__(
56-
self,
57-
*args,
58-
**kwargs
59-
)
56+
self.resp = SimpleNamespace(**{
57+
"status": 204,
58+
"url": "http://example",
59+
"reason": "reason"
60+
})
61+
62+
async def __aenter__(self, *args, **kwargs):
63+
"""."""
64+
return self.resp
6065

6166
async def __aexit__(self, *excinfo):
6267
"""."""

0 commit comments

Comments
 (0)