Repository navigation
Expand file tree
/
Copy pathexec_auth.ts
More file actions
173 lines (156 loc) · 5.49 KB
/
Copy pathexec_auth.ts
File metadata and controls
173 lines (156 loc) · 5.49 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
import { OutgoingHttpHeaders } from 'node:http';
import https from 'node:https';
import { Authenticator } from './auth.js';
import { User } from './config_types.js';
import {
checkExecCredentialPluginPolicy,
ExecCredentialPluginPolicy,
validateExecCredentialPluginPolicy,
} from './exec_credential_policy.js';
import child_process from 'node:child_process';
export interface CredentialStatus {
readonly token: string;
readonly clientCertificateData: string;
readonly clientKeyData: string;
readonly expirationTimestamp?: string;
}
export interface Credential {
readonly status: CredentialStatus;
}
export class ExecAuth implements Authenticator {
private tokenCache: { [key: string]: Credential | null } = {};
private policy?: ExecCredentialPluginPolicy;
private execFn: (
command: string,
args?: readonly string[],
options?: child_process.SpawnOptionsWithoutStdio,
) => child_process.ChildProcessWithoutNullStreams = child_process.spawn;
/**
* @param policy optional application policy restricting which exec credential plugins may run.
* Defaults to allowing all plugins.
*/
constructor(policy?: ExecCredentialPluginPolicy) {
this.setPolicy(policy);
}
/**
* Sets the policy restricting which exec credential plugins may run.
* The policy applies to every subsequent plugin execution, including token refreshes.
* Cached credentials are discarded when the policy changes.
* @param policy the policy, undefined allows all plugins.
*/
public setPolicy(policy?: ExecCredentialPluginPolicy): void {
validateExecCredentialPluginPolicy(policy);
this.policy = policy;
this.tokenCache = {};
}
public isAuthProvider(user: User): boolean {
if (!user) {
return false;
}
if (user.exec) {
return true;
}
if (!user.authProvider) {
return false;
}
return (
user.authProvider.name === 'exec' || !!(user.authProvider.config && user.authProvider.config.exec)
);
}
public async applyAuthentication(user: User, opts: https.RequestOptions): Promise<void> {
const credential = await this.getCredential(user);
if (!credential) {
return;
}
if (credential.status.clientCertificateData) {
opts.cert = credential.status.clientCertificateData;
}
if (credential.status.clientKeyData) {
opts.key = credential.status.clientKeyData;
}
const token = this.getToken(credential);
if (token) {
if (!opts.headers) {
opts.headers = {} as OutgoingHttpHeaders;
}
opts.headers!['Authorization'] = `Bearer ${token}`;
}
}
private getToken(credential: Credential): string | null {
if (!credential) {
return null;
}
if (credential.status.token) {
return credential.status.token;
}
return null;
}
private async getCredential(user: User): Promise<Credential | null> {
// TODO: Add a unit test for token caching.
const cachedToken = this.tokenCache[user.name];
if (cachedToken) {
if (!cachedToken.status.expirationTimestamp) {
return cachedToken;
}
const date = Date.parse(cachedToken.status.expirationTimestamp);
if (date > Date.now()) {
return cachedToken;
}
this.tokenCache[user.name] = null;
}
let exec: any = null;
if (user.authProvider && user.authProvider.config) {
exec = user.authProvider.config.exec;
}
if (user.exec) {
exec = user.exec;
}
if (!exec) {
return null;
}
if (!exec.command) {
throw new Error('No command was specified for exec authProvider!');
}
const command = checkExecCredentialPluginPolicy(this.policy, exec.command);
let opts = {};
if (exec.env) {
const env = { ...process.env };
exec.env.forEach((elt) => (env[elt.name] = elt.value));
opts = { ...opts, env };
}
return new Promise((resolve, reject) => {
let stdoutData: string = '';
let stderrData: string = '';
let savedError: Error | undefined = undefined;
const subprocess = this.execFn(command, exec.args, opts);
subprocess.stdout.setEncoding('utf8');
subprocess.stderr.setEncoding('utf8');
subprocess.stdout.on('data', (data: string) => {
stdoutData += data;
});
subprocess.stderr.on('data', (data: string) => {
stderrData += data;
});
subprocess.on('error', (error) => {
savedError = error;
});
subprocess.on('close', (code) => {
if (savedError) {
reject(savedError);
return;
}
if (code !== 0) {
reject(new Error(stderrData));
return;
}
try {
const obj = JSON.parse(stdoutData) as Credential;
this.tokenCache[user.name] = obj;
resolve(obj);
} catch (error) {
reject(error);
}
});
});
}
}