-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathCloneAppRules.html
273 lines (251 loc) · 11.5 KB
/
CloneAppRules.html
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
<!doctype html>
<html>
<head>
<meta name=viewport content='initial-scale=1.0, minimum-scale=0.25'>
<title>Clone App Rules (new)</title>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>Clone App Rules (new)</h1>
<p>This tool will clone rules from a "source" app to one or more "destination" apps.</p>
<b>Setup</b>
<ol>
<li>Show your bookmarks toolbar. In Chrome, … > Bookmarks > Show Bookmarks Bar. In Firefox, right-click in the title bar and click Bookmarks Toolbar.
<li>Drag/drop this <a id=bm>Clone Rules v0.16</a> to the bookmarks toolbar.
</ol>
<br>
<b>Usage</b>
<ol>
<li>In your Okta org, pick one app as your "source".
<li>Create one or more rules in it -- it won't clone the "Catch-all Rule".
<li>Click the "Clone Rules" button from your bookmarks toolbar.
<li>You can use a CSV or the UI.
<ol>
<li>To use a CSV:
<ol>
<li>If needed, click "Get Apps", then "Export Apps CSV" to export all apps. Edit the CSV so only your desired "destination" apps remain
(i.e., delete any apps you don't want to clone to).
<li>Click "Import Apps CSV" to clone the rules.
</ol>
<li>Or, to use the UI:
<ol>
<li>Click "Get Apps".
<li>Select 1 or more "destination" apps and click "Clone".
</ol>
</ol>
<li>It will generate a "cloned rules" CSV for your records, or if you need to rollback. Please store this somewhere safe, eg, on a shared drive.
<li>If necessary, rollback using the "Rollback Rules" button to import the "cloned rules" CSV.
</ol>
<br>
<a href=https://github.com/gabrielsroka/gabrielsroka.github.io/blob/master/CloneAppRules.html>Source code</a>
<script id=code>
(function () {
const headers = {'x-okta-user-agent-extended': 'clone-tool/16'};
if (!window.$) {
alert('Drag/drop this link to your bookmarks toolbar.');
return;
}
const appId = getAppId();
if (!appId) {
alert('Please pick an app first.');
return;
}
var policyId;
var rules = [];
var appLabel;
/* Main popup. */
const popup = createPopup('Clone Application Rules');
const form = $('<form>' +
'Applications<div class=results><input type=button class=getApps value="Get Apps"></div><br> ' +
'<input type=submit disabled value=Clone> ' +
'<input type=button disabled class=checkAll value="Check All"> <input type=button disabled class=uncheckAll value="Uncheck All"> ' +
'<br><br><input type=button disabled class=exportAppsCSV value="Export Apps CSV">' +
'<br><br><label>Import Apps CSV<br><input type=file class=importApps></label>' +
'<br><br><label>Rollback Rules<br><input type=file class=rollbackRules></label>' +
'<br><br><div class=status></div><div class=error></div><br><div class=cloned></div></form>').appendTo(popup);
/* Import app CSV and clone rules. */
form.find('input.importApps').change(function () {
const reader = new FileReader();
reader.onload = () => parseAppFile(reader.result);
if (this.files.length > 0) reader.readAsText(this.files[0]);
});
async function parseAppFile(file) {
const lineSeparator = /\r\n|\r|\n/;
const fieldSeparator = ',';
const lines = file.split(lineSeparator);
if (lines[lines.length - 1] == '') lines.pop();
const fields = lines.shift().split(fieldSeparator);
const headers = Object.fromEntries(fields.map((val, i) => [val, i])); /* Map header name to number. */
const apps = lines.map(line => {
const fields = line.replace(/"/g, '').split(fieldSeparator); /* TODO: improve support for "s */
return {policyId: fields[headers.id], name: fields[headers.name]};
});
await cloneRules(apps);
}
/* Clone rules (from Clone button). */
form.submit(async event => {
event.preventDefault();
const checked = form.find('input:checked');
/* Use standard array map instead of jQuery map. */
const apps = checked.toArray().map(chk => ({policyId: chk.value, name: chk.parentNode.textContent}));
await cloneRules(apps)
});
async function cloneRules(apps) {
if (rules.length == 0) await getRules();
form.find('div.cloned').html('');
form.find('div.error').html('');
const cloned = [];
const csv = [];
for (const app of apps) {
for (const rule of rules) {
try {
const clonedRule = await postJSON({url: `/api/v1/policies/${app.policyId}/rules`, data: rule});
form.find('div.status').html(app.name + ', ' + rule.name);
cloned.push(app.name + ', ' + rule.name);
csv.push(toCSV(app.policyId, clonedRule.id, app.name, rule.name));
} catch (jqXHR) {
const e = jqXHR.responseJSON;
form.find('div.error').html('Error:<br>' + e.errorSummary + '<br>' + e.errorCauses.map(c => c.errorSummary).join('<br>'));
}
}
}
form.find('div.cloned').html('Cloned:<br>' + cloned.sort().join('<br>'));
form.find('div.status').html('');
downloadCSV(popup, 'policyId,ruleId,appName,ruleName', csv, appLabel + ' cloned rules');
}
async function getRules() {
if (!policyId) {
const app = await getJSON(`/api/v1/apps/${appId}`);
policyId = app._links.accessPolicy.href.split('/').pop();
appLabel = app.label;
}
rules = await getJSON(`/api/v1/policies/${policyId}/rules`);
rules.pop(); /* Don't clone the 'Catch-all Rule'. */
rules.forEach(rule => {
rule.name += ' (clone)';
delete rule.id;
delete rule.resourceDisplayName;
delete rule._links;
});
}
/* Rollback rules from CSV. */
form.find('input.rollbackRules').change(function () {
const reader = new FileReader();
reader.onload = () => parseRuleFile(reader.result);
if (this.files.length > 0) reader.readAsText(this.files[0]);
});
async function parseRuleFile(file) {
const lineSeparator = /\r\n|\r|\n/;
const fieldSeparator = ',';
const lines = file.split(lineSeparator);
if (lines[lines.length - 1] == '') lines.pop();
const fields = lines.shift().split(fieldSeparator);
const headers = Object.fromEntries(fields.map((val, i) => [val, i])); /* Map header name to number. */
form.find('div.cloned').html('');
form.find('div.error').html('');
const rolled = [];
for (const line of lines) {
const fields = line.replace(/"/g, '').split(fieldSeparator); /* TODO: improve support for "s */
const policyId = fields[headers.policyId];
const ruleId = fields[headers.ruleId];
try {
await deleteJSON(`/api/v1/policies/${policyId}/rules/${ruleId}`);
form.find('div.status').html(fields[headers.appName] + ', ' + fields[headers.ruleName]);
rolled.push(fields[headers.appName] + ', ' + fields[headers.ruleName]);
} catch (jqXHR) {
const e = jqXHR.responseJSON;
form.find('div.error').html('Error:<br>' + e.errorSummary + '<br>' + e.errorCauses.map(c => c.errorSummary).join('<br>'));
}
}
form.find('div.cloned').html('Rolled back:<br>' + rolled.sort().join('<br>'));
form.find('div.status').html('');
}
/* Find policies and apps, show checkboxes. */
form.find('input.getApps').click(async function () {
const chks = [];
const csv = [];
var url = '/api/v1/apps';
while (url) {
const response = await fetch(url, {headers});
if (!response.ok) {
const err = await response.json();
if (response.status == 404) {
alert("Unable to fetch all apps. You might have a corrupted app. Please contact Okta Support. " + err.errorSummary);
} else {
alert(err.errorSummary);
}
return;
}
const apps = await response.json();
for (const app of apps) {
if (app._links.accessPolicy) {
const pId = app._links.accessPolicy.href.split('/').pop();
if (appId == app.id) {
policyId = pId;
appLabel = app.label;
} else if (!['active_directory', 'ldap_sun_one', 'csv_directory_v2'].includes(app.name)) {
const sortBy = `<!--${app.label}-->`;
chks.push(`${sortBy}<label><input type=checkbox value='${pId}' checked>${app.label}</label>`);
csv.push(toCSV(pId, app.label));
form.find('div.status').html(`Loading app ${csv.length}...`);
}
}
}
url = response.headers.get('link')?.match('<https://[^/]+(/[^>]+)>; rel="next"')?.[1];
}
form.find('input.exportAppsCSV').click(() => downloadCSV(popup, 'id,name', csv, 'apps'));
const results = chks.length > 0 ? chks.sort().join('<br>') : 'Not found';
form.find('div.results').html(results);
form.find('div.status').html('');
form.find('input').prop('disabled', false);
});
form.find('input.checkAll').click(() => form.find('input[type=checkbox]').prop('checked', true));
form.find('input.uncheckAll').click(() => form.find('input[type=checkbox]').prop('checked', false));
function createPopup(title) {
const popup = $(`<div style='position: absolute; z-index: 1000; top: 0px; max-height: calc(100% - 28px); max-width: calc(100% - 28px); padding: 8px; margin: 4px; overflow: auto; ` +
`background-color: white; border: 1px solid #ddd;'>` +
`${title}<div style='display: block; float: right;'><a href='https://gabrielsroka.github.io/CloneAppRules.html' target='_blank' rel='noopener' style='padding: 4px'>?</a> ` +
`<a class=close style='cursor: pointer; padding: 4px'>X</a></div><br><br></div>`).appendTo(document.body);
popup.find('a.close').click(() => popup.remove());
return $('<div></div>').appendTo(popup);
}
function toCSV(...fields) {
return fields.map(field => `"${field == undefined ? '' : field.toString().replace(/"/g, '""')}"`).join(',');
}
function downloadCSV(popup, header, lines, filename) {
var a = $('<a>').appendTo(popup);
a.attr('href', URL.createObjectURL(new Blob([header + '\n' + lines.join('\n')], {type: 'text/csv'})));
var date = (new Date()).toISOString().replace(/T/, ' ').replace(/:/g, '-').slice(0, 19);
a.attr('download', `${filename} ${date}.csv`);
a[0].click();
}
function getAppId() {
const path = location.pathname;
const pathparts = path.split('/');
if (path.match('admin/app') && (pathparts.length == 6 || pathparts.length == 7)) {
return pathparts[5];
}
}
function getJSON(url) {
return $.get({url, headers});
}
function postJSON(settings) {
settings.contentType = 'application/json';
settings.data = JSON.stringify(settings.data);
settings.headers = headers;
return $.post(settings);
}
function deleteJSON(url) {
return $.ajax({url, headers, method: "DELETE"});
}
})
</script>
<script>
bm.href = 'javascript:' + code.innerText + '();';
</script>
</body>
</html>