-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathopenshift.ts
More file actions
198 lines (187 loc) · 6.78 KB
/
Copy pathopenshift.ts
File metadata and controls
198 lines (187 loc) · 6.78 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
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import got from 'got';
import * as kubeconfig from './kubeconfig.js';
import * as extensionApi from '@podman-desktop/api';
import { CoreV1Api, KubeConfig, V1Secret, V1ServiceAccount } from '@kubernetes/client-node';
import { getRegistrationServiceTimeout } from './sandbox.js';
import { delay } from './utils.js';
export interface InternalRegistryInfo {
host: string;
username: string;
token: string;
}
export async function whoami(clusterUrl: string, token: string): Promise<string> {
const gotOptions = {
headers: {
Authorization: `Bearer ${token}`,
},
};
const username: string = await got(`${clusterUrl}/apis/user.openshift.io/v1/users/~`, gotOptions).then(response => {
if (response.statusCode === 200) {
const responseObj = JSON.parse(response.body);
return responseObj.metadata.name;
}
throw new Error('Developer Sandbox username cannot be detected.');
});
return username;
}
export async function getOpenShiftInternalRegistryPublicHost(contextName: string): Promise<InternalRegistryInfo> {
const config = kubeconfig.createOrLoadFromFile(extensionApi.kubernetes.getKubeconfig().fsPath);
const context = config.getContextObject(contextName);
if (!context) {
throw new Error(`Context '${contextName}' not found in kubeconfig.`);
}
const cluster = config.getCluster(context.cluster);
if (!cluster) {
throw new Error(`Cluster for context '${contextName}' not found in kubeconfig.`);
}
const user = config.getUser(context.user);
if (!user || !user.token) {
throw new Error(`User or token for context '${contextName}' not found in kubeconfig.`);
}
const gotOptions = {
headers: {
Authorization: `Bearer ${user.token}`,
},
};
const publicRegistry: string = await got(
`${cluster.server}/apis/image.openshift.io/v1/namespaces/openshift/imagestreams`,
gotOptions,
).then(response => {
if (response.statusCode === 200) {
const responseObj = JSON.parse(response.body);
if (responseObj.items.length) {
return responseObj.items[0].status.publicDockerImageRepository;
}
}
throw new Error('Could not detect host name for internal Developer Sandbox image registry.');
});
const host = publicRegistry.substring(0, publicRegistry.indexOf('/'));
const username: string = await whoami(cluster.server, user.token);
const matches = username.match(/^system:serviceaccount:([a-zA-Z-_.]+)-dev:pipeline$/);
if (!matches) {
throw new Error(`Cannot detect username for Developer Sandbox connection '${contextName}'.`);
}
return {
host,
username: matches[1],
token: user.token,
};
}
export function prepareKubeConfig(
clusterName: string,
clusterUsername: string,
contextName: string,
server: string,
username: string,
accessToken: string,
): KubeConfig {
const kcu = new KubeConfig();
const clusterProxy = {
name: clusterName,
server: server,
skipTLSVerify: false,
};
const user = {
name: clusterUsername,
token: accessToken,
};
const context = {
cluster: clusterProxy.name,
name: contextName,
user: user.name,
namespace: `${username}-dev`,
};
kcu.addCluster(clusterProxy);
kcu.addUser(user);
kcu.addContext(context);
kcu.setCurrentContext(context.name);
return kcu;
}
async function installPipelineSecretToken(
k8sApi: CoreV1Api,
pipelineServiceAccount: V1ServiceAccount,
username: string,
): Promise<V1Secret | undefined> {
if (!pipelineServiceAccount.metadata?.name || !pipelineServiceAccount.metadata?.uid) {
throw new Error('Service account is missing required metadata.');
}
const secretName = `pipeline-secret-${username}-dev`;
const v1Secret = {
apiVersion: 'v1',
kind: 'Secret',
metadata: {
name: secretName,
annotations: {
'kubernetes.io/service-account.name': pipelineServiceAccount.metadata.name,
'kubernetes.io/service-account.uid': pipelineServiceAccount.metadata.uid,
},
},
type: 'kubernetes.io/service-account-token',
} as V1Secret;
await k8sApi.createNamespacedSecret({ namespace: `${username}-dev`, body: v1Secret });
const timeout = getRegistrationServiceTimeout();
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
try {
const response = await k8sApi.readNamespacedSecret({
name: secretName,
namespace: `${username}-dev`,
});
return response;
} catch (error) {
const err = error as { response?: { statusCode?: number } };
if (err.response?.statusCode === 404) {
console.error(`Cannot read created sandbox secret ${secretName}`);
await delay(250);
} else {
console.error(String(error));
throw error;
}
}
}
}
export async function getPipelineServiceAccountToken(
proxy: string,
username: string,
idToken: string,
): Promise<string> {
const kcu = prepareKubeConfig('sandbox-proxy', 'sso-user', 'sandbox-proxy-context', proxy, username, idToken);
const k8sApi = kcu.makeApiClient(CoreV1Api);
const serviceAccounts = await k8sApi.listNamespacedServiceAccount({ namespace: `${username}-dev` });
const pipelineServiceAccount = serviceAccounts.items.find(
serviceAccount => serviceAccount.metadata?.name === 'pipeline',
) as V1ServiceAccount | undefined;
if (!pipelineServiceAccount) {
throw new Error(`Couldn't find service account required to create Developer Sandbox connection.`);
}
const secrets = await k8sApi.listNamespacedSecret({ namespace: `${username}-dev` });
let pipelineTokenSecret = secrets?.items.find(secret => secret.metadata?.name === `pipeline-secret-${username}-dev`);
if (!pipelineTokenSecret) {
try {
pipelineTokenSecret = await installPipelineSecretToken(k8sApi, pipelineServiceAccount, username);
} catch (error) {
throw new Error(`An error occurred when creating secret for Developer Sandbox connection.`);
}
}
if (!pipelineTokenSecret?.data?.token) {
throw new Error('Failed to get required service account token.');
}
return Buffer.from(pipelineTokenSecret.data.token, 'base64').toString();
}