-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmanage_permissions_v1.py
More file actions
executable file
·260 lines (205 loc) · 7.17 KB
/
manage_permissions_v1.py
File metadata and controls
executable file
·260 lines (205 loc) · 7.17 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
#!/usr/bin/env python
"""
Manage organisation pointer type permissions for NRLF apps in a given environment ENV
"""
import json
import os
import fire
from aws_session_assume import get_boto_session
from nrlf.core.constants import TYPE_ATTRIBUTES
nrl_env = os.getenv("ENV", "dev")
nrl_auth_bucket_name = os.getenv(
"NRL_AUTH_BUCKET_NAME", f"nhsd-nrlf--{nrl_env}-authorization-store"
)
COMPARE_AND_CONFIRM = (
True
if nrl_env == "prod"
else os.getenv("COMPARE_AND_CONFIRM", "false").lower() == "true"
)
print(f"Using NRL environment: {nrl_env}")
print(f"Using NRL auth bucket: {nrl_auth_bucket_name}")
print(f"Compare and confirm mode: {COMPARE_AND_CONFIRM}")
print()
def _get_s3_client():
boto_session = get_boto_session(nrl_env)
return boto_session.client("s3")
def _list_s3_keys(file_key_prefix: str) -> list[str]:
s3 = _get_s3_client()
paginator = s3.get_paginator("list_objects_v2")
params = {
"Bucket": nrl_auth_bucket_name,
"Prefix": file_key_prefix,
}
page_iterator = paginator.paginate(**params)
keys: list[str] = []
for page in page_iterator:
if "Contents" in page:
keys.extend([item["Key"] for item in page["Contents"]])
if not keys:
print(f"No files found with prefix: {file_key_prefix}")
return []
return keys
def _get_perms_from_s3(file_key: str) -> str | None:
s3 = _get_s3_client()
try:
item = s3.get_object(Bucket=nrl_auth_bucket_name, Key=file_key)
except s3.exceptions.NoSuchKey:
print(f"Permissions file {file_key} does not exist in the bucket.")
return None
if "Body" not in item:
print(f"No body found for permissions file {file_key}.")
return None
return item["Body"].read().decode("utf-8")
def list_apps() -> None:
"""
List all applications in the NRL environment.
"""
keys = _list_s3_keys("")
apps = {key.split("/")[0] for key in keys}
if not apps:
print("No applications found in the bucket.")
return
print(f"There are {len(apps)} apps in {nrl_env} env:")
for app in apps:
print(f"- {app}")
def list_orgs(app_id: str) -> None:
"""
List all organizations for a specific application.
"""
keys = _list_s3_keys(f"{app_id}/")
orgs = [
key.split("/", maxsplit=2)[1].removesuffix(".json")
for key in keys
if key and key.endswith(".json")
]
if not orgs:
print(f"No organizations found for app {app_id}.")
print(f"There are {len(orgs)} organizations for app {app_id}:")
for org in orgs:
print(f"- {org}")
def list_available_types() -> None:
"""
List all pointer types that can be used in permissions.
"""
print("The following pointer-types can be assigned:")
for pointer_type, attributes in TYPE_ATTRIBUTES.items():
print("- %-45s (%s)" % (pointer_type, attributes["display"][:45]))
def show_perms(app_id: str, org_ods: str) -> None:
"""
Show the permissions for a specific application and organization.
"""
perms = _get_perms_from_s3(f"{app_id}/{org_ods}.json")
if not perms:
print(f"No permissions file found for {app_id}/{org_ods}.")
return
pointertype_perms = json.loads(perms)
if not pointertype_perms:
print(f"No pointer-types found in permission file for {app_id}/{org_ods}.")
return
type_data = {
pointertype_perm: TYPE_ATTRIBUTES.get(
pointertype_perm, {"display": "Unknown type"}
)
for pointertype_perm in pointertype_perms
}
types = [
"%-45s (%s)" % (type_data[pointertype_perm]["display"][:44], pointertype_perm)
for pointertype_perm in pointertype_perms
]
print(f"{app_id}/{org_ods} is allowed to access these pointer-types:")
for type_display in types:
print(f"- {type_display}")
def set_perms(app_id: str, org_ods: str, *pointer_types: str) -> None:
"""
Set permissions for an application and organization to access specific pointer types.
"""
if not pointer_types:
print(
"No pointer types provided. Please specify at least one pointer type or use clear_perms command."
)
return
if len(pointer_types) == 1 and pointer_types[0] == "all":
print("Setting permissions for access to all pointer types.")
pointer_types = tuple(TYPE_ATTRIBUTES.keys())
unknown_types = [pt for pt in pointer_types if pt not in TYPE_ATTRIBUTES]
if unknown_types:
print(f"Error: Unknown pointer types provided: {', '.join(unknown_types)}")
print()
return
permissions_content = json.dumps(pointer_types, indent=4)
if COMPARE_AND_CONFIRM:
current_perms = _get_perms_from_s3(f"{app_id}/{org_ods}.json")
if current_perms == permissions_content:
print(
f"No changes needed for {app_id}/{org_ods}. Current permissions match the new ones."
)
return
print()
print(f"Current permissions for {app_id}/{org_ods}:")
print(current_perms if current_perms else "No permissions set.")
print()
print("New permissions to be set to:")
print(f"{permissions_content}")
print()
confirm = (
input("Do you want to proceed with these changes? (yes/NO): ")
.strip()
.lower()
)
if confirm != "yes":
print("Operation cancelled at user request.")
return
s3 = _get_s3_client()
s3.put_object(
Bucket=nrl_auth_bucket_name,
Key=f"{app_id}/{org_ods}.json",
Body=permissions_content,
ContentType="application/json",
)
print()
print(f"Set permissions for {app_id}/{org_ods}")
print()
show_perms(app_id, org_ods)
def clear_perms(app_id: str, org_ods: str) -> None:
"""
Clear permissions for an application and organization.
This will remove all permissions for the specified app and org.
"""
if COMPARE_AND_CONFIRM:
current_perms = _get_perms_from_s3(f"{app_id}/{org_ods}.json")
if not current_perms or current_perms == "[]":
print(
f"No need to clear permissions for {app_id}/{org_ods} as it currently has no permissions set."
)
return
print()
print(f"Current permissions for {app_id}/{org_ods}:")
print(current_perms)
print()
confirm = (
input("Are you SURE you want to clear these permissions? (yes/NO): ")
.strip()
.lower()
)
if confirm != "yes":
print("Operation cancelled at user request.")
return
s3 = _get_s3_client()
s3.put_object(
Bucket=nrl_auth_bucket_name,
Key=f"{app_id}/{org_ods}.json",
Body="[]",
ContentType="application/json",
)
print(f"Cleared permissions for {app_id}/{org_ods}.")
if __name__ == "__main__":
fire.Fire(
{
"list_apps": list_apps,
"list_orgs": list_orgs,
"list_available_types": list_available_types,
"show_perms": show_perms,
"set_perms": set_perms,
"clear_perms": clear_perms,
}
)