/
containerRegistryTokenCredential.ts
193 lines (174 loc) · 5.86 KB
/
containerRegistryTokenCredential.ts
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { createSerializer, OperationOptions, OperationSpec } from "@azure/core-client";
import { AccessToken, GetTokenOptions, TokenCredential } from "@azure/core-auth";
import { AcrAccessToken, AcrRefreshToken, GeneratedClient } from "./generated";
import * as Mappers from "./generated/models/mappers";
import * as Parameters from "./generated/models/parameters";
import { base64decode } from "./utils/base64";
export interface ContainerRegistryGetTokenOptions extends GetTokenOptions {
service: string;
}
export class ContainerRegistryRefreshTokenCredential implements TokenCredential {
readonly tokenService: ContainerRegistryTokenService;
readonly isAnonymousAccess: boolean;
constructor(
authClient: GeneratedClient,
private authenticationScope: string,
private credential?: TokenCredential
) {
this.tokenService = new ContainerRegistryTokenService(authClient);
this.isAnonymousAccess = !this.credential;
}
async getToken(
_scopes: string | string[],
options: ContainerRegistryGetTokenOptions
): Promise<AccessToken | null> {
if (!this.credential) {
return null;
}
const aadToken = await this.credential.getToken(this.authenticationScope, options);
if (!aadToken) {
throw new Error("Failed to retrieve AAD token.");
}
return this.tokenService.ExchangeAadAccessTokenForAcrRefreshTokenAsync(
aadToken.token,
options.service,
options
);
}
}
const customExchangeAadTokenForAcrRefreshTokenOperationSpec: OperationSpec = {
path: "/oauth2/exchange",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.AcrRefreshToken
},
default: {
bodyMapper: Mappers.AcrErrors
}
},
// formDataParameters: [Parameters.aadAccesstoken],
requestBody: {
parameterPath: ["options", "payload"],
mapper: {
type: {
name: "Stream"
}
}
},
urlParameters: [Parameters.url],
headerParameters: [Parameters.contentType3, Parameters.accept4],
serializer: createSerializer(Mappers, /* isXml */ false)
};
interface CustomAuthOptions extends OperationOptions {
payload: string;
}
const customExchangeAcrRefreshTokenForAcrAccessTokenOperationSpec: OperationSpec = {
path: "/oauth2/token",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.AcrAccessToken
},
default: {
bodyMapper: Mappers.AcrErrors
}
},
// formDataParameters: [Parameters.acrRefreshToken],
requestBody: {
parameterPath: ["options", "payload"],
mapper: {
type: {
name: "Stream"
}
}
},
urlParameters: [Parameters.url],
headerParameters: [Parameters.contentType3, Parameters.accept4],
serializer: createSerializer(Mappers, /* isXml */ false)
};
export class ContainerRegistryTokenService {
constructor(private authClient: GeneratedClient) {}
async ExchangeAadAccessTokenForAcrRefreshTokenAsync(
aadAccessToken: string,
service: string,
options: GetTokenOptions
): Promise<AccessToken> {
// const acrRefreshToken = await this.authClient.authentication.exchangeAadTokenForAcrRefreshToken(
// {
// aadAccesstoken: {
// grantType: "access_token",
// service,
// aadAccesstoken: aadAccessToken,
// }
// }
// );
// TODO: (jeremymeng) revert custom sendOperationRequest call after FormData is working in core
const payload = `grant_type=access_token&service=${encodeURIComponent(
service
)}&access_token=${encodeURIComponent(aadAccessToken)}`;
const customOptions: CustomAuthOptions = {
payload
};
const acrRefreshToken = await this.authClient.sendOperationRequest<AcrRefreshToken>(
{ options: { ...options, ...customOptions } },
customExchangeAadTokenForAcrRefreshTokenOperationSpec
);
if (!acrRefreshToken.refreshToken) {
throw new Error("Failed to exchange AAD access token for an ACR refresh token.");
}
// ACR refresh token expires after three hours
const jwtParts = acrRefreshToken.refreshToken.split(".");
if (jwtParts.length < 3) {
throw new Error("Invalid JWT structure from ACR refresh token.");
}
if (!jwtParts[1]) {
throw new Error("Invalid JWT payload.");
}
const jwtPayload = JSON.parse(base64decode(jwtParts[1]));
if (!jwtPayload.exp) {
throw new Error("Invalid JWT payload structure. No expiration.");
}
// JWT expiry is in seconds
const expiry = Number.parseInt(jwtPayload.exp) * 1000;
return {
token: acrRefreshToken.refreshToken,
expiresOnTimestamp: expiry
};
}
async ExchangeAcrRefreshTokenForAcrAccessTokenAsync(
acrRefreshToken: string,
service: string,
scope: string,
grantType: "refresh_token" | "password",
options: GetTokenOptions
): Promise<string> {
// const acrAccessToken = await this.authClient.authentication.exchangeAcrRefreshTokenForAcrAccessToken(
// {
// acrRefreshToken: {
// grantType: "refresh_token",
// acrRefreshToken,
// service,
// scope
// }
// }
// );
// TODO: (jeremymeng) revert custom sendOperationRequest call after FormData is working in core
const payload = `grant_type=${grantType}&service=${encodeURIComponent(service)}&refresh_token=${
acrRefreshToken ? encodeURIComponent(acrRefreshToken) : ""
}&scope=${encodeURIComponent(scope)}`;
const customOptions: CustomAuthOptions = {
payload
};
const acrAccessToken = await this.authClient.sendOperationRequest<AcrAccessToken>(
{ options: { ...options, ...customOptions } },
customExchangeAcrRefreshTokenForAcrAccessTokenOperationSpec
);
if (!acrAccessToken.accessToken) {
throw new Error("Failed to exchange ACR refresh token for an ACR access token");
}
return acrAccessToken.accessToken;
}
}