asfpy 0.52__tar.gz → 0.53__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.
Potentially problematic release.
This version of asfpy might be problematic. Click here for more details.
- asfpy-0.53/PKG-INFO +72 -0
- asfpy-0.53/asfpy/NOTES +129 -0
- asfpy-0.53/asfpy/crypto.py +105 -0
- asfpy-0.53/asfpy/db.py +119 -0
- asfpy-0.53/asfpy/ldap.py +440 -0
- asfpy-0.53/asfpy/t.py +8 -0
- asfpy-0.53/asfpy/t2.py +7 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/twatcher.py +16 -9
- asfpy-0.53/pyproject.toml +44 -0
- asfpy-0.52/MANIFEST.in +0 -1
- asfpy-0.52/PKG-INFO +0 -15
- asfpy-0.52/asfpy.egg-info/PKG-INFO +0 -15
- asfpy-0.52/asfpy.egg-info/SOURCES.txt +0 -21
- asfpy-0.52/asfpy.egg-info/dependency_links.txt +0 -1
- asfpy-0.52/asfpy.egg-info/not-zip-safe +0 -1
- asfpy-0.52/asfpy.egg-info/requires.txt +0 -11
- asfpy-0.52/asfpy.egg-info/top_level.txt +0 -1
- asfpy-0.52/setup.cfg +0 -4
- asfpy-0.52/setup.py +0 -47
- {asfpy-0.52 → asfpy-0.53}/README.md +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/__init__.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/aioldap.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/clitools.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/daemon.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/justone.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/ldapadmin.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/messaging.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/pubsub.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/sqlite.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/syslog.py +0 -0
- {asfpy-0.52 → asfpy-0.53}/asfpy/whoami.py +0 -0
asfpy-0.53/PKG-INFO
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: asfpy
|
|
3
|
+
Version: 0.53
|
|
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
|
+
|
asfpy-0.53/asfpy/NOTES
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
host = "mail-relay.apache.org",
|
|
2
|
+
recipient = email,
|
|
3
|
+
subject = "Welcome to the Apache Software Foundation!",
|
|
4
|
+
sender = '<root@apache.org>',
|
|
5
|
+
message = messageBody,
|
|
6
|
+
|
|
7
|
+
host = "mail-relay.apache.org",
|
|
8
|
+
recipient = ["private@"+project+".apache.org","root@apache.org"],
|
|
9
|
+
subject = "[NOTICE] Account created: "+fullName+" ("+uid+")",
|
|
10
|
+
sender = '<root@apache.org>',
|
|
11
|
+
message = messageBody,
|
|
12
|
+
|
|
13
|
+
host = "mail-relay.apache.org",
|
|
14
|
+
recipient = 'root@apache.org',
|
|
15
|
+
subject = "[NOTICE] Account created: "+fullName+" ("+uid+")",
|
|
16
|
+
sender = '<root@apache.org>',
|
|
17
|
+
message = messageBody,
|
|
18
|
+
|
|
19
|
+
host="mail-relay.apache.org",
|
|
20
|
+
recipient=recip,
|
|
21
|
+
subject=subj,
|
|
22
|
+
sender='<root@apache.org>',
|
|
23
|
+
message=messageBody,
|
|
24
|
+
|
|
25
|
+
asfyaml.py:
|
|
26
|
+
asfpy.messaging.mail(
|
|
27
|
+
sender='GitBox <gitbox@apache.org>',
|
|
28
|
+
recipients=['private@%s.apache.org' % pname],
|
|
29
|
+
subject=subject,
|
|
30
|
+
message=message)
|
|
31
|
+
|
|
32
|
+
download-integrity-checker:
|
|
33
|
+
sender="ASF Infrastructure <root@apache.org>",
|
|
34
|
+
subject=f"Verification of download artifacts on dist.apache.org FAILED for {project}!",
|
|
35
|
+
recipients=recipients,
|
|
36
|
+
message=EMAIL_TEMPLATE.format(**locals())
|
|
37
|
+
|
|
38
|
+
kif.py:
|
|
39
|
+
asfpy.messaging.mail(sender=ecfg['from'], recipient=ecfg['rcpt'], subject=subject, message=msg)
|
|
40
|
+
|
|
41
|
+
boxer:
|
|
42
|
+
asfpy.messaging.mail(
|
|
43
|
+
sender="GitBox <gitbox@apache.org>",
|
|
44
|
+
recipients=[NEW_REPO_NOTIFY, f"private@{pmc}.apache.org"],
|
|
45
|
+
subject=f"New GitBox/GitHub repository set up: {reponame}",
|
|
46
|
+
message=NEW_REPO_NOTIFY_MSG % locals()
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
gitbox_syncer/github_sync.py
|
|
50
|
+
asfpy.messaging.mail(
|
|
51
|
+
recipient = '<team@infra.apache.org>',
|
|
52
|
+
subject = "gitbox repository %s: push from unknown github user!" % reponame,
|
|
53
|
+
sender = '<gitbox@apache.org>',
|
|
54
|
+
message = tmpl_unknown_user % locals(),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
sscommon.py:
|
|
58
|
+
asfpy.messaging.mail(
|
|
59
|
+
sender = sender,
|
|
60
|
+
recipients = receivers,
|
|
61
|
+
subject = subject,
|
|
62
|
+
message = msg
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
https://github.com/apache/infrastructure-github-event-notifier/blob/e036b4728fa5d3b69794c268601034eabe95f9d5/notifier.py
|
|
67
|
+
asfpy.messaging.mail(
|
|
68
|
+
sender="GitBox <git@apache.org>",
|
|
69
|
+
recipient=recipient,
|
|
70
|
+
subject=real_subject,
|
|
71
|
+
message=real_text,
|
|
72
|
+
messageid=msgid,
|
|
73
|
+
headers=msg_headers,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
https://github.com/apache/infrastructure-p6/blob/bbe6148c2d3a6efff50ccfe4845aa65c110bf84a/modules/gitbox/files/asfgit/hooks/post-receive.d/03-check-rel.py
|
|
77
|
+
asfpy.messaging.mail(
|
|
78
|
+
sender="<gitbox@apache.org>",
|
|
79
|
+
subject = subject,
|
|
80
|
+
recipient = "<notifications@infra.apache.org>",
|
|
81
|
+
message=msg
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
https://github.com/apache/infrastructure-github-discussions-notifier/blob/1e03320894298135a4e3f9f3518de7a4abb712a4/ghd-notifier.py
|
|
85
|
+
asfpy.messaging.mail(
|
|
86
|
+
sender="GitBox <git@apache.org>", recipient=recipient, subject=subject, message=text, messageid=msgid, headers=msg_headers
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
https://github.com/apache/infrastructure-gha-notifier/blob/43c7748f697b85d345bb63393da255fddf363a4c/ghactions.py
|
|
90
|
+
asfpy.messaging.mail(
|
|
91
|
+
sender="GitBox <git@apache.org>", recipient=recipient, subject=subject, message=text
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
https://github.com/apache/infrastructure-github-code-syncer/blob/614826674907e265c77f42c9b259d7f786a1dd30/payloadparser.py
|
|
95
|
+
asfpy.messaging.mail(
|
|
96
|
+
recipient="<private@infra.apache.org>",
|
|
97
|
+
subject="[REVIEW NEEDED] github repository %s: push from unknown github user!" % reponame,
|
|
98
|
+
sender="<gitbox@apache.org>",
|
|
99
|
+
message=tmpl_unknown_user % locals(),
|
|
100
|
+
)
|
|
101
|
+
asfpy.messaging.mail(
|
|
102
|
+
recipient="<notifications@infra.apache.org>",
|
|
103
|
+
subject="gitbox repository %s: sqlite operational error!" % reponame,
|
|
104
|
+
sender="<gitbox@apache.org>",
|
|
105
|
+
message="gitbox.db could not be written to: %s" % txt,
|
|
106
|
+
)
|
|
107
|
+
asfpy.messaging.mail(
|
|
108
|
+
recipient="<notifications@infra.apache.org>",
|
|
109
|
+
subject="gitbox repository %s: missed event/push!" % reponame,
|
|
110
|
+
sender="<gitbox@apache.org>",
|
|
111
|
+
message=tmpl_missed_webhook % locals(),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
https://github.com/apache/infrastructure-p6/blob/4692b7ede4f819b9075f241f57354a0a72fb6911/modules/gitbox/files/asfgit/hooks/post-receive.d/05-asfyaml.py
|
|
115
|
+
asfpy.messaging.mail(recipients = [blamemail, main_contact], subject = "Failed to parse .asf.yaml in %s.git!" % cfg.repo_name, message = str(e))
|
|
116
|
+
asfpy.messaging.mail(recipients = [blamemail, main_contact], subject = subject, message = errors)
|
|
117
|
+
asfpy.messaging.mail(recipients = [blamemail, main_contact], subject = subject, message = msg)
|
|
118
|
+
|
|
119
|
+
https://github.com/apache/infrastructure-webmod/blob/db9cec85690573d7307307ffd1f7f1b0e024c0d8/scripts/modreq.py
|
|
120
|
+
asfpy.messaging.mail(
|
|
121
|
+
sender = "ASF WebMod <root@apache.org>",
|
|
122
|
+
recipient = f"private@{domain}",
|
|
123
|
+
subject = f"Mailing list moderators for {mlist} updated by {session['uid']}",
|
|
124
|
+
message = f"The following changes to the moderator list have been made by {session['uid']}:\n{message}\n",
|
|
125
|
+
host = state.config["smtp"],
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
https://github.com/apache/infrastructure-occ/blob/163f8292019e38af935e27a157732464bd13a7d0/occ.py
|
|
129
|
+
asfpy.messaging.mail(recipient=blamelist, subject=blamesubject, message=TMPL_FAILURE % (e.exitcode, e.reason))
|
|
@@ -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.53/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)
|
asfpy-0.53/asfpy/ldap.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
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
|
+
""" ASF LDAP Account Manager """
|
|
19
|
+
|
|
20
|
+
import sys
|
|
21
|
+
assert sys.version_info >= (3, 2)
|
|
22
|
+
|
|
23
|
+
import ldap
|
|
24
|
+
import ldap.modlist
|
|
25
|
+
import ldif
|
|
26
|
+
import re
|
|
27
|
+
import crypt
|
|
28
|
+
import random
|
|
29
|
+
import string
|
|
30
|
+
|
|
31
|
+
LDAP_SANDBOX = "ldaps://ldap-sandbox.apache.org:636"
|
|
32
|
+
LDAP_MASTER = "ldaps://ldap-us.apache.org:636"
|
|
33
|
+
LDAP_SUFFIX = 'dc=apache,dc=org'
|
|
34
|
+
LDAP_PEOPLE_BASE = 'ou=people,dc=apache,dc=org'
|
|
35
|
+
LDAP_GROUPS_BASE = 'ou=groups,dc=apache,dc=org'
|
|
36
|
+
LDAP_APLDAP_BASE = 'cn=apldap,ou=groups,ou=services,dc=apache,dc=org'
|
|
37
|
+
LDAP_CHAIRS_BASE = 'cn=pmc-chairs,ou=groups,ou=services,dc=apache,dc=org'
|
|
38
|
+
LDAP_PMCS_BASE = 'ou=project,ou=groups,dc=apache,dc=org'
|
|
39
|
+
LDAP_ROLES_BASE = 'ou=role,ou=groups,dc=apache,dc=org'
|
|
40
|
+
LDAP_DN = 'uid=%s,ou=people,dc=apache,dc=org'
|
|
41
|
+
LDAP_CN = 'cn=%s,%s'
|
|
42
|
+
|
|
43
|
+
# INFRA-21590 ApacheID cannot have dashes.
|
|
44
|
+
LDAP_VALID_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_]+$")
|
|
45
|
+
# New user account UIDs will be larger than this value.
|
|
46
|
+
# Conversely: service accounts will be less than this.
|
|
47
|
+
# NOTE: this value was chosen to ensure enough lower-value
|
|
48
|
+
# UIDs were available for service accounts, until we
|
|
49
|
+
# reach the heat death of the universe.
|
|
50
|
+
MINIMUM_USER_UID = 6000
|
|
51
|
+
|
|
52
|
+
# New service account UIDs will be larger than this value,
|
|
53
|
+
# but below that of MINIMUM_UID.
|
|
54
|
+
# NOTE: since the GID is chosen to match the UID, we start
|
|
55
|
+
# at 5010, to avoid collision with: "nacho" uid=1122 gid=5004
|
|
56
|
+
MINIMUM_SVC_UID = 5010
|
|
57
|
+
|
|
58
|
+
assert MINIMUM_USER_UID > MINIMUM_SVC_UID
|
|
59
|
+
|
|
60
|
+
ASSERTION_FAILED = "Common backend assertions failed, LDAP corruption?"
|
|
61
|
+
BACKEND_TIMEOUT = "The backend authentication server timed out, please retry later."
|
|
62
|
+
|
|
63
|
+
def bytify(ldiff):
|
|
64
|
+
""" Convert all values in a dict to byte-string """
|
|
65
|
+
for k, v in ldiff.items():
|
|
66
|
+
if type(v) is list:
|
|
67
|
+
n = 0
|
|
68
|
+
for xv in v:
|
|
69
|
+
if type(v[n]) is str:
|
|
70
|
+
v[n] = xv.encode('utf-8')
|
|
71
|
+
n += 1
|
|
72
|
+
else:
|
|
73
|
+
if type(v) is str:
|
|
74
|
+
v = [v.encode('utf-8')]
|
|
75
|
+
ldiff[k] = v
|
|
76
|
+
return ldiff
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def stringify(ldiff):
|
|
80
|
+
""" Convert all values in a dict to string """
|
|
81
|
+
for k, v in ldiff.items():
|
|
82
|
+
# Convert single-list to string
|
|
83
|
+
if type(v) is list and len(v) == 1:
|
|
84
|
+
v = v[0]
|
|
85
|
+
|
|
86
|
+
if type(v) is list:
|
|
87
|
+
n = 0
|
|
88
|
+
for xv in v:
|
|
89
|
+
if type(v[n]) is bytes:
|
|
90
|
+
v[n] = xv.decode('utf-8')
|
|
91
|
+
n += 1
|
|
92
|
+
else:
|
|
93
|
+
if type(v) is bytes:
|
|
94
|
+
v = v.decode('utf-8')
|
|
95
|
+
ldiff[k] = v
|
|
96
|
+
return ldiff
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ConnectionException(Exception):
|
|
100
|
+
""" Simple exception with a message and an optional origin exception (WIP) """
|
|
101
|
+
def __init__(self, message, origin=None):
|
|
102
|
+
super().__init__(message)
|
|
103
|
+
self.origin = origin
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ValidatorException(Exception):
|
|
107
|
+
""" Simple validator exception with a message and an optional triggering attribute """
|
|
108
|
+
def __init__(self, message, attrib=None):
|
|
109
|
+
super().__init__(message)
|
|
110
|
+
self.attribute = attrib
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class committer:
|
|
114
|
+
""" Committer class, allows for munging data """
|
|
115
|
+
|
|
116
|
+
def __init__(self, mgr, res):
|
|
117
|
+
self.manager = mgr
|
|
118
|
+
self.dn = res[0][0]
|
|
119
|
+
self.dn_enc = self.dn.encode('ascii')
|
|
120
|
+
self.attributes = stringify(res[0][1])
|
|
121
|
+
self.uid = self.attributes['uid']
|
|
122
|
+
|
|
123
|
+
def add_project(self, project):
|
|
124
|
+
""" Add person to project (as committer) """
|
|
125
|
+
dn = LDAP_CN % (project, LDAP_PMCS_BASE)
|
|
126
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_ADD, 'member', self.dn_enc)])
|
|
127
|
+
|
|
128
|
+
def add_pmc(self, project):
|
|
129
|
+
""" Add person to project (as PMC member) """
|
|
130
|
+
dn = LDAP_CN % (project, LDAP_PMCS_BASE)
|
|
131
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_ADD, 'owner', self.dn_enc)])
|
|
132
|
+
|
|
133
|
+
def add_basic_group(self, group):
|
|
134
|
+
""" Add person to basic posixGroup entry """
|
|
135
|
+
dn = LDAP_CN % (group, LDAP_GROUPS_BASE)
|
|
136
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_ADD, 'memberUid', self.uid.encode('ascii'))])
|
|
137
|
+
|
|
138
|
+
def add_role(self, role):
|
|
139
|
+
""" Add person to basic posixGroup entry """
|
|
140
|
+
dn = LDAP_CN % (role, LDAP_ROLES_BASE)
|
|
141
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_ADD, 'member', self.dn_enc)])
|
|
142
|
+
|
|
143
|
+
def remove_project(self, project):
|
|
144
|
+
""" Remove person from project (as committer) """
|
|
145
|
+
dn = LDAP_CN % (project, LDAP_PMCS_BASE)
|
|
146
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_DELETE, 'member', self.dn_enc)])
|
|
147
|
+
|
|
148
|
+
def remove_pmc(self, project):
|
|
149
|
+
""" Remove person from PMC """
|
|
150
|
+
dn = LDAP_CN % (project, LDAP_PMCS_BASE)
|
|
151
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_DELETE, 'owner', self.dn_enc)])
|
|
152
|
+
|
|
153
|
+
def remove_basic_group(self, group):
|
|
154
|
+
""" Remove person from basic posixGroup entry """
|
|
155
|
+
dn = LDAP_CN % (group, LDAP_GROUPS_BASE)
|
|
156
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_DELETE, 'memberUid', self.uid.encode('ascii'))])
|
|
157
|
+
|
|
158
|
+
def remove_role(self, role):
|
|
159
|
+
""" Add person to basic posixGroup entry """
|
|
160
|
+
dn = LDAP_CN % (role, LDAP_ROLES_BASE)
|
|
161
|
+
self.manager.lc.modify_s(dn, [(ldap.MOD_DELETE, 'member', self.dn_enc)])
|
|
162
|
+
|
|
163
|
+
def rename(self, newuid):
|
|
164
|
+
""" Rename an account, fixing in all projects """
|
|
165
|
+
xuid = newuid
|
|
166
|
+
if type(newuid) is str:
|
|
167
|
+
newuid = newuid.encode('ascii')
|
|
168
|
+
else:
|
|
169
|
+
xuid = newuid.decode('ascii')
|
|
170
|
+
# Validate uid
|
|
171
|
+
if not LDAP_VALID_UID_RE.match(xuid):
|
|
172
|
+
raise ValidatorException("Invalid UID, must match ^[a-z0-9][a-z0-9_]+$")
|
|
173
|
+
|
|
174
|
+
# Test if uid exists
|
|
175
|
+
if self.manager.load_account(xuid):
|
|
176
|
+
raise ConnectionException("An account with this uid already exists")
|
|
177
|
+
|
|
178
|
+
# Test for clashing cn's
|
|
179
|
+
res = self.manager.lc.search_s(LDAP_SUFFIX, ldap.SCOPE_SUBTREE, 'cn=%s' % xuid)
|
|
180
|
+
if res:
|
|
181
|
+
raise ValidatorException("availid clashes with project name %s!" % res[0][0], 'uid')
|
|
182
|
+
|
|
183
|
+
# We'll need to assign a new uidNumber as well..
|
|
184
|
+
uidnumber = self.manager.next_user_uid()
|
|
185
|
+
|
|
186
|
+
# Switch email and home dir
|
|
187
|
+
changeset = []
|
|
188
|
+
o_email = self.attributes['asf-committer-email'].encode('ascii')
|
|
189
|
+
n_email = b'%s@apache.org' % newuid
|
|
190
|
+
o_homedir = self.attributes['homeDirectory'].encode('ascii')
|
|
191
|
+
n_homedir = b'/home/%s' % newuid
|
|
192
|
+
changeset.append((ldap.MOD_DELETE, 'asf-committer-email', o_email))
|
|
193
|
+
changeset.append((ldap.MOD_ADD, 'asf-committer-email', n_email))
|
|
194
|
+
changeset.append((ldap.MOD_DELETE, 'homeDirectory', o_homedir))
|
|
195
|
+
changeset.append((ldap.MOD_ADD, 'homeDirectory', n_homedir))
|
|
196
|
+
|
|
197
|
+
# Change UID Number - has to be done all in one atomic go.
|
|
198
|
+
ouidn = self.attributes['uidNumber'].encode('ascii')
|
|
199
|
+
nuidn = b'%u' % uidnumber
|
|
200
|
+
print("Changing uidNumber/gidNumber to %s..." % uidnumber)
|
|
201
|
+
changeset.append((ldap.MOD_DELETE, 'gidNumber', ouidn))
|
|
202
|
+
changeset.append((ldap.MOD_ADD, 'gidNumber', nuidn))
|
|
203
|
+
changeset.append((ldap.MOD_DELETE, 'uidNumber', ouidn))
|
|
204
|
+
changeset.append((ldap.MOD_ADD, 'uidNumber', nuidn))
|
|
205
|
+
self.manager.lc.modify_s(self.dn, changeset)
|
|
206
|
+
|
|
207
|
+
# Change DN
|
|
208
|
+
odn = self.dn_enc.decode('ascii')
|
|
209
|
+
newdn = LDAP_DN % xuid
|
|
210
|
+
newdn_enc = newdn.encode('ascii')
|
|
211
|
+
print("Changing %s to %s" % (odn, newdn))
|
|
212
|
+
self.manager.lc.modrdn_s(odn, 'uid=%s' % xuid)
|
|
213
|
+
# Search and rename
|
|
214
|
+
|
|
215
|
+
# Replace long refs: member + owner
|
|
216
|
+
for role in ['member', 'owner']:
|
|
217
|
+
res = self.manager.lc.search_s(LDAP_SUFFIX, ldap.SCOPE_SUBTREE, '%s=%s' % (role, self.dn_enc.decode('ascii')))
|
|
218
|
+
for entry in res:
|
|
219
|
+
cn = entry[0]
|
|
220
|
+
myhash = entry[1]
|
|
221
|
+
if self.dn_enc in myhash[role]:
|
|
222
|
+
print("Modifying (long) %s attribute in %s ..." % (role, cn))
|
|
223
|
+
self.manager.lc.modify_s(cn, [(ldap.MOD_DELETE, role, self.dn_enc)])
|
|
224
|
+
self.manager.lc.modify_s(cn, [(ldap.MOD_ADD, role, newdn_enc)])
|
|
225
|
+
|
|
226
|
+
# Replace short refs: memberUid
|
|
227
|
+
ouid = self.uid.encode('ascii')
|
|
228
|
+
for role in ['memberUid']:
|
|
229
|
+
res = self.manager.lc.search_s(LDAP_SUFFIX, ldap.SCOPE_SUBTREE, '(&(objectClass=posixGroup)(%s=%s))' % (role, self.uid))
|
|
230
|
+
for entry in res:
|
|
231
|
+
cn = entry[0]
|
|
232
|
+
myhash = entry[1]
|
|
233
|
+
if ouid in myhash[role]:
|
|
234
|
+
print("Modifying (short) %s attribute in %s ..." % (role, cn))
|
|
235
|
+
self.manager.lc.modify_s(cn, [(ldap.MOD_DELETE, role, ouid)])
|
|
236
|
+
self.manager.lc.modify_s(cn, [(ldap.MOD_ADD, role, newuid)])
|
|
237
|
+
|
|
238
|
+
# Change in-object
|
|
239
|
+
self.uid = xuid
|
|
240
|
+
self.dn_enc = newdn_enc
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class manager:
|
|
244
|
+
|
|
245
|
+
""" Top LDAP Manager class for whomever is using the script """
|
|
246
|
+
def __init__(self, user, password, host=LDAP_SANDBOX):
|
|
247
|
+
# Verify correct user ID syntax, construct DN
|
|
248
|
+
if not re.match(r"^[-_a-z0-9]+$", user):
|
|
249
|
+
raise ConnectionException("Invalid characters in User ID. Must be alphanumerical or dashes only.")
|
|
250
|
+
|
|
251
|
+
# Init LDAP connection
|
|
252
|
+
lc = ldap.initialize(host)
|
|
253
|
+
|
|
254
|
+
lc.set_option(ldap.OPT_REFERRALS, 0)
|
|
255
|
+
lc.set_option(ldap.OPT_TIMEOUT, 5)
|
|
256
|
+
|
|
257
|
+
# Attempt to bind with user and pass provided
|
|
258
|
+
try:
|
|
259
|
+
lc.simple_bind_s(LDAP_DN % user, password)
|
|
260
|
+
except ldap.INVALID_CREDENTIALS:
|
|
261
|
+
raise ConnectionException("Invalid username or password supplied!")
|
|
262
|
+
except ldap.TIMEOUT:
|
|
263
|
+
raise ConnectionException(BACKEND_TIMEOUT)
|
|
264
|
+
|
|
265
|
+
# So far so good, set uid
|
|
266
|
+
self.uid = user
|
|
267
|
+
self.dn = LDAP_DN % user
|
|
268
|
+
self.lc = lc
|
|
269
|
+
|
|
270
|
+
# Get full name etc
|
|
271
|
+
try:
|
|
272
|
+
res = lc.search_s(LDAP_DN % user, ldap.SCOPE_BASE)
|
|
273
|
+
assert(len(res) == 1)
|
|
274
|
+
assert(len(res[0]) == 2)
|
|
275
|
+
fn = res[0][1].get('cn')
|
|
276
|
+
assert(type(fn) is list and len(fn) == 1)
|
|
277
|
+
self.fullname = str(fn[0], 'utf-8')
|
|
278
|
+
self.email = '%s@apache.org' % user
|
|
279
|
+
except ldap.TIMEOUT:
|
|
280
|
+
raise ConnectionException(BACKEND_TIMEOUT)
|
|
281
|
+
except AssertionError:
|
|
282
|
+
raise ConnectionException(ASSERTION_FAILED)
|
|
283
|
+
|
|
284
|
+
# Get apldap status
|
|
285
|
+
try:
|
|
286
|
+
res = lc.search_s(LDAP_APLDAP_BASE, ldap.SCOPE_BASE)
|
|
287
|
+
assert(len(res) == 1)
|
|
288
|
+
assert(len(res[0]) == 2)
|
|
289
|
+
members = res[0][1].get('member')
|
|
290
|
+
assert(type(members) is list and len(members) > 0)
|
|
291
|
+
self.isAdmin = bytes(LDAP_DN % user, 'utf-8') in members
|
|
292
|
+
except ldap.TIMEOUT:
|
|
293
|
+
raise ConnectionException(BACKEND_TIMEOUT)
|
|
294
|
+
except AssertionError:
|
|
295
|
+
raise ConnectionException(ASSERTION_FAILED)
|
|
296
|
+
|
|
297
|
+
def load_account(self, uid):
|
|
298
|
+
if type(uid) is bytes:
|
|
299
|
+
uid = uid.decode('ascii')
|
|
300
|
+
# Check if account exists!
|
|
301
|
+
res = self.lc.search_s(LDAP_PEOPLE_BASE, ldap.SCOPE_SUBTREE, 'uid=%s' % uid)
|
|
302
|
+
if res:
|
|
303
|
+
return committer(self, res)
|
|
304
|
+
return None
|
|
305
|
+
|
|
306
|
+
def _find_gaps(self, l):
|
|
307
|
+
return [item for item in range(l[0], l[-1]+1) if item not in l]
|
|
308
|
+
|
|
309
|
+
def next_user_uid(self):
|
|
310
|
+
""" Find lowest available user account uid with a matching available gid """
|
|
311
|
+
|
|
312
|
+
try:
|
|
313
|
+
r = self.lc.search_s(LDAP_PEOPLE_BASE, ldap.SCOPE_SUBTREE, 'uid=*', ['uidNumber', 'gidNumber'])
|
|
314
|
+
un_avail_uids = sorted([int(item[1]["uidNumber"][0].decode('utf8')) for item in r])
|
|
315
|
+
un_avail_gids = sorted([int(item[1]["gidNumber"][0].decode('utf8')) for item in r])
|
|
316
|
+
avail_uids = self._find_gaps(un_avail_uids)
|
|
317
|
+
avail_gids = self._find_gaps(un_avail_gids)
|
|
318
|
+
|
|
319
|
+
# In case there are no gaps, increment the last returned UID
|
|
320
|
+
# If the new UID is not unavailable append it to the list of
|
|
321
|
+
# available_uids.
|
|
322
|
+
n_uid = int(un_avail_uids[-1]+1)
|
|
323
|
+
while n_uid in un_avail_gids:
|
|
324
|
+
n_uid+=1
|
|
325
|
+
|
|
326
|
+
avail_uids.append(n_uid)
|
|
327
|
+
|
|
328
|
+
# Ensure you got something
|
|
329
|
+
assert(type(avail_uids) is list and len(avail_uids) > 0 and type(avail_gids) is list and len(avail_gids) > 0)
|
|
330
|
+
|
|
331
|
+
for uid in avail_uids:
|
|
332
|
+
if uid >= MINIMUM_USER_UID and uid in avail_gids:
|
|
333
|
+
return(uid)
|
|
334
|
+
continue
|
|
335
|
+
|
|
336
|
+
except ldap.TIMEOUT:
|
|
337
|
+
raise ConnectionException(BACKEND_TIMEOUT)
|
|
338
|
+
except AssertionError:
|
|
339
|
+
raise ConnectionException(ASSERTION_FAILED)
|
|
340
|
+
|
|
341
|
+
def create_account(
|
|
342
|
+
self,
|
|
343
|
+
uid,
|
|
344
|
+
email,
|
|
345
|
+
fullname,
|
|
346
|
+
forcePass=None,
|
|
347
|
+
requireTwo=True,
|
|
348
|
+
):
|
|
349
|
+
""" Attempts to create a committer account in LDAP """
|
|
350
|
+
if not self.isAdmin:
|
|
351
|
+
raise ConnectionException("You do not have sufficient access to create accounts")
|
|
352
|
+
|
|
353
|
+
# Validate uid
|
|
354
|
+
if not LDAP_VALID_UID_RE.match(uid):
|
|
355
|
+
raise ValidatorException("Invalid UID, must match ^[a-z0-9][a-z0-9_]+$")
|
|
356
|
+
|
|
357
|
+
# Test if uid exists
|
|
358
|
+
if self.load_account(uid):
|
|
359
|
+
raise ConnectionException("An account with this uid already exists")
|
|
360
|
+
|
|
361
|
+
# Test for clashing cn's
|
|
362
|
+
res = self.lc.search_s(LDAP_SUFFIX, ldap.SCOPE_SUBTREE, 'cn=%s' % uid)
|
|
363
|
+
if res:
|
|
364
|
+
raise ValidatorException("availid clashes with project name %s!" % res[0][0], 'uid')
|
|
365
|
+
|
|
366
|
+
uidnumber = self.next_user_uid()
|
|
367
|
+
|
|
368
|
+
# Get surname and given name, validate against spurious whitespace
|
|
369
|
+
names = fullname.split(' ')
|
|
370
|
+
if len(names) < 2 and requireTwo:
|
|
371
|
+
raise ValidatorException("Full name needs at least two parts!", 'fullname')
|
|
372
|
+
givenName = names[0]
|
|
373
|
+
surName = names[-1]
|
|
374
|
+
for n in names:
|
|
375
|
+
if not n.strip():
|
|
376
|
+
raise ValidatorException("Found part of name with too much spacing!", 'fullname')
|
|
377
|
+
|
|
378
|
+
# Validate email
|
|
379
|
+
if not re.match(r"^\S+@\S+?\.\S+$", email):
|
|
380
|
+
raise ValidatorException("Invalid email address supplied!", 'email')
|
|
381
|
+
|
|
382
|
+
# Set password, b64-encoded crypt of random string
|
|
383
|
+
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(16))
|
|
384
|
+
if forcePass:
|
|
385
|
+
password = forcePass
|
|
386
|
+
password_crypted = crypt.crypt(password, crypt.mksalt(method=crypt.METHOD_MD5))
|
|
387
|
+
|
|
388
|
+
ldiff = {
|
|
389
|
+
'objectClass': ['person', 'top', 'posixAccount', 'organizationalPerson', 'inetOrgPerson', 'asf-committer', 'hostObject', 'ldapPublicKey'],
|
|
390
|
+
'loginShell': '/bin/bash',
|
|
391
|
+
'asf-sascore': '10',
|
|
392
|
+
'givenName': givenName,
|
|
393
|
+
'sn': surName,
|
|
394
|
+
'mail': email,
|
|
395
|
+
'gidNumber': '9000',
|
|
396
|
+
'uidNumber': str(uidnumber),
|
|
397
|
+
'asf-committer-email': '%s@apache.org' % uid,
|
|
398
|
+
'cn': fullname,
|
|
399
|
+
'homeDirectory': '/home/%s' % uid,
|
|
400
|
+
'userPassword': '{CRYPT}' + password_crypted,
|
|
401
|
+
'host': 'home.apache.org',
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
# Convert everything to bytestrings because ldap demands it...
|
|
405
|
+
bytify(ldiff)
|
|
406
|
+
|
|
407
|
+
# Run LDIF on server
|
|
408
|
+
dn = LDAP_DN % uid
|
|
409
|
+
am = ldap.modlist.addModlist(ldiff)
|
|
410
|
+
self.lc.add_s(dn, am)
|
|
411
|
+
|
|
412
|
+
return self.load_account(uid)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
class LDIFWriter_Sane(ldif.LDIFWriter):
|
|
416
|
+
"""
|
|
417
|
+
LDIFWriter with b64 detection overridden to allow for use of utf-8 rather than bytes
|
|
418
|
+
Also disables b64 encoding for the 'dn' attribute
|
|
419
|
+
"""
|
|
420
|
+
|
|
421
|
+
def _needs_base64_encoding(self, attr_type, attr_value):
|
|
422
|
+
"""
|
|
423
|
+
returns False if attr_type is 'dn'
|
|
424
|
+
returns True if attr_value has to be base-64 encoded because
|
|
425
|
+
of special chars or because attr_type is in self._base64_attrs
|
|
426
|
+
"""
|
|
427
|
+
if attr_type.lower() == 'dn':
|
|
428
|
+
# We must always exclude DN
|
|
429
|
+
# as our own library makes this a str (utf-8)
|
|
430
|
+
return False
|
|
431
|
+
if type(attr_value) is bytes:
|
|
432
|
+
return super()._needs_base64_encoding(attr_type, attr_value)
|
|
433
|
+
# short-cut to avoid encoding unless necessary
|
|
434
|
+
if attr_type.lower() in self._base64_attrs:
|
|
435
|
+
return True
|
|
436
|
+
try:
|
|
437
|
+
return super()._needs_base64_encoding(attr_type, attr_value.encode('utf-8'))
|
|
438
|
+
except UnicodeEncodeError:
|
|
439
|
+
return False
|
|
440
|
+
|
asfpy-0.53/asfpy/t.py
ADDED
asfpy-0.53/asfpy/t2.py
ADDED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
import logging
|
|
33
33
|
|
|
34
34
|
import ezt
|
|
35
|
-
import
|
|
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.
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
67
|
-
|
|
68
|
-
path = str(event
|
|
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.53"
|
|
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 +0,0 @@
|
|
|
1
|
-
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
asfpy
|
asfpy-0.52/setup.cfg
DELETED
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
|