-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate-s2s-script.js
More file actions
150 lines (127 loc) · 4.79 KB
/
create-s2s-script.js
File metadata and controls
150 lines (127 loc) · 4.79 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
/**
* Licensed Materials - Property of IBM
* (c) Copyright IBM Corporation 2025. All Rights Reserved.
*
* Note to U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule
* Contract with IBM Corp.
*/
const fs = require('node:fs');
const { resolve } = require('node:path');
const { exit } = require('node:process');
const API_KEY = process.env['IBMCLOUD_API_KEY'];
if (!API_KEY) throw Error(`Missing 'IBMCLOUD_API_KEY'`);
const TC_ID = process.env['TARGET_TOOLCHAIN_ID'];
if (!TC_ID) throw Error(`Missing 'TARGET_TOOLCHAIN_ID'`);
const CLOUD_PLATFORM = process.env['IBMCLOUD_PLATFORM'] || 'cloud.ibm.com';
if (!CLOUD_PLATFORM) throw Error(`Missing 'IBMCLOUD_PLATFORM'`);
const IAM_BASE_URL = process.env['IAM_BASE_URL'] || 'https://iam.cloud.ibm.com';
if (!IAM_BASE_URL) throw Error(`Missing 'IAM_BASE_URL'`);
const GENERATED_TIME = process.env['GENERATED_TIME'];
if (!GENERATED_TIME) throw Error(`Missing 'GENERATED_TIME'`);
const INPUT_PATH = resolve('create-s2s.json');
const ERROR_PATH = resolve(`.s2s-script-failures-${GENERATED_TIME}`);
async function getBearer() {
const url = `${IAM_BASE_URL}/identity/token`;
const params = new URLSearchParams();
params.append('grant_type', 'urn:ibm:params:oauth:grant-type:apikey');
params.append('apikey', API_KEY);
params.append('response_type', 'cloud_iam');
try {
const response = await fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params
});
if (!response.ok) {
throw new Error(`Failed to get bearer token with status: ${response.status}, ${response.statusText}`);
}
return (await response.json()).access_token;
} catch (error) {
console.error(`Failed to get bearer token: ${error.message}`);
}
}
/* expecting item as an object with the format of:
{
"parameters": {
"name": "",
"integration-status": "",
"instance-id-type": "",
"region": "",
"resource-group": "",
"instance-name": "",
"instance-crn": "",
"setup-authorization-type": ""
},
"toolchainId": "",
"serviceId": "",
"env_id": ""
}
*/
async function createS2sAuthPolicy(bearer, item) {
const url = `https://${CLOUD_PLATFORM}/devops/setup/api/v2/s2s_authorization?${new URLSearchParams({
toolchainId: TC_ID,
serviceId: item['serviceId'],
env_id: item['env_id']
}).toString()}`;
const data = JSON.stringify({
'parameters': {
'name': item['parameters']['name'],
'integration-status': '',
'instance-id-type': item['parameters']['instance-id-type'],
'region': item['parameters']['region'],
'resource-group': item['parameters']['resource-group'],
'instance-name': item['parameters']['instance-name'],
'instance-crn': item['parameters']['instance-crn'],
'setup-authorization-type': 'select'
}
});
try {
const response = await fetch(url, {
method: "POST",
headers: {
'Authorization': `Bearer ${bearer}`,
'Content-Type': 'application/json',
},
body: data,
});
if (!response.ok) {
return Promise.reject(`Failed to create service-to-service authorization policy for ${item['serviceId']} '${item['parameters']['label'] ?? item['parameters']['name']}' with status: ${response.status} ${response.statusText}`);
}
} catch (error) {
return Promise.reject(`Failed to create service-to-service authorization policy for ${item['serviceId']}: ${error.message}`);
}
}
// main
getBearer().then(async (bearer) => {
// remove temp file from previous runs
if (fs.existsSync(ERROR_PATH)) {
fs.rmSync(ERROR_PATH);
}
const inputArr = JSON.parse(fs.readFileSync(INPUT_PATH));
const promises = [];
inputArr.forEach((item) => {
promises.push(createS2sAuthPolicy(bearer, item));
});
await Promise.allSettled(promises).then((res) => {
const rejectReasons = res.filter(r => r.status === 'rejected').map(r => r.reason);
if (rejectReasons.length > 0) {
let errFileContents = '';
rejectReasons.forEach((reason) => {
console.error(reason);
// create temp file on error
errFileContents += reason;
errFileContents += '\n';
});
fs.writeFileSync(ERROR_PATH, errFileContents);
exit(1);
}
});
}).catch((reason) => {
console.error(reason);
// create temp file on error
fs.writeFileSync(ERROR_PATH, reason + '\n');
});