@odatano/core 2.0.0-rc.7 → 2.0.0-rc.8
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/README.md +2 -0
- package/package.json +2 -1
- package/src/index.d.ts +2 -2
- package/src/index.js +2 -2
- package/srv/utils/agent-grants-config.d.ts +4 -3
- package/srv/utils/agent-grants-config.js +14 -10
- package/srv/utils/agent-token-auth.d.ts +9 -96
- package/srv/utils/agent-token-auth.js +21 -179
package/README.md
CHANGED
|
@@ -88,6 +88,8 @@ Service available at `http://localhost:4004`. See the [Quick Start Guide](docs/Q
|
|
|
88
88
|
> **Heads-up.** `cds serve` uses CAP's mocked auth: `@requires: 'authenticated-user'` accepts any Basic-Auth header against a mock user (`alice`, `bob`, …) — passwords are not checked. Anonymous requests get 401, but anyone reaching the port can authenticate.
|
|
89
89
|
>
|
|
90
90
|
> Production needs the `[production]` profile (`NODE_ENV=production`), which switches to `auth: xsuaa`. Don't expose a dev-mode instance. See the [Security Guide](docs/guides/SECURITY_GUIDE.md#authentication-xsuaa).
|
|
91
|
+
>
|
|
92
|
+
> The Docker image runs `NODE_ENV=production` with HTTP basic auth via `@odatano/cap-auth` (`ODATANO_HTTP_PASSWORD` required, user `ODATANO_HTTP_USER` default `odatano`, roles `ODATANO_HTTP_ROLES` default `Admin`; 20 failed attempts per 15 min per client address and user, then 429). `ODATANO_AUTH=dummy` disables authentication for local testing only. `getLiveness()` and `VerifyDataSignature` stay anonymous.
|
|
91
93
|
|
|
92
94
|
## Services
|
|
93
95
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@odatano/core",
|
|
3
|
-
"version": "2.0.0-rc.
|
|
3
|
+
"version": "2.0.0-rc.8",
|
|
4
4
|
"description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
|
|
5
5
|
"imports": {
|
|
6
6
|
"#cds-models/*": "./@cds-models/*/index.js"
|
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
"@harmoniclabs/cbor": "^2.0.1",
|
|
34
34
|
"@harmoniclabs/crypto": "^0.3.0",
|
|
35
35
|
"@harmoniclabs/uint8array-utils": "^1.0.4",
|
|
36
|
+
"@odatano/cap-auth": "^0.1.0",
|
|
36
37
|
"@sap/xssec": "^4",
|
|
37
38
|
"axios": "^1.18.0",
|
|
38
39
|
"bech32": "^2.0.0",
|
package/src/index.d.ts
CHANGED
|
@@ -6,8 +6,8 @@ export { getAppContext, getCardanoIndexer, getCardanoClient, getCardanoTxBuilder
|
|
|
6
6
|
export { getHsmSigner } from '../srv/blockchain/signing/hsm-signer';
|
|
7
7
|
export { issueAgentGrant, updateAgentGrant, rotateAgentGrantToken, revokeAgentGrantById, getGrantUsage, resolveUsageWindow, hashAgentToken, AGENT_TOKEN_HEADER, AGENT_TOKEN_PREFIX, AGENT_ROLE, AGENT_ALLOWLISTABLE_ACTIONS, AGENT_ALWAYS_ALLOWED_EVENTS, } from '../srv/utils/agent-grants';
|
|
8
8
|
export type { IssueAgentGrantInput, IssuedAgentGrant, AgentGrantStatus, UpdateAgentGrantInput, UpdateAgentGrantResult, RotatedAgentGrant, AgentGrantUsage, GrantUsageCall, UsageWindow, } from '../srv/utils/agent-grants';
|
|
9
|
-
export { registerTransportLane } from '
|
|
10
|
-
export type { TransportLane, LaneOutcome } from '
|
|
9
|
+
export { registerTransportLane } from '@odatano/cap-auth';
|
|
10
|
+
export type { TransportLane, LaneOutcome } from '@odatano/cap-auth';
|
|
11
11
|
export { loadAgentGrantsConfig } from '../srv/utils/agent-grants-config';
|
|
12
12
|
export type { AgentGrantsConfig } from '../srv/utils/agent-grants-config';
|
|
13
13
|
export type { HsmConfig, HsmSignResult } from '../srv/utils/types';
|
package/src/index.js
CHANGED
|
@@ -81,8 +81,8 @@ Object.defineProperty(exports, "AGENT_TOKEN_PREFIX", { enumerable: true, get: fu
|
|
|
81
81
|
Object.defineProperty(exports, "AGENT_ROLE", { enumerable: true, get: function () { return agent_grants_1.AGENT_ROLE; } });
|
|
82
82
|
Object.defineProperty(exports, "AGENT_ALLOWLISTABLE_ACTIONS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALLOWLISTABLE_ACTIONS; } });
|
|
83
83
|
Object.defineProperty(exports, "AGENT_ALWAYS_ALLOWED_EVENTS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALWAYS_ALLOWED_EVENTS; } });
|
|
84
|
-
var
|
|
85
|
-
Object.defineProperty(exports, "registerTransportLane", { enumerable: true, get: function () { return
|
|
84
|
+
var cap_auth_1 = require("@odatano/cap-auth");
|
|
85
|
+
Object.defineProperty(exports, "registerTransportLane", { enumerable: true, get: function () { return cap_auth_1.registerTransportLane; } });
|
|
86
86
|
var agent_grants_config_1 = require("../srv/utils/agent-grants-config");
|
|
87
87
|
Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_1.loadAgentGrantsConfig; } });
|
|
88
88
|
// Re-export pure CBOR utilities (no CAP round-trip needed)
|
|
@@ -52,9 +52,10 @@ export declare function loadAgentGrantsConfig(env?: Record<string, string | unde
|
|
|
52
52
|
* middlewares — the last moment `cds.requires.auth.impl` can still change).
|
|
53
53
|
*
|
|
54
54
|
* When enabled:
|
|
55
|
-
* - the transport auth becomes
|
|
56
|
-
* `x-agent-token`
|
|
57
|
-
* request to the strategy that was configured
|
|
55
|
+
* - the transport auth becomes @odatano/cap-auth (unless the host runs it
|
|
56
|
+
* already) with the `x-agent-token` lane of srv/utils/agent-token-auth
|
|
57
|
+
* registered; every other request goes to the strategy that was configured
|
|
58
|
+
* before (CAP's own for `kind`, or the host's custom impl as `delegateImpl`);
|
|
58
59
|
* - each of the six services gets the enforcement hook once it is served.
|
|
59
60
|
*
|
|
60
61
|
* Never throws: a misconfiguration is logged and the feature stays off, so a
|
|
@@ -10,7 +10,6 @@ exports.customAuthImpl = customAuthImpl;
|
|
|
10
10
|
exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
|
|
11
11
|
exports.activateAgentGrants = activateAgentGrants;
|
|
12
12
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
13
|
-
const path_1 = __importDefault(require("path"));
|
|
14
13
|
exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
|
|
15
14
|
exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
|
|
16
15
|
/**
|
|
@@ -43,8 +42,8 @@ function configuredAuth() {
|
|
|
43
42
|
return { kind: auth };
|
|
44
43
|
return (auth ?? {});
|
|
45
44
|
}
|
|
46
|
-
/**
|
|
47
|
-
const OUR_IMPL = '
|
|
45
|
+
/** The transport middleware, recognisable in `auth.impl` so activation stays idempotent. */
|
|
46
|
+
const OUR_IMPL = 'cap-auth';
|
|
48
47
|
/**
|
|
49
48
|
* A custom `cds.requires.auth.impl` the host configured before us (anything
|
|
50
49
|
* that is not this package's middleware). It keeps authenticating every
|
|
@@ -93,9 +92,10 @@ const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
|
|
|
93
92
|
* middlewares — the last moment `cds.requires.auth.impl` can still change).
|
|
94
93
|
*
|
|
95
94
|
* When enabled:
|
|
96
|
-
* - the transport auth becomes
|
|
97
|
-
* `x-agent-token`
|
|
98
|
-
* request to the strategy that was configured
|
|
95
|
+
* - the transport auth becomes @odatano/cap-auth (unless the host runs it
|
|
96
|
+
* already) with the `x-agent-token` lane of srv/utils/agent-token-auth
|
|
97
|
+
* registered; every other request goes to the strategy that was configured
|
|
98
|
+
* before (CAP's own for `kind`, or the host's custom impl as `delegateImpl`);
|
|
99
99
|
* - each of the six services gets the enforcement hook once it is served.
|
|
100
100
|
*
|
|
101
101
|
* Never throws: a misconfiguration is logged and the feature stays off, so a
|
|
@@ -117,15 +117,19 @@ function activateAgentGrants() {
|
|
|
117
117
|
if (!current.includes(OUR_IMPL)) {
|
|
118
118
|
// A host's own auth.impl is preserved as the delegate: the lane only adds
|
|
119
119
|
// the token path in front of it, it never replaces the host's gate.
|
|
120
|
+
// The absolute path: in plugin mode cds.root is the consumer app, which
|
|
121
|
+
// need not resolve this package's dependency.
|
|
120
122
|
const original = customAuthImpl(auth);
|
|
121
123
|
cds_1.default.env.requires.auth = {
|
|
122
124
|
...auth,
|
|
123
|
-
kind: auth.kind
|
|
124
|
-
impl:
|
|
125
|
-
|
|
126
|
-
...(original ? { agentGrantsDelegateImpl: original } : {})
|
|
125
|
+
kind: agentGrants.delegate === 'custom' ? auth.kind : agentGrants.delegate,
|
|
126
|
+
impl: require.resolve('@odatano/cap-auth'),
|
|
127
|
+
...(original ? { delegateImpl: original } : {})
|
|
127
128
|
};
|
|
128
129
|
}
|
|
130
|
+
const { registerTransportLane } = require('@odatano/cap-auth');
|
|
131
|
+
const { agentTokenLane } = require('./agent-token-auth');
|
|
132
|
+
registerTransportLane(agentTokenLane);
|
|
129
133
|
cds_1.default.on('serving', (srv) => {
|
|
130
134
|
const { AGENT_SERVICE_NAMES, attachAgentGrantEnforcement } = require('./agent-grants');
|
|
131
135
|
if (AGENT_SERVICE_NAMES.includes(srv.name))
|
|
@@ -1,106 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
|
|
9
|
-
*
|
|
10
|
-
* - runs every registered LANE first. The built-in lane admits a request that
|
|
11
|
-
* carries `x-agent-token` on one of the six ODATANO service paths (exact
|
|
12
|
-
* segment match, no lookalike prefixes): the token is authenticated HERE
|
|
13
|
-
* (unknown 401, expired 410, non-leaking) and the request continues as the
|
|
14
|
-
* principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
|
|
15
|
-
* rides on the express request (`req.agentGrant`) for the enforcement hook.
|
|
16
|
-
* Other packages (@odatano/x402) add lanes with `registerTransportLane`
|
|
17
|
-
* instead of fighting for the single `auth.impl` slot.
|
|
18
|
-
* - otherwise DELEGATES to CAP's own strategy for the configured kind
|
|
19
|
-
* (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
|
|
20
|
-
* for every request without a token is exactly what it was before.
|
|
21
|
-
*
|
|
22
|
-
* Failed token attempts are throttled per client address (20 per 15 minutes):
|
|
23
|
-
* one static hash lookup must not become an offline-speed guessing oracle.
|
|
2
|
+
* The `x-agent-token` transport lane for `@odatano/cap-auth`: a token on one
|
|
3
|
+
* of the ODATANO service paths is authenticated here (unknown 401, expired
|
|
4
|
+
* 410, non-leaking) and the request continues as `agent:<grantId>` with the
|
|
5
|
+
* role `agent-grant`; the grant rides on the express request for the
|
|
6
|
+
* enforcement hook. A token on any other path is left to the delegate.
|
|
7
|
+
* Failed attempts are throttled per client address (20 per 15 minutes).
|
|
24
8
|
*/
|
|
25
|
-
import
|
|
26
|
-
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
27
|
-
import { type AgentGrantRow } from './agent-grants';
|
|
28
|
-
type ExpressReq = IncomingMessage & {
|
|
29
|
-
headers: Record<string, string | string[] | undefined>;
|
|
30
|
-
originalUrl?: string;
|
|
31
|
-
baseUrl?: string;
|
|
32
|
-
path?: string;
|
|
33
|
-
ip?: string;
|
|
34
|
-
user?: unknown;
|
|
35
|
-
agentGrant?: AgentGrantRow;
|
|
36
|
-
};
|
|
37
|
-
type ExpressRes = ServerResponse & {
|
|
38
|
-
status?: (code: number) => ExpressRes;
|
|
39
|
-
set?: (name: string, value: string) => ExpressRes;
|
|
40
|
-
json?: (body: unknown) => void;
|
|
41
|
-
};
|
|
42
|
-
type Next = (err?: unknown) => void;
|
|
43
|
-
export type AuthMiddleware = (req: ExpressReq, res: ExpressRes, next: Next) => unknown;
|
|
44
|
-
/** What a lane's `authenticate` may answer. */
|
|
45
|
-
export type LaneOutcome =
|
|
46
|
-
/** The lane authenticated the request; continue as this principal. */
|
|
47
|
-
{
|
|
48
|
-
user: cds.User;
|
|
49
|
-
}
|
|
50
|
-
/** The lane already sent a response (401/410/429); stop here. */
|
|
51
|
-
| {
|
|
52
|
-
handled: true;
|
|
53
|
-
}
|
|
54
|
-
/** Not this lane's request after all; try the next lane, then the delegate. */
|
|
55
|
-
| null;
|
|
56
|
-
export interface TransportLane {
|
|
57
|
-
/** Unique name; registering the same name twice replaces the lane. */
|
|
58
|
-
name: string;
|
|
59
|
-
/** Cheap check on headers/path; no I/O. */
|
|
60
|
-
match: (req: ExpressReq) => boolean;
|
|
61
|
-
/** Authenticate; may respond itself. */
|
|
62
|
-
authenticate: (req: ExpressReq, res: ExpressRes) => Promise<LaneOutcome>;
|
|
63
|
-
}
|
|
64
|
-
/** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
|
|
65
|
-
export declare function registerTransportLane(lane: TransportLane): void;
|
|
66
|
-
/** Registered lane names, in order (tests, diagnostics). */
|
|
67
|
-
export declare function transportLanes(): string[];
|
|
68
|
-
/** Remove every lane except the built-in one (tests). */
|
|
69
|
-
export declare function __resetTransportLanesForTests(): void;
|
|
9
|
+
import { type TransportLane } from '@odatano/cap-auth';
|
|
70
10
|
/** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
|
|
71
11
|
export declare function __setAgentServicePathsForTests(paths: string[] | null): void;
|
|
12
|
+
/** Forget throttle state and the path cache (tests). */
|
|
13
|
+
export declare function __resetAgentTokenLaneForTests(): void;
|
|
72
14
|
/** Mount paths of the six services, read from `cds.services` once they are served. */
|
|
73
15
|
export declare function agentServicePaths(): string[];
|
|
74
16
|
/** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
|
|
75
17
|
export declare function inAgentLane(path: string, servicePaths?: string[]): boolean;
|
|
76
18
|
export declare const agentTokenLane: TransportLane;
|
|
77
|
-
interface AuthOptions {
|
|
78
|
-
kind?: string;
|
|
79
|
-
impl?: string;
|
|
80
|
-
/** Set by activateAgentGrants: the strategy that keeps authenticating non-token requests. */
|
|
81
|
-
agentGrantsDelegate?: string;
|
|
82
|
-
/**
|
|
83
|
-
* Set by activateAgentGrants when the host had its own `auth.impl` before us:
|
|
84
|
-
* that module (path as configured, resolved like CAP does it) is the delegate,
|
|
85
|
-
* whatever `kind` says. The host's gate keeps running for every non-token
|
|
86
|
-
* request, on every path.
|
|
87
|
-
*/
|
|
88
|
-
agentGrantsDelegateImpl?: string;
|
|
89
|
-
[key: string]: unknown;
|
|
90
|
-
}
|
|
91
|
-
/** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
|
|
92
|
-
/**
|
|
93
|
-
* Resolve a host-configured `auth.impl` the way CAP's auth factory does
|
|
94
|
-
* (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
|
|
95
|
-
* cds.root, else with a `./` prefix. Exported for the unit tests.
|
|
96
|
-
*/
|
|
97
|
-
export declare function resolveCustomImpl(impl: string, root?: string): string;
|
|
98
|
-
export declare function loadDelegate(options: AuthOptions, kind: string): AuthMiddleware;
|
|
99
|
-
export declare function createAgentTokenAuth(options: AuthOptions, delegate?: AuthMiddleware): AuthMiddleware;
|
|
100
|
-
/**
|
|
101
|
-
* CAP requires this module and, seeing a function with fewer than three
|
|
102
|
-
* parameters, calls it with the merged auth options to obtain the middleware.
|
|
103
|
-
*/
|
|
104
|
-
export default function agentTokenAuthFactory(options: AuthOptions): AuthMiddleware;
|
|
105
|
-
export {};
|
|
106
19
|
//# sourceMappingURL=agent-token-auth.d.ts.map
|
|
@@ -1,78 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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.
|
|
3
|
+
* The `x-agent-token` transport lane for `@odatano/cap-auth`: a token on one
|
|
4
|
+
* of the ODATANO service paths is authenticated here (unknown 401, expired
|
|
5
|
+
* 410, non-leaking) and the request continues as `agent:<grantId>` with the
|
|
6
|
+
* role `agent-grant`; the grant rides on the express request for the
|
|
7
|
+
* enforcement hook. A token on any other path is left to the delegate.
|
|
8
|
+
* Failed attempts are throttled per client address (20 per 15 minutes).
|
|
25
9
|
*/
|
|
26
10
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
27
11
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
28
12
|
};
|
|
29
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
14
|
exports.agentTokenLane = void 0;
|
|
31
|
-
exports.registerTransportLane = registerTransportLane;
|
|
32
|
-
exports.transportLanes = transportLanes;
|
|
33
|
-
exports.__resetTransportLanesForTests = __resetTransportLanesForTests;
|
|
34
15
|
exports.__setAgentServicePathsForTests = __setAgentServicePathsForTests;
|
|
16
|
+
exports.__resetAgentTokenLaneForTests = __resetAgentTokenLaneForTests;
|
|
35
17
|
exports.agentServicePaths = agentServicePaths;
|
|
36
18
|
exports.inAgentLane = inAgentLane;
|
|
37
|
-
exports.resolveCustomImpl = resolveCustomImpl;
|
|
38
|
-
exports.loadDelegate = loadDelegate;
|
|
39
|
-
exports.createAgentTokenAuth = createAgentTokenAuth;
|
|
40
|
-
exports.default = agentTokenAuthFactory;
|
|
41
19
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
20
|
+
const cap_auth_1 = require("@odatano/cap-auth");
|
|
42
21
|
const agent_grants_1 = require("./agent-grants");
|
|
43
22
|
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
23
|
const tokenFailures = new rate_limiter_1.RateLimiter({ windowMs: 15 * 60 * 1000, maxRequests: 20, maxKeys: 10_000 });
|
|
77
24
|
let servicePathsCache = null;
|
|
78
25
|
let servicePathsPinned = false;
|
|
@@ -81,6 +28,12 @@ function __setAgentServicePathsForTests(paths) {
|
|
|
81
28
|
servicePathsCache = paths;
|
|
82
29
|
servicePathsPinned = paths !== null;
|
|
83
30
|
}
|
|
31
|
+
/** Forget throttle state and the path cache (tests). */
|
|
32
|
+
function __resetAgentTokenLaneForTests() {
|
|
33
|
+
tokenFailures.reset();
|
|
34
|
+
servicePathsCache = null;
|
|
35
|
+
servicePathsPinned = false;
|
|
36
|
+
}
|
|
84
37
|
/** Mount paths of the six services, read from `cds.services` once they are served. */
|
|
85
38
|
function agentServicePaths() {
|
|
86
39
|
if (servicePathsPinned && servicePathsCache)
|
|
@@ -94,146 +47,35 @@ function agentServicePaths() {
|
|
|
94
47
|
servicePathsCache = paths;
|
|
95
48
|
return paths;
|
|
96
49
|
}
|
|
97
|
-
function requestPath(req) {
|
|
98
|
-
const raw = String(req.originalUrl || req.url || req.path || '');
|
|
99
|
-
return raw.split('?')[0];
|
|
100
|
-
}
|
|
101
50
|
/** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
|
|
102
51
|
function inAgentLane(path, servicePaths = agentServicePaths()) {
|
|
103
|
-
|
|
52
|
+
const bare = path.split('?')[0];
|
|
53
|
+
return servicePaths.some((p) => (0, cap_auth_1.inLaneOf)(bare, p));
|
|
104
54
|
}
|
|
105
55
|
function clientKey(req) {
|
|
106
56
|
const ip = req.ip ?? req.socket?.remoteAddress ?? 'unknown';
|
|
107
57
|
return `ip=${String(ip).replace(/:/g, '.')}:agent-token`;
|
|
108
58
|
}
|
|
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
59
|
exports.agentTokenLane = {
|
|
125
60
|
name: 'agent-token',
|
|
126
61
|
match: (req) => typeof req.headers?.[agent_grants_1.AGENT_TOKEN_HEADER] === 'string' && req.headers[agent_grants_1.AGENT_TOKEN_HEADER].length > 0,
|
|
127
62
|
authenticate: async (req, res) => {
|
|
128
63
|
const token = req.headers[agent_grants_1.AGENT_TOKEN_HEADER];
|
|
129
|
-
if (!inAgentLane(requestPath(req)))
|
|
130
|
-
|
|
131
|
-
// (and will 401 a request that carries nothing else).
|
|
132
|
-
return null;
|
|
133
|
-
}
|
|
64
|
+
if (!inAgentLane((0, cap_auth_1.requestPath)(req)))
|
|
65
|
+
return { next: true };
|
|
134
66
|
const key = clientKey(req);
|
|
135
67
|
const locked = tokenFailures.peek(key);
|
|
136
68
|
if (!locked.allowed)
|
|
137
|
-
return
|
|
69
|
+
return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
|
|
138
70
|
const resolution = await (0, agent_grants_1.resolveAgentToken)(token);
|
|
139
71
|
if (!resolution.ok) {
|
|
140
72
|
const failed = tokenFailures.check(key);
|
|
141
73
|
if (!failed.allowed)
|
|
142
|
-
return
|
|
143
|
-
return
|
|
74
|
+
return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
|
|
75
|
+
return (0, cap_auth_1.respondError)(res, resolution.status, resolution.message);
|
|
144
76
|
}
|
|
145
77
|
req.agentGrant = resolution.grant;
|
|
146
78
|
return { user: (0, agent_grants_1.makeAgentUser)(resolution.grant) };
|
|
147
79
|
},
|
|
148
80
|
};
|
|
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
81
|
//# sourceMappingURL=agent-token-auth.js.map
|