forked from kernelci/kernelci-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusermanager.py
More file actions
executable file
·694 lines (621 loc) · 23.7 KB
/
usermanager.py
File metadata and controls
executable file
·694 lines (621 loc) · 23.7 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#!/usr/bin/env python3
import argparse
import getpass
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
try:
import tomllib
except ImportError as exc: # pragma: no cover - Python < 3.11
raise SystemExit("Python 3.11+ is required for tomllib.") from exc
DEFAULT_CONFIG_PATHS = [
os.path.join(os.getcwd(), "usermanager.toml"),
os.path.join(os.path.expanduser("~"), ".config", "kernelci", "usermanager.toml"),
]
def _load_config(path: str | None) -> dict:
if not path:
return {}
if not os.path.exists(path):
return {}
with open(path, "rb") as handle:
return tomllib.load(handle)
def _resolve_config_path(path: str | None) -> str | None:
if path:
return path
for candidate in DEFAULT_CONFIG_PATHS:
if os.path.exists(candidate):
return candidate
return None
def _get_setting(args_value, env_key, config, config_key):
if args_value:
return args_value
env_value = os.getenv(env_key)
if env_value:
return env_value
current = config
for key in config_key.split("."):
if not isinstance(current, dict):
return None
current = current.get(key)
return current
def _get_instance_config(config, instance_name):
if not isinstance(config, dict):
return {}
instances = config.get("instances", {})
if not isinstance(instances, dict):
return {}
return instances.get(instance_name, {}) or {}
def _prompt_if_missing(value, prompt_text, secret=False, default=None):
if value:
return value
if secret:
return getpass.getpass(prompt_text)
prompt = prompt_text
if default:
prompt = f"{prompt_text} [{default}] "
response = input(prompt)
if not response and default is not None:
return default
return response
def _parse_group_list(values):
if not values:
return []
if isinstance(values, str):
values = [values]
groups = []
for value in values:
for group in value.split(","):
group = group.strip()
if group:
groups.append(group)
return groups
def _dedupe(items):
seen = set()
output = []
for item in items:
if item in seen:
continue
seen.add(item)
output.append(item)
return output
def _extract_group_names(payload):
groups = payload.get("groups") or []
names = []
for group in groups:
if isinstance(group, dict):
name = group.get("name")
else:
name = getattr(group, "name", None)
if name:
names.append(name)
return _dedupe(names)
def _apply_group_changes(current, add_groups, remove_groups):
current = _dedupe(current)
remove_set = set(remove_groups)
updated = [group for group in current if group not in remove_set]
for group in add_groups:
if group not in updated and group not in remove_set:
updated.append(group)
return updated
def _resolve_user_id(user_id, api_url, token):
if _looks_like_object_id(user_id):
return user_id
status, body = _request_json("GET", f"{api_url}/users", token=token)
if status >= 400:
_print_response(status, body)
raise SystemExit(1)
try:
payload = json.loads(body) if body else []
except json.JSONDecodeError as exc:
raise SystemExit("Failed to parse users response") from exc
items = _parse_paginated_items(payload)
matches = []
for user in items:
if not isinstance(user, dict):
continue
if user.get("email") == user_id or user.get("username") == user_id:
matches.append(user)
if not matches:
raise SystemExit(f"No user found with email/username: {user_id}")
if len(matches) > 1:
raise SystemExit(f"Multiple users found with email/username: {user_id}")
resolved_id = matches[0].get("id")
if not resolved_id:
raise SystemExit(f"User with {user_id} has no id")
return resolved_id
def _parse_paginated_items(payload):
if isinstance(payload, dict) and "items" in payload:
return payload.get("items") or []
if isinstance(payload, list):
return payload
return []
def _looks_like_object_id(value):
return bool(re.fullmatch(r"[0-9a-fA-F]{24}", value))
def _resolve_group_id(group_id, api_url, token):
if _looks_like_object_id(group_id):
return group_id
query = urllib.parse.urlencode({"name": group_id})
status, body = _request_json("GET", f"{api_url}/user-groups?{query}", token=token)
if status >= 400:
_print_response(status, body)
raise SystemExit(1)
try:
payload = json.loads(body) if body else {}
except json.JSONDecodeError as exc:
raise SystemExit("Failed to parse user-groups response") from exc
items = _parse_paginated_items(payload)
matches = [
group
for group in items
if isinstance(group, dict) and group.get("name") == group_id
]
if not matches:
raise SystemExit(f"No group found with name: {group_id}")
if len(matches) > 1:
raise SystemExit(f"Multiple groups found with name: {group_id}")
resolved_id = matches[0].get("id")
if not resolved_id:
raise SystemExit(f"Group {group_id} has no id")
return resolved_id
def _resolve_group_name(group_name, api_url, token):
if not _looks_like_object_id(group_name):
return group_name
status, body = _request_json(
"GET", f"{api_url}/user-groups/{group_name}", token=token
)
if status >= 400:
_print_response(status, body)
raise SystemExit(1)
try:
payload = json.loads(body) if body else {}
except json.JSONDecodeError as exc:
raise SystemExit("Failed to parse user-group response") from exc
resolved_name = payload.get("name")
if not resolved_name:
raise SystemExit(f"Group {group_name} has no name")
return resolved_name
def _resolve_group_names(group_names, api_url, token):
return _dedupe([_resolve_group_name(name, api_url, token) for name in group_names])
def _update_user_groups(resolved_id, add_groups, remove_groups, api_url, token):
status, body = _request_json("GET", f"{api_url}/user/{resolved_id}", token=token)
if status >= 400:
_print_response(status, body)
raise SystemExit(1)
try:
payload = json.loads(body) if body else {}
except json.JSONDecodeError as exc:
raise SystemExit("Failed to parse user response") from exc
current_groups = _extract_group_names(payload)
data = {
"groups": _apply_group_changes(current_groups, add_groups, remove_groups),
}
return _request_json("PATCH", f"{api_url}/user/{resolved_id}", data, token=token)
def _request_json(method, url, data=None, token=None, form=False):
headers = {"accept": "application/json"}
body = None
if data is not None:
if form:
body = urllib.parse.urlencode(data).encode("utf-8")
headers["Content-Type"] = "application/x-www-form-urlencoded"
else:
body = json.dumps(data).encode("utf-8")
headers["Content-Type"] = "application/json"
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, data=body, headers=headers, method=method)
try:
with urllib.request.urlopen(req) as response:
payload = response.read().decode("utf-8")
return response.status, payload
except urllib.error.HTTPError as exc:
payload = exc.read().decode("utf-8")
return exc.code, payload
def _print_response(status, payload):
try:
parsed = json.loads(payload) if payload else None
except json.JSONDecodeError:
parsed = None
if parsed is not None:
print(json.dumps(parsed, indent=2))
elif payload:
print(payload)
else:
print(f"Status: {status}")
def _require_token(token, args):
return _prompt_if_missing(
token,
f"{args.token_label} token: ",
secret=True,
)
def main():
command_help = [
("accept-invite", "Accept an invite"),
("assign-group", "Assign group(s) to a user"),
("config-example", "Print a sample usermanager.toml"),
("create-group", "Create user group"),
("deassign-group", "Remove group(s) from a user"),
("delete-group", "Delete user group"),
("delete-user", "Delete user by id/email/username"),
("generate-api-token", "Print just the access token for a user"),
("get-group", "Get user group by id or name"),
("get-user", "Get user by id/email/username"),
("invite", "Invite a new user"),
("invite-url", "Preview invite URL base"),
("list-groups", "List user groups"),
("list-users", "List users"),
("login", "Get a full auth token response"),
("update-user", "Patch user by id/email/username"),
("whoami", "Show current user"),
]
command_list = "\n".join(
" {:<18} {}".format(name, desc) for name, desc in command_help)
default_paths = "\n".join(
" - {}".format(path) for path in DEFAULT_CONFIG_PATHS)
parser = argparse.ArgumentParser(
description="KernelCI API user management helper",
epilog=(
"Commands:\n"
f"{command_list}\n\n"
"Examples:\n"
" ./scripts/usermanager.py invite --username alice --email "
"alice@example.org --return-token\n"
" ./scripts/usermanager.py accept-invite --token <INVITE-TOKEN>\n"
" ./scripts/usermanager.py login --username alice\n"
" ./scripts/usermanager.py whoami\n"
" ./scripts/usermanager.py list-users --instance staging\n"
" ./scripts/usermanager.py config-example\n"
"\n"
"Default config lookup (first match wins):\n"
f"{default_paths}\n"
"\n"
"Run '<command> -h' for command-specific help.\n"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--config",
help="Path to usermanager.toml (defaults to first match in the lookup list below)",
)
parser.add_argument(
"--api-url", help="API base URL, e.g. " "http://localhost:8001/latest"
)
parser.add_argument("--token", help="Bearer token for admin/user actions")
parser.add_argument("--instance", help="Instance name from config")
parser.add_argument(
"--token-label", default="Auth", help="Label used when prompting for a token"
)
subparsers = parser.add_subparsers(dest="command", required=True)
accept = subparsers.add_parser("accept-invite", help="Accept an invite")
accept.add_argument("--token")
accept.add_argument("--password")
assign_group = subparsers.add_parser(
"assign-group", help="Assign group(s) to a user"
)
assign_group.add_argument("user_id")
assign_group.add_argument(
"--group",
action="append",
default=[],
help="Group name or id; can be used multiple times or with commas",
)
subparsers.add_parser("config-example", help="Print a sample usermanager.toml")
create_group = subparsers.add_parser("create-group", help="Create user group")
create_group.add_argument("name")
deassign_group = subparsers.add_parser(
"deassign-group", help="Remove group(s) from a user"
)
deassign_group.add_argument("user_id")
deassign_group.add_argument(
"--group",
action="append",
default=[],
help="Group name or id; can be used multiple times or with commas",
)
delete_group = subparsers.add_parser("delete-group", help="Delete user group")
delete_group.add_argument("group_id")
delete_user = subparsers.add_parser("delete-user", help="Delete user by id")
delete_user.add_argument("user_id")
generate_token = subparsers.add_parser(
"generate-api-token", help="Print just the access token for a user"
)
generate_token.add_argument("--username", required=True)
generate_token.add_argument("--password")
get_group = subparsers.add_parser("get-group", help="Get user group by id or name")
get_group.add_argument("group_id")
get_user = subparsers.add_parser("get-user", help="Get user by id")
get_user.add_argument("user_id")
invite = subparsers.add_parser("invite", help="Invite a new user")
invite.add_argument("--username", required=True)
invite.add_argument("--email", required=True)
invite.add_argument("--groups", default="")
invite.add_argument("--superuser", action="store_true")
invite.add_argument("--send-email", action="store_true", default=True)
invite.add_argument("--no-send-email", action="store_true")
invite.add_argument("--return-token", action="store_true")
invite.add_argument("--resend-if-exists", action="store_true")
invite_url = subparsers.add_parser("invite-url", help="Preview invite URL base")
list_groups = subparsers.add_parser("list-groups", help="List user groups")
list_users = subparsers.add_parser("list-users", help="List users")
login = subparsers.add_parser("login", help="Get an auth token")
login.add_argument("--username", required=True)
login.add_argument("--password")
update_user = subparsers.add_parser("update-user", help="Patch user by id")
update_user.add_argument("user_id")
update_user.add_argument("--data", help="JSON object with fields to update")
update_user.add_argument("--username", help="Set username")
update_user.add_argument("--email", help="Set email")
update_user.add_argument("--password", help="Set password")
update_user.add_argument(
"--superuser", dest="is_superuser", action="store_true", help="Grant superuser"
)
update_user.add_argument(
"--no-superuser",
dest="is_superuser",
action="store_false",
help="Revoke superuser",
)
update_user.add_argument(
"--active", dest="is_active", action="store_true", help="Set is_active true"
)
update_user.add_argument(
"--inactive", dest="is_active", action="store_false", help="Set is_active false"
)
update_user.add_argument(
"--verified",
dest="is_verified",
action="store_true",
help="Set is_verified true",
)
update_user.add_argument(
"--unverified",
dest="is_verified",
action="store_false",
help="Set is_verified false",
)
update_user.set_defaults(is_active=None, is_verified=None, is_superuser=None)
update_user.add_argument(
"--set-groups",
help="Replace all groups with a comma-separated list",
)
update_user.add_argument(
"--add-group",
action="append",
default=[],
help="Add group(s); can be used multiple times or with commas",
)
update_user.add_argument(
"--remove-group",
action="append",
default=[],
help="Remove group(s); can be used multiple times or with commas",
)
whoami = subparsers.add_parser("whoami", help="Show current user")
args = parser.parse_args()
if args.command == "config-example":
print(
'default_instance = "local"\n\n'
"[instances.local]\n"
'url = "http://localhost:8001/latest"\n'
'token = "<admin-or-user-token>"\n\n'
"[instances.staging]\n"
'url = "https://staging.kernelci.org:9000/latest"\n'
'token = "<admin-or-user-token>"\n'
)
return
config_path = _resolve_config_path(args.config)
config = _load_config(config_path)
instance_name = (
args.instance
or os.getenv("KCI_API_INSTANCE")
or config.get("default_instance")
or "default"
)
instance_config = _get_instance_config(config, instance_name)
api_url = args.api_url or os.getenv("KCI_API_URL")
if not api_url:
api_url = instance_config.get("url")
if not api_url:
api_url = _get_setting(None, "KCI_API_URL", config, "api.url")
api_url = _prompt_if_missing(
api_url,
"API URL",
default="http://localhost:8001/latest",
).rstrip("/")
token = args.token or os.getenv("KCI_API_TOKEN")
if not token:
token = instance_config.get("token")
if not token:
token = _get_setting(None, "KCI_API_TOKEN", config, "api.token")
if args.command in {
"invite",
"invite-url",
"whoami",
"list-users",
"get-user",
"update-user",
"delete-user",
"assign-group",
"deassign-group",
"list-groups",
"get-group",
"create-group",
"delete-group",
}:
token = _require_token(token, args)
if args.command == "invite":
groups = [g for g in args.groups.split(",") if g]
payload = {
"username": args.username,
"email": args.email,
"groups": groups,
"is_superuser": args.superuser,
"send_email": False if args.no_send_email else args.send_email,
"return_token": args.return_token,
"resend_if_exists": args.resend_if_exists,
}
status, body = _request_json(
"POST", f"{api_url}/user/invite", payload, token=token
)
elif args.command == "invite-url":
status, body = _request_json("GET", f"{api_url}/user/invite/url", token=token)
elif args.command == "accept-invite":
invite_token = _prompt_if_missing(
args.token,
"Invite token: ",
secret=True,
)
password = _prompt_if_missing(
args.password,
"New password: ",
secret=True,
)
payload = {"token": invite_token, "password": password}
status, body = _request_json("POST", f"{api_url}/user/accept-invite", payload)
elif args.command == "login":
password = _prompt_if_missing(
args.password,
"Password: ",
secret=True,
)
payload = {"username": args.username, "password": password}
status, body = _request_json(
"POST",
f"{api_url}/user/login",
payload,
form=True,
)
elif args.command == "generate-api-token":
password = _prompt_if_missing(
args.password,
"Password: ",
secret=True,
)
payload = {"username": args.username, "password": password}
status, body = _request_json(
"POST",
f"{api_url}/user/login",
payload,
form=True,
)
if status < 400:
try:
payload = json.loads(body) if body else {}
except json.JSONDecodeError as exc:
raise SystemExit("Failed to parse login response") from exc
token = payload.get("access_token")
if not token:
raise SystemExit("Login response missing access_token")
print(token)
return
elif args.command == "whoami":
status, body = _request_json("GET", f"{api_url}/whoami", token=token)
elif args.command == "list-users":
status, body = _request_json("GET", f"{api_url}/users", token=token)
elif args.command == "get-user":
resolved_id = _resolve_user_id(args.user_id, api_url, token)
status, body = _request_json(
"GET", f"{api_url}/user/{resolved_id}", token=token
)
elif args.command == "update-user":
resolved_id = _resolve_user_id(args.user_id, api_url, token)
data = {}
if args.data:
try:
data = json.loads(args.data)
except json.JSONDecodeError as exc:
raise SystemExit("Invalid JSON for --data") from exc
if not isinstance(data, dict):
raise SystemExit("--data must be a JSON object")
if args.username:
data["username"] = args.username
if args.email:
data["email"] = args.email
if args.password:
data["password"] = args.password
if args.is_superuser is not None:
data["is_superuser"] = args.is_superuser
if args.is_active is not None:
data["is_active"] = args.is_active
if args.is_verified is not None:
data["is_verified"] = args.is_verified
set_groups = _parse_group_list(args.set_groups)
add_groups = _parse_group_list(args.add_group)
remove_groups = _parse_group_list(args.remove_group)
if set_groups:
set_groups = _resolve_group_names(set_groups, api_url, token)
if add_groups:
add_groups = _resolve_group_names(add_groups, api_url, token)
if remove_groups:
remove_groups = _resolve_group_names(remove_groups, api_url, token)
if set_groups or add_groups or remove_groups:
if set_groups:
current_groups = set_groups
else:
status, body = _request_json(
"GET", f"{api_url}/user/{resolved_id}", token=token
)
if status >= 400:
_print_response(status, body)
raise SystemExit(1)
try:
payload = json.loads(body) if body else {}
except json.JSONDecodeError as exc:
raise SystemExit("Failed to parse user response") from exc
current_groups = _extract_group_names(payload)
data["groups"] = _apply_group_changes(
current_groups, add_groups, remove_groups
)
if not data:
raise SystemExit("No updates specified. Use --data or flags.")
status, body = _request_json(
"PATCH", f"{api_url}/user/{resolved_id}", data, token=token
)
elif args.command == "delete-user":
resolved_id = _resolve_user_id(args.user_id, api_url, token)
status, body = _request_json(
"DELETE", f"{api_url}/user/{resolved_id}", token=token
)
elif args.command == "assign-group":
resolved_id = _resolve_user_id(args.user_id, api_url, token)
add_groups = _parse_group_list(args.group)
if not add_groups:
raise SystemExit("No groups specified. Use --group.")
add_groups = _resolve_group_names(add_groups, api_url, token)
status, body = _update_user_groups(resolved_id, add_groups, [], api_url, token)
elif args.command == "deassign-group":
resolved_id = _resolve_user_id(args.user_id, api_url, token)
remove_groups = _parse_group_list(args.group)
if not remove_groups:
raise SystemExit("No groups specified. Use --group.")
remove_groups = _resolve_group_names(remove_groups, api_url, token)
status, body = _update_user_groups(
resolved_id, [], remove_groups, api_url, token
)
elif args.command == "list-groups":
status, body = _request_json("GET", f"{api_url}/user-groups", token=token)
elif args.command == "get-group":
resolved_id = _resolve_group_id(args.group_id, api_url, token)
status, body = _request_json(
"GET", f"{api_url}/user-groups/{resolved_id}", token=token
)
elif args.command == "create-group":
payload = {"name": args.name}
status, body = _request_json(
"POST", f"{api_url}/user-groups", payload, token=token
)
elif args.command == "delete-group":
resolved_id = _resolve_group_id(args.group_id, api_url, token)
status, body = _request_json(
"DELETE", f"{api_url}/user-groups/{resolved_id}", token=token
)
else:
raise SystemExit("Unknown command")
_print_response(status, body)
if status >= 400:
raise SystemExit(1)
if __name__ == "__main__":
main()