asfpy 0.52__tar.gz → 0.54__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
asfpy-0.54/PKG-INFO ADDED
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.1
2
+ Name: asfpy
3
+ Version: 0.54
4
+ Summary: ASF Common Python Methods
5
+ Author: ASF Infrastructure
6
+ Author-email: users@infra.apache.org
7
+ Requires-Python: >=3.9,<4
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: aiohttp (>=3.10.5,<4.0.0)
15
+ Requires-Dist: bonsai (>=1.5.3,<2.0.0)
16
+ Requires-Dist: cffi (>=1.17.1,<2.0.0)
17
+ Requires-Dist: cryptography (>=43.0.1,<44.0.0)
18
+ Requires-Dist: easydict (>=1.13,<2.0)
19
+ Requires-Dist: ezt (>=1.1,<2.0)
20
+ Requires-Dist: python-ldap (>=3.4.4,<4.0.0)
21
+ Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
22
+ Requires-Dist: requests (>=2.32.3,<3.0.0)
23
+ Requires-Dist: watchfiles (>=1.0.0,<2.0.0)
24
+ Description-Content-Type: text/markdown
25
+
26
+ # asfpy - ASF Infrastructure Common Library for Python functions
27
+
28
+ This Python library contains features commonly used at the Apache Software Foundation.
29
+
30
+ (For asfpy 0.37 and below, look at our old [Subversion repository](https://svn.apache.org/repos/infra/infrastructure/trunk/projects/asfpy/))
31
+
32
+
33
+ ## Building asfpy package
34
+
35
+ Preparation
36
+
37
+ * `apt install python3.10-venv`
38
+ * `pip3 install build twine`
39
+
40
+ Bump the version number in `setup.py` and run:
41
+ `python3 -m build`
42
+
43
+
44
+ ## Publishing a new asfpy package
45
+
46
+ After building the asfpy package, run the following command, where $version is the new version to publish:
47
+
48
+ `python3 -m twine upload dist/asfpy-$version*` (for instance `dist/asfpy-0.38*`)
49
+
50
+ The above command will upload the `.whl` and the `.tar.gz` (the glob-asterisk is important!)
51
+
52
+ See [this guide](https://realpython.com/pypi-publish-python-package/#publish-your-package-to-pypi) for more details on working with PyPi.
53
+
54
+ Please also create a tag for the release.
55
+
56
+ ### for testing
57
+
58
+ Create an account on https://test.pypi.org/, then add a token with an
59
+ "all projects" scope. Place that into your `.pypirc` like so:
60
+
61
+ ```
62
+ [testpypi]
63
+ repository = https://test.pypi.org/legacy/
64
+ username = __token__
65
+ password = pypi-tokenstringgoeshere
66
+ ```
67
+
68
+ Then you can test an upload with:
69
+ `python3 -m twine upload -r testpypi dist/asf-py$version*`
70
+
71
+ The package should upload to the test.pypi.org service.
72
+
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Licensed to the Apache Software Foundation (ASF) under one or more
4
+ # contributor license agreements. See the NOTICE file distributed with
5
+ # this work for additional information regarding copyright ownership.
6
+ # The ASF licenses this file to You under the Apache License, Version 2.0
7
+ # (the "License"); you may not use this file except in compliance with
8
+ # the License. You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """Auxiliary crypto features. Just ED25519 signing for now."""
18
+ import binascii
19
+
20
+ import cryptography.exceptions
21
+ import cryptography.hazmat.primitives.asymmetric.ed25519
22
+ import cryptography.hazmat.primitives.serialization
23
+ import secrets
24
+ import base64
25
+
26
+ # Defaults PEM format for our ED25519 keys
27
+ ED25519_ENCODING = cryptography.hazmat.primitives.serialization.Encoding.PEM
28
+ ED25519_PRIVKEY_FORMAT = cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8
29
+ ED25519_PUBKEY_FORMAT = cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo
30
+ ED25519_PEM_ENCRYPTION = cryptography.hazmat.primitives.serialization.NoEncryption()
31
+
32
+
33
+ class ED25519:
34
+ def __init__(self, pubkey: str = None, privkey: str = None):
35
+ """Loads an existing ED25519 key or instantiates a new ED25519 key pair.
36
+ If pubkey is set, it loads it as a PEM-formatted key, same with privkey.
37
+ If no public or private key is passed on, a new keypair is created instead."""
38
+ if pubkey:
39
+ self._pubkey = cryptography.hazmat.primitives.serialization.load_pem_public_key(pubkey.encode("us-ascii"))
40
+ self._privkey = None
41
+ elif privkey:
42
+ self._privkey = cryptography.hazmat.primitives.serialization.load_pem_private_key(
43
+ privkey.encode("us-ascii"), password=None
44
+ )
45
+ else:
46
+ self._privkey = cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.generate()
47
+
48
+ # Private keys can be used to generate as many public keys as needed, so we can create one for testing.
49
+ if self._privkey:
50
+ self._pubkey = self._privkey.public_key()
51
+
52
+ @property
53
+ def pubkey(self):
54
+ """ "Returns the public key (if present) in PEM format"""
55
+ assert self._pubkey, "No public key found, cannot PEM-encode nothing!"
56
+ return self._pubkey.public_bytes(encoding=ED25519_ENCODING, format=ED25519_PUBKEY_FORMAT).decode("us-ascii")
57
+
58
+ @property
59
+ def privkey(self):
60
+ """ "Returns the private key (if present) in PEM format"""
61
+ assert self._privkey, "No public key found, cannot PEM-encode nothing!"
62
+ return self._privkey.private_bytes(
63
+ encoding=ED25519_ENCODING, format=ED25519_PRIVKEY_FORMAT, encryption_algorithm=ED25519_PEM_ENCRYPTION
64
+ ).decode("us-ascii")
65
+
66
+ def sign_data(self, data: str = "", output_b64=False):
67
+ """Signs a string with the private key for authenticity purposes.
68
+ The signature includes a nonce for randomizing the response and returns three lines, split by newline:
69
+ data-plus-nonce-signature
70
+ nonce
71
+ data
72
+
73
+ The blob can be verified by verify_data, which will return the verified data if the signature is valid,
74
+ else None.
75
+
76
+ If output_b64 is True, the signed data is base64-encoded and returned as a single line. This can be
77
+ useful for HTTP-based access tokens.
78
+ """
79
+ nonce = secrets.token_hex(32)
80
+ data_plus_nonce = "\n".join([nonce, data])
81
+ data_signature = self._privkey.sign(data_plus_nonce.encode("us-ascii"))
82
+ response = "\n".join([base64.b64encode(data_signature).decode("us-ascii"), nonce, data])
83
+ if output_b64:
84
+ response = base64.b64encode(response.encode('us-ascii')).decode('us-ascii')
85
+ return response
86
+
87
+ def verify_response(self, data: str):
88
+ """Verifies the authenticity of a data blob. If signed by the private key,
89
+ returns the original data that was signed, otherwise None"""
90
+ try:
91
+ if "\n" not in data: # base64-encoded one-liner?
92
+ try:
93
+ data = base64.b64decode(data).decode('us-ascii')
94
+ except binascii.Error: # Not base64!
95
+ return None
96
+ signature, data_plus_nonce = data.split("\n", 1)
97
+ signature = base64.b64decode(signature)
98
+ except ValueError: # Bad token format or invalid base64 signature, FAILURE.
99
+ return
100
+ try:
101
+ _nonce, data_verified = data_plus_nonce.split("\n", 1)
102
+ self._pubkey.verify(signature, data_plus_nonce.encode("us-ascii"))
103
+ return data_verified
104
+ except cryptography.exceptions.InvalidSignature:
105
+ return
asfpy-0.54/asfpy/db.py ADDED
@@ -0,0 +1,119 @@
1
+ #
2
+ # Licensed to the Apache Software Foundation (ASF) under one or more
3
+ # contributor license agreements. See the NOTICE file distributed with
4
+ # this work for additional information regarding copyright ownership.
5
+ # The ASF licenses this file to You under the Apache License, Version 2.0
6
+ # (the "License"); you may not use this file except in compliance with
7
+ # the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+ # ----
18
+ #
19
+ # Convenience wrapper for working with a SQLite database.
20
+ #
21
+ # This wrapper has several primary purposes:
22
+ #
23
+ # 1. Easily create a cursor for each statement that might be
24
+ # executed by the application.
25
+ # 2. Remember the specific string object for those statements,
26
+ # and re-use them in cursor.execute() for better performance.
27
+ # 3. Rows fetched with SELECT statements are wrapped into a
28
+ # EasyDict() instance, such that columns can be easily
29
+ # accessed as attributes.
30
+ #
31
+
32
+ import sqlite3
33
+ import functools
34
+
35
+ import yaml
36
+ import easydict
37
+
38
+
39
+ class DB:
40
+ """Wrapper/functional class for accessing Sqlite3 databases.
41
+
42
+ This class focuses on returning EasyDict instances for query results,
43
+ so that columns can be indexed by name instead of position.
44
+
45
+ In addition, it makes it easy to create cursors for later usage. Naming
46
+ the cursors establishes a self-documenting mechanism when performing
47
+ the statement or query. These cursors may be establishing through the
48
+ use a .yaml file to clarify the SQL operations in a file for that
49
+ purpose, instead of mixing them throughout a codebase.
50
+ """
51
+
52
+ def __init__(self, fname, yaml_fname=None, yaml_section='queries'):
53
+
54
+ def row_factory(cursor, row):
55
+ "Return an EasyDict of the row, for attribute access."
56
+ return easydict.EasyDict(sqlite3.Row(cursor, row))
57
+
58
+ # Note: isolation_level=None means autocommit mode.
59
+ self.conn = sqlite3.connect(fname, isolation_level=None)
60
+ self.conn.row_factory = row_factory
61
+
62
+ # If a YAML file containing SQL queries is presented, then create
63
+ # cursors for each statement, and storing those cursors as (named)
64
+ # attributes on SELF, for later use by the calling application.
65
+ if yaml_fname:
66
+ # Note: this could be a general configuration file for the
67
+ # application. We'll look at just one section of it.
68
+ yml = yaml.safe_load(open(yaml_fname))
69
+
70
+ # The YAML_SECTION (default "queries") should have names of
71
+ # queries, to use as attributes, and the value should be the
72
+ # SQL statement/query.
73
+ for name, sql in yml.get(yaml_section, { }).items():
74
+ if hasattr(self, name):
75
+ ### ValueError seems to be the bog standard for duplicates
76
+ raise ValueError(f'duplicate: {name}')
77
+ #print(f'{name}: {sql}')
78
+ setattr(self, name, self.cursor_for(sql))
79
+
80
+ def cursor_for(self, statement):
81
+ "Return our custom cursor for the given statement."
82
+ return self.conn.cursor(_Cursor.factory_for(statement))
83
+
84
+
85
+ class _Cursor(sqlite3.Cursor):
86
+ "A cursor subclass providing helper methods."
87
+
88
+ @classmethod
89
+ def factory_for(cls, statement):
90
+ "Return a factory to construct instances for the given STATEMENT."
91
+ return functools.partial(cls, statement)
92
+
93
+ def __init__(self, statement, conn):
94
+ super().__init__(conn)
95
+ self.statement = statement
96
+
97
+ def perform(self, *params):
98
+ "Perform the statement with PARAMs, or prepare the query."
99
+
100
+ # Use the exact same STATEMENT each time. Python's SQLite module
101
+ # caches the parsed statement, if the string is the same object.
102
+ self.execute(self.statement, params)
103
+
104
+ def first_row(self, *params):
105
+ "Helper method to fetch the first row of a query."
106
+ self.perform(*params)
107
+ row = self.fetchone()
108
+ # We do not want to close the cursor. Thus, we must run the fetch
109
+ # to completion instead. For queries using .first_row() this should
110
+ # be no further rows.
111
+ _ = self.fetchall()
112
+ return row # note the ROW_FACTORY implies this is an EasyDict
113
+
114
+
115
+ if __name__ == '__main__':
116
+ ### maybe run some tests?
117
+ import sys
118
+ sys.stderr.write('ERROR: this module is not for command line use.\n')
119
+ sys.exit(1)
@@ -32,7 +32,7 @@
32
32
  import logging
33
33
 
34
34
  import ezt
35
- import asyncinotify
35
+ import watchfiles
36
36
 
37
37
  LOGGER = logging.getLogger(__name__)
38
38
 
@@ -43,7 +43,7 @@ class TemplateWatcher:
43
43
  # PATH : (ezt.Template, BASE_FORMAT)
44
44
  self.templates = { }
45
45
 
46
- self.inotify = asyncinotify.Inotify()
46
+ self.files = set()
47
47
 
48
48
  def load_template(self, path, **kwargs):
49
49
  """Load template at PATH with **KWARGS.
@@ -54,18 +54,25 @@ class TemplateWatcher:
54
54
  Returns an instance of ezt.Template()
55
55
  """
56
56
 
57
+ LOGGER.info(f'Watching: {path}')
57
58
  t = ezt.Template(path, **kwargs)
58
59
  bf = kwargs.get('base_format', ezt.FORMAT_RAW)
59
- self.templates[path] = (t, bf)
60
- self.inotify.add_watch(path,
61
- asyncinotify.Mask.MODIFY
62
- | asyncinotify.Mask.MASK_CREATE)
60
+
61
+ # Use str(path) in case PATH is a pathlib.Path instance.
62
+ self.templates[str(path)] = (t, bf)
63
+
64
+ self.files.add(path)
65
+
63
66
  return t
64
67
 
68
+ @staticmethod
69
+ def watch_filter(change: watchfiles.Change, path: str) -> bool:
70
+ return change in {watchfiles.Change.added, watchfiles.Change.modified}
71
+
65
72
  async def watch_forever(self):
66
- with self.inotify:
67
- async for event in self.inotify:
68
- path = str(event.path)
73
+ async for changes in watchfiles.awatch(*self.files, watch_filter=self.watch_filter):
74
+ for event in changes:
75
+ path = str(event[1])
69
76
  LOGGER.info(f'Template changed: {path}')
70
77
  #print(event)
71
78
 
@@ -0,0 +1,44 @@
1
+ [tool.poetry]
2
+ name = "asfpy"
3
+ version = "0.54"
4
+ description='ASF Common Python Methods'
5
+ authors = ["ASF Infrastructure <users@infra.apache.org>"]
6
+ readme = "README.md"
7
+ classifiers = [
8
+ "License :: OSI Approved :: Apache Software License",
9
+ "Programming Language :: Python :: 3"
10
+ ]
11
+
12
+ [tool.poetry.dependencies]
13
+ python = ">=3.9,<4"
14
+ aiohttp = "^3.10.5"
15
+ bonsai = "^1.5.3"
16
+ ezt = "^1.1"
17
+ python-ldap = "^3.4.4"
18
+ requests = "^2.32.3"
19
+ easydict = "^1.13"
20
+ pyyaml = "^6.0.2"
21
+ cryptography = "^43.0.1"
22
+ cffi = "^1.17.1"
23
+ watchfiles = "^1.0.0"
24
+
25
+
26
+ [build-system]
27
+ requires = ["poetry-core"]
28
+ build-backend = "poetry.core.masonry.api"
29
+
30
+ [tool.poetry.group.dev.dependencies]
31
+ pytest = "*"
32
+ pylint = "*"
33
+
34
+ [tool.poetry.group.ldap]
35
+ optional = true
36
+
37
+ [tool.poetry.group.ldap.dependencies]
38
+ python-ldap = "*"
39
+
40
+ [tool.poetry.group.aioldap]
41
+ optional = true
42
+
43
+ [tool.poetry.group.aioldap.dependencies]
44
+ bonsai = "*"
asfpy-0.52/MANIFEST.in DELETED
@@ -1 +0,0 @@
1
- prune test/
asfpy-0.52/PKG-INFO DELETED
@@ -1,15 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: asfpy
3
- Version: 0.52
4
- Summary: ASF Common Python Methods
5
- Home-page: https://github.com/apache/infrastructure-asfpy/
6
- Author: ASF Infrastructure
7
- Author-email: users@infra.apache.org
8
- License: Apache
9
- Platform: UNKNOWN
10
- Description-Content-Type: text/plain
11
- Provides-Extra: ldap
12
- Provides-Extra: aioldap
13
-
14
- This is a common set of functions used by the ASF Infrastructure team such as libraries for sending email, ldap management and generic process daemonization.
15
-
@@ -1,15 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: asfpy
3
- Version: 0.52
4
- Summary: ASF Common Python Methods
5
- Home-page: https://github.com/apache/infrastructure-asfpy/
6
- Author: ASF Infrastructure
7
- Author-email: users@infra.apache.org
8
- License: Apache
9
- Platform: UNKNOWN
10
- Description-Content-Type: text/plain
11
- Provides-Extra: ldap
12
- Provides-Extra: aioldap
13
-
14
- This is a common set of functions used by the ASF Infrastructure team such as libraries for sending email, ldap management and generic process daemonization.
15
-
@@ -1,21 +0,0 @@
1
- MANIFEST.in
2
- README.md
3
- setup.py
4
- asfpy/__init__.py
5
- asfpy/aioldap.py
6
- asfpy/clitools.py
7
- asfpy/daemon.py
8
- asfpy/justone.py
9
- asfpy/ldapadmin.py
10
- asfpy/messaging.py
11
- asfpy/pubsub.py
12
- asfpy/sqlite.py
13
- asfpy/syslog.py
14
- asfpy/twatcher.py
15
- asfpy/whoami.py
16
- asfpy.egg-info/PKG-INFO
17
- asfpy.egg-info/SOURCES.txt
18
- asfpy.egg-info/dependency_links.txt
19
- asfpy.egg-info/not-zip-safe
20
- asfpy.egg-info/requires.txt
21
- asfpy.egg-info/top_level.txt
@@ -1 +0,0 @@
1
-
@@ -1,11 +0,0 @@
1
- requests
2
- ezt
3
- requests
4
- aiohttp
5
- asyncinotify
6
-
7
- [aioldap]
8
- bonsai
9
-
10
- [ldap]
11
- python-ldap
@@ -1 +0,0 @@
1
- asfpy
asfpy-0.52/setup.cfg DELETED
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
asfpy-0.52/setup.py DELETED
@@ -1,47 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- # Licensed to the Apache Software Foundation (ASF) under one or more
4
- # contributor license agreements. See the NOTICE file distributed with
5
- # this work for additional information regarding copyright ownership.
6
- # The ASF licenses this file to You under the Apache License, Version 2.0
7
- # (the "License"); you may not use this file except in compliance with
8
- # the License. You may obtain a copy of the License at
9
- #
10
- # http://www.apache.org/licenses/LICENSE-2.0
11
- #
12
- # Unless required by applicable law or agreed to in writing, software
13
- # distributed under the License is distributed on an "AS IS" BASIS,
14
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- # See the License for the specific language governing permissions and
16
- # limitations under the License.
17
-
18
- import setuptools
19
-
20
-
21
- def main():
22
- setuptools.setup(name='asfpy',
23
- version='0.52',
24
- description='ASF Common Python Methods',
25
- long_description="This is a common set of functions used by the ASF Infrastructure team such as libraries for sending email, ldap management and generic process daemonization.",
26
- long_description_content_type = "text/plain",
27
- url='https://github.com/apache/infrastructure-asfpy/',
28
- author='ASF Infrastructure',
29
- author_email='users@infra.apache.org',
30
- license='Apache',
31
- packages=['asfpy'],
32
- install_requires=[
33
- 'requests',
34
- 'ezt',
35
- 'requests',
36
- 'aiohttp',
37
- 'asyncinotify',
38
- ],
39
- extras_require= {
40
- 'ldap': ['python-ldap'],
41
- 'aioldap': ['bonsai'],
42
- },
43
- zip_safe=False)
44
-
45
-
46
- if __name__ == '__main__':
47
- main()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes