-
Notifications
You must be signed in to change notification settings - Fork 7
/
cli.py
279 lines (250 loc) · 8.62 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""Administrative command-line interface."""
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Optional, Union
import click
import structlog
import uvicorn
from cryptography.fernet import Fernet
from fastapi.openapi.utils import get_openapi
from safir.asyncio import run_with_asyncio
from safir.database import create_database_engine, initialize_database
from sqlalchemy import text
from .dependencies.config import config_dependency
from .factory import Factory
from .keypair import RSAKeyPair
from .main import create_app
from .models.token import Token
from .schema import Base
from .slack import SlackAlertClient
__all__ = [
"delete_all_data",
"generate_key",
"generate_token",
"help",
"init",
"main",
"maintenance",
"openapi_schema",
"run",
]
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.version_option(message="%(version)s")
def main() -> None:
"""Administrative command-line interface for gafaelfawr."""
pass
@main.command()
@click.argument("topic", default=None, required=False, nargs=1)
@click.pass_context
def help(ctx: click.Context, topic: Union[None, str]) -> None:
"""Show help for any command."""
# The help command implementation is taken from
# https://www.burgundywall.com/post/having-click-help-subcommand
if topic:
if topic in main.commands:
click.echo(main.commands[topic].get_help(ctx))
else:
raise click.UsageError(f"Unknown help topic {topic}", ctx)
else:
assert ctx.parent
click.echo(ctx.parent.get_help())
@main.command()
@click.option(
"--fix", default=False, is_flag=True, help="Fix issues found, if possible"
)
@click.option(
"--settings",
envvar="GAFAELFAWR_SETTINGS_PATH",
type=str,
default=None,
help="Application settings file.",
)
@run_with_asyncio
async def audit(fix: bool, settings: Optional[str]) -> None:
"""Run a consistency check on Gafaelfawr's data stores.
Any problems found will be reported to Slack.
"""
if settings:
config_dependency.set_settings_path(settings)
config = await config_dependency()
if not config.slack_webhook:
msg = "Slack alerting required for audit but not configured"
raise click.UsageError(msg)
logger = structlog.get_logger("gafaelfawr")
logger.debug("Starting audit")
slack = SlackAlertClient(config.slack_webhook, "Gafaelfawr", logger)
engine = create_database_engine(
config.database_url, config.database_password
)
async with Factory.standalone(config, engine) as factory:
token_service = factory.create_token_service()
async with factory.session.begin():
alerts = await token_service.audit(fix=fix)
if alerts:
message = (
"Gafaelfawr data inconsistencies found:\n• "
+ "\n• ".join(alerts)
+ "\n"
)
await slack.message(message)
await engine.dispose()
logger.debug("Finished audit")
@main.command()
@click.option(
"--settings",
envvar="GAFAELFAWR_SETTINGS_PATH",
type=str,
default=None,
help="Application settings file.",
)
@run_with_asyncio
async def delete_all_data(settings: Optional[str]) -> None:
"""Delete all data from Redis and the database.
Intended for destructive upgrades, such as when switching from one
upstream authentication provider to another when all of the usernames will
change. This does not delete or reset UID and GID assignments from
Firestore.
"""
if settings:
config_dependency.set_settings_path(settings)
config = await config_dependency()
logger = structlog.get_logger("gafaelfawr")
logger.debug("Starting to delete all data")
engine = create_database_engine(
config.database_url, config.database_password
)
tables = (t.name for t in Base.metadata.sorted_tables)
async with Factory.standalone(config, engine) as factory:
admin_service = factory.create_admin_service()
async with factory.session.begin():
stmt = text(f'TRUNCATE TABLE {", ".join(tables)}')
logger.info("Truncating all tables")
await factory.session.execute(stmt)
await admin_service.add_initial_admins(config.initial_admins)
token_service = factory.create_token_service()
logger.info("Deleting all tokens from Redis")
await token_service.delete_all_tokens()
if config.oidc_server:
oidc_service = factory.create_oidc_service()
logger.info("Deleting all OpenID Connect codes from Redis")
await oidc_service.delete_all_codes()
await engine.dispose()
logger.debug("Finished deleting all data")
@main.command()
def generate_key() -> None:
"""Generate a new RSA key pair and print the private key."""
keypair = RSAKeyPair.generate()
print(keypair.private_key_as_pem())
@main.command()
def generate_session_secret() -> None:
"""Generate a new Gafaelfawr session secret."""
print(Fernet.generate_key().decode())
@main.command()
def generate_token() -> None:
"""Generate an encoded token (such as the bootstrap token)."""
print(str(Token()))
@main.command()
@click.option(
"--settings",
envvar="GAFAELFAWR_SETTINGS_PATH",
type=str,
default=None,
help="Application settings file.",
)
@run_with_asyncio
async def init(settings: Optional[str]) -> None:
"""Initialize the database storage."""
if settings:
config_dependency.set_settings_path(settings)
config = await config_dependency()
logger = structlog.get_logger("gafaelfawr")
logger.debug("Initializing database")
engine = create_database_engine(
config.database_url, config.database_password
)
await initialize_database(engine, logger, schema=Base.metadata)
async with Factory.standalone(config, engine) as factory:
admin_service = factory.create_admin_service()
logger.debug("Adding initial administrators")
async with factory.session.begin():
await admin_service.add_initial_admins(config.initial_admins)
if config.firestore:
firestore = factory.create_firestore_storage()
logger.debug("Initializing Firestore")
await firestore.initialize()
await engine.dispose()
logger.debug("Finished initializing data stores")
@main.command()
@click.option(
"--settings",
envvar="GAFAELFAWR_SETTINGS_PATH",
type=str,
default=None,
help="Application settings file.",
)
@run_with_asyncio
async def maintenance(settings: Optional[str]) -> None:
"""Perform background maintenance."""
if settings:
config_dependency.set_settings_path(settings)
config = await config_dependency()
logger = structlog.get_logger("gafaelfawr")
logger.debug("Starting background maintenance")
engine = create_database_engine(
config.database_url, config.database_password
)
async with Factory.standalone(config, engine, check_db=True) as factory:
token_service = factory.create_token_service()
async with factory.session.begin():
logger.info("Marking expired tokens in database")
await token_service.expire_tokens()
logger.info("Truncating token history")
await token_service.truncate_history()
await engine.dispose()
logger.debug("Finished background maintenance")
@main.command()
@click.option(
"--add-back-link",
default=False,
is_flag=True,
help="Add back link (used when generating application documentation)",
)
@click.option(
"--output",
default=None,
type=click.Path(path_type=Path),
help="Output path (output to stdout if not given).",
)
def openapi_schema(add_back_link: bool, output: Optional[Path]) -> None:
"""Generate the OpenAPI schema."""
app = create_app(load_config=False)
description = app.description
if add_back_link:
description += "\n\n[Return to Gafaelfawr documentation](api.html)."
schema = get_openapi(
title=app.title,
description=description,
version=app.version,
routes=app.routes,
)
if output:
output.parent.mkdir(exist_ok=True)
with output.open("w") as f:
json.dump(schema, f)
else:
json.dump(schema, sys.stdout)
@main.command()
@click.option(
"--port", default=8080, type=int, help="Port to run the application on."
)
def run(port: int) -> None:
"""Run the application (for testing only)."""
uvicorn.run(
"gafaelfawr.main:create_app",
factory=True,
port=port,
reload=True,
reload_dirs=["src"],
)