@vizamodo/aws-sts-core 0.4.30 → 0.4.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import type { AwsCredentialResult } from "../types";
2
+ export declare function resetIsolateCache(): void;
2
3
  export declare function issueAwsCredentials(input: {
3
4
  roleArn: string;
4
5
  profileArn: string;
package/dist/sts/issue.js CHANGED
@@ -26,6 +26,16 @@ let signingKeyPromise = null;
26
26
  let cachedSigningKey = null;
27
27
  let cachedCertBase64 = null;
28
28
  let cachedPrivateKeyBase64 = null;
29
+ // ---- single-flight hard refresh guard + cooldown ----
30
+ let hardRefreshPromise = null;
31
+ let lastHardRefreshAt = 0;
32
+ const HARD_REFRESH_COOLDOWN_MS = 2000;
33
+ export function resetIsolateCache() {
34
+ signingKeyPromise = null;
35
+ cachedSigningKey = null;
36
+ cachedCertBase64 = null;
37
+ cachedPrivateKeyBase64 = null;
38
+ }
29
39
  // ---- certificate serial cache (DER walk is CPU-bound, cert rarely rotates) ----
30
40
  let cachedCertSerialDec = null;
31
41
  let cachedCertSerialSource = null;
@@ -89,47 +99,54 @@ export async function issueAwsCredentials(input) {
89
99
  const certSerialDec = parseCertSerialDec(normalizedCert);
90
100
  const cacheKey = `${region}|${roleArn}|${profileArn}|${trustAnchorArn}|${certSerialDec}`;
91
101
  return getCachedOrFetch(cacheKey, async () => {
92
- // ---- Build SigV4 request (moved inside fetcher) ----
93
- const { signingKey } = await getSigningMaterial({
94
- certBase64: normalizedCert,
95
- privateKeyPkcs8Base64,
96
- });
97
- const host = `${SERVICE}.${region}.amazonaws.com`;
98
- const iso = new Date().toISOString();
99
- const amzDate = isoToAmzDate(iso);
100
- const dateStamp = iso.slice(0, 4) + iso.slice(5, 7) + iso.slice(8, 10);
101
- const body = JSON.stringify({ trustAnchorArn, profileArn, roleArn, durationSeconds: sessionTtl });
102
- const payloadHash = await sha256Hex(body);
103
- const baseHeaders = {
104
- "content-type": "application/json",
105
- "host": host,
106
- "x-amz-date": amzDate,
107
- "x-amz-x509": normalizedCert,
108
- };
109
- const { canonicalHeaders, signedHeaders } = canonicalizeHeaders(baseHeaders);
110
- const credentialScope = `${dateStamp}/${region}/${SERVICE}/aws4_request`;
111
- const canonicalRequest = buildCanonicalRequest({
112
- method: "POST",
113
- canonicalUri: PATH,
114
- query: "",
115
- canonicalHeaders,
116
- signedHeaders,
117
- payloadHash,
118
- });
119
- const canonicalRequestHash = await sha256Hex(canonicalRequest);
120
- const stringToSign = buildStringToSign({
121
- algorithm: ALGORITHM,
122
- amzDate,
123
- credentialScope,
124
- canonicalRequestHash,
125
- });
126
- const signatureHex = await signStringToSign(stringToSign, signingKey);
127
- const finalHeaders = new Headers({
128
- "Content-Type": "application/json",
129
- "X-Amz-Date": amzDate,
130
- "X-Amz-X509": normalizedCert,
131
- "Authorization": `${ALGORITHM} Credential=${certSerialDec}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signatureHex}`,
132
- });
102
+ async function buildSignedHeaders() {
103
+ const { signingKey } = await getSigningMaterial({
104
+ certBase64: normalizedCert,
105
+ privateKeyPkcs8Base64,
106
+ });
107
+ const host = `${SERVICE}.${region}.amazonaws.com`;
108
+ const iso = new Date().toISOString();
109
+ const amzDate = isoToAmzDate(iso);
110
+ const dateStamp = iso.slice(0, 4) + iso.slice(5, 7) + iso.slice(8, 10);
111
+ const body = JSON.stringify({ trustAnchorArn, profileArn, roleArn, durationSeconds: sessionTtl });
112
+ const payloadHash = await sha256Hex(body);
113
+ const baseHeaders = {
114
+ "content-type": "application/json",
115
+ "host": host,
116
+ "x-amz-date": amzDate,
117
+ "x-amz-x509": normalizedCert,
118
+ };
119
+ const { canonicalHeaders, signedHeaders } = canonicalizeHeaders(baseHeaders);
120
+ const credentialScope = `${dateStamp}/${region}/${SERVICE}/aws4_request`;
121
+ const canonicalRequest = buildCanonicalRequest({
122
+ method: "POST",
123
+ canonicalUri: PATH,
124
+ query: "",
125
+ canonicalHeaders,
126
+ signedHeaders,
127
+ payloadHash,
128
+ });
129
+ const canonicalRequestHash = await sha256Hex(canonicalRequest);
130
+ const stringToSign = buildStringToSign({
131
+ algorithm: ALGORITHM,
132
+ amzDate,
133
+ credentialScope,
134
+ canonicalRequestHash,
135
+ });
136
+ const signatureHex = await signStringToSign(stringToSign, signingKey);
137
+ const headers = new Headers({
138
+ "Content-Type": "application/json",
139
+ "X-Amz-Date": amzDate,
140
+ "X-Amz-X509": normalizedCert,
141
+ "Authorization": `${ALGORITHM} Credential=${certSerialDec}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signatureHex}`,
142
+ });
143
+ return {
144
+ headers,
145
+ body,
146
+ host,
147
+ };
148
+ }
149
+ const { headers: finalHeaders, body, host } = await buildSignedHeaders();
133
150
  const issuedAt = Date.now();
134
151
  let res;
135
152
  try {
@@ -144,7 +161,50 @@ export async function issueAwsCredentials(input) {
144
161
  throw new InternalError("aws_unreachable");
145
162
  }
146
163
  if (!res.ok) {
147
- console.warn("[aws-rejected]", { status: res.status, region, profile });
164
+ const status = res.status;
165
+ // Safe internal hard reset trigger:
166
+ // Only reset isolate cache on explicit forceRefresh AND first failure
167
+ if (forceRefresh && status === 403) {
168
+ const now = Date.now();
169
+ // Cooldown guard to avoid rapid consecutive hard resets
170
+ if (now - lastHardRefreshAt < HARD_REFRESH_COOLDOWN_MS) {
171
+ console.warn("[aws-rejected][cooldown-skip-hard-reset]", { status, region });
172
+ throw new InternalError("aws_rejected");
173
+ }
174
+ // Single-flight: only one request performs hard refresh
175
+ if (!hardRefreshPromise) {
176
+ hardRefreshPromise = (async () => {
177
+ console.warn("[aws-rejected][hard-reset-trigger]", { status, region });
178
+ lastHardRefreshAt = Date.now();
179
+ resetIsolateCache();
180
+ const { headers: retryHeaders, body: retryBody, host: retryHost } = await buildSignedHeaders();
181
+ const retryRes = await fetch(`https://${retryHost}${PATH}`, {
182
+ method: "POST",
183
+ headers: retryHeaders,
184
+ body: retryBody,
185
+ });
186
+ if (!retryRes.ok) {
187
+ console.warn("[aws-rejected][after-hard-reset]", { status: retryRes.status, region });
188
+ throw new InternalError("aws_rejected");
189
+ }
190
+ const retryJson = await retryRes.json();
191
+ const retryCreds = retryJson?.credentialSet?.[0]?.credentials;
192
+ if (!retryCreds?.accessKeyId || !retryCreds?.secretAccessKey || !retryCreds?.sessionToken) {
193
+ throw new InternalError("aws_malformed_credentials");
194
+ }
195
+ return {
196
+ accessKeyId: retryCreds.accessKeyId,
197
+ secretAccessKey: retryCreds.secretAccessKey,
198
+ sessionToken: retryCreds.sessionToken,
199
+ expiration: retryCreds.expiration,
200
+ };
201
+ })().finally(() => {
202
+ hardRefreshPromise = null;
203
+ });
204
+ }
205
+ return await hardRefreshPromise;
206
+ }
207
+ console.warn("[aws-rejected]", { status, region, profile });
148
208
  throw new InternalError("aws_rejected");
149
209
  }
150
210
  const json = await res.json();
@@ -170,7 +230,7 @@ export async function issueAwsCredentials(input) {
170
230
  return value;
171
231
  }, {
172
232
  ttlSec: 60,
173
- ...(forceRefresh !== undefined ? { forceRefresh } : {})
233
+ forceRefresh: !!forceRefresh
174
234
  });
175
235
  }
176
236
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vizamodo/aws-sts-core",
3
- "version": "0.4.30",
3
+ "version": "0.4.32",
4
4
  "description": "Pure AWS STS + SigV4 (X509 Roles Anywhere) core logic",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",