@ultimat3/auth 31.2.0 → 31.3.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/CLAUDE.md +6 -0
- package/README.md +6 -0
- package/package.json +5 -4
- package/src/auth-ports.ts +104 -0
- package/src/auth.ts +20 -30
- package/src/limiter-install.ts +13 -0
- package/src/saml-test-idp.ts +189 -0
- package/src/saml-test-signer.ts +67 -0
package/CLAUDE.md
CHANGED
|
@@ -41,6 +41,11 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
|
|
|
41
41
|
window, a one-statement take; a live lockout is never rewritten. †
|
|
42
42
|
- **`installAuthLimiters` (`@ultimat3/auth/adapter`) is the HOST's install point and takes a
|
|
43
43
|
FACTORY**: `config.limiter` → installed factory → `memoryAuthLimiter`. †
|
|
44
|
+
- **Every installed port is read where it is USED, never captured by `defineAuth`** (`auth-ports.ts`,
|
|
45
|
+
31.3): `limiter`, `orgLimiter`, `orgRateLimit`, `totpReplay` are getters, rebuilt only when the
|
|
46
|
+
install changes. The boot installs after `runtime.ts` loads; a captured port was per-pod memory
|
|
47
|
+
for life. Installed at construction: judged then; not yet: judged at first use
|
|
48
|
+
(`X_AUTH_LIMITER_NOT_SHARED` there). `limiter-install.test.ts` "installed AFTER defineAuth".
|
|
44
49
|
- **`normaliseEmail` is the ONE normalisation, ABOVE the `AuthAdapter` seam**: trim + lowercase,
|
|
45
50
|
never a `+tag` or gmail dot; no adapter folds case. †
|
|
46
51
|
- **`json.ts` owns `isRecord` and `decodeJwtSegment`; no second copy.** An array is not a record.
|
|
@@ -200,6 +205,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
|
|
|
200
205
|
| `client-scope.ts` | `clientScopeOf(actor)`, the OPAQUE id for `<meta name="ultimate-scope">`: keyed SHA-256 (`SESSION_SECRET`, else a per-process key and one warning) over kind, id, impersonator; `''` anonymous |
|
|
201
206
|
| `identity-provider*.ts` | SSO port, `signInWithIdentity`, OIDC adapter, route core, state cookie, status table |
|
|
202
207
|
| `saml-*.ts` | SAML adapter: strict XML reader, exc-c14n, XML-DSig, response checks, metadata, AuthnRequest |
|
|
208
|
+
| `saml-test-idp.ts` / `saml-test-signer.ts` (`./saml-test-idp`) | the in-process test IdP and its RSA signer, SHIPPED (moved from `*-fixture.ts` in 31.3): this package's SAML suites, `@ultimat3/testing`'s `fakeSamlIdentityProvider` and an app's test sign with the one implementation. Never on `.` |
|
|
203
209
|
|
|
204
210
|
```bash
|
|
205
211
|
bun test ./packages/auth/
|
package/README.md
CHANGED
|
@@ -1042,6 +1042,12 @@ is `X_SAML_METADATA_INVALID` at boot. An id the routes do not serve is `X_IDENTI
|
|
|
1042
1042
|
An adapter of your own is held to the same contract by
|
|
1043
1043
|
`identityProviderConformance` (`@ultimat3/testing/conformance`).
|
|
1044
1044
|
|
|
1045
|
+
Testing a SAML sign-in: `fakeSamlIdentityProvider({ audience, users })` from `@ultimat3/testing`
|
|
1046
|
+
answers the AuthnRequest an SP's redirect carries with a signed response, as a chosen user, and `tamper()`s
|
|
1047
|
+
it. It runs over `@ultimat3/auth/saml-test-idp` (`samlTestIdp()`, `readAuthnRequest()`,
|
|
1048
|
+
`encodeResponse()`), the in-process IdP this package's own SAML suites sign with — one signer,
|
|
1049
|
+
one path.
|
|
1050
|
+
|
|
1045
1051
|
## API keys — how an agent authenticates
|
|
1046
1052
|
|
|
1047
1053
|
`ult_<env>_<id>_<secret>`. The plaintext is shown once; the row holds `sha256(secret)` and is
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/auth",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.3.0",
|
|
4
4
|
"description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
".": "./src/index.ts",
|
|
31
31
|
"./adapter": "./src/adapter-subpath.ts",
|
|
32
32
|
"./client": "./src/client.ts",
|
|
33
|
+
"./saml-test-idp": "./src/saml-test-idp.ts",
|
|
33
34
|
"./soft-authenticator": "./src/soft-authenticator.ts"
|
|
34
35
|
},
|
|
35
36
|
"files": [
|
|
@@ -48,8 +49,8 @@
|
|
|
48
49
|
"test": "bun test"
|
|
49
50
|
},
|
|
50
51
|
"dependencies": {
|
|
51
|
-
"@ultimat3/core": "31.
|
|
52
|
-
"@ultimat3/db": "31.
|
|
53
|
-
"@ultimat3/schema": "31.
|
|
52
|
+
"@ultimat3/core": "31.3.0",
|
|
53
|
+
"@ultimat3/db": "31.3.0",
|
|
54
|
+
"@ultimat3/schema": "31.3.0"
|
|
54
55
|
}
|
|
55
56
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Single responsibility: the credential ports an `Auth` reads — the two limiters and the TOTP
|
|
2
|
+
// replay guard — resolved where they are USED, never captured when `defineAuth` runs. What
|
|
3
|
+
// `defineAuth` was PASSED always wins.
|
|
4
|
+
//
|
|
5
|
+
// Why: the boot installs them after `runtime.ts` loads, and anything `runtime.ts` imports may call
|
|
6
|
+
// `defineAuth` first: captured, that app kept per-pod memory guards for life (lockouts × replicas,
|
|
7
|
+
// a TOTP code or SAML assertion replayable on every other pod).
|
|
8
|
+
|
|
9
|
+
import type { Clock } from '@ultimat3/core';
|
|
10
|
+
import { totpReplayGuardInvalid } from './errors';
|
|
11
|
+
import {
|
|
12
|
+
authLimiterInstall,
|
|
13
|
+
installedAuthLimiter,
|
|
14
|
+
installedTotpReplay,
|
|
15
|
+
totpReplayInstall,
|
|
16
|
+
} from './limiter-install';
|
|
17
|
+
import { memoryTotpReplayGuard, type TotpReplayGuard } from './mfa';
|
|
18
|
+
import {
|
|
19
|
+
type AuthLimiter,
|
|
20
|
+
type AuthRateLimitPolicy,
|
|
21
|
+
assertAuthLimiterPolicy,
|
|
22
|
+
memoryAuthLimiter,
|
|
23
|
+
} from './rate-limit';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The installed port, rebuilt only when the install changes; else `fallback`, built once. `check`
|
|
27
|
+
* runs on every port built, so a mismatch is refused where it first appears.
|
|
28
|
+
*/
|
|
29
|
+
function resolving<F, P>(
|
|
30
|
+
installed: () => F | undefined,
|
|
31
|
+
build: () => P | undefined,
|
|
32
|
+
fallback: () => P,
|
|
33
|
+
): () => P {
|
|
34
|
+
let from: F | undefined;
|
|
35
|
+
let port: P | undefined;
|
|
36
|
+
let local: P | undefined;
|
|
37
|
+
return () => {
|
|
38
|
+
const current = installed();
|
|
39
|
+
if (current === undefined) {
|
|
40
|
+
local ??= fallback();
|
|
41
|
+
return local;
|
|
42
|
+
}
|
|
43
|
+
if (current !== from || port === undefined) {
|
|
44
|
+
port = build() ?? fallback();
|
|
45
|
+
from = current;
|
|
46
|
+
}
|
|
47
|
+
return port;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A limiter for `policy`: passed, else installed, else this process' memory. `exempt`: the fallback is not compared. */
|
|
52
|
+
export function limiterPort(
|
|
53
|
+
passed: AuthLimiter | undefined,
|
|
54
|
+
policy: AuthRateLimitPolicy,
|
|
55
|
+
clock: Clock,
|
|
56
|
+
exempt: boolean,
|
|
57
|
+
): () => AuthLimiter {
|
|
58
|
+
if (passed !== undefined) {
|
|
59
|
+
assertAuthLimiterPolicy(policy, passed);
|
|
60
|
+
return () => passed;
|
|
61
|
+
}
|
|
62
|
+
const checked = (limiter: AuthLimiter): AuthLimiter => {
|
|
63
|
+
assertAuthLimiterPolicy(policy, limiter);
|
|
64
|
+
return limiter;
|
|
65
|
+
};
|
|
66
|
+
const read = resolving(
|
|
67
|
+
authLimiterInstall,
|
|
68
|
+
() => {
|
|
69
|
+
const built = installedAuthLimiter(policy);
|
|
70
|
+
return built === undefined ? undefined : checked(built);
|
|
71
|
+
},
|
|
72
|
+
() => (exempt ? memoryAuthLimiter(clock, policy) : checked(memoryAuthLimiter(clock, policy))),
|
|
73
|
+
);
|
|
74
|
+
// Installed already: built and judged now, so a factory that ignores the policy is refused at
|
|
75
|
+
// `defineAuth` as before. Not installed: judged at first use, after the boot had its chance.
|
|
76
|
+
if (authLimiterInstall() !== undefined) read();
|
|
77
|
+
return read;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const validGuard = (guard: TotpReplayGuard): TotpReplayGuard => {
|
|
81
|
+
// Unreachable from TypeScript and reachable from a guard written before `claim`, which would
|
|
82
|
+
// otherwise be found at the first second factor, as a TypeError, on a production sign-in.
|
|
83
|
+
const declared: { readonly claim?: unknown } = guard;
|
|
84
|
+
if (typeof declared.claim !== 'function') throw totpReplayGuardInvalid();
|
|
85
|
+
return guard;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** Where spent TOTP steps (and SAML assertions) are claimed: passed, else installed, else memory. */
|
|
89
|
+
export function totpReplayPort(passed: TotpReplayGuard | undefined): () => TotpReplayGuard {
|
|
90
|
+
if (passed !== undefined) {
|
|
91
|
+
const guard = validGuard(passed);
|
|
92
|
+
return () => guard;
|
|
93
|
+
}
|
|
94
|
+
const read = resolving(
|
|
95
|
+
totpReplayInstall,
|
|
96
|
+
() => {
|
|
97
|
+
const built = installedTotpReplay();
|
|
98
|
+
return built === undefined ? undefined : validGuard(built);
|
|
99
|
+
},
|
|
100
|
+
memoryTotpReplayGuard,
|
|
101
|
+
);
|
|
102
|
+
if (totpReplayInstall() !== undefined) read();
|
|
103
|
+
return read;
|
|
104
|
+
}
|
package/src/auth.ts
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
import { type Clock, systemClock, timingSafeEqual, uuidV7 } from '@ultimat3/core';
|
|
7
7
|
import { t } from '@ultimat3/schema';
|
|
8
8
|
import type { AuthAdapter, AuthSession, AuthUser } from './adapter';
|
|
9
|
+
import { limiterPort, totpReplayPort } from './auth-ports';
|
|
9
10
|
import { normaliseEmail } from './email';
|
|
10
|
-
import { mfaRequiredUnenforceable, sessionUnknown
|
|
11
|
-
import { installedAuthLimiter, installedTotpReplay } from './limiter-install';
|
|
11
|
+
import { mfaRequiredUnenforceable, sessionUnknown } from './errors';
|
|
12
12
|
import { openLoginAttempt } from './login-attempt';
|
|
13
13
|
import { type HandleDirectory, loginIdentity } from './login-identity';
|
|
14
|
-
import {
|
|
14
|
+
import type { TotpReplayGuard } from './mfa';
|
|
15
15
|
import { mfaChallengeRequired } from './mfa-challenge';
|
|
16
16
|
import type { OAuthProviderId } from './oauth';
|
|
17
17
|
import {
|
|
@@ -31,10 +31,8 @@ import { assertPasswordPolicy, assertRateLimitPolicy, assertSessionPolicy } from
|
|
|
31
31
|
import {
|
|
32
32
|
type AuthLimiter,
|
|
33
33
|
type AuthRateLimitPolicy,
|
|
34
|
-
assertAuthLimiterPolicy,
|
|
35
34
|
DEFAULT_AUTH_RATE_LIMIT,
|
|
36
35
|
loginFailed,
|
|
37
|
-
memoryAuthLimiter,
|
|
38
36
|
orgRateLimit,
|
|
39
37
|
} from './rate-limit';
|
|
40
38
|
import {
|
|
@@ -218,23 +216,9 @@ export function defineAuth(config: AuthConfigInput): Auth {
|
|
|
218
216
|
// the database connection), then one process' worth of state. Without the middle arm a
|
|
219
217
|
// scaffolded app had to remember to build a shared limiter itself, which is the opposite of
|
|
220
218
|
// what this framework promises — and `x new` scaffolds two replicas.
|
|
221
|
-
const limiter =
|
|
222
|
-
config.limiter ?? installedAuthLimiter(rateLimit) ?? memoryAuthLimiter(clock, rateLimit);
|
|
223
|
-
assertAuthLimiterPolicy(rateLimit, limiter);
|
|
224
|
-
// The tenant bucket is a noisy-neighbour cap, not a credential-guessing allowance, so an app
|
|
225
|
-
// that declares `scope: 'shared'` for its LOCKOUT is not also required to ship a shared limiter
|
|
226
|
-
// for this one — per replica it approximates to `orgMaxAttempts × replicas`, which is a
|
|
227
|
-
// throughput ceiling and discloses nothing. Only the LOCAL fallback is exempt, and exempting it
|
|
228
|
-
// is what buys that: `memoryAuthLimiter` always reports `'process'`, which is the one arm the
|
|
229
|
-
// scope check would refuse. A limiter somebody else supplied — injected by the app or built by
|
|
230
|
-
// the host's factory — is compared exactly as the general bucket's is, because a factory that
|
|
231
|
-
// ignores the policy it was handed otherwise enforces numbers the app never declared while
|
|
232
|
-
// `Auth.orgRateLimit` reports the app's. That asymmetry was the whole defect: the same factory
|
|
233
|
-
// is refused for one bucket and trusted for the other.
|
|
219
|
+
const limiter = limiterPort(config.limiter, rateLimit, clock, false);
|
|
234
220
|
const orgLimits = orgRateLimit(rateLimit);
|
|
235
|
-
const
|
|
236
|
-
const orgLimiter = suppliedOrgLimiter ?? memoryAuthLimiter(clock, orgLimits);
|
|
237
|
-
if (suppliedOrgLimiter !== undefined) assertAuthLimiterPolicy(orgLimits, suppliedOrgLimiter);
|
|
221
|
+
const orgLimiter = limiterPort(config.orgLimiter, orgLimits, clock, true);
|
|
238
222
|
// Read through a widened local on purpose: the field's type is the literal `false`, so this
|
|
239
223
|
// branch is unreachable from TypeScript and reachable from every JS caller and every config
|
|
240
224
|
// parsed out of JSON — the same split `invariantColumns()` keeps its Proxy behind a compile
|
|
@@ -242,11 +226,9 @@ export function defineAuth(config: AuthConfigInput): Auth {
|
|
|
242
226
|
const declaredMfa: { readonly required?: unknown } = config.mfa ?? {};
|
|
243
227
|
if (declaredMfa.required === true) throw mfaRequiredUnenforceable();
|
|
244
228
|
const mfa: AuthMfaPolicy = { issuer: config.mfa?.issuer ?? DEFAULT_MFA_ISSUER, required: false };
|
|
245
|
-
|
|
246
|
-
//
|
|
247
|
-
|
|
248
|
-
const declaredReplay: { readonly claim?: unknown } = totpReplay;
|
|
249
|
-
if (typeof declaredReplay.claim !== 'function') throw totpReplayGuardInvalid();
|
|
229
|
+
// Each port is read where it is used (`auth-ports.ts`): the boot installs them after `runtime.ts`
|
|
230
|
+
// loads, so one captured here would be the per-process default for the app's whole life.
|
|
231
|
+
const totpReplay = totpReplayPort(config.totpReplay);
|
|
250
232
|
const passkeys =
|
|
251
233
|
config.passkeys === undefined ? undefined : resolvePasskeyPolicy(config.passkeys);
|
|
252
234
|
return Object.freeze({
|
|
@@ -255,13 +237,21 @@ export function defineAuth(config: AuthConfigInput): Auth {
|
|
|
255
237
|
sessions: { store: config.adapter, policy: session, clock },
|
|
256
238
|
password,
|
|
257
239
|
rateLimit,
|
|
258
|
-
limiter
|
|
240
|
+
get limiter(): AuthLimiter {
|
|
241
|
+
return limiter();
|
|
242
|
+
},
|
|
259
243
|
// What the limiter in use actually enforces, not the derivation — the two differ in `scope`
|
|
260
244
|
// exactly when the app declared 'shared' and left this limiter to the default.
|
|
261
|
-
orgRateLimit:
|
|
262
|
-
|
|
245
|
+
get orgRateLimit(): AuthRateLimitPolicy {
|
|
246
|
+
return orgLimiter().policy;
|
|
247
|
+
},
|
|
248
|
+
get orgLimiter(): AuthLimiter {
|
|
249
|
+
return orgLimiter();
|
|
250
|
+
},
|
|
263
251
|
mfa,
|
|
264
|
-
totpReplay
|
|
252
|
+
get totpReplay(): TotpReplayGuard {
|
|
253
|
+
return totpReplay();
|
|
254
|
+
},
|
|
265
255
|
// BREAKING (majors only): the default is `[]`, never the live registry.
|
|
266
256
|
//
|
|
267
257
|
// It was `oauthProviderIds()`, so `defineAuth({ providers })`'s own documented purpose — the
|
package/src/limiter-install.ts
CHANGED
|
@@ -149,3 +149,16 @@ export function resetTotpReplay(): void {
|
|
|
149
149
|
export function installedTotpReplay(): TotpReplayGuard | undefined {
|
|
150
150
|
return replayFactory.current()?.();
|
|
151
151
|
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The installed limiter FACTORY itself, so a reader can tell one install from the next and rebuild
|
|
155
|
+
* only then (`auth-ports.ts`). Not exported from `src/index.ts`, for `installedAuthLimiter`'s reason.
|
|
156
|
+
*/
|
|
157
|
+
export function authLimiterInstall(): AuthLimiterFactory | undefined {
|
|
158
|
+
return factory.current();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The installed TOTP replay factory, for `authLimiterInstall`'s reason. */
|
|
162
|
+
export function totpReplayInstall(): TotpReplayFactory | undefined {
|
|
163
|
+
return replayFactory.current();
|
|
164
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// TEST TOOL, shipped as `@ultimat3/auth/saml-test-idp`. A SAML IdP in-process: metadata, and signed
|
|
2
|
+
// responses written DIRECTLY in canonical form — every namespace declared where exc-c14n renders it,
|
|
3
|
+
// attributes pre-sorted, no empty-tag shorthand — so the digest is SHA-256 of the literal string and
|
|
4
|
+
// the signer never calls the `saml-c14n.ts` it is testing.
|
|
5
|
+
//
|
|
6
|
+
// This package's suites, `@ultimat3/testing`'s `fakeSamlIdentityProvider` and an app's sign-in test
|
|
7
|
+
// share it: one signer, one path.
|
|
8
|
+
|
|
9
|
+
import { finiteOption } from '@ultimat3/core';
|
|
10
|
+
import { c14nAttribute, c14nText } from './saml-c14n';
|
|
11
|
+
import {
|
|
12
|
+
BEARER,
|
|
13
|
+
DSIG_NS,
|
|
14
|
+
ENVELOPED,
|
|
15
|
+
EXC_C14N,
|
|
16
|
+
MD_NS,
|
|
17
|
+
NAMEID_PERSISTENT,
|
|
18
|
+
RSA_SHA256,
|
|
19
|
+
SAML_NS,
|
|
20
|
+
SAMLP_NS,
|
|
21
|
+
SHA256,
|
|
22
|
+
STATUS_SUCCESS,
|
|
23
|
+
} from './saml-dom';
|
|
24
|
+
import { parseSamlMetadata, type SamlIdpMetadata } from './saml-metadata';
|
|
25
|
+
import { type TestRsaSigner, testRsaSigner } from './saml-test-signer';
|
|
26
|
+
|
|
27
|
+
export type { TestRsaSigner } from './saml-test-signer';
|
|
28
|
+
export { testRsaSigner } from './saml-test-signer';
|
|
29
|
+
|
|
30
|
+
export const TEST_IDP_ENTITY_ID = 'https://idp.example.test/metadata';
|
|
31
|
+
export const TEST_IDP_SSO_URL = 'https://idp.example.test/sso';
|
|
32
|
+
|
|
33
|
+
export interface TestResponseSpec {
|
|
34
|
+
readonly requestId: string;
|
|
35
|
+
readonly acsUrl: string;
|
|
36
|
+
readonly audience: string;
|
|
37
|
+
readonly now: Date;
|
|
38
|
+
readonly nameId?: string;
|
|
39
|
+
readonly nameIdFormat?: string;
|
|
40
|
+
/** `null` omits the email attribute. */
|
|
41
|
+
readonly email?: string | null;
|
|
42
|
+
/** The `displayName` attribute; default `Ada Lovelace`, `null` omits it. */
|
|
43
|
+
readonly name?: string | null;
|
|
44
|
+
/** The confirmation's Recipient alone; default `acsUrl`. */
|
|
45
|
+
readonly recipient?: string;
|
|
46
|
+
readonly issuer?: string;
|
|
47
|
+
readonly assertionId?: string;
|
|
48
|
+
readonly lifetimeMs?: number;
|
|
49
|
+
readonly notBefore?: Date;
|
|
50
|
+
readonly status?: string;
|
|
51
|
+
readonly signAssertion?: boolean;
|
|
52
|
+
readonly signResponse?: boolean;
|
|
53
|
+
readonly signer?: TestRsaSigner;
|
|
54
|
+
readonly digestAlgorithm?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface TestIdp {
|
|
58
|
+
readonly signer: TestRsaSigner;
|
|
59
|
+
readonly metadataXml: string;
|
|
60
|
+
readonly idp: SamlIdpMetadata;
|
|
61
|
+
/** The response document, in canonical form. Tamper with it, then `encode` it. */
|
|
62
|
+
responseXml(spec: TestResponseSpec): Promise<string>;
|
|
63
|
+
respond(spec: TestResponseSpec): Promise<string>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const encodeResponse = (xml: string): string =>
|
|
67
|
+
btoa(String.fromCharCode(...new TextEncoder().encode(xml)));
|
|
68
|
+
|
|
69
|
+
/** Text and attribute values in canonical form: the spec's tables, shared with the verifier. */
|
|
70
|
+
const esc = c14nText;
|
|
71
|
+
const escAttr = c14nAttribute;
|
|
72
|
+
const at = (date: Date): string => `${date.toISOString().slice(0, 19)}Z`;
|
|
73
|
+
const randomId = (): string => `_${crypto.randomUUID().replaceAll('-', '')}`;
|
|
74
|
+
|
|
75
|
+
async function sha256Base64(value: string): Promise<string> {
|
|
76
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
|
|
77
|
+
return btoa(String.fromCharCode(...new Uint8Array(digest)));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** `<ds:Signature>` for the canonical `signed` (which carries ID `id`), in canonical form. */
|
|
81
|
+
async function signatureFor(signed: string, id: string, signer: TestRsaSigner, digestAlg: string) {
|
|
82
|
+
const body =
|
|
83
|
+
`<ds:CanonicalizationMethod Algorithm="${EXC_C14N}"></ds:CanonicalizationMethod>` +
|
|
84
|
+
`<ds:SignatureMethod Algorithm="${RSA_SHA256}"></ds:SignatureMethod>` +
|
|
85
|
+
`<ds:Reference URI="#${id}"><ds:Transforms>` +
|
|
86
|
+
`<ds:Transform Algorithm="${ENVELOPED}"></ds:Transform>` +
|
|
87
|
+
`<ds:Transform Algorithm="${EXC_C14N}"></ds:Transform></ds:Transforms>` +
|
|
88
|
+
`<ds:DigestMethod Algorithm="${digestAlg}"></ds:DigestMethod>` +
|
|
89
|
+
`<ds:DigestValue>${await sha256Base64(signed)}</ds:DigestValue></ds:Reference>`;
|
|
90
|
+
const value = await signer.sign(`<ds:SignedInfo xmlns:ds="${DSIG_NS}">${body}</ds:SignedInfo>`);
|
|
91
|
+
return (
|
|
92
|
+
`<ds:Signature xmlns:ds="${DSIG_NS}"><ds:SignedInfo>${body}</ds:SignedInfo>` +
|
|
93
|
+
`<ds:SignatureValue>${value}</ds:SignatureValue><ds:KeyInfo><ds:X509Data>` +
|
|
94
|
+
`<ds:X509Certificate>${signer.certificate}</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature>`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Splice the signature in right after the element's first `</saml:Issuer>`. */
|
|
99
|
+
const envelop = (canonical: string, signature: string): string =>
|
|
100
|
+
canonical.replace('</saml:Issuer>', `</saml:Issuer>${signature}`);
|
|
101
|
+
|
|
102
|
+
function assertionXml(spec: TestResponseSpec, id: string): string {
|
|
103
|
+
// Negative is legal — an already-expired assertion is a case a test signs — so finite, not a count.
|
|
104
|
+
const lifetimeMs = finiteOption('samlTestIdp', 'lifetimeMs', spec.lifetimeMs ?? 300_000);
|
|
105
|
+
const notOnOrAfter = at(new Date(spec.now.getTime() + lifetimeMs));
|
|
106
|
+
const notBefore = at(spec.notBefore ?? new Date(spec.now.getTime() - 30_000));
|
|
107
|
+
const email = spec.email === undefined ? 'ada@corp.example' : spec.email;
|
|
108
|
+
const emailAttribute =
|
|
109
|
+
email === null
|
|
110
|
+
? ''
|
|
111
|
+
: `<saml:Attribute Name="email"><saml:AttributeValue>${esc(email)}</saml:AttributeValue></saml:Attribute>`;
|
|
112
|
+
const name = spec.name === undefined ? 'Ada Lovelace' : spec.name;
|
|
113
|
+
const nameAttribute =
|
|
114
|
+
name === null
|
|
115
|
+
? ''
|
|
116
|
+
: `<saml:Attribute Name="displayName"><saml:AttributeValue>${esc(name)}</saml:AttributeValue></saml:Attribute>`;
|
|
117
|
+
return (
|
|
118
|
+
`<saml:Assertion xmlns:saml="${SAML_NS}" ID="${id}" IssueInstant="${at(spec.now)}" Version="2.0">` +
|
|
119
|
+
`<saml:Issuer>${esc(spec.issuer ?? TEST_IDP_ENTITY_ID)}</saml:Issuer><saml:Subject>` +
|
|
120
|
+
`<saml:NameID Format="${spec.nameIdFormat ?? NAMEID_PERSISTENT}">${esc(spec.nameId ?? 'u-1001')}</saml:NameID>` +
|
|
121
|
+
`<saml:SubjectConfirmation Method="${BEARER}"><saml:SubjectConfirmationData InResponseTo="${escAttr(spec.requestId)}"` +
|
|
122
|
+
` NotOnOrAfter="${notOnOrAfter}" Recipient="${escAttr(spec.recipient ?? spec.acsUrl)}"></saml:SubjectConfirmationData>` +
|
|
123
|
+
`</saml:SubjectConfirmation></saml:Subject><saml:Conditions NotBefore="${notBefore}" NotOnOrAfter="${notOnOrAfter}">` +
|
|
124
|
+
`<saml:AudienceRestriction><saml:Audience>${esc(spec.audience)}</saml:Audience></saml:AudienceRestriction>` +
|
|
125
|
+
`</saml:Conditions><saml:AuthnStatement AuthnInstant="${at(spec.now)}" SessionIndex="s-1">` +
|
|
126
|
+
'<saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password' +
|
|
127
|
+
'</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement><saml:AttributeStatement>' +
|
|
128
|
+
emailAttribute +
|
|
129
|
+
nameAttribute +
|
|
130
|
+
'</saml:AttributeStatement></saml:Assertion>'
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function samlTestIdp(signer?: TestRsaSigner): Promise<TestIdp> {
|
|
135
|
+
const own = signer ?? (await testRsaSigner());
|
|
136
|
+
const metadataXml =
|
|
137
|
+
`<md:EntityDescriptor xmlns:md="${MD_NS}" xmlns:ds="${DSIG_NS}" entityID="${TEST_IDP_ENTITY_ID}">` +
|
|
138
|
+
'<md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">' +
|
|
139
|
+
`<md:KeyDescriptor use="signing"><ds:KeyInfo><ds:X509Data><ds:X509Certificate>\n${own.certificate}\n` +
|
|
140
|
+
'</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor>' +
|
|
141
|
+
'<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://idp.example.test/post"/>' +
|
|
142
|
+
`<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="${TEST_IDP_SSO_URL}"/>` +
|
|
143
|
+
'</md:IDPSSODescriptor></md:EntityDescriptor>';
|
|
144
|
+
|
|
145
|
+
const responseXml = async (spec: TestResponseSpec): Promise<string> => {
|
|
146
|
+
const key = spec.signer ?? own;
|
|
147
|
+
const digestAlg = spec.digestAlgorithm ?? SHA256;
|
|
148
|
+
const assertionId = spec.assertionId ?? randomId();
|
|
149
|
+
let assertion = assertionXml(spec, assertionId);
|
|
150
|
+
if (spec.signAssertion ?? true) {
|
|
151
|
+
assertion = envelop(assertion, await signatureFor(assertion, assertionId, key, digestAlg));
|
|
152
|
+
}
|
|
153
|
+
// Inside the response, the saml prefix is already rendered by... nobody: Response does not
|
|
154
|
+
// use it, so exc-c14n renders it on the Issuer and the Assertion — exactly as written here.
|
|
155
|
+
const id = randomId();
|
|
156
|
+
const response =
|
|
157
|
+
`<samlp:Response xmlns:samlp="${SAMLP_NS}" Destination="${escAttr(spec.acsUrl)}" ID="${id}"` +
|
|
158
|
+
` InResponseTo="${escAttr(spec.requestId)}" IssueInstant="${at(spec.now)}" Version="2.0">` +
|
|
159
|
+
`<saml:Issuer xmlns:saml="${SAML_NS}">${esc(spec.issuer ?? TEST_IDP_ENTITY_ID)}</saml:Issuer>` +
|
|
160
|
+
`<samlp:Status><samlp:StatusCode Value="${spec.status ?? STATUS_SUCCESS}"></samlp:StatusCode></samlp:Status>` +
|
|
161
|
+
`${assertion}</samlp:Response>`;
|
|
162
|
+
return spec.signResponse === true
|
|
163
|
+
? envelop(response, await signatureFor(response, id, key, digestAlg))
|
|
164
|
+
: response;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
signer: own,
|
|
169
|
+
metadataXml,
|
|
170
|
+
idp: parseSamlMetadata(metadataXml),
|
|
171
|
+
responseXml,
|
|
172
|
+
respond: async (spec) => encodeResponse(await responseXml(spec)),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** What `samlAuthnRequest` put on the redirect: inflated, so a test can answer it. */
|
|
177
|
+
export function readAuthnRequest(location: string): {
|
|
178
|
+
id: string;
|
|
179
|
+
relayState: string;
|
|
180
|
+
xml: string;
|
|
181
|
+
} {
|
|
182
|
+
const url = new URL(location);
|
|
183
|
+
const deflated = Uint8Array.from(atob(url.searchParams.get('SAMLRequest') ?? ''), (c) =>
|
|
184
|
+
c.charCodeAt(0),
|
|
185
|
+
);
|
|
186
|
+
const xml = new TextDecoder().decode(Bun.inflateSync(deflated));
|
|
187
|
+
const id = /\bID="([^"]+)"/.exec(xml)?.[1] ?? '';
|
|
188
|
+
return { id, relayState: url.searchParams.get('RelayState') ?? '', xml };
|
|
189
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// TEST TOOL, `saml-test-idp.ts`'s signer. An RSA-2048 key pair and a self-signed X.509 certificate
|
|
2
|
+
// for it, minted in-process with Web Crypto and hand-written DER: what a SAML IdP's metadata
|
|
3
|
+
// publishes and signs with.
|
|
4
|
+
|
|
5
|
+
export interface TestRsaSigner {
|
|
6
|
+
/** Base64 DER, as `<ds:X509Certificate>` carries it. */
|
|
7
|
+
readonly certificate: string;
|
|
8
|
+
sign(data: string): Promise<string>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const concat = (parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {
|
|
12
|
+
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
13
|
+
let at = 0;
|
|
14
|
+
for (const part of parts) {
|
|
15
|
+
out.set(part, at);
|
|
16
|
+
at += part.length;
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const lengthOf = (n: number): Uint8Array =>
|
|
22
|
+
n < 0x80 ? Uint8Array.of(n) : n < 0x100 ? Uint8Array.of(0x81, n) : Uint8Array.of(0x82, n >> 8, n);
|
|
23
|
+
const tlv = (tag: number, ...parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {
|
|
24
|
+
const body = concat(parts);
|
|
25
|
+
return concat([Uint8Array.of(tag), lengthOf(body.length), body]);
|
|
26
|
+
};
|
|
27
|
+
const seq = (...parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => tlv(0x30, ...parts);
|
|
28
|
+
const text = (value: string): Uint8Array => new TextEncoder().encode(value);
|
|
29
|
+
|
|
30
|
+
/** sha256WithRSAEncryption, NULL parameters. */
|
|
31
|
+
const SHA256_RSA = seq(
|
|
32
|
+
Uint8Array.of(0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b),
|
|
33
|
+
Uint8Array.of(0x05, 0x00),
|
|
34
|
+
);
|
|
35
|
+
const COMMON_NAME = Uint8Array.of(0x06, 0x03, 0x55, 0x04, 0x03);
|
|
36
|
+
const NAME = seq(tlv(0x31, seq(COMMON_NAME, tlv(0x0c, text('test-idp')))));
|
|
37
|
+
const VALIDITY = seq(tlv(0x17, text('000101000000Z')), tlv(0x18, text('20991231235959Z')));
|
|
38
|
+
|
|
39
|
+
const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
|
|
40
|
+
|
|
41
|
+
export async function testRsaSigner(): Promise<TestRsaSigner> {
|
|
42
|
+
const algorithm = {
|
|
43
|
+
name: 'RSASSA-PKCS1-v1_5',
|
|
44
|
+
modulusLength: 2048,
|
|
45
|
+
publicExponent: Uint8Array.of(1, 0, 1),
|
|
46
|
+
hash: 'SHA-256',
|
|
47
|
+
};
|
|
48
|
+
const pair = await crypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
|
|
49
|
+
const spki = new Uint8Array(await crypto.subtle.exportKey('spki', pair.publicKey));
|
|
50
|
+
const tbs = seq(
|
|
51
|
+
tlv(0xa0, tlv(0x02, Uint8Array.of(2))),
|
|
52
|
+
tlv(0x02, Uint8Array.of(1)),
|
|
53
|
+
SHA256_RSA,
|
|
54
|
+
NAME,
|
|
55
|
+
VALIDITY,
|
|
56
|
+
NAME,
|
|
57
|
+
spki,
|
|
58
|
+
);
|
|
59
|
+
const signRaw = async (data: Uint8Array<ArrayBuffer>): Promise<Uint8Array> =>
|
|
60
|
+
new Uint8Array(await crypto.subtle.sign('RSASSA-PKCS1-v1_5', pair.privateKey, data));
|
|
61
|
+
const signature = await signRaw(tbs);
|
|
62
|
+
const certificate = seq(tbs, SHA256_RSA, tlv(0x03, Uint8Array.of(0), signature));
|
|
63
|
+
return {
|
|
64
|
+
certificate: base64(certificate),
|
|
65
|
+
sign: async (data) => base64(await signRaw(new TextEncoder().encode(data))),
|
|
66
|
+
};
|
|
67
|
+
}
|