"""Generate isolated preview credentials and the initial Keycloak realm.""" import argparse import json import os import secrets from pathlib import Path 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(): values = { name: secrets.token_urlsafe(24) for name in ('postgres', 'inventory', 'identity', 'preview-admin', 'preview-viewer') } with vault.open('x') as stream: json.dump(values, stream, indent=2) values = json.loads(vault.read_text()) write_env(directory / 'postgres.env', { 'POSTGRES_PASSWORD': values['postgres'], 'INVENTORY_PASSWORD': values['inventory'], 'KC_DB_PASSWORD': values['identity'], }) write_env(directory / 'keycloak.env', {'KC_DB_PASSWORD': values['identity']}) write_env(directory / 'inventory.env', {'ATLAS_DB_PASSWORD': values['inventory']}) (directory / 'item-atlas-admin-preview-realm.json').write_text(json.dumps(realm(values))) def write_env(path, values): path.write_text(''.join(f'{name}={value}\n' for name, value in values.items())) def realm(values): origin = 'http://127.0.0.1:18482' return { 'realm': 'item-atlas-admin-preview', 'displayName': '见物后台预览', 'enabled': True, 'sslRequired': 'none', 'registrationAllowed': False, 'bruteForceProtected': True, 'roles': {'realm': [{'name': 'atlas-space-admin'}]}, 'clients': [{ 'clientId': 'atlas-admin', 'enabled': True, 'protocol': 'openid-connect', 'publicClient': True, 'standardFlowEnabled': True, 'implicitFlowEnabled': False, 'directAccessGrantsEnabled': False, 'redirectUris': [origin + '/'], 'webOrigins': [origin], 'attributes': { 'pkce.code.challenge.method': 'S256', 'post.logout.redirect.uris': origin + '/', }, 'protocolMappers': [ { 'name': 'Inventory API audience', 'protocol': 'openid-connect', 'protocolMapper': 'oidc-audience-mapper', 'config': { 'included.custom.audience': 'item-atlas-api', 'access.token.claim': 'true', }, }, { 'name': 'Atlas management roles', 'protocol': 'openid-connect', 'protocolMapper': 'oidc-usermodel-realm-role-mapper', 'config': { 'claim.name': 'atlas_roles', 'multivalued': 'true', 'jsonType.label': 'String', 'access.token.claim': 'true', }, }, ], }], 'users': [ { 'username': username, 'firstName': 'Atlas', 'lastName': 'Preview', 'email': f'{username}@example.invalid', 'emailVerified': True, 'enabled': True, 'realmRoles': roles, 'credentials': [{ 'type': 'password', 'value': values[username], 'temporary': False, }], } for username, roles in ( ('preview-admin', ['atlas-space-admin']), ('preview-viewer', []), ) ], } 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)