53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
"""Prepare credentials for the internal alert inbox in a private directory."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import secrets
|
|
import string
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
|
|
def password_hash(username, password):
|
|
result = subprocess.run(
|
|
['htpasswd', '-niBC', '10', username],
|
|
input=password + '\n', text=True, capture_output=True, check=True,
|
|
)
|
|
return result.stdout.strip().split(':', 1)[1]
|
|
|
|
|
|
def prepare(directory):
|
|
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
if directory.stat().st_mode & 0o077:
|
|
raise SystemExit('Use a private directory (chmod 700) outside the Git worktree.')
|
|
|
|
vault = directory / 'credentials.json'
|
|
if not vault.exists():
|
|
alphabet = string.ascii_lowercase + string.digits
|
|
values = {
|
|
'viewer_password': secrets.token_urlsafe(24),
|
|
'publisher_password': secrets.token_urlsafe(24),
|
|
'publisher_token': 'tk_' + ''.join(secrets.choice(alphabet) for _ in range(29)),
|
|
}
|
|
with vault.open('x') as stream:
|
|
json.dump(values, stream, indent=2)
|
|
values = json.loads(vault.read_text())
|
|
viewer = 'atlas-alert-viewer'
|
|
publisher = 'atlas-alert-publisher'
|
|
users = ','.join(
|
|
f'{name}:{password_hash(name, values[field])}:user'
|
|
for name, field in ((viewer, 'viewer_password'), (publisher, 'publisher_password'))
|
|
)
|
|
token = values['publisher_token']
|
|
(directory / 'inbox.env').write_text(
|
|
f'NTFY_AUTH_USERS={users}\nNTFY_AUTH_TOKENS={publisher}:{token}:Alertmanager\n',
|
|
)
|
|
(directory / 'publisher-token').write_text(token)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('directory', type=Path, help='Private directory outside the Git worktree')
|
|
os.umask(0o077)
|
|
prepare(parser.parse_args().directory)
|