@onkernel/sdk 0.149.0 → 0.151.0
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.
- package/CHANGELOG.md +25 -0
- package/client.d.mts +29 -4
- package/client.d.mts.map +1 -1
- package/client.d.ts +29 -4
- package/client.d.ts.map +1 -1
- package/client.js +32 -3
- package/client.js.map +1 -1
- package/client.mjs +32 -3
- package/client.mjs.map +1 -1
- package/lib/credentials/client-auth.d.mts +88 -0
- package/lib/credentials/client-auth.d.mts.map +1 -0
- package/lib/credentials/client-auth.d.ts +88 -0
- package/lib/credentials/client-auth.d.ts.map +1 -0
- package/lib/credentials/client-auth.js +166 -0
- package/lib/credentials/client-auth.js.map +1 -0
- package/lib/credentials/client-auth.mjs +162 -0
- package/lib/credentials/client-auth.mjs.map +1 -0
- package/lib/credentials/credential-chain.d.mts +20 -0
- package/lib/credentials/credential-chain.d.mts.map +1 -0
- package/lib/credentials/credential-chain.d.ts +20 -0
- package/lib/credentials/credential-chain.d.ts.map +1 -0
- package/lib/credentials/credential-chain.js +81 -0
- package/lib/credentials/credential-chain.js.map +1 -0
- package/lib/credentials/credential-chain.mjs +77 -0
- package/lib/credentials/credential-chain.mjs.map +1 -0
- package/lib/credentials/identity-token.d.mts +59 -0
- package/lib/credentials/identity-token.d.mts.map +1 -0
- package/lib/credentials/identity-token.d.ts +59 -0
- package/lib/credentials/identity-token.d.ts.map +1 -0
- package/lib/credentials/identity-token.js +243 -0
- package/lib/credentials/identity-token.js.map +1 -0
- package/lib/credentials/identity-token.mjs +202 -0
- package/lib/credentials/identity-token.mjs.map +1 -0
- package/lib/credentials/oidc-federation.d.mts +65 -0
- package/lib/credentials/oidc-federation.d.mts.map +1 -0
- package/lib/credentials/oidc-federation.d.ts +65 -0
- package/lib/credentials/oidc-federation.d.ts.map +1 -0
- package/lib/credentials/oidc-federation.js +200 -0
- package/lib/credentials/oidc-federation.js.map +1 -0
- package/lib/credentials/oidc-federation.mjs +196 -0
- package/lib/credentials/oidc-federation.mjs.map +1 -0
- package/lib/credentials/token-cache.d.mts +64 -0
- package/lib/credentials/token-cache.d.mts.map +1 -0
- package/lib/credentials/token-cache.d.ts +64 -0
- package/lib/credentials/token-cache.d.ts.map +1 -0
- package/lib/credentials/token-cache.js +147 -0
- package/lib/credentials/token-cache.js.map +1 -0
- package/lib/credentials/token-cache.mjs +143 -0
- package/lib/credentials/token-cache.mjs.map +1 -0
- package/lib/credentials/types.d.mts +126 -0
- package/lib/credentials/types.d.mts.map +1 -0
- package/lib/credentials/types.d.ts +126 -0
- package/lib/credentials/types.d.ts.map +1 -0
- package/lib/credentials/types.js +182 -0
- package/lib/credentials/types.js.map +1 -0
- package/lib/credentials/types.mjs +169 -0
- package/lib/credentials/types.mjs.map +1 -0
- package/lib/credentials.d.mts +6 -0
- package/lib/credentials.d.mts.map +1 -0
- package/lib/credentials.d.ts +6 -0
- package/lib/credentials.d.ts.map +1 -0
- package/lib/credentials.js +19 -0
- package/lib/credentials.js.map +1 -0
- package/lib/credentials.mjs +6 -0
- package/lib/credentials.mjs.map +1 -0
- package/package.json +9 -1
- package/resources/api-keys.d.mts +192 -16
- package/resources/api-keys.d.mts.map +1 -1
- package/resources/api-keys.d.ts +192 -16
- package/resources/api-keys.d.ts.map +1 -1
- package/resources/api-keys.js +19 -7
- package/resources/api-keys.js.map +1 -1
- package/resources/api-keys.mjs +19 -7
- package/resources/api-keys.mjs.map +1 -1
- package/resources/auth/auth.d.mts +2 -2
- package/resources/auth/auth.d.mts.map +1 -1
- package/resources/auth/auth.d.ts +2 -2
- package/resources/auth/auth.d.ts.map +1 -1
- package/resources/auth/auth.js.map +1 -1
- package/resources/auth/auth.mjs.map +1 -1
- package/resources/auth/connections.d.mts +16 -2
- package/resources/auth/connections.d.mts.map +1 -1
- package/resources/auth/connections.d.ts +16 -2
- package/resources/auth/connections.d.ts.map +1 -1
- package/resources/auth/context.d.mts +69 -3
- package/resources/auth/context.d.mts.map +1 -1
- package/resources/auth/context.d.ts +69 -3
- package/resources/auth/context.d.ts.map +1 -1
- package/resources/auth/index.d.mts +1 -1
- package/resources/auth/index.d.mts.map +1 -1
- package/resources/auth/index.d.ts +1 -1
- package/resources/auth/index.d.ts.map +1 -1
- package/resources/auth/index.js.map +1 -1
- package/resources/auth/index.mjs.map +1 -1
- package/resources/browser-pools.d.mts +41 -6
- package/resources/browser-pools.d.mts.map +1 -1
- package/resources/browser-pools.d.ts +41 -6
- package/resources/browser-pools.d.ts.map +1 -1
- package/resources/browsers/browsers.d.mts +105 -45
- package/resources/browsers/browsers.d.mts.map +1 -1
- package/resources/browsers/browsers.d.ts +105 -45
- package/resources/browsers/browsers.d.ts.map +1 -1
- package/resources/browsers/browsers.js.map +1 -1
- package/resources/browsers/browsers.mjs.map +1 -1
- package/resources/browsers/index.d.mts +1 -1
- package/resources/browsers/index.d.mts.map +1 -1
- package/resources/browsers/index.d.ts +1 -1
- package/resources/browsers/index.d.ts.map +1 -1
- package/resources/browsers/index.js.map +1 -1
- package/resources/browsers/index.mjs.map +1 -1
- package/resources/browsers/telemetry.d.mts +4 -4
- package/resources/browsers/telemetry.d.mts.map +1 -1
- package/resources/browsers/telemetry.d.ts +4 -4
- package/resources/browsers/telemetry.d.ts.map +1 -1
- package/resources/index.d.mts +6 -2
- package/resources/index.d.mts.map +1 -1
- package/resources/index.d.ts +6 -2
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js +9 -1
- package/resources/index.js.map +1 -1
- package/resources/index.mjs +4 -0
- package/resources/index.mjs.map +1 -1
- package/resources/invocations.d.mts +13 -1
- package/resources/invocations.d.mts.map +1 -1
- package/resources/invocations.d.ts +13 -1
- package/resources/invocations.d.ts.map +1 -1
- package/resources/service-accounts.d.mts +73 -0
- package/resources/service-accounts.d.mts.map +1 -0
- package/resources/service-accounts.d.ts +73 -0
- package/resources/service-accounts.d.ts.map +1 -0
- package/resources/service-accounts.js +50 -0
- package/resources/service-accounts.js.map +1 -0
- package/resources/service-accounts.mjs +46 -0
- package/resources/service-accounts.mjs.map +1 -0
- package/resources/vaults/items.d.mts +68 -2
- package/resources/vaults/items.d.mts.map +1 -1
- package/resources/vaults/items.d.ts +68 -2
- package/resources/vaults/items.d.ts.map +1 -1
- package/resources/workload-identity-authentication-events.d.mts +36 -0
- package/resources/workload-identity-authentication-events.d.mts.map +1 -0
- package/resources/workload-identity-authentication-events.d.ts +36 -0
- package/resources/workload-identity-authentication-events.d.ts.map +1 -0
- package/resources/workload-identity-authentication-events.js +16 -0
- package/resources/workload-identity-authentication-events.js.map +1 -0
- package/resources/workload-identity-authentication-events.mjs +12 -0
- package/resources/workload-identity-authentication-events.mjs.map +1 -0
- package/resources/workload-identity-federation-rules.d.mts +194 -0
- package/resources/workload-identity-federation-rules.d.mts.map +1 -0
- package/resources/workload-identity-federation-rules.d.ts +194 -0
- package/resources/workload-identity-federation-rules.d.ts.map +1 -0
- package/resources/workload-identity-federation-rules.js +47 -0
- package/resources/workload-identity-federation-rules.js.map +1 -0
- package/resources/workload-identity-federation-rules.mjs +43 -0
- package/resources/workload-identity-federation-rules.mjs.map +1 -0
- package/resources/workload-identity-issuers.d.mts +169 -0
- package/resources/workload-identity-issuers.d.mts.map +1 -0
- package/resources/workload-identity-issuers.d.ts +169 -0
- package/resources/workload-identity-issuers.d.ts.map +1 -0
- package/resources/workload-identity-issuers.js +54 -0
- package/resources/workload-identity-issuers.js.map +1 -0
- package/resources/workload-identity-issuers.mjs +50 -0
- package/resources/workload-identity-issuers.mjs.map +1 -0
- package/src/client.ts +134 -1
- package/src/lib/credentials/client-auth.ts +194 -0
- package/src/lib/credentials/credential-chain.ts +95 -0
- package/src/lib/credentials/identity-token.ts +284 -0
- package/src/lib/credentials/oidc-federation.ts +304 -0
- package/src/lib/credentials/token-cache.ts +172 -0
- package/src/lib/credentials/types.ts +267 -0
- package/src/lib/credentials.ts +30 -0
- package/src/resources/api-keys.ts +217 -15
- package/src/resources/auth/auth.ts +6 -2
- package/src/resources/auth/connections.ts +17 -2
- package/src/resources/auth/context.ts +81 -3
- package/src/resources/auth/index.ts +1 -1
- package/src/resources/browser-pools.ts +46 -6
- package/src/resources/browsers/browsers.ts +115 -44
- package/src/resources/browsers/index.ts +1 -0
- package/src/resources/browsers/telemetry.ts +4 -3
- package/src/resources/index.ts +42 -0
- package/src/resources/invocations.ts +15 -1
- package/src/resources/service-accounts.ts +128 -0
- package/src/resources/vaults/items.ts +80 -2
- package/src/resources/workload-identity-authentication-events.ts +72 -0
- package/src/resources/workload-identity-federation-rules.ts +314 -0
- package/src/resources/workload-identity-issuers.ts +273 -0
- package/src/version.ts +1 -1
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import type { Fetch } from '../../internal/builtin-types';
|
|
2
|
+
import { getDefaultFetch } from '../../internal/shims';
|
|
3
|
+
import { readEnv } from '../../internal/utils/env';
|
|
4
|
+
import type { IdentityTokenProvider, IdentityTokenRequest } from './types';
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
|
|
7
|
+
describeFailure,
|
|
8
|
+
WorkloadIdentityError,
|
|
9
|
+
readLimitedText,
|
|
10
|
+
resolveAuthBaseURL,
|
|
11
|
+
withTimeout,
|
|
12
|
+
} from './types';
|
|
13
|
+
|
|
14
|
+
export type IdentityTokenSourceOptions = {
|
|
15
|
+
/**
|
|
16
|
+
* The audience to request. Defaults to `KERNEL_IDENTITY_TOKEN_AUDIENCE`,
|
|
17
|
+
* else the auth base URL (for example `https://auth.onkernel.com`). The
|
|
18
|
+
* federation rule's `expected_audience` must be set to the same value.
|
|
19
|
+
*/
|
|
20
|
+
audience?: string | undefined;
|
|
21
|
+
/** Defaults to the `fetch` of the client using the source, else the global `fetch`. */
|
|
22
|
+
fetch?: Fetch | undefined;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const replayHints = new WeakMap<IdentityTokenProvider, string>();
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What to tell the caller when the token endpoint reports that the token
|
|
29
|
+
* this provider returned was already used. The advice depends on where the
|
|
30
|
+
* token comes from, which only the built-in file and static sources know.
|
|
31
|
+
*/
|
|
32
|
+
export function replayHintFor(provider: IdentityTokenProvider): string {
|
|
33
|
+
return (
|
|
34
|
+
replayHints.get(provider) ??
|
|
35
|
+
'Every exchange needs a fresh provider token, and the identity token provider returned one that was already exchanged.'
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Reads the token from a file on every call, so a token the platform rotates
|
|
41
|
+
* (such as a Kubernetes projected service account token) is picked up.
|
|
42
|
+
*/
|
|
43
|
+
export function identityTokenFromFile(path: string): IdentityTokenProvider {
|
|
44
|
+
if (!path) {
|
|
45
|
+
throw new WorkloadIdentityError('Identity token file path is empty');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const provider: IdentityTokenProvider = async () => {
|
|
49
|
+
let content: string;
|
|
50
|
+
try {
|
|
51
|
+
// Loaded on first use, and not as a literal specifier, so the SDK still
|
|
52
|
+
// loads and bundles on runtimes that have no file system.
|
|
53
|
+
const specifier = 'node:fs/promises';
|
|
54
|
+
const fs: typeof import('node:fs/promises') = await import(
|
|
55
|
+
/* webpackIgnore: true */ /* @vite-ignore */ specifier
|
|
56
|
+
);
|
|
57
|
+
content = await fs.readFile(path, 'utf-8');
|
|
58
|
+
} catch (err) {
|
|
59
|
+
throw new WorkloadIdentityError(`Failed to read identity token file at ${path}: ${err}`, {
|
|
60
|
+
cause: err,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
const token = content.trim();
|
|
64
|
+
if (!token) {
|
|
65
|
+
throw new WorkloadIdentityError(`Identity token file at ${path} is empty`);
|
|
66
|
+
}
|
|
67
|
+
return token;
|
|
68
|
+
};
|
|
69
|
+
replayHints.set(
|
|
70
|
+
provider,
|
|
71
|
+
`Every exchange needs a fresh provider token, and the identity token file at ${path} held the same token as a previous exchange. Whatever writes that file must replace the token before each refresh. For a Kubernetes projected service account token, which the kubelet replaces only as it nears expiry, configure the issuer in Kernel to allow reuse instead.`,
|
|
72
|
+
);
|
|
73
|
+
return provider;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Wraps one token as an {@link IdentityTokenProvider} that can be used for
|
|
78
|
+
* exactly one exchange.
|
|
79
|
+
*
|
|
80
|
+
* Most providers' tokens are single-use, and a fixed value cannot be
|
|
81
|
+
* replaced with a fresh one, so the second call throws instead of sending
|
|
82
|
+
* the same token again. Use {@link identityTokenFromFile}, a built-in source
|
|
83
|
+
* or your own callback for anything that outlives one access token.
|
|
84
|
+
*/
|
|
85
|
+
export function identityTokenFromValue(token: string): IdentityTokenProvider {
|
|
86
|
+
if (!token) {
|
|
87
|
+
throw new WorkloadIdentityError('Identity token value is empty');
|
|
88
|
+
}
|
|
89
|
+
let used = false;
|
|
90
|
+
const provider: IdentityTokenProvider = () => {
|
|
91
|
+
if (used) {
|
|
92
|
+
throw new WorkloadIdentityError(
|
|
93
|
+
'The static identity token has already been exchanged once and cannot be reused: every exchange needs a fresh provider token. A static token (such as KERNEL_IDENTITY_TOKEN) is good for one access token only. To keep a client authenticated, use a source that returns a fresh token on every call: KERNEL_IDENTITY_TOKEN_FILE, KERNEL_IDENTITY_TOKEN_SOURCE, or an identityTokenProvider callback.',
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
used = true;
|
|
97
|
+
return token;
|
|
98
|
+
};
|
|
99
|
+
replayHints.set(
|
|
100
|
+
provider,
|
|
101
|
+
'Every exchange needs a fresh provider token; a static KERNEL_IDENTITY_TOKEN can be exchanged only once.',
|
|
102
|
+
);
|
|
103
|
+
return provider;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Requests an ID token from GitHub Actions. The workflow or job needs
|
|
108
|
+
* `permissions: id-token: write`.
|
|
109
|
+
*/
|
|
110
|
+
export function identityTokenFromGitHubActions(
|
|
111
|
+
options: IdentityTokenSourceOptions = {},
|
|
112
|
+
): IdentityTokenProvider {
|
|
113
|
+
return async (request) => {
|
|
114
|
+
const requestURL = readEnv('ACTIONS_ID_TOKEN_REQUEST_URL');
|
|
115
|
+
const requestToken = readEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN');
|
|
116
|
+
if (!requestURL || !requestToken) {
|
|
117
|
+
throw new WorkloadIdentityError(
|
|
118
|
+
'GitHub Actions did not provide an ID token endpoint: ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN are not set. Add `permissions: id-token: write` to the workflow or job.',
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
const audience = encodeURIComponent(resolveAudience(options, request));
|
|
122
|
+
const url = `${requestURL}${requestURL.includes('?') ? '&' : '?'}audience=${audience}`;
|
|
123
|
+
const body = await fetchIdentityToken('GitHub Actions ID token endpoint', options, request, url, {
|
|
124
|
+
Accept: 'application/json',
|
|
125
|
+
Authorization: `Bearer ${requestToken}`,
|
|
126
|
+
});
|
|
127
|
+
let token: unknown;
|
|
128
|
+
try {
|
|
129
|
+
token = JSON.parse(body)?.value;
|
|
130
|
+
} catch {
|
|
131
|
+
token = undefined;
|
|
132
|
+
}
|
|
133
|
+
if (typeof token !== 'string' || !token) {
|
|
134
|
+
throw new WorkloadIdentityError('GitHub Actions ID token endpoint returned a response with no token');
|
|
135
|
+
}
|
|
136
|
+
return token;
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const GCP_IDENTITY_URL =
|
|
141
|
+
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity';
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Requests an identity token for the attached service account from the
|
|
145
|
+
* Google Cloud metadata server.
|
|
146
|
+
*/
|
|
147
|
+
export function identityTokenFromGCPMetadata(
|
|
148
|
+
options: IdentityTokenSourceOptions = {},
|
|
149
|
+
): IdentityTokenProvider {
|
|
150
|
+
return async (request) => {
|
|
151
|
+
const audience = encodeURIComponent(resolveAudience(options, request));
|
|
152
|
+
const url = `${GCP_IDENTITY_URL}?audience=${audience}&format=full`;
|
|
153
|
+
const body = await fetchIdentityToken('Google Cloud metadata server', options, request, url, {
|
|
154
|
+
'Metadata-Flavor': 'Google',
|
|
155
|
+
});
|
|
156
|
+
const token = body.trim();
|
|
157
|
+
if (!token) {
|
|
158
|
+
throw new WorkloadIdentityError('Google Cloud metadata server returned an empty identity token');
|
|
159
|
+
}
|
|
160
|
+
return token;
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export type AWSSTSIdentityTokenOptions = {
|
|
165
|
+
/** See {@link IdentityTokenSourceOptions.audience}. */
|
|
166
|
+
audience?: string | undefined;
|
|
167
|
+
/** Defaults to `AWS_REGION`, else `AWS_DEFAULT_REGION`, else `us-east-1`. */
|
|
168
|
+
region?: string | undefined;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
type STSClient = { send(command: object): Promise<{ WebIdentityToken?: string | undefined }> };
|
|
172
|
+
type STSModule = {
|
|
173
|
+
STSClient: new (config: { region: string }) => STSClient;
|
|
174
|
+
GetWebIdentityTokenCommand?: new (input: {
|
|
175
|
+
Audience: string[];
|
|
176
|
+
SigningAlgorithm: string;
|
|
177
|
+
DurationSeconds: number;
|
|
178
|
+
}) => object;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Requests a token from AWS STS `GetWebIdentityToken` with the workload's
|
|
183
|
+
* ambient AWS credentials.
|
|
184
|
+
*
|
|
185
|
+
* Needs the optional `@aws-sdk/client-sts` package, which is loaded on first
|
|
186
|
+
* use. The call goes to a regional STS endpoint through the AWS SDK's own
|
|
187
|
+
* HTTP client, not the Kernel client's `fetch`.
|
|
188
|
+
*/
|
|
189
|
+
export function identityTokenFromAWSSTS(options: AWSSTSIdentityTokenOptions = {}): IdentityTokenProvider {
|
|
190
|
+
// One client for the life of the source, so the AWS SDK caches and
|
|
191
|
+
// refreshes the ambient credentials itself.
|
|
192
|
+
let client: STSClient | undefined;
|
|
193
|
+
let Command: NonNullable<STSModule['GetWebIdentityTokenCommand']> | undefined;
|
|
194
|
+
|
|
195
|
+
return async (request) => {
|
|
196
|
+
const audience = resolveAudience(options, request);
|
|
197
|
+
if (!client || !Command) {
|
|
198
|
+
const sts = await loadSTS();
|
|
199
|
+
Command = sts.GetWebIdentityTokenCommand;
|
|
200
|
+
client = new sts.STSClient({
|
|
201
|
+
region: options.region || readEnv('AWS_REGION') || readEnv('AWS_DEFAULT_REGION') || 'us-east-1',
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
let token: string | undefined;
|
|
205
|
+
try {
|
|
206
|
+
const response = await client.send(
|
|
207
|
+
new Command({ Audience: [audience], SigningAlgorithm: 'RS256', DurationSeconds: 300 }),
|
|
208
|
+
);
|
|
209
|
+
token = response.WebIdentityToken;
|
|
210
|
+
} catch (err) {
|
|
211
|
+
throw new WorkloadIdentityError(`AWS STS GetWebIdentityToken failed: ${err}`, { cause: err });
|
|
212
|
+
}
|
|
213
|
+
if (!token) {
|
|
214
|
+
throw new WorkloadIdentityError('AWS STS GetWebIdentityToken returned no token');
|
|
215
|
+
}
|
|
216
|
+
return token;
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const STS_PACKAGE = '@aws-sdk/client-sts';
|
|
221
|
+
const STS_MIN_VERSION = '3.935.0';
|
|
222
|
+
|
|
223
|
+
async function loadSTS(): Promise<STSModule & Required<Pick<STSModule, 'GetWebIdentityTokenCommand'>>> {
|
|
224
|
+
let sts: STSModule;
|
|
225
|
+
try {
|
|
226
|
+
// Not a literal specifier: the package is optional, and bundlers must not
|
|
227
|
+
// try to resolve it for users who never select this source.
|
|
228
|
+
const specifier = STS_PACKAGE;
|
|
229
|
+
sts = await import(/* webpackIgnore: true */ /* @vite-ignore */ specifier);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
throw new WorkloadIdentityError(
|
|
232
|
+
`The aws_sts identity token source needs the optional ${STS_PACKAGE} package (version ${STS_MIN_VERSION} or later). Install it with \`npm install ${STS_PACKAGE}\`.`,
|
|
233
|
+
{ cause: err },
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
const Command = sts.GetWebIdentityTokenCommand;
|
|
237
|
+
if (typeof Command !== 'function') {
|
|
238
|
+
throw new WorkloadIdentityError(
|
|
239
|
+
`The installed ${STS_PACKAGE} is too old to call GetWebIdentityToken; version ${STS_MIN_VERSION} or later is required. Upgrade it with \`npm install ${STS_PACKAGE}@latest\`.`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
return { STSClient: sts.STSClient, GetWebIdentityTokenCommand: Command };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function resolveAudience(
|
|
246
|
+
options: { audience?: string | undefined },
|
|
247
|
+
request: IdentityTokenRequest | undefined,
|
|
248
|
+
): string {
|
|
249
|
+
return (
|
|
250
|
+
options.audience || readEnv('KERNEL_IDENTITY_TOKEN_AUDIENCE') || request?.audience || resolveAuthBaseURL()
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function fetchIdentityToken(
|
|
255
|
+
source: string,
|
|
256
|
+
options: IdentityTokenSourceOptions,
|
|
257
|
+
request: IdentityTokenRequest | undefined,
|
|
258
|
+
url: string,
|
|
259
|
+
headers: Record<string, string>,
|
|
260
|
+
): Promise<string> {
|
|
261
|
+
const fetch = options.fetch ?? request?.fetch ?? getDefaultFetch();
|
|
262
|
+
const secrets = [(headers['Authorization'] ?? '').replace(/^Bearer /, '')];
|
|
263
|
+
return withTimeout(DEFAULT_CREDENTIALS_TIMEOUT_IN_MS, async (signal) => {
|
|
264
|
+
let response: Response;
|
|
265
|
+
try {
|
|
266
|
+
response = await fetch(url, { method: 'GET', redirect: 'manual', headers, signal });
|
|
267
|
+
} catch (err) {
|
|
268
|
+
throw new WorkloadIdentityError(`Failed to reach the ${source}: ${describeFailure(err, secrets)}`);
|
|
269
|
+
}
|
|
270
|
+
if (response.status !== 200) {
|
|
271
|
+
await response.body?.cancel().catch(() => {});
|
|
272
|
+
throw new WorkloadIdentityError(`The ${source} responded with status ${response.status}`, {
|
|
273
|
+
statusCode: response.status,
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
return await readLimitedText(response);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
throw new WorkloadIdentityError(
|
|
280
|
+
`Failed to read the response from the ${source}: ${describeFailure(err, secrets)}`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import type { Fetch } from '../../internal/builtin-types';
|
|
2
|
+
import { getDefaultFetch } from '../../internal/shims';
|
|
3
|
+
import { VERSION } from '../../version';
|
|
4
|
+
import { replayHintFor } from './identity-token';
|
|
5
|
+
import type {
|
|
6
|
+
AccessTokenProviderOptions,
|
|
7
|
+
FederationAccessToken,
|
|
8
|
+
FederationPrincipal,
|
|
9
|
+
FederationTokenDetails,
|
|
10
|
+
IdentityTokenProvider,
|
|
11
|
+
} from './types';
|
|
12
|
+
import {
|
|
13
|
+
DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
|
|
14
|
+
describeFailure,
|
|
15
|
+
GRANT_TYPE_JWT_BEARER,
|
|
16
|
+
MAX_ASSERTION_BYTES,
|
|
17
|
+
TOKEN_ENDPOINT,
|
|
18
|
+
WorkloadIdentityError,
|
|
19
|
+
nowAsSeconds,
|
|
20
|
+
readLimitedText,
|
|
21
|
+
redactSensitive,
|
|
22
|
+
requireSecureTokenEndpoint,
|
|
23
|
+
resolveAuthBaseURL,
|
|
24
|
+
resolveResource,
|
|
25
|
+
withTimeout,
|
|
26
|
+
} from './types';
|
|
27
|
+
|
|
28
|
+
type ExchangeOptions = {
|
|
29
|
+
/**
|
|
30
|
+
* The host that exchanges identity tokens. Defaults to
|
|
31
|
+
* `KERNEL_AUTH_BASE_URL`, else `https://auth.onkernel.com` when the API
|
|
32
|
+
* base URL is the production default. A custom API base URL needs it set.
|
|
33
|
+
*/
|
|
34
|
+
authBaseURL?: string | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* The API the access token is for. Defaults to the origin of the API base
|
|
37
|
+
* URL, for example `https://api.onkernel.com`. The token endpoint compares
|
|
38
|
+
* it exactly, so it must not end in a slash.
|
|
39
|
+
*/
|
|
40
|
+
resource?: string | undefined;
|
|
41
|
+
/** Defaults to the `fetch` of the client using the credentials, else the global `fetch`. */
|
|
42
|
+
fetch?: Fetch | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* How long one token request may take, in milliseconds.
|
|
45
|
+
*
|
|
46
|
+
* @default 30000
|
|
47
|
+
*/
|
|
48
|
+
timeout?: number | undefined;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export type OIDCFederationConfig = ExchangeOptions & {
|
|
52
|
+
/**
|
|
53
|
+
* Called once per exchange. It must return a fresh token every time: most
|
|
54
|
+
* providers' tokens can be exchanged only once.
|
|
55
|
+
*/
|
|
56
|
+
identityTokenProvider: IdentityTokenProvider;
|
|
57
|
+
/** The `wifr_...` ID of the federation rule to authenticate against. */
|
|
58
|
+
federationRuleId: string;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export type FederationAssertionExchangeParams = ExchangeOptions & {
|
|
62
|
+
/** The identity provider's token. It is sent as given and never reused. */
|
|
63
|
+
assertion: string;
|
|
64
|
+
/** The `wifr_...` ID of the federation rule to authenticate against. */
|
|
65
|
+
federationRuleId: string;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export type FederationExchangeResult = { accessToken: string } & FederationTokenDetails;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Exchanges a token from the workload's identity provider for a short-lived
|
|
72
|
+
* Kernel access token (the RFC 7523 jwt-bearer grant).
|
|
73
|
+
*
|
|
74
|
+
* Every call asks `identityTokenProvider` for a fresh token and exchanges
|
|
75
|
+
* it; nothing is cached and nothing is retried. Pass the result as the
|
|
76
|
+
* client's `credentials` option, which wraps it in a {@link TokenCache}.
|
|
77
|
+
*
|
|
78
|
+
* The token endpoint returns no refresh token: when the access token is
|
|
79
|
+
* about to expire, a new identity token is exchanged.
|
|
80
|
+
*/
|
|
81
|
+
export function oidcFederationProvider(
|
|
82
|
+
config: OIDCFederationConfig,
|
|
83
|
+
): (opts?: AccessTokenProviderOptions) => Promise<FederationAccessToken> {
|
|
84
|
+
if (!config.federationRuleId) {
|
|
85
|
+
throw new WorkloadIdentityError('federationRuleId is required');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return async (opts) => {
|
|
89
|
+
const apiBaseURL = opts?.client?.baseURL;
|
|
90
|
+
const authBaseURL = resolveAuthBaseURL(config.authBaseURL, apiBaseURL);
|
|
91
|
+
requireSecureTokenEndpoint(authBaseURL);
|
|
92
|
+
const resource = resolveResource(config.resource, apiBaseURL);
|
|
93
|
+
const fetch = config.fetch ?? opts?.client?.fetch ?? getDefaultFetch();
|
|
94
|
+
|
|
95
|
+
const assertion = await config.identityTokenProvider({ audience: authBaseURL, fetch });
|
|
96
|
+
const { accessToken, ...details } = await exchange({
|
|
97
|
+
assertion,
|
|
98
|
+
replayHint: replayHintFor(config.identityTokenProvider),
|
|
99
|
+
federationRuleId: config.federationRuleId,
|
|
100
|
+
authBaseURL,
|
|
101
|
+
resource,
|
|
102
|
+
fetch,
|
|
103
|
+
userAgent: `Kernel/JS ${VERSION} oidcFederationProvider`,
|
|
104
|
+
timeout: config.timeout ?? DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
|
|
105
|
+
});
|
|
106
|
+
return { token: accessToken, ...details };
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Exchanges one identity provider token for a Kernel access token, for
|
|
112
|
+
* callers that want to manage the access token themselves. It needs no
|
|
113
|
+
* Kernel credential.
|
|
114
|
+
*
|
|
115
|
+
* The assertion is spent by the call: to get another access token, obtain a
|
|
116
|
+
* fresh assertion from the identity provider first.
|
|
117
|
+
*/
|
|
118
|
+
export async function exchangeFederationAssertion(
|
|
119
|
+
params: FederationAssertionExchangeParams,
|
|
120
|
+
): Promise<FederationExchangeResult> {
|
|
121
|
+
if (!params.federationRuleId) {
|
|
122
|
+
throw new WorkloadIdentityError('federationRuleId is required');
|
|
123
|
+
}
|
|
124
|
+
const authBaseURL = resolveAuthBaseURL(params.authBaseURL);
|
|
125
|
+
requireSecureTokenEndpoint(authBaseURL);
|
|
126
|
+
return exchange({
|
|
127
|
+
assertion: params.assertion,
|
|
128
|
+
replayHint: 'Every exchange needs a fresh provider token; this assertion was already exchanged.',
|
|
129
|
+
federationRuleId: params.federationRuleId,
|
|
130
|
+
authBaseURL,
|
|
131
|
+
resource: resolveResource(params.resource),
|
|
132
|
+
fetch: params.fetch ?? getDefaultFetch(),
|
|
133
|
+
userAgent: `Kernel/JS ${VERSION} exchangeFederationAssertion`,
|
|
134
|
+
timeout: params.timeout ?? DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function exchange(request: {
|
|
139
|
+
assertion: string;
|
|
140
|
+
/** Appended to the error when the token endpoint reports the assertion as already used. */
|
|
141
|
+
replayHint: string;
|
|
142
|
+
federationRuleId: string;
|
|
143
|
+
authBaseURL: string;
|
|
144
|
+
resource: string;
|
|
145
|
+
fetch: Fetch;
|
|
146
|
+
userAgent: string;
|
|
147
|
+
timeout: number;
|
|
148
|
+
}): Promise<FederationExchangeResult> {
|
|
149
|
+
const { assertion } = request;
|
|
150
|
+
if (typeof assertion !== 'string' || !assertion) {
|
|
151
|
+
throw new WorkloadIdentityError('Identity token is empty');
|
|
152
|
+
}
|
|
153
|
+
// The token endpoint rejects larger assertions. Failing here names the
|
|
154
|
+
// problem, which is usually a path or certificate passed as the token.
|
|
155
|
+
const assertionBytes = new TextEncoder().encode(assertion).length;
|
|
156
|
+
if (assertionBytes > MAX_ASSERTION_BYTES) {
|
|
157
|
+
throw new WorkloadIdentityError(
|
|
158
|
+
`Identity token is ${Math.ceil(assertionBytes / 1024)} KiB, which exceeds the 16 KiB limit`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// The token endpoint rejects any parameter other than these four, and any
|
|
163
|
+
// Authorization header.
|
|
164
|
+
const body = new URLSearchParams({
|
|
165
|
+
grant_type: GRANT_TYPE_JWT_BEARER,
|
|
166
|
+
assertion,
|
|
167
|
+
federation_rule_id: request.federationRuleId,
|
|
168
|
+
resource: request.resource,
|
|
169
|
+
}).toString();
|
|
170
|
+
const url = `${request.authBaseURL}${TOKEN_ENDPOINT}`;
|
|
171
|
+
const startedAt = nowAsSeconds();
|
|
172
|
+
|
|
173
|
+
return withTimeout(request.timeout, async (signal) => {
|
|
174
|
+
let response: Response;
|
|
175
|
+
try {
|
|
176
|
+
response = await request.fetch(url, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
redirect: 'manual',
|
|
179
|
+
headers: {
|
|
180
|
+
Accept: 'application/json',
|
|
181
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
182
|
+
'User-Agent': request.userAgent,
|
|
183
|
+
},
|
|
184
|
+
body,
|
|
185
|
+
signal,
|
|
186
|
+
});
|
|
187
|
+
} catch (err) {
|
|
188
|
+
const reason =
|
|
189
|
+
signal.aborted ? `timed out after ${request.timeout}ms` : describeFailure(err, [assertion]);
|
|
190
|
+
throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${reason}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const requestId = response.headers.get('x-request-id') ?? response.headers.get('request-id');
|
|
194
|
+
let text: string;
|
|
195
|
+
try {
|
|
196
|
+
text = await readLimitedText(response);
|
|
197
|
+
} catch (err) {
|
|
198
|
+
throw new WorkloadIdentityError(
|
|
199
|
+
`Failed to read the response from token endpoint ${url}: ${describeFailure(err, [assertion])}`,
|
|
200
|
+
{ statusCode: response.status, requestId },
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
throw exchangeError(response.status, text, requestId, request);
|
|
205
|
+
}
|
|
206
|
+
return parseTokenResponse(response.status, text, requestId, startedAt);
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function exchangeError(
|
|
211
|
+
status: number,
|
|
212
|
+
text: string,
|
|
213
|
+
requestId: string | null,
|
|
214
|
+
{ assertion, replayHint, resource }: { assertion: string; replayHint: string; resource: string },
|
|
215
|
+
): WorkloadIdentityError {
|
|
216
|
+
let parsed: unknown;
|
|
217
|
+
try {
|
|
218
|
+
parsed = JSON.parse(text);
|
|
219
|
+
} catch {
|
|
220
|
+
parsed = undefined;
|
|
221
|
+
}
|
|
222
|
+
const body = redactSensitive(parsed, [assertion]);
|
|
223
|
+
const errorCode = body?.['error'] ?? null;
|
|
224
|
+
const errorDescription = body?.['error_description'] ?? null;
|
|
225
|
+
|
|
226
|
+
let hint = '';
|
|
227
|
+
if (errorDescription && /already used/i.test(errorDescription)) {
|
|
228
|
+
hint = replayHint;
|
|
229
|
+
} else if (errorCode === 'invalid_target') {
|
|
230
|
+
hint = `The token endpoint does not accept the resource "${resource}". Set the resource option to the Kernel API origin, with no trailing slash.`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let detail =
|
|
234
|
+
errorCode ?
|
|
235
|
+
`${errorCode}${errorDescription ? `: ${errorDescription}` : ''}`
|
|
236
|
+
: 'the response is not an OAuth error';
|
|
237
|
+
if (hint) detail = `${detail.replace(/\.$/, '')}. ${hint}`;
|
|
238
|
+
return new WorkloadIdentityError(
|
|
239
|
+
`Token exchange failed with status ${status}${requestId ? ` (request ID ${requestId})` : ''}: ${detail}`,
|
|
240
|
+
{ statusCode: status, errorCode, errorDescription, requestId, body },
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function parseTokenResponse(
|
|
245
|
+
status: number,
|
|
246
|
+
text: string,
|
|
247
|
+
requestId: string | null,
|
|
248
|
+
startedAt: number,
|
|
249
|
+
): FederationExchangeResult {
|
|
250
|
+
let data: unknown;
|
|
251
|
+
try {
|
|
252
|
+
data = JSON.parse(text);
|
|
253
|
+
} catch {
|
|
254
|
+
data = undefined;
|
|
255
|
+
}
|
|
256
|
+
// A success body holds the access token, so none of it goes into an error.
|
|
257
|
+
const invalid = (problem: string) =>
|
|
258
|
+
new WorkloadIdentityError(`Token endpoint returned an unusable response (status ${status}): ${problem}`, {
|
|
259
|
+
statusCode: status,
|
|
260
|
+
requestId,
|
|
261
|
+
});
|
|
262
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
263
|
+
throw invalid('the body is not a JSON object');
|
|
264
|
+
}
|
|
265
|
+
const fields = data as Record<string, unknown>;
|
|
266
|
+
const accessToken = fields['access_token'];
|
|
267
|
+
if (typeof accessToken !== 'string' || !accessToken) {
|
|
268
|
+
throw invalid('access_token is missing');
|
|
269
|
+
}
|
|
270
|
+
const tokenType = fields['token_type'];
|
|
271
|
+
if (tokenType !== undefined && (typeof tokenType !== 'string' || tokenType.toLowerCase() !== 'bearer')) {
|
|
272
|
+
throw invalid('token_type is not Bearer');
|
|
273
|
+
}
|
|
274
|
+
const expiresIn = fields['expires_in'];
|
|
275
|
+
if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
|
|
276
|
+
throw invalid('expires_in is missing or not a positive number');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const stringOrNull = (value: unknown) => (typeof value === 'string' ? value : null);
|
|
280
|
+
const rawPrincipal = fields['principal'] as Record<string, unknown> | null | undefined;
|
|
281
|
+
let principal: FederationPrincipal | null = null;
|
|
282
|
+
if (
|
|
283
|
+
typeof rawPrincipal === 'object' &&
|
|
284
|
+
rawPrincipal !== null &&
|
|
285
|
+
typeof rawPrincipal['type'] === 'string' &&
|
|
286
|
+
typeof rawPrincipal['id'] === 'string'
|
|
287
|
+
) {
|
|
288
|
+
principal = { type: rawPrincipal['type'], id: rawPrincipal['id'] };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
return {
|
|
292
|
+
accessToken,
|
|
293
|
+
// Counted from before the request was sent, so the token is never
|
|
294
|
+
// treated as valid for longer than the server allows.
|
|
295
|
+
expiresAt: startedAt + expiresIn,
|
|
296
|
+
expiresIn,
|
|
297
|
+
scope: stringOrNull(fields['scope']),
|
|
298
|
+
orgId: stringOrNull(fields['org_id']),
|
|
299
|
+
accessScope: stringOrNull(fields['access_scope']),
|
|
300
|
+
projectId: stringOrNull(fields['project_id']),
|
|
301
|
+
principal,
|
|
302
|
+
federationRuleId: stringOrNull(fields['federation_rule_id']),
|
|
303
|
+
};
|
|
304
|
+
}
|