@odatano/core 2.0.0-rc.4 → 2.0.0-rc.5

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.
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ /**
3
+ * Transport authentication with lanes: CAP's configured strategy PLUS an
4
+ * `x-agent-token` lane (AGENT_GRANTS_DESIGN.md §3).
5
+ *
6
+ * CAP's auth middleware 401s a request without transport credentials before any
7
+ * service hook runs, so an agent holding only an `odat_` token could never
8
+ * reach a service. This middleware is installed as `cds.requires.auth.impl` by
9
+ * src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
10
+ *
11
+ * - runs every registered LANE first. The built-in lane admits a request that
12
+ * carries `x-agent-token` on one of the six ODATANO service paths (exact
13
+ * segment match, no lookalike prefixes): the token is authenticated HERE
14
+ * (unknown 401, expired 410, non-leaking) and the request continues as the
15
+ * principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
16
+ * rides on the express request (`req.agentGrant`) for the enforcement hook.
17
+ * Other packages (@odatano/x402) add lanes with `registerTransportLane`
18
+ * instead of fighting for the single `auth.impl` slot.
19
+ * - otherwise DELEGATES to CAP's own strategy for the configured kind
20
+ * (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
21
+ * for every request without a token is exactly what it was before.
22
+ *
23
+ * Failed token attempts are throttled per client address (20 per 15 minutes):
24
+ * one static hash lookup must not become an offline-speed guessing oracle.
25
+ */
26
+ var __importDefault = (this && this.__importDefault) || function (mod) {
27
+ return (mod && mod.__esModule) ? mod : { "default": mod };
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.agentTokenLane = void 0;
31
+ exports.registerTransportLane = registerTransportLane;
32
+ exports.transportLanes = transportLanes;
33
+ exports.__resetTransportLanesForTests = __resetTransportLanesForTests;
34
+ exports.__setAgentServicePathsForTests = __setAgentServicePathsForTests;
35
+ exports.agentServicePaths = agentServicePaths;
36
+ exports.inAgentLane = inAgentLane;
37
+ exports.resolveCustomImpl = resolveCustomImpl;
38
+ exports.loadDelegate = loadDelegate;
39
+ exports.createAgentTokenAuth = createAgentTokenAuth;
40
+ exports.default = agentTokenAuthFactory;
41
+ const cds_1 = __importDefault(require("@sap/cds"));
42
+ const agent_grants_1 = require("./agent-grants");
43
+ const rate_limiter_1 = require("./rate-limiter");
44
+ const lanes = [];
45
+ /** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
46
+ function registerTransportLane(lane) {
47
+ const i = lanes.findIndex((l) => l.name === lane.name);
48
+ if (i >= 0)
49
+ lanes[i] = lane;
50
+ else
51
+ lanes.push(lane);
52
+ }
53
+ /** Registered lane names, in order (tests, diagnostics). */
54
+ function transportLanes() {
55
+ return lanes.map((l) => l.name);
56
+ }
57
+ /** Remove every lane except the built-in one (tests). */
58
+ function __resetTransportLanesForTests() {
59
+ lanes.length = 0;
60
+ tokenFailures.reset();
61
+ servicePathsCache = null;
62
+ servicePathsPinned = false;
63
+ }
64
+ /** Built-in CAP strategies by kind, same table as @sap/cds/lib/srv/middlewares/auth/index.js. */
65
+ const BUILTIN = {
66
+ mocked: 'basic-auth',
67
+ basic: 'basic-auth',
68
+ ias: 'ias-auth',
69
+ jwt: 'jwt-auth',
70
+ xsuaa: 'jwt-auth',
71
+ dummy: 'dummy-auth',
72
+ };
73
+ // ---------------------------------------------------------------------------
74
+ // Built-in lane: x-agent-token on the ODATANO service paths
75
+ // ---------------------------------------------------------------------------
76
+ const tokenFailures = new rate_limiter_1.RateLimiter({ windowMs: 15 * 60 * 1000, maxRequests: 20, maxKeys: 10_000 });
77
+ let servicePathsCache = null;
78
+ let servicePathsPinned = false;
79
+ /** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
80
+ function __setAgentServicePathsForTests(paths) {
81
+ servicePathsCache = paths;
82
+ servicePathsPinned = paths !== null;
83
+ }
84
+ /** Mount paths of the six services, read from `cds.services` once they are served. */
85
+ function agentServicePaths() {
86
+ if (servicePathsPinned && servicePathsCache)
87
+ return servicePathsCache;
88
+ if (servicePathsCache && servicePathsCache.length === agent_grants_1.AGENT_SERVICE_NAMES.length)
89
+ return servicePathsCache;
90
+ const services = cds_1.default.services ?? {};
91
+ const paths = Object.values(services)
92
+ .filter((s) => s && agent_grants_1.AGENT_SERVICE_NAMES.includes(String(s.name)) && typeof s.path === 'string')
93
+ .map((s) => String(s.path).replace(/\/+$/, ''));
94
+ servicePathsCache = paths;
95
+ return paths;
96
+ }
97
+ function requestPath(req) {
98
+ const raw = String(req.originalUrl || req.url || req.path || '');
99
+ return raw.split('?')[0];
100
+ }
101
+ /** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
102
+ function inAgentLane(path, servicePaths = agentServicePaths()) {
103
+ return servicePaths.some((p) => path === p || path.startsWith(p + '/'));
104
+ }
105
+ function clientKey(req) {
106
+ const ip = req.ip ?? req.socket?.remoteAddress ?? 'unknown';
107
+ return `ip=${String(ip).replace(/:/g, '.')}:agent-token`;
108
+ }
109
+ function respond(res, status, message, retryAfterMs) {
110
+ if (retryAfterMs !== undefined)
111
+ res.set?.('Retry-After', String(Math.max(1, Math.ceil(retryAfterMs / 1000))));
112
+ const body = { error: { code: String(status), message } };
113
+ if (typeof res.status === 'function' && typeof res.json === 'function') {
114
+ res.status(status);
115
+ res.json(body);
116
+ }
117
+ else {
118
+ res.statusCode = status;
119
+ res.setHeader('content-type', 'application/json');
120
+ res.end(JSON.stringify(body));
121
+ }
122
+ return { handled: true };
123
+ }
124
+ exports.agentTokenLane = {
125
+ name: 'agent-token',
126
+ match: (req) => typeof req.headers?.[agent_grants_1.AGENT_TOKEN_HEADER] === 'string' && req.headers[agent_grants_1.AGENT_TOKEN_HEADER].length > 0,
127
+ authenticate: async (req, res) => {
128
+ const token = req.headers[agent_grants_1.AGENT_TOKEN_HEADER];
129
+ if (!inAgentLane(requestPath(req))) {
130
+ // A token on any other path is not ours to admit; the delegate decides
131
+ // (and will 401 a request that carries nothing else).
132
+ return null;
133
+ }
134
+ const key = clientKey(req);
135
+ const locked = tokenFailures.peek(key);
136
+ if (!locked.allowed)
137
+ return respond(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
138
+ const resolution = await (0, agent_grants_1.resolveAgentToken)(token);
139
+ if (!resolution.ok) {
140
+ const failed = tokenFailures.check(key);
141
+ if (!failed.allowed)
142
+ return respond(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
143
+ return respond(res, resolution.status, resolution.message);
144
+ }
145
+ req.agentGrant = resolution.grant;
146
+ return { user: (0, agent_grants_1.makeAgentUser)(resolution.grant) };
147
+ },
148
+ };
149
+ function ensureBuiltinLane() {
150
+ if (!lanes.some((l) => l.name === exports.agentTokenLane.name))
151
+ lanes.unshift(exports.agentTokenLane);
152
+ }
153
+ /** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
154
+ /**
155
+ * Resolve a host-configured `auth.impl` the way CAP's auth factory does
156
+ * (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
157
+ * cds.root, else with a `./` prefix. Exported for the unit tests.
158
+ */
159
+ function resolveCustomImpl(impl, root = String(cds_1.default.root ?? process.cwd())) {
160
+ try {
161
+ return require.resolve(impl, { paths: [root] });
162
+ }
163
+ catch {
164
+ return require.resolve(`./${impl}`, { paths: [root] });
165
+ }
166
+ }
167
+ function asMiddleware(loaded, delegateOptions, what) {
168
+ // default export of an ESM / .ts module
169
+ const candidate = loaded?.default ?? loaded;
170
+ const mw = typeof candidate === 'function' && candidate.length < 3
171
+ ? candidate(delegateOptions)
172
+ : candidate;
173
+ if (typeof mw !== 'function') {
174
+ throw new Error(`agent-token-auth: ${what} did not yield a middleware function`);
175
+ }
176
+ return mw;
177
+ }
178
+ function loadDelegate(options, kind) {
179
+ // The delegate must not see our impl (it would recurse) nor our private keys.
180
+ const delegateOptions = { ...options };
181
+ delete delegateOptions.impl;
182
+ delete delegateOptions.agentGrantsDelegate;
183
+ delete delegateOptions.agentGrantsDelegateImpl;
184
+ // A host that brought its own auth.impl keeps it: whatever it enforced
185
+ // before agent grants were switched on, it still enforces for every request
186
+ // that does not carry a token, on every path.
187
+ const custom = options.agentGrantsDelegateImpl;
188
+ if (custom) {
189
+ const resolved = resolveCustomImpl(custom);
190
+ return asMiddleware(require(resolved), { ...delegateOptions, impl: custom }, `custom auth impl '${custom}'`);
191
+ }
192
+ const builtin = BUILTIN[kind.replace(/-auth$/, '')];
193
+ if (!builtin)
194
+ throw new Error(`agent-token-auth: no built-in CAP auth strategy for kind '${kind}'`);
195
+ // Same module CAP itself would have loaded for this kind. Pinned by the
196
+ // @sap/cds peer dependency; the self-test in asMiddleware fails fast if the shape moves.
197
+ const factory = require(`@sap/cds/lib/srv/middlewares/auth/${builtin}`);
198
+ return asMiddleware(factory, { ...delegateOptions, kind }, `CAP auth strategy '${builtin}'`);
199
+ }
200
+ function createAgentTokenAuth(options, delegate) {
201
+ const delegateKind = String(options.agentGrantsDelegate ?? options.kind ?? 'mocked');
202
+ const inner = delegate ?? loadDelegate(options, delegateKind);
203
+ ensureBuiltinLane();
204
+ const delegateLabel = options.agentGrantsDelegateImpl ? `custom impl ${options.agentGrantsDelegateImpl}` : `'${delegateKind}'`;
205
+ cds_1.default.log('AgentGrants').info(`agent-token transport lane active, delegating other requests to ${delegateLabel}`);
206
+ return async function agentTokenAuth(req, res, next) {
207
+ for (const lane of lanes) {
208
+ if (!lane.match(req))
209
+ continue;
210
+ let outcome;
211
+ try {
212
+ outcome = await lane.authenticate(req, res);
213
+ }
214
+ catch (err) {
215
+ cds_1.default.log('AgentGrants').error(`transport lane '${lane.name}' failed: ${String(err?.message ?? err)}`);
216
+ respond(res, 500, 'authentication lane failed');
217
+ return;
218
+ }
219
+ if (outcome === null)
220
+ continue;
221
+ if ('handled' in outcome)
222
+ return;
223
+ req.user = outcome.user;
224
+ const ctx = cds_1.default.context;
225
+ if (ctx)
226
+ ctx.user = outcome.user;
227
+ return next();
228
+ }
229
+ return inner(req, res, next);
230
+ };
231
+ }
232
+ /**
233
+ * CAP requires this module and, seeing a function with fewer than three
234
+ * parameters, calls it with the merged auth options to obtain the middleware.
235
+ */
236
+ function agentTokenAuthFactory(options) {
237
+ return createAgentTokenAuth(options);
238
+ }
239
+ //# sourceMappingURL=agent-token-auth.js.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * In-memory sliding-window rate limiter, ported from NIGHTGATE
3
+ * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
4
+ * agent-token attempts; nothing here touches the database.
5
+ */
6
+ export interface RateLimiterOptions {
7
+ windowMs: number;
8
+ maxRequests: number;
9
+ /** Max tracked keys (default 10 000). */
10
+ maxKeys?: number;
11
+ /** Stale-key sweep interval (default 60 000 ms). */
12
+ sweepIntervalMs?: number;
13
+ /**
14
+ * Max distinct keys ONE group may hold (default 64). The group is the key up
15
+ * to its first ':' (the principal in `principal:scope` keys). Bounds what a
16
+ * single caller can do to the shared table: without it, made-up scopes under
17
+ * one principal evicted every other caller's window.
18
+ */
19
+ maxKeysPerGroup?: number;
20
+ }
21
+ export interface RateCheckResult {
22
+ allowed: boolean;
23
+ retryAfterMs: number;
24
+ }
25
+ /**
26
+ * Rate-limit key for a CAP request: the principal (user, else client address)
27
+ * plus the scope. Batch parts carry no address and a proxy hides the real one,
28
+ * so the address is the last resort only. The principal is the limiter's GROUP
29
+ * (see maxKeysPerGroup), hence no ':' in it.
30
+ */
31
+ export declare function principalRateKey(req: unknown, scope: string): string;
32
+ export declare class RateLimiter {
33
+ private readonly windowMs;
34
+ private readonly maxRequests;
35
+ private readonly maxKeys;
36
+ private readonly maxKeysPerGroup;
37
+ private readonly groupCounts;
38
+ private readonly hits;
39
+ private readonly sweepTimer;
40
+ constructor(opts: RateLimiterOptions);
41
+ check(key: string): RateCheckResult;
42
+ /** Would ONE more hit fit? Records nothing. */
43
+ peek(key: string): RateCheckResult;
44
+ /** Forget every key (tests). */
45
+ reset(): void;
46
+ /**
47
+ * Consume `count` slots atomically: either ALL fit into the window and are
48
+ * recorded, or NONE are (a rejected caller has consumed nothing).
49
+ */
50
+ checkMany(key: string, count: number): RateCheckResult;
51
+ private dropKey;
52
+ /** Remove keys with no hits within the current window. */
53
+ private sweep;
54
+ /** Stop the background sweep timer. */
55
+ destroy(): void;
56
+ }
57
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ /**
3
+ * In-memory sliding-window rate limiter, ported from NIGHTGATE
4
+ * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
5
+ * agent-token attempts; nothing here touches the database.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.RateLimiter = void 0;
9
+ exports.principalRateKey = principalRateKey;
10
+ /** The group a key belongs to: everything before the first ':' (the principal). */
11
+ function groupOf(key) {
12
+ const i = key.indexOf(':');
13
+ return i < 0 ? key : key.slice(0, i);
14
+ }
15
+ /**
16
+ * Rate-limit key for a CAP request: the principal (user, else client address)
17
+ * plus the scope. Batch parts carry no address and a proxy hides the real one,
18
+ * so the address is the last resort only. The principal is the limiter's GROUP
19
+ * (see maxKeysPerGroup), hence no ':' in it.
20
+ */
21
+ function principalRateKey(req, scope) {
22
+ const r = req;
23
+ const user = r?.user?.id;
24
+ const ip = r?._?.req?.ip ?? r?.http?.req?.ip ?? r?.ip;
25
+ const principal = user ? `user=${String(user)}`
26
+ : ip ? `ip=${String(ip).replace(/:/g, '.')}`
27
+ : 'anonymous';
28
+ return `${principal}:${scope}`;
29
+ }
30
+ class RateLimiter {
31
+ windowMs;
32
+ maxRequests;
33
+ maxKeys;
34
+ maxKeysPerGroup;
35
+ groupCounts = new Map();
36
+ hits = new Map();
37
+ sweepTimer;
38
+ constructor(opts) {
39
+ this.windowMs = opts.windowMs;
40
+ this.maxRequests = opts.maxRequests;
41
+ this.maxKeys = opts.maxKeys || 10_000;
42
+ this.maxKeysPerGroup = opts.maxKeysPerGroup || 64;
43
+ this.sweepTimer = setInterval(() => this.sweep(), opts.sweepIntervalMs || 60_000);
44
+ if (typeof this.sweepTimer.unref === 'function')
45
+ this.sweepTimer.unref();
46
+ }
47
+ check(key) {
48
+ return this.checkMany(key, 1);
49
+ }
50
+ /** Would ONE more hit fit? Records nothing. */
51
+ peek(key) {
52
+ const now = Date.now();
53
+ const inWindow = (this.hits.get(key) ?? []).filter((t) => t > now - this.windowMs);
54
+ if (inWindow.length < this.maxRequests)
55
+ return { allowed: true, retryAfterMs: 0 };
56
+ const oldest = Math.min(...inWindow);
57
+ return { allowed: false, retryAfterMs: Math.max(oldest + this.windowMs - now, 0) };
58
+ }
59
+ /** Forget every key (tests). */
60
+ reset() {
61
+ this.hits.clear();
62
+ this.groupCounts.clear();
63
+ }
64
+ /**
65
+ * Consume `count` slots atomically: either ALL fit into the window and are
66
+ * recorded, or NONE are (a rejected caller has consumed nothing).
67
+ */
68
+ checkMany(key, count) {
69
+ if (count <= 0)
70
+ return { allowed: true, retryAfterMs: 0 };
71
+ const now = Date.now();
72
+ const windowStart = now - this.windowMs;
73
+ if (!this.hits.has(key)) {
74
+ const group = groupOf(key);
75
+ if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
76
+ return { allowed: false, retryAfterMs: this.windowMs };
77
+ }
78
+ // At capacity a NEW key evicts the least recently used one (the map is
79
+ // insertion ordered and `set` below re-inserts on every hit).
80
+ if (this.hits.size >= this.maxKeys) {
81
+ const oldest = this.hits.keys().next().value;
82
+ if (oldest !== undefined)
83
+ this.dropKey(oldest);
84
+ }
85
+ this.groupCounts.set(group, (this.groupCounts.get(group) ?? 0) + 1);
86
+ }
87
+ let timestamps = this.hits.get(key) || [];
88
+ timestamps = timestamps.filter((t) => t > windowStart);
89
+ this.hits.delete(key); // re-insert below = most recently used
90
+ if (timestamps.length + count > this.maxRequests) {
91
+ timestamps.sort((a, b) => a - b);
92
+ const oldestInWindow = timestamps[0];
93
+ const retryAfterMs = oldestInWindow === undefined ? this.windowMs : oldestInWindow + this.windowMs - now;
94
+ this.hits.set(key, timestamps);
95
+ return { allowed: false, retryAfterMs: Math.max(retryAfterMs, 0) };
96
+ }
97
+ for (let i = 0; i < count; i++)
98
+ timestamps.push(now);
99
+ this.hits.set(key, timestamps);
100
+ return { allowed: true, retryAfterMs: 0 };
101
+ }
102
+ dropKey(key) {
103
+ if (!this.hits.delete(key))
104
+ return;
105
+ const group = groupOf(key);
106
+ const n = (this.groupCounts.get(group) ?? 1) - 1;
107
+ if (n <= 0)
108
+ this.groupCounts.delete(group);
109
+ else
110
+ this.groupCounts.set(group, n);
111
+ }
112
+ /** Remove keys with no hits within the current window. */
113
+ sweep() {
114
+ const windowStart = Date.now() - this.windowMs;
115
+ for (const [key, timestamps] of this.hits) {
116
+ if (!timestamps.some((t) => t > windowStart))
117
+ this.dropKey(key);
118
+ }
119
+ }
120
+ /** Stop the background sweep timer. */
121
+ destroy() {
122
+ clearInterval(this.sweepTimer);
123
+ }
124
+ }
125
+ exports.RateLimiter = RateLimiter;
126
+ //# sourceMappingURL=rate-limiter.js.map