@fastloop/kit-iap 0.0.0-stage → 0.21.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/LICENSE +25 -0
- package/dist/iap.d.ts +23 -0
- package/dist/iap.js +118 -0
- package/dist/sign.d.ts +20 -0
- package/dist/sign.js +91 -0
- package/package.json +25 -4
- package/source/iap.ts +174 -0
- package/source/sign.ts +131 -0
- package/vectors/cases.json +65 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fastloop
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
The MIT License above covers the code in this package: the stylesheets, tokens.json,
|
|
24
|
+
the icon drawings and the build scripts. It does not cover the Fastloop name, logos or
|
|
25
|
+
product icons in assets/. Those are trademarks; see TRADEMARKS.md.
|
package/dist/iap.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
declare const IapRejected_base: Schema.Class<IapRejected, Schema.TaggedStruct<"IapRejected", {
|
|
3
|
+
readonly message: Schema.String;
|
|
4
|
+
}>, import("effect/Cause").YieldableError>;
|
|
5
|
+
export declare class IapRejected extends IapRejected_base {
|
|
6
|
+
}
|
|
7
|
+
declare const IapUnavailable_base: Schema.Class<IapUnavailable, Schema.TaggedStruct<"IapUnavailable", {
|
|
8
|
+
readonly message: Schema.String;
|
|
9
|
+
}>, import("effect/Cause").YieldableError>;
|
|
10
|
+
/** Google's key list could not be read, so the proof could not be checked either way. */
|
|
11
|
+
export declare class IapUnavailable extends IapUnavailable_base {
|
|
12
|
+
}
|
|
13
|
+
export interface IapOptions {
|
|
14
|
+
readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
15
|
+
readonly now?: () => number;
|
|
16
|
+
readonly keyTimeoutMillis?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare const verifyIapAssertion: (header: string | null | undefined, audience: string, options?: IapOptions) => Effect.Effect<{
|
|
19
|
+
readonly email: string;
|
|
20
|
+
readonly sub: string;
|
|
21
|
+
readonly hd?: string;
|
|
22
|
+
}, IapRejected | IapUnavailable>;
|
|
23
|
+
export { IapSigningFailed, signedIapToken, type SignOptions } from "./sign.ts";
|
package/dist/iap.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
export class IapRejected extends Schema.TaggedError()("IapRejected", { message: Schema.String }) {
|
|
3
|
+
}
|
|
4
|
+
/** Google's key list could not be read, so the proof could not be checked either way. */
|
|
5
|
+
export class IapUnavailable extends Schema.TaggedError()("IapUnavailable", { message: Schema.String }) {
|
|
6
|
+
}
|
|
7
|
+
const url = "https://www.gstatic.com/iap/verify/public_key-jwk";
|
|
8
|
+
const Jwk = Schema.Struct({
|
|
9
|
+
kty: Schema.String,
|
|
10
|
+
kid: Schema.String,
|
|
11
|
+
alg: Schema.optionalKey(Schema.String),
|
|
12
|
+
crv: Schema.optionalKey(Schema.String),
|
|
13
|
+
x: Schema.optionalKey(Schema.String),
|
|
14
|
+
y: Schema.optionalKey(Schema.String),
|
|
15
|
+
});
|
|
16
|
+
const Keys = Schema.Struct({ keys: Schema.Array(Jwk) });
|
|
17
|
+
const Header = Schema.Struct({
|
|
18
|
+
alg: Schema.Literal("ES256"),
|
|
19
|
+
kid: Schema.String,
|
|
20
|
+
});
|
|
21
|
+
const Claims = Schema.Struct({
|
|
22
|
+
iss: Schema.String,
|
|
23
|
+
aud: Schema.String,
|
|
24
|
+
iat: Schema.Int,
|
|
25
|
+
exp: Schema.Int,
|
|
26
|
+
email: Schema.NonEmptyString,
|
|
27
|
+
sub: Schema.NonEmptyString,
|
|
28
|
+
hd: Schema.optionalKey(Schema.String),
|
|
29
|
+
});
|
|
30
|
+
const rejected = () => new IapRejected({ message: "The sign-in proof is invalid." });
|
|
31
|
+
const unavailable = () => new IapUnavailable({ message: "The sign-in keys could not be read." });
|
|
32
|
+
const caches = new WeakMap();
|
|
33
|
+
const load = (fetcher, timeoutMillis) => {
|
|
34
|
+
const started = Date.now();
|
|
35
|
+
const entry = {
|
|
36
|
+
started,
|
|
37
|
+
expires: started + 55 * 60 * 1000,
|
|
38
|
+
settled: false,
|
|
39
|
+
keys: (async () => {
|
|
40
|
+
const response = await fetcher(url, {
|
|
41
|
+
signal: AbortSignal.timeout(timeoutMillis),
|
|
42
|
+
});
|
|
43
|
+
if (!response.ok)
|
|
44
|
+
throw new Error("Key service unavailable");
|
|
45
|
+
return Schema.decodeUnknownSync(Keys)(await response.json());
|
|
46
|
+
})(),
|
|
47
|
+
};
|
|
48
|
+
caches.set(fetcher, entry);
|
|
49
|
+
entry.keys.then(() => {
|
|
50
|
+
entry.settled = true;
|
|
51
|
+
}, () => {
|
|
52
|
+
if (caches.get(fetcher) === entry)
|
|
53
|
+
caches.delete(fetcher);
|
|
54
|
+
});
|
|
55
|
+
return entry;
|
|
56
|
+
};
|
|
57
|
+
const read = async (entry) => {
|
|
58
|
+
try {
|
|
59
|
+
return await entry.keys;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw unavailable();
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const decode = (part) => JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
66
|
+
export const verifyIapAssertion = (header, audience, options = {}) => Effect.tryPromise({
|
|
67
|
+
try: async () => {
|
|
68
|
+
if (!header)
|
|
69
|
+
throw rejected();
|
|
70
|
+
const parts = header.split(".");
|
|
71
|
+
const [head, body, signature] = parts;
|
|
72
|
+
if (parts.length !== 3 || !head || !body || !signature)
|
|
73
|
+
throw rejected();
|
|
74
|
+
const parsed = Schema.decodeUnknownSync(Header)(decode(head));
|
|
75
|
+
const fetcher = options.fetch ?? fetch;
|
|
76
|
+
const timeoutMillis = options.keyTimeoutMillis ?? 5000;
|
|
77
|
+
const started = Date.now();
|
|
78
|
+
let entry = caches.get(fetcher);
|
|
79
|
+
// A list read before this call may predate a key rotation, so an unknown kid reads it once more.
|
|
80
|
+
// A list loading or loaded during this call is already current, so each call waits on one fetch at most.
|
|
81
|
+
const earlier = entry !== undefined && entry.settled && entry.expires > started;
|
|
82
|
+
if (!entry ||
|
|
83
|
+
entry.expires <= started ||
|
|
84
|
+
(!entry.settled && started - entry.started > timeoutMillis))
|
|
85
|
+
entry = load(fetcher, timeoutMillis);
|
|
86
|
+
let key = (await read(entry)).keys.find((item) => item.kid === parsed.kid);
|
|
87
|
+
if (!key && earlier) {
|
|
88
|
+
const current = caches.get(fetcher);
|
|
89
|
+
key = (await read(current && current !== entry
|
|
90
|
+
? current
|
|
91
|
+
: load(fetcher, timeoutMillis))).keys.find((item) => item.kid === parsed.kid);
|
|
92
|
+
}
|
|
93
|
+
if (!key)
|
|
94
|
+
throw rejected();
|
|
95
|
+
const publicKey = await crypto.subtle.importKey("jwk", key, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
|
|
96
|
+
const valid = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicKey, Buffer.from(signature, "base64url"), new TextEncoder().encode(`${head}.${body}`));
|
|
97
|
+
if (!valid)
|
|
98
|
+
throw rejected();
|
|
99
|
+
const claims = Schema.decodeUnknownSync(Claims)(decode(body));
|
|
100
|
+
const now = Math.floor((options.now ?? Date.now)() / 1000);
|
|
101
|
+
if (claims.iss !== "https://cloud.google.com/iap" ||
|
|
102
|
+
claims.aud !== audience ||
|
|
103
|
+
claims.exp < now - 30 ||
|
|
104
|
+
claims.exp <= claims.iat ||
|
|
105
|
+
claims.exp - claims.iat > 660 ||
|
|
106
|
+
claims.iat > now + 30)
|
|
107
|
+
throw rejected();
|
|
108
|
+
return claims.hd === undefined
|
|
109
|
+
? { email: claims.email, sub: claims.sub }
|
|
110
|
+
: { email: claims.email, sub: claims.sub, hd: claims.hd };
|
|
111
|
+
},
|
|
112
|
+
catch: (error) => (error instanceof IapUnavailable ? error : rejected()),
|
|
113
|
+
}).pipe(
|
|
114
|
+
// Only the one key fetch waits on anything, so running out of time means the keys were unreadable.
|
|
115
|
+
Effect.timeout(options.keyTimeoutMillis ?? 5000), Effect.mapError((error) => error instanceof IapRejected || error instanceof IapUnavailable
|
|
116
|
+
? error
|
|
117
|
+
: unavailable()));
|
|
118
|
+
export { IapSigningFailed, signedIapToken } from "./sign.js";
|
package/dist/sign.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
declare const IapSigningFailed_base: Schema.Class<IapSigningFailed, Schema.TaggedStruct<"IapSigningFailed", {
|
|
3
|
+
readonly code: Schema.Literals<readonly ["identity_unavailable", "signing_unavailable", "invalid_response"]>;
|
|
4
|
+
}>, import("effect/Cause").YieldableError>;
|
|
5
|
+
export declare class IapSigningFailed extends IapSigningFailed_base {
|
|
6
|
+
}
|
|
7
|
+
export interface SignOptions {
|
|
8
|
+
readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
9
|
+
readonly now?: () => number;
|
|
10
|
+
readonly timeoutMillis?: number;
|
|
11
|
+
}
|
|
12
|
+
/** Mints a token IAP accepts from the running service account: the metadata
|
|
13
|
+
* server names the account, and IAM signs `{iss, sub, aud, iat, exp}` as it,
|
|
14
|
+
* valid 10 minutes. The process owns no private key, and the metadata access
|
|
15
|
+
* token goes only to Google's own endpoints. The audience is used as given, so
|
|
16
|
+
* the caller checks that it covers the URL the token is sent to. Tokens are
|
|
17
|
+
* kept per `fetch` and audience until a minute before they expire, and callers
|
|
18
|
+
* asking at the same time share one signing request. Errors carry only a code. */
|
|
19
|
+
export declare const signedIapToken: (audience: string, options?: SignOptions) => Effect.Effect<string, IapSigningFailed>;
|
|
20
|
+
export {};
|
package/dist/sign.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
export class IapSigningFailed extends Schema.TaggedError()("IapSigningFailed", {
|
|
3
|
+
code: Schema.Literals([
|
|
4
|
+
"identity_unavailable",
|
|
5
|
+
"signing_unavailable",
|
|
6
|
+
"invalid_response",
|
|
7
|
+
]),
|
|
8
|
+
}) {
|
|
9
|
+
}
|
|
10
|
+
const MetadataAccess = Schema.Struct({ access_token: Schema.NonEmptyString });
|
|
11
|
+
const SignedToken = Schema.Struct({ signedJwt: Schema.NonEmptyString });
|
|
12
|
+
const metadata = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
|
|
13
|
+
const iam = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts";
|
|
14
|
+
const failed = (code) => () => {
|
|
15
|
+
throw new IapSigningFailed({ code });
|
|
16
|
+
};
|
|
17
|
+
const caches = new WeakMap();
|
|
18
|
+
const mint = async (audience, request, now, timeout) => {
|
|
19
|
+
const md = {
|
|
20
|
+
redirect: "manual",
|
|
21
|
+
headers: { "Metadata-Flavor": "Google" },
|
|
22
|
+
signal: AbortSignal.timeout(timeout),
|
|
23
|
+
};
|
|
24
|
+
const [identity, access] = await Promise.all([
|
|
25
|
+
request(`${metadata}/email`, md),
|
|
26
|
+
request(`${metadata}/token`, md),
|
|
27
|
+
]).catch(failed("identity_unavailable"));
|
|
28
|
+
if (!identity.ok || !access.ok)
|
|
29
|
+
throw new IapSigningFailed({ code: "identity_unavailable" });
|
|
30
|
+
const email = (await identity.text()).trim();
|
|
31
|
+
if (!/^[a-z0-9._-]+@[a-z0-9.-]+\.gserviceaccount\.com$/.test(email))
|
|
32
|
+
throw new IapSigningFailed({ code: "invalid_response" });
|
|
33
|
+
const { access_token } = Schema.decodeUnknownSync(MetadataAccess)(await access.json());
|
|
34
|
+
const iat = Math.floor(now() / 1000), exp = iat + 600;
|
|
35
|
+
const response = await request(`${iam}/${encodeURIComponent(email)}:signJwt`, {
|
|
36
|
+
method: "POST",
|
|
37
|
+
redirect: "manual",
|
|
38
|
+
signal: AbortSignal.timeout(timeout),
|
|
39
|
+
headers: {
|
|
40
|
+
authorization: `Bearer ${access_token}`,
|
|
41
|
+
"content-type": "application/json",
|
|
42
|
+
},
|
|
43
|
+
body: JSON.stringify({
|
|
44
|
+
payload: JSON.stringify({
|
|
45
|
+
iss: email,
|
|
46
|
+
sub: email,
|
|
47
|
+
aud: audience,
|
|
48
|
+
iat,
|
|
49
|
+
exp,
|
|
50
|
+
}),
|
|
51
|
+
}),
|
|
52
|
+
}).catch(failed("signing_unavailable"));
|
|
53
|
+
if (!response.ok)
|
|
54
|
+
throw new IapSigningFailed({ code: "signing_unavailable" });
|
|
55
|
+
const { signedJwt } = Schema.decodeUnknownSync(SignedToken)(await response.json());
|
|
56
|
+
return { value: signedJwt, until: (exp - 60) * 1000 };
|
|
57
|
+
};
|
|
58
|
+
/** Mints a token IAP accepts from the running service account: the metadata
|
|
59
|
+
* server names the account, and IAM signs `{iss, sub, aud, iat, exp}` as it,
|
|
60
|
+
* valid 10 minutes. The process owns no private key, and the metadata access
|
|
61
|
+
* token goes only to Google's own endpoints. The audience is used as given, so
|
|
62
|
+
* the caller checks that it covers the URL the token is sent to. Tokens are
|
|
63
|
+
* kept per `fetch` and audience until a minute before they expire, and callers
|
|
64
|
+
* asking at the same time share one signing request. Errors carry only a code. */
|
|
65
|
+
export const signedIapToken = (audience, options = {}) => Effect.tryPromise({
|
|
66
|
+
try: () => {
|
|
67
|
+
const request = options.fetch ?? fetch, now = options.now ?? Date.now;
|
|
68
|
+
let byAudience = caches.get(request);
|
|
69
|
+
if (!byAudience)
|
|
70
|
+
caches.set(request, (byAudience = new Map()));
|
|
71
|
+
let kept = byAudience.get(audience);
|
|
72
|
+
if (!kept)
|
|
73
|
+
byAudience.set(audience, (kept = { until: 0 }));
|
|
74
|
+
if (kept.value && kept.until > now())
|
|
75
|
+
return Promise.resolve(kept.value);
|
|
76
|
+
const entry = kept;
|
|
77
|
+
entry.pending ??= mint(audience, request, now, options.timeoutMillis ?? 10000)
|
|
78
|
+
.then(({ value, until }) => {
|
|
79
|
+
entry.value = value;
|
|
80
|
+
entry.until = until;
|
|
81
|
+
return value;
|
|
82
|
+
})
|
|
83
|
+
.finally(() => {
|
|
84
|
+
entry.pending = undefined;
|
|
85
|
+
});
|
|
86
|
+
return entry.pending;
|
|
87
|
+
},
|
|
88
|
+
catch: (error) => error instanceof IapSigningFailed
|
|
89
|
+
? error
|
|
90
|
+
: new IapSigningFailed({ code: "invalid_response" }),
|
|
91
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fastloop/kit-iap",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.21.0",
|
|
4
|
+
"description": "Checks the signed header Google's Identity-Aware Proxy adds to each request.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/iap.d.ts",
|
|
10
|
+
"bun": "./source/iap.ts",
|
|
11
|
+
"node": "./dist/iap.js",
|
|
12
|
+
"default": "./source/iap.ts"
|
|
13
|
+
},
|
|
14
|
+
"./vectors/cases.json": "./vectors/cases.json"
|
|
15
|
+
},
|
|
16
|
+
"peerDependencies": {
|
|
17
|
+
"effect": "4.0.0-rc.117"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"source",
|
|
22
|
+
"vectors/cases.json"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/source/iap.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
export class IapRejected extends Schema.TaggedError<IapRejected>()(
|
|
4
|
+
"IapRejected",
|
|
5
|
+
{ message: Schema.String },
|
|
6
|
+
) {}
|
|
7
|
+
|
|
8
|
+
/** Google's key list could not be read, so the proof could not be checked either way. */
|
|
9
|
+
export class IapUnavailable extends Schema.TaggedError<IapUnavailable>()(
|
|
10
|
+
"IapUnavailable",
|
|
11
|
+
{ message: Schema.String },
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
export interface IapOptions {
|
|
15
|
+
readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
16
|
+
readonly now?: () => number;
|
|
17
|
+
readonly keyTimeoutMillis?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const url = "https://www.gstatic.com/iap/verify/public_key-jwk";
|
|
21
|
+
const Jwk = Schema.Struct({
|
|
22
|
+
kty: Schema.String,
|
|
23
|
+
kid: Schema.String,
|
|
24
|
+
alg: Schema.optionalKey(Schema.String),
|
|
25
|
+
crv: Schema.optionalKey(Schema.String),
|
|
26
|
+
x: Schema.optionalKey(Schema.String),
|
|
27
|
+
y: Schema.optionalKey(Schema.String),
|
|
28
|
+
});
|
|
29
|
+
const Keys = Schema.Struct({ keys: Schema.Array(Jwk) });
|
|
30
|
+
const Header = Schema.Struct({
|
|
31
|
+
alg: Schema.Literal("ES256"),
|
|
32
|
+
kid: Schema.String,
|
|
33
|
+
});
|
|
34
|
+
const Claims = Schema.Struct({
|
|
35
|
+
iss: Schema.String,
|
|
36
|
+
aud: Schema.String,
|
|
37
|
+
iat: Schema.Int,
|
|
38
|
+
exp: Schema.Int,
|
|
39
|
+
email: Schema.NonEmptyString,
|
|
40
|
+
sub: Schema.NonEmptyString,
|
|
41
|
+
hd: Schema.optionalKey(Schema.String),
|
|
42
|
+
});
|
|
43
|
+
const rejected = () =>
|
|
44
|
+
new IapRejected({ message: "The sign-in proof is invalid." });
|
|
45
|
+
const unavailable = () =>
|
|
46
|
+
new IapUnavailable({ message: "The sign-in keys could not be read." });
|
|
47
|
+
type Fetcher = NonNullable<IapOptions["fetch"]>;
|
|
48
|
+
type KeyList = typeof Keys.Type;
|
|
49
|
+
// One key list per fetcher. Callers that arrive while it loads wait on the same fetch.
|
|
50
|
+
interface Cached {
|
|
51
|
+
readonly started: number;
|
|
52
|
+
readonly expires: number;
|
|
53
|
+
settled: boolean;
|
|
54
|
+
readonly keys: Promise<KeyList>;
|
|
55
|
+
}
|
|
56
|
+
const caches = new WeakMap<Fetcher, Cached>();
|
|
57
|
+
const load = (fetcher: Fetcher, timeoutMillis: number): Cached => {
|
|
58
|
+
const started = Date.now();
|
|
59
|
+
const entry: Cached = {
|
|
60
|
+
started,
|
|
61
|
+
expires: started + 55 * 60 * 1000,
|
|
62
|
+
settled: false,
|
|
63
|
+
keys: (async () => {
|
|
64
|
+
const response = await fetcher(url, {
|
|
65
|
+
signal: AbortSignal.timeout(timeoutMillis),
|
|
66
|
+
});
|
|
67
|
+
if (!response.ok) throw new Error("Key service unavailable");
|
|
68
|
+
return Schema.decodeUnknownSync(Keys)(await response.json());
|
|
69
|
+
})(),
|
|
70
|
+
};
|
|
71
|
+
caches.set(fetcher, entry);
|
|
72
|
+
entry.keys.then(
|
|
73
|
+
() => {
|
|
74
|
+
entry.settled = true;
|
|
75
|
+
},
|
|
76
|
+
() => {
|
|
77
|
+
if (caches.get(fetcher) === entry) caches.delete(fetcher);
|
|
78
|
+
},
|
|
79
|
+
);
|
|
80
|
+
return entry;
|
|
81
|
+
};
|
|
82
|
+
const read = async (entry: Cached): Promise<KeyList> => {
|
|
83
|
+
try {
|
|
84
|
+
return await entry.keys;
|
|
85
|
+
} catch {
|
|
86
|
+
throw unavailable();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const decode = (part: string): unknown =>
|
|
90
|
+
JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
91
|
+
|
|
92
|
+
export const verifyIapAssertion = (
|
|
93
|
+
header: string | null | undefined,
|
|
94
|
+
audience: string,
|
|
95
|
+
options: IapOptions = {},
|
|
96
|
+
): Effect.Effect<
|
|
97
|
+
{ readonly email: string; readonly sub: string; readonly hd?: string },
|
|
98
|
+
IapRejected | IapUnavailable
|
|
99
|
+
> =>
|
|
100
|
+
Effect.tryPromise({
|
|
101
|
+
try: async () => {
|
|
102
|
+
if (!header) throw rejected();
|
|
103
|
+
const parts = header.split(".");
|
|
104
|
+
const [head, body, signature] = parts;
|
|
105
|
+
if (parts.length !== 3 || !head || !body || !signature) throw rejected();
|
|
106
|
+
const parsed = Schema.decodeUnknownSync(Header)(decode(head));
|
|
107
|
+
const fetcher = options.fetch ?? fetch;
|
|
108
|
+
const timeoutMillis = options.keyTimeoutMillis ?? 5000;
|
|
109
|
+
const started = Date.now();
|
|
110
|
+
let entry = caches.get(fetcher);
|
|
111
|
+
// A list read before this call may predate a key rotation, so an unknown kid reads it once more.
|
|
112
|
+
// A list loading or loaded during this call is already current, so each call waits on one fetch at most.
|
|
113
|
+
const earlier =
|
|
114
|
+
entry !== undefined && entry.settled && entry.expires > started;
|
|
115
|
+
if (
|
|
116
|
+
!entry ||
|
|
117
|
+
entry.expires <= started ||
|
|
118
|
+
(!entry.settled && started - entry.started > timeoutMillis)
|
|
119
|
+
)
|
|
120
|
+
entry = load(fetcher, timeoutMillis);
|
|
121
|
+
let key = (await read(entry)).keys.find(
|
|
122
|
+
(item) => item.kid === parsed.kid,
|
|
123
|
+
);
|
|
124
|
+
if (!key && earlier) {
|
|
125
|
+
const current = caches.get(fetcher);
|
|
126
|
+
key = (
|
|
127
|
+
await read(
|
|
128
|
+
current && current !== entry
|
|
129
|
+
? current
|
|
130
|
+
: load(fetcher, timeoutMillis),
|
|
131
|
+
)
|
|
132
|
+
).keys.find((item) => item.kid === parsed.kid);
|
|
133
|
+
}
|
|
134
|
+
if (!key) throw rejected();
|
|
135
|
+
const publicKey = await crypto.subtle.importKey(
|
|
136
|
+
"jwk",
|
|
137
|
+
key,
|
|
138
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
139
|
+
false,
|
|
140
|
+
["verify"],
|
|
141
|
+
);
|
|
142
|
+
const valid = await crypto.subtle.verify(
|
|
143
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
144
|
+
publicKey,
|
|
145
|
+
Buffer.from(signature, "base64url"),
|
|
146
|
+
new TextEncoder().encode(`${head}.${body}`),
|
|
147
|
+
);
|
|
148
|
+
if (!valid) throw rejected();
|
|
149
|
+
const claims = Schema.decodeUnknownSync(Claims)(decode(body));
|
|
150
|
+
const now = Math.floor((options.now ?? Date.now)() / 1000);
|
|
151
|
+
if (
|
|
152
|
+
claims.iss !== "https://cloud.google.com/iap" ||
|
|
153
|
+
claims.aud !== audience ||
|
|
154
|
+
claims.exp < now - 30 ||
|
|
155
|
+
claims.exp <= claims.iat ||
|
|
156
|
+
claims.exp - claims.iat > 660 ||
|
|
157
|
+
claims.iat > now + 30
|
|
158
|
+
)
|
|
159
|
+
throw rejected();
|
|
160
|
+
return claims.hd === undefined
|
|
161
|
+
? { email: claims.email, sub: claims.sub }
|
|
162
|
+
: { email: claims.email, sub: claims.sub, hd: claims.hd };
|
|
163
|
+
},
|
|
164
|
+
catch: (error) => (error instanceof IapUnavailable ? error : rejected()),
|
|
165
|
+
}).pipe(
|
|
166
|
+
// Only the one key fetch waits on anything, so running out of time means the keys were unreadable.
|
|
167
|
+
Effect.timeout(options.keyTimeoutMillis ?? 5000),
|
|
168
|
+
Effect.mapError((error) =>
|
|
169
|
+
error instanceof IapRejected || error instanceof IapUnavailable
|
|
170
|
+
? error
|
|
171
|
+
: unavailable(),
|
|
172
|
+
),
|
|
173
|
+
);
|
|
174
|
+
export { IapSigningFailed, signedIapToken, type SignOptions } from "./sign.ts";
|
package/source/sign.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
export class IapSigningFailed extends Schema.TaggedError<IapSigningFailed>()(
|
|
4
|
+
"IapSigningFailed",
|
|
5
|
+
{
|
|
6
|
+
code: Schema.Literals([
|
|
7
|
+
"identity_unavailable",
|
|
8
|
+
"signing_unavailable",
|
|
9
|
+
"invalid_response",
|
|
10
|
+
]),
|
|
11
|
+
},
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
export interface SignOptions {
|
|
15
|
+
readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
16
|
+
readonly now?: () => number;
|
|
17
|
+
readonly timeoutMillis?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Fetcher = NonNullable<SignOptions["fetch"]>;
|
|
21
|
+
type Kept = {
|
|
22
|
+
value?: string;
|
|
23
|
+
until: number;
|
|
24
|
+
pending?: Promise<string> | undefined;
|
|
25
|
+
};
|
|
26
|
+
const MetadataAccess = Schema.Struct({ access_token: Schema.NonEmptyString });
|
|
27
|
+
const SignedToken = Schema.Struct({ signedJwt: Schema.NonEmptyString });
|
|
28
|
+
const metadata =
|
|
29
|
+
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
|
|
30
|
+
const iam =
|
|
31
|
+
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts";
|
|
32
|
+
const failed = (code: IapSigningFailed["code"]) => (): never => {
|
|
33
|
+
throw new IapSigningFailed({ code });
|
|
34
|
+
};
|
|
35
|
+
const caches = new WeakMap<Fetcher, Map<string, Kept>>();
|
|
36
|
+
|
|
37
|
+
const mint = async (
|
|
38
|
+
audience: string,
|
|
39
|
+
request: Fetcher,
|
|
40
|
+
now: () => number,
|
|
41
|
+
timeout: number,
|
|
42
|
+
) => {
|
|
43
|
+
const md = {
|
|
44
|
+
redirect: "manual",
|
|
45
|
+
headers: { "Metadata-Flavor": "Google" },
|
|
46
|
+
signal: AbortSignal.timeout(timeout),
|
|
47
|
+
} satisfies RequestInit;
|
|
48
|
+
const [identity, access] = await Promise.all([
|
|
49
|
+
request(`${metadata}/email`, md),
|
|
50
|
+
request(`${metadata}/token`, md),
|
|
51
|
+
]).catch(failed("identity_unavailable"));
|
|
52
|
+
if (!identity.ok || !access.ok)
|
|
53
|
+
throw new IapSigningFailed({ code: "identity_unavailable" });
|
|
54
|
+
const email = (await identity.text()).trim();
|
|
55
|
+
if (!/^[a-z0-9._-]+@[a-z0-9.-]+\.gserviceaccount\.com$/.test(email))
|
|
56
|
+
throw new IapSigningFailed({ code: "invalid_response" });
|
|
57
|
+
const { access_token } = Schema.decodeUnknownSync(MetadataAccess)(
|
|
58
|
+
await access.json(),
|
|
59
|
+
);
|
|
60
|
+
const iat = Math.floor(now() / 1000),
|
|
61
|
+
exp = iat + 600;
|
|
62
|
+
const response = await request(
|
|
63
|
+
`${iam}/${encodeURIComponent(email)}:signJwt`,
|
|
64
|
+
{
|
|
65
|
+
method: "POST",
|
|
66
|
+
redirect: "manual",
|
|
67
|
+
signal: AbortSignal.timeout(timeout),
|
|
68
|
+
headers: {
|
|
69
|
+
authorization: `Bearer ${access_token}`,
|
|
70
|
+
"content-type": "application/json",
|
|
71
|
+
},
|
|
72
|
+
body: JSON.stringify({
|
|
73
|
+
payload: JSON.stringify({
|
|
74
|
+
iss: email,
|
|
75
|
+
sub: email,
|
|
76
|
+
aud: audience,
|
|
77
|
+
iat,
|
|
78
|
+
exp,
|
|
79
|
+
}),
|
|
80
|
+
}),
|
|
81
|
+
},
|
|
82
|
+
).catch(failed("signing_unavailable"));
|
|
83
|
+
if (!response.ok) throw new IapSigningFailed({ code: "signing_unavailable" });
|
|
84
|
+
const { signedJwt } = Schema.decodeUnknownSync(SignedToken)(
|
|
85
|
+
await response.json(),
|
|
86
|
+
);
|
|
87
|
+
return { value: signedJwt, until: (exp - 60) * 1000 };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** Mints a token IAP accepts from the running service account: the metadata
|
|
91
|
+
* server names the account, and IAM signs `{iss, sub, aud, iat, exp}` as it,
|
|
92
|
+
* valid 10 minutes. The process owns no private key, and the metadata access
|
|
93
|
+
* token goes only to Google's own endpoints. The audience is used as given, so
|
|
94
|
+
* the caller checks that it covers the URL the token is sent to. Tokens are
|
|
95
|
+
* kept per `fetch` and audience until a minute before they expire, and callers
|
|
96
|
+
* asking at the same time share one signing request. Errors carry only a code. */
|
|
97
|
+
export const signedIapToken = (
|
|
98
|
+
audience: string,
|
|
99
|
+
options: SignOptions = {},
|
|
100
|
+
): Effect.Effect<string, IapSigningFailed> =>
|
|
101
|
+
Effect.tryPromise({
|
|
102
|
+
try: () => {
|
|
103
|
+
const request = options.fetch ?? fetch,
|
|
104
|
+
now = options.now ?? Date.now;
|
|
105
|
+
let byAudience = caches.get(request);
|
|
106
|
+
if (!byAudience) caches.set(request, (byAudience = new Map()));
|
|
107
|
+
let kept = byAudience.get(audience);
|
|
108
|
+
if (!kept) byAudience.set(audience, (kept = { until: 0 }));
|
|
109
|
+
if (kept.value && kept.until > now()) return Promise.resolve(kept.value);
|
|
110
|
+
const entry = kept;
|
|
111
|
+
entry.pending ??= mint(
|
|
112
|
+
audience,
|
|
113
|
+
request,
|
|
114
|
+
now,
|
|
115
|
+
options.timeoutMillis ?? 10000,
|
|
116
|
+
)
|
|
117
|
+
.then(({ value, until }) => {
|
|
118
|
+
entry.value = value;
|
|
119
|
+
entry.until = until;
|
|
120
|
+
return value;
|
|
121
|
+
})
|
|
122
|
+
.finally(() => {
|
|
123
|
+
entry.pending = undefined;
|
|
124
|
+
});
|
|
125
|
+
return entry.pending;
|
|
126
|
+
},
|
|
127
|
+
catch: (error) =>
|
|
128
|
+
error instanceof IapSigningFailed
|
|
129
|
+
? error
|
|
130
|
+
: new IapSigningFailed({ code: "invalid_response" }),
|
|
131
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"about": "IAP assertion test vectors. A verifier fetches `jwks` as Google's key set, treats `now` (unix seconds) as the clock, checks against `audience`, and must return `expect` ({email, sub}) or reject when `expect` is null. Accept clock skew of 30 s; reject lifetimes over 660 s.",
|
|
3
|
+
"now": 1800000000,
|
|
4
|
+
"audience": "/projects/123456789/global/backendServices/987654321",
|
|
5
|
+
"jwks": {
|
|
6
|
+
"keys": [
|
|
7
|
+
{
|
|
8
|
+
"kid": "kit-test-key",
|
|
9
|
+
"alg": "ES256",
|
|
10
|
+
"use": "sig",
|
|
11
|
+
"crv": "P-256",
|
|
12
|
+
"kty": "EC",
|
|
13
|
+
"x": "QuT2qh-QPTjFH2F6Qa6GjhK6nC__EEON66j8-FhvbPM",
|
|
14
|
+
"y": "BHhkoUspXYNfWohlJhlEJeKNp8nWEfvrWiM4gRPiAAs"
|
|
15
|
+
}
|
|
16
|
+
]
|
|
17
|
+
},
|
|
18
|
+
"cases": [
|
|
19
|
+
{
|
|
20
|
+
"name": "valid",
|
|
21
|
+
"description": "Fresh assertion for the expected audience.",
|
|
22
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtpdC10ZXN0LWtleSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwiYXVkIjoiL3Byb2plY3RzLzEyMzQ1Njc4OS9nbG9iYWwvYmFja2VuZFNlcnZpY2VzLzk4NzY1NDMyMSIsImlhdCI6MTc5OTk5OTk5MCwiZXhwIjoxODAwMDAwNTkwLCJlbWFpbCI6InBlcnNvbkBleGFtcGxlLnRlc3QiLCJzdWIiOiJhY2NvdW50cy5nb29nbGUuY29tOjEyMzQ1Njc4OTAifQ.4G5MWqfj5CDxikADyHpWYJZk5toAOVDR7h3GWezaA5KqlHWJwluCqmu_jlHOyoqZrAi6a1sCWv8mtYdAl5BzhA",
|
|
23
|
+
"expect": {
|
|
24
|
+
"email": "person@example.test",
|
|
25
|
+
"sub": "accounts.google.com:1234567890"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"name": "expired",
|
|
30
|
+
"description": "exp is more than 30 s in the past.",
|
|
31
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtpdC10ZXN0LWtleSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwiYXVkIjoiL3Byb2plY3RzLzEyMzQ1Njc4OS9nbG9iYWwvYmFja2VuZFNlcnZpY2VzLzk4NzY1NDMyMSIsImlhdCI6MTc5OTk5OTMwMCwiZXhwIjoxNzk5OTk5OTAwLCJlbWFpbCI6InBlcnNvbkBleGFtcGxlLnRlc3QiLCJzdWIiOiJhY2NvdW50cy5nb29nbGUuY29tOjEyMzQ1Njc4OTAifQ.y6IWaOo9FURo-S70F2diU95Mrti7zyj9ngWdObo5Q560qENJw-b6oYLSap0SwX4BKHa4ZjPkrMtsHm8SDQTXpA",
|
|
32
|
+
"expect": null
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"name": "iat-in-future",
|
|
36
|
+
"description": "iat is more than 30 s ahead of the clock.",
|
|
37
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtpdC10ZXN0LWtleSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwiYXVkIjoiL3Byb2plY3RzLzEyMzQ1Njc4OS9nbG9iYWwvYmFja2VuZFNlcnZpY2VzLzk4NzY1NDMyMSIsImlhdCI6MTgwMDAwMDEwMCwiZXhwIjoxODAwMDAwNDAwLCJlbWFpbCI6InBlcnNvbkBleGFtcGxlLnRlc3QiLCJzdWIiOiJhY2NvdW50cy5nb29nbGUuY29tOjEyMzQ1Njc4OTAifQ.qLhjJcJK8p866lt3mAb2mlNwzl4VFvSJu_U6tM-MuBu89IRI3qX4SkHWwvRYrTr_uKmLySzXR7WZYjAPw2PDow",
|
|
38
|
+
"expect": null
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"name": "lifetime-too-long",
|
|
42
|
+
"description": "exp - iat is 661 s, over the 660 s limit.",
|
|
43
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtpdC10ZXN0LWtleSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwiYXVkIjoiL3Byb2plY3RzLzEyMzQ1Njc4OS9nbG9iYWwvYmFja2VuZFNlcnZpY2VzLzk4NzY1NDMyMSIsImlhdCI6MTc5OTk5OTk5MCwiZXhwIjoxODAwMDAwNjUxLCJlbWFpbCI6InBlcnNvbkBleGFtcGxlLnRlc3QiLCJzdWIiOiJhY2NvdW50cy5nb29nbGUuY29tOjEyMzQ1Njc4OTAifQ.bkMP0sdzn4tm5A-sjYiv_Hp6VHvTjuSjcLmtLe3z_GhFuf72aF5DeJu4pURrtakR55XTmHy7KkyMewJPtI5gjw",
|
|
44
|
+
"expect": null
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"name": "wrong-audience",
|
|
48
|
+
"description": "aud names a different backend service.",
|
|
49
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtpdC10ZXN0LWtleSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwiYXVkIjoiL3Byb2plY3RzLzEvZ2xvYmFsL2JhY2tlbmRTZXJ2aWNlcy8yIiwiaWF0IjoxNzk5OTk5OTkwLCJleHAiOjE4MDAwMDA1OTAsImVtYWlsIjoicGVyc29uQGV4YW1wbGUudGVzdCIsInN1YiI6ImFjY291bnRzLmdvb2dsZS5jb206MTIzNDU2Nzg5MCJ9.XKNkFFy339dtRdr_e8RvExBrmv1pbBpRVGk7VvQvPGTzqb6ZVMn2UiM422rRU_8jIdI4EtirI3s0pSxsECvtGg",
|
|
50
|
+
"expect": null
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"name": "wrong-issuer",
|
|
54
|
+
"description": "iss is not Google's IAP issuer.",
|
|
55
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtpdC10ZXN0LWtleSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhdWQiOiIvcHJvamVjdHMvMTIzNDU2Nzg5L2dsb2JhbC9iYWNrZW5kU2VydmljZXMvOTg3NjU0MzIxIiwiaWF0IjoxNzk5OTk5OTkwLCJleHAiOjE4MDAwMDA1OTAsImVtYWlsIjoicGVyc29uQGV4YW1wbGUudGVzdCIsInN1YiI6ImFjY291bnRzLmdvb2dsZS5jb206MTIzNDU2Nzg5MCJ9.vCrtaScCMkQUJUgbIWfGYoN2GkbBCBPBt4YLTo0sVAB8QrqXJXosCAVCagt-AXfeEA49y647ViRD_G_H7POabg",
|
|
56
|
+
"expect": null
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"name": "unknown-kid",
|
|
60
|
+
"description": "Signed by the test key but names a kid the key set lacks.",
|
|
61
|
+
"assertion": "eyJhbGciOiJFUzI1NiIsImtpZCI6Im5vdC1pbi1rZXktc2V0IiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwiYXVkIjoiL3Byb2plY3RzLzEyMzQ1Njc4OS9nbG9iYWwvYmFja2VuZFNlcnZpY2VzLzk4NzY1NDMyMSIsImlhdCI6MTc5OTk5OTk5MCwiZXhwIjoxODAwMDAwNTkwLCJlbWFpbCI6InBlcnNvbkBleGFtcGxlLnRlc3QiLCJzdWIiOiJhY2NvdW50cy5nb29nbGUuY29tOjEyMzQ1Njc4OTAifQ.Vm3NiBzofcSFAg15ZyJwU5zoP2Lqnit8k4-HZ92KMvrtdG_tX7GnMSsKDqJrzurBa7V8Zru2yceiqeIrYO54Yg",
|
|
62
|
+
"expect": null
|
|
63
|
+
}
|
|
64
|
+
]
|
|
65
|
+
}
|
package/README.md
DELETED