@odatano/core 2.0.0-rc.5 → 2.0.0-rc.6
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/@cds-models/CardanoAgentService/index.d.ts +107 -3
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +28 -0
- package/@cds-models/CardanoIndexerService/index.js +4 -0
- package/@cds-models/odatano/cardano/index.d.ts +36 -0
- package/@cds-models/odatano/cardano/index.js +3 -0
- package/README.md +23 -4
- package/db/schema.cds +33 -0
- package/package.json +3 -2
- package/src/index.d.ts +2 -2
- package/src/index.js +5 -1
- package/srv/blockchain/backends/ogmios-backend.d.ts +23 -3
- package/srv/blockchain/backends/ogmios-backend.js +72 -5
- package/srv/cardano-agent-service.cds +69 -3
- package/srv/cardano-indexer-service.cds +20 -0
- package/srv/cardano-indexer-service.js +3 -0
- package/srv/utils/agent-grants-config.d.ts +17 -1
- package/srv/utils/agent-grants-config.js +22 -2
- package/srv/utils/agent-grants.d.ts +111 -8
- package/srv/utils/agent-grants.js +342 -62
- package/srv/utils/liveness.d.ts +23 -0
- package/srv/utils/liveness.js +49 -0
|
@@ -15,10 +15,13 @@
|
|
|
15
15
|
* lastUsedAt. Ownership needs no special code: a token's jobs are created
|
|
16
16
|
* with createdBy = `agent:<grantId>`, so the existing `createdBy = $user`
|
|
17
17
|
* gates and the `$user.grantId` row restrictions do the narrowing.
|
|
18
|
-
* - `registerAgentGrantHandlers`:
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
18
|
+
* - `registerAgentGrantHandlers`: the grant lifecycle for CardanoAgentService
|
|
19
|
+
* (CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken /
|
|
20
|
+
* RevokeAgentGrant, GetGrantStatus / GetGrantUsage), on top of the
|
|
21
|
+
* programmatic `issueAgentGrant` / `updateAgentGrant` /
|
|
22
|
+
* `rotateAgentGrantToken` / `revokeAgentGrantById` that @odatano/x402 uses
|
|
23
|
+
* to sell grants. Names are this repo's PascalCase; semantics follow
|
|
24
|
+
* NIGHTGATE's so a gateway (ODATANO ACCESS) drives both with one code path.
|
|
22
25
|
*
|
|
23
26
|
* The token is a capability, not an identity: it never carries the operator's
|
|
24
27
|
* roles, so every `@requires: 'Admin'` surface refuses it by construction.
|
|
@@ -27,7 +30,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
27
30
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
28
31
|
};
|
|
29
32
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
-
exports.AgentGrantInputError = exports.AGENT_JOB_KINDS = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_WALLET_ACTIONS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_SERVICE_NAMES = exports.GRANTS_ENTITY = exports.AGENT_PRINCIPAL_PREFIX = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = void 0;
|
|
33
|
+
exports.USAGE_WINDOW_DEFAULT_MS = exports.USAGE_WINDOW_MAX_MS = exports.GRANT_IMMUTABLE_FIELDS = exports.AgentGrantInputError = exports.AGENT_JOB_KINDS = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_WALLET_ACTIONS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_SERVICE_NAMES = exports.GRANT_USAGE_ENTITY = exports.GRANTS_ENTITY = exports.AGENT_PRINCIPAL_PREFIX = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = void 0;
|
|
31
34
|
exports.__resetGrantRateLimiterForTests = __resetGrantRateLimiterForTests;
|
|
32
35
|
exports.hashAgentToken = hashAgentToken;
|
|
33
36
|
exports.agentPrincipalId = agentPrincipalId;
|
|
@@ -38,6 +41,10 @@ exports.makeAgentUser = makeAgentUser;
|
|
|
38
41
|
exports.validateGrantInput = validateGrantInput;
|
|
39
42
|
exports.issueAgentGrant = issueAgentGrant;
|
|
40
43
|
exports.revokeAgentGrantById = revokeAgentGrantById;
|
|
44
|
+
exports.rotateAgentGrantToken = rotateAgentGrantToken;
|
|
45
|
+
exports.updateAgentGrant = updateAgentGrant;
|
|
46
|
+
exports.resolveUsageWindow = resolveUsageWindow;
|
|
47
|
+
exports.getGrantUsage = getGrantUsage;
|
|
41
48
|
exports.toGrantStatus = toGrantStatus;
|
|
42
49
|
exports.registerAgentGrantHandlers = registerAgentGrantHandlers;
|
|
43
50
|
exports.attachAgentGrantEnforcement = attachAgentGrantEnforcement;
|
|
@@ -45,12 +52,15 @@ exports.budgetRunnerFor = budgetRunnerFor;
|
|
|
45
52
|
exports.enforceAgentGrant = enforceAgentGrant;
|
|
46
53
|
exports.consumeDailyBudget = consumeDailyBudget;
|
|
47
54
|
exports.refundDailyBudget = refundDailyBudget;
|
|
55
|
+
exports.recordGrantUsage = recordGrantUsage;
|
|
56
|
+
exports.refundGrantUsage = refundGrantUsage;
|
|
48
57
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
49
58
|
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
50
59
|
const tx_utils_1 = require("./tx-utils");
|
|
51
60
|
const rate_limiter_1 = require("./rate-limiter");
|
|
52
61
|
const errors_1 = require("./errors");
|
|
53
62
|
const error_codes_1 = require("./error-codes");
|
|
63
|
+
const agent_grants_config_1 = require("./agent-grants-config");
|
|
54
64
|
const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
|
|
55
65
|
const logger = cds_1.default.log('AgentGrants');
|
|
56
66
|
exports.AGENT_TOKEN_HEADER = 'x-agent-token';
|
|
@@ -61,6 +71,8 @@ exports.AGENT_ROLE = 'agent-grant';
|
|
|
61
71
|
/** `agent:<grantId>`: the principal id a token request runs under. */
|
|
62
72
|
exports.AGENT_PRINCIPAL_PREFIX = 'agent:';
|
|
63
73
|
exports.GRANTS_ENTITY = 'odatano.cardano.CardanoAgentGrants';
|
|
74
|
+
/** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
|
|
75
|
+
exports.GRANT_USAGE_ENTITY = 'odatano.cardano.CardanoAgentGrantUsage';
|
|
64
76
|
/** The services the hook attaches to and the transport lane opens. */
|
|
65
77
|
exports.AGENT_SERVICE_NAMES = [
|
|
66
78
|
'CardanoODataService',
|
|
@@ -115,18 +127,27 @@ exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
|
|
|
115
127
|
'GetBuildDetails', 'GetTransactionBuildsByAddress', 'DeriveScriptAddress', 'ExtractPaymentKeyHash',
|
|
116
128
|
// CardanoSignService: reads and stateless verification
|
|
117
129
|
'GetSigningRequest', 'GetSigningRequestsByAddress', 'VerifyDataSignature', 'GetHsmStatus',
|
|
118
|
-
// CardanoWorkerService / CardanoIndexerService: status
|
|
119
|
-
'GetJobStatus', 'GetWorkerStatus', 'getStatus',
|
|
120
|
-
// CardanoAgentService: the token's own grant
|
|
121
|
-
'GetGrantStatus',
|
|
130
|
+
// CardanoWorkerService / CardanoIndexerService: status and liveness
|
|
131
|
+
'GetJobStatus', 'GetWorkerStatus', 'getStatus', 'getLiveness',
|
|
132
|
+
// CardanoAgentService: the token's own grant (GetGrantUsage is narrowed to it in enforceAgentGrant)
|
|
133
|
+
'GetGrantStatus', 'GetGrantUsage',
|
|
122
134
|
]);
|
|
123
135
|
/** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
|
|
124
136
|
exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
|
|
125
|
-
/**
|
|
126
|
-
|
|
127
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Grant administration (Create / Update / Rotate / Revoke): N per principal per
|
|
139
|
+
* hour, N from `agentGrants.adminRateLimit` / `AGENT_GRANT_ADMIN_RATE_LIMIT`
|
|
140
|
+
* (default 10, NIGHTGATE's `NIGHTGATE_GRANT_ADMIN_RATE_LIMIT`). Built on first
|
|
141
|
+
* use so the knob is read once the config is loaded, and re-read after a reset.
|
|
142
|
+
*/
|
|
143
|
+
let grantAdminRateLimiter = null;
|
|
144
|
+
function grantAdminLimiter() {
|
|
145
|
+
grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, agent_grants_config_1.loadGrantAdminRateLimit)() });
|
|
146
|
+
return grantAdminRateLimiter;
|
|
147
|
+
}
|
|
148
|
+
/** Forget every rate-limit window and re-read the limit from the config (tests). */
|
|
128
149
|
function __resetGrantRateLimiterForTests() {
|
|
129
|
-
grantAdminRateLimiter
|
|
150
|
+
grantAdminRateLimiter = null;
|
|
130
151
|
lastUsedTouched.clear();
|
|
131
152
|
}
|
|
132
153
|
function dbRunner() {
|
|
@@ -200,60 +221,61 @@ function makeAgentUser(grant) {
|
|
|
200
221
|
}
|
|
201
222
|
/** A refused grant input; carries the 400 the action answers with. */
|
|
202
223
|
class AgentGrantInputError extends errors_1.BackendError {
|
|
203
|
-
constructor(message, target) {
|
|
204
|
-
super(
|
|
224
|
+
constructor(message, target, context = 'CreateAgentGrant') {
|
|
225
|
+
super(`${context}: ${message}`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, target);
|
|
205
226
|
}
|
|
206
227
|
}
|
|
207
228
|
exports.AgentGrantInputError = AgentGrantInputError;
|
|
208
|
-
function validateGrantInput(input, now = new Date()) {
|
|
229
|
+
function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant') {
|
|
230
|
+
const fail = (message, target) => new AgentGrantInputError(message, target, context);
|
|
209
231
|
const actions = input.allowedActions;
|
|
210
232
|
if (!Array.isArray(actions) || actions.length === 0) {
|
|
211
|
-
throw
|
|
233
|
+
throw fail('allowedActions must be a non-empty array', 'allowedActions');
|
|
212
234
|
}
|
|
213
235
|
const unknown = actions.filter((a) => !exports.AGENT_ALLOWLISTABLE_ACTIONS.includes(a));
|
|
214
236
|
if (unknown.length > 0) {
|
|
215
|
-
throw
|
|
237
|
+
throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${exports.AGENT_ALLOWLISTABLE_ACTIONS.join(', ')}`, 'allowedActions');
|
|
216
238
|
}
|
|
217
239
|
const uniqueActions = [...new Set(actions)];
|
|
218
240
|
const walletId = typeof input.walletId === 'string' && input.walletId.trim() ? input.walletId.trim() : null;
|
|
219
241
|
const wantsWallet = uniqueActions.some((a) => exports.AGENT_WALLET_ACTIONS.has(a));
|
|
220
242
|
if (wantsWallet && !walletId) {
|
|
221
|
-
throw
|
|
243
|
+
throw fail('walletId is required when SubmitWalletJob or CancelJob is allowed', 'walletId');
|
|
222
244
|
}
|
|
223
245
|
if (walletId && walletId.length > 50)
|
|
224
|
-
throw
|
|
246
|
+
throw fail('walletId must be at most 50 characters', 'walletId');
|
|
225
247
|
let allowedJobKinds = [];
|
|
226
248
|
if (input.allowedJobKinds !== undefined && input.allowedJobKinds !== null) {
|
|
227
249
|
if (!Array.isArray(input.allowedJobKinds))
|
|
228
|
-
throw
|
|
250
|
+
throw fail('allowedJobKinds must be an array', 'allowedJobKinds');
|
|
229
251
|
const badKinds = input.allowedJobKinds.filter((k) => !exports.AGENT_JOB_KINDS.includes(k));
|
|
230
252
|
if (badKinds.length > 0) {
|
|
231
|
-
throw
|
|
253
|
+
throw fail(`allowedJobKinds contains unknown kinds: ${badKinds.join(', ')}. Known: ${exports.AGENT_JOB_KINDS.join(', ')}`, 'allowedJobKinds');
|
|
232
254
|
}
|
|
233
255
|
allowedJobKinds = [...new Set(input.allowedJobKinds)];
|
|
234
256
|
if (allowedJobKinds.length > 0 && !wantsWallet) {
|
|
235
|
-
throw
|
|
257
|
+
throw fail('allowedJobKinds needs SubmitWalletJob in allowedActions', 'allowedJobKinds');
|
|
236
258
|
}
|
|
237
259
|
}
|
|
238
260
|
let maxJobsPerDay = null;
|
|
239
261
|
if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
|
|
240
262
|
const n = Number(input.maxJobsPerDay);
|
|
241
263
|
if (!Number.isInteger(n) || n < 1)
|
|
242
|
-
throw
|
|
264
|
+
throw fail('maxJobsPerDay must be a positive integer', 'maxJobsPerDay');
|
|
243
265
|
maxJobsPerDay = n;
|
|
244
266
|
}
|
|
245
267
|
let validUntil = null;
|
|
246
268
|
if (input.validUntil) {
|
|
247
269
|
const t = new Date(input.validUntil);
|
|
248
270
|
if (Number.isNaN(t.getTime()))
|
|
249
|
-
throw
|
|
271
|
+
throw fail('validUntil must be a valid ISO-8601 timestamp', 'validUntil');
|
|
250
272
|
if (t.getTime() <= now.getTime())
|
|
251
|
-
throw
|
|
273
|
+
throw fail('validUntil must be in the future', 'validUntil');
|
|
252
274
|
validUntil = t.toISOString();
|
|
253
275
|
}
|
|
254
276
|
const agentLabel = typeof input.agentLabel === 'string' && input.agentLabel.trim() ? input.agentLabel.trim() : null;
|
|
255
277
|
if (agentLabel && agentLabel.length > 100)
|
|
256
|
-
throw
|
|
278
|
+
throw fail('agentLabel must be at most 100 characters', 'agentLabel');
|
|
257
279
|
return { allowedActions: uniqueActions, walletId, allowedJobKinds, maxJobsPerDay, validUntil, agentLabel };
|
|
258
280
|
}
|
|
259
281
|
/**
|
|
@@ -311,6 +333,138 @@ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
|
|
|
311
333
|
logger.info(`agent grant ${grantId} revoked`);
|
|
312
334
|
return revoked;
|
|
313
335
|
}
|
|
336
|
+
/**
|
|
337
|
+
* Replace the grant's token; the old one is an unknown token from the next
|
|
338
|
+
* request (the lane reads tokenHash per request, so nothing needs invalidating;
|
|
339
|
+
* a request in flight with the old token completes). Budget, wallet, allow
|
|
340
|
+
* list and expiry survive. Null when the grant does not exist or is revoked.
|
|
341
|
+
*/
|
|
342
|
+
async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
|
|
343
|
+
if (!grantId)
|
|
344
|
+
return null;
|
|
345
|
+
const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
|
|
346
|
+
const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set({ tokenHash: hashAgentToken(token) }).where({ ID: grantId, isActive: true }));
|
|
347
|
+
if (Number(affected) === 0)
|
|
348
|
+
return null;
|
|
349
|
+
logger.info(`agent grant ${grantId} token rotated`);
|
|
350
|
+
return { grantId, token };
|
|
351
|
+
}
|
|
352
|
+
/** Row fields a grant edit never touches; a different wallet binding is a different grant (NIGHTGATE: sessionId). */
|
|
353
|
+
exports.GRANT_IMMUTABLE_FIELDS = ['walletId', 'userId', 'tokenHash'];
|
|
354
|
+
const GRANT_EDITABLE_FIELDS = [
|
|
355
|
+
'agentLabel', 'allowedActions', 'allowedJobKinds', 'maxJobsPerDay', 'validUntil',
|
|
356
|
+
];
|
|
357
|
+
/**
|
|
358
|
+
* Change the given fields of an ACTIVE grant. A field absent from `input`
|
|
359
|
+
* keeps its value; an explicit null clears agentLabel, allowedJobKinds,
|
|
360
|
+
* maxJobsPerDay or validUntil (NIGHTGATE's updateAgentGrant semantics).
|
|
361
|
+
* allowedActions cannot be emptied. The merged row goes through
|
|
362
|
+
* validateGrantInput, so the cross-field rules hold: wallet actions need the
|
|
363
|
+
* grant's (immutable) wallet, job kinds need SubmitWalletJob, a given
|
|
364
|
+
* validUntil lies in the future. Lowering maxJobsPerDay below jobsUsedToday is
|
|
365
|
+
* allowed; the grant is simply over budget until the UTC day rolls.
|
|
366
|
+
*
|
|
367
|
+
* Validation errors surface as AgentGrantInputError (400); an unknown grant is
|
|
368
|
+
* 404 and a revoked one 409 GRANT_REVOKED (revoked grants are never edited;
|
|
369
|
+
* re-mint instead).
|
|
370
|
+
*/
|
|
371
|
+
async function updateAgentGrant(grantId, input, runner = dbRunner()) {
|
|
372
|
+
const has = (k) => Object.prototype.hasOwnProperty.call(input, k);
|
|
373
|
+
const existing = (await runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grantId })));
|
|
374
|
+
if (!existing)
|
|
375
|
+
return { ok: false, status: 404, message: 'Grant not found' };
|
|
376
|
+
if (existing.isActive === false)
|
|
377
|
+
return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
|
|
378
|
+
// The merged row. validUntil only when given: an untouched expiry that has
|
|
379
|
+
// meanwhile passed is the lane's 410, not this edit's 400.
|
|
380
|
+
const n = validateGrantInput({
|
|
381
|
+
allowedActions: has('allowedActions') ? input.allowedActions : parseGrantList(existing.allowedActions),
|
|
382
|
+
walletId: existing.walletId ?? null,
|
|
383
|
+
allowedJobKinds: has('allowedJobKinds') ? input.allowedJobKinds : parseGrantList(existing.allowedJobKinds),
|
|
384
|
+
maxJobsPerDay: has('maxJobsPerDay') ? input.maxJobsPerDay : existing.maxJobsPerDay,
|
|
385
|
+
validUntil: has('validUntil') ? input.validUntil : null,
|
|
386
|
+
agentLabel: has('agentLabel') ? input.agentLabel : existing.agentLabel,
|
|
387
|
+
}, new Date(), 'UpdateAgentGrant');
|
|
388
|
+
const patch = {};
|
|
389
|
+
if (has('allowedActions'))
|
|
390
|
+
patch.allowedActions = JSON.stringify(n.allowedActions);
|
|
391
|
+
if (has('allowedJobKinds'))
|
|
392
|
+
patch.allowedJobKinds = n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null;
|
|
393
|
+
if (has('maxJobsPerDay'))
|
|
394
|
+
patch.maxJobsPerDay = n.maxJobsPerDay;
|
|
395
|
+
if (has('validUntil'))
|
|
396
|
+
patch.validUntil = n.validUntil;
|
|
397
|
+
if (has('agentLabel'))
|
|
398
|
+
patch.agentLabel = n.agentLabel;
|
|
399
|
+
const updated = GRANT_EDITABLE_FIELDS.filter((f) => has(f));
|
|
400
|
+
if (updated.length === 0)
|
|
401
|
+
return { ok: true, grantId, updated: [] };
|
|
402
|
+
// Conditional on isActive: a concurrent revoke wins over the edit.
|
|
403
|
+
const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
|
|
404
|
+
if (Number(affected) === 0)
|
|
405
|
+
return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
|
|
406
|
+
logger.info(`agent grant ${grantId} updated (${updated.join(', ')})`);
|
|
407
|
+
return { ok: true, grantId, updated };
|
|
408
|
+
}
|
|
409
|
+
// ---------------------------------------------------------------------------
|
|
410
|
+
// Usage history (GetGrantUsage)
|
|
411
|
+
// ---------------------------------------------------------------------------
|
|
412
|
+
exports.USAGE_WINDOW_MAX_MS = 366 * 24 * 60 * 60 * 1000;
|
|
413
|
+
exports.USAGE_WINDOW_DEFAULT_MS = 30 * 24 * 60 * 60 * 1000;
|
|
414
|
+
/** ISO timestamp or undefined; `null` when the value does not parse. */
|
|
415
|
+
function parseTimestamp(raw) {
|
|
416
|
+
if (raw === undefined || raw === null || raw === '')
|
|
417
|
+
return undefined;
|
|
418
|
+
const t = new Date(String(raw));
|
|
419
|
+
return Number.isNaN(t.getTime()) ? null : t.toISOString();
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* since (default until - 30 days) .. until (default now), at most 366 days
|
|
423
|
+
* (NIGHTGATE's rules and wording). Counters are per UTC day, so the days both
|
|
424
|
+
* ends fall on are included whole.
|
|
425
|
+
*/
|
|
426
|
+
function resolveUsageWindow(since, until, now = new Date()) {
|
|
427
|
+
const to = parseTimestamp(until);
|
|
428
|
+
const from = parseTimestamp(since);
|
|
429
|
+
if (to === null)
|
|
430
|
+
return { ok: false, message: 'until must be a valid ISO-8601 timestamp', target: 'until' };
|
|
431
|
+
if (from === null)
|
|
432
|
+
return { ok: false, message: 'since must be a valid ISO-8601 timestamp', target: 'since' };
|
|
433
|
+
const toMs = to ? new Date(to).getTime() : now.getTime();
|
|
434
|
+
const fromMs = from ? new Date(from).getTime() : toMs - exports.USAGE_WINDOW_DEFAULT_MS;
|
|
435
|
+
if (fromMs > toMs)
|
|
436
|
+
return { ok: false, message: 'since must not lie after until', target: 'since' };
|
|
437
|
+
if (toMs - fromMs > exports.USAGE_WINDOW_MAX_MS)
|
|
438
|
+
return { ok: false, message: 'the window may span at most 366 days', target: 'since' };
|
|
439
|
+
const sinceIso = new Date(fromMs).toISOString();
|
|
440
|
+
const untilIso = new Date(toMs).toISOString();
|
|
441
|
+
return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
|
|
442
|
+
}
|
|
443
|
+
/** The grant's admitted calls in `window`, grouped by service and action (one SUM per group). */
|
|
444
|
+
async function getGrantUsage(grant, window, runner = dbRunner()) {
|
|
445
|
+
const rows = ((await runner.run(SELECT.from(exports.GRANT_USAGE_ENTITY)
|
|
446
|
+
.columns('service', 'action', { func: 'sum', args: [{ ref: ['calls'] }], as: 'calls' }, { func: 'sum', args: [{ ref: ['refunded'] }], as: 'refunded' })
|
|
447
|
+
.where({ grant_ID: grant.ID, day: { '>=': window.sinceDay } })
|
|
448
|
+
.and({ day: { '<=': window.untilDay } })
|
|
449
|
+
.groupBy('service', 'action'))) ?? []);
|
|
450
|
+
const calls = rows
|
|
451
|
+
.map((r) => {
|
|
452
|
+
const admitted = Number(r.calls ?? 0);
|
|
453
|
+
const refunded = Number(r.refunded ?? 0);
|
|
454
|
+
return { service: String(r.service ?? ''), action: String(r.action ?? ''), count: Math.max(admitted - refunded, 0), refunded };
|
|
455
|
+
})
|
|
456
|
+
.sort((a, b) => a.service.localeCompare(b.service) || a.action.localeCompare(b.action));
|
|
457
|
+
const status = toGrantStatus(grant);
|
|
458
|
+
return {
|
|
459
|
+
grantId: grant.ID,
|
|
460
|
+
since: window.since,
|
|
461
|
+
until: window.until,
|
|
462
|
+
calls,
|
|
463
|
+
total: calls.reduce((sum, c) => sum + c.count, 0),
|
|
464
|
+
jobsUsedToday: status.jobsUsedToday,
|
|
465
|
+
maxJobsPerDay: status.maxJobsPerDay,
|
|
466
|
+
};
|
|
467
|
+
}
|
|
314
468
|
function toGrantStatus(grant) {
|
|
315
469
|
return {
|
|
316
470
|
grantId: grant.ID,
|
|
@@ -329,20 +483,39 @@ function toGrantStatus(grant) {
|
|
|
329
483
|
// ---------------------------------------------------------------------------
|
|
330
484
|
// CardanoAgentService handlers
|
|
331
485
|
// ---------------------------------------------------------------------------
|
|
486
|
+
/**
|
|
487
|
+
* The common prelude of the four administration actions: the rate limit first
|
|
488
|
+
* (refusals consume the window, like NIGHTGATE), then the token principal
|
|
489
|
+
* (belt and braces: none of these is always-allowed or allow-listable, so the
|
|
490
|
+
* hook 403s, and @requires: 'Admin' refuses the role-less principal anyway),
|
|
491
|
+
* then authentication. False after a reject.
|
|
492
|
+
*/
|
|
493
|
+
function checkGrantAdmin(req, verb) {
|
|
494
|
+
const rate = grantAdminLimiter().check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
|
|
495
|
+
if (!rate.allowed) {
|
|
496
|
+
req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
|
|
497
|
+
return false;
|
|
498
|
+
}
|
|
499
|
+
if (agentGrantOf(req)) {
|
|
500
|
+
req.reject(403, `an agent grant cannot ${verb} grants`);
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
if (!req.user?.id) {
|
|
504
|
+
req.reject(401, 'authentication required');
|
|
505
|
+
return false;
|
|
506
|
+
}
|
|
507
|
+
return true;
|
|
508
|
+
}
|
|
509
|
+
function userIs(req, role) {
|
|
510
|
+
const user = req.user;
|
|
511
|
+
return typeof user?.is === 'function' ? user.is(role) === true : false;
|
|
512
|
+
}
|
|
332
513
|
/** Validation rejections are thrown BEFORE any transaction work (project convention). */
|
|
333
514
|
function registerAgentGrantHandlers(srv) {
|
|
334
515
|
srv.on('CreateAgentGrant', async (req) => {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
if (agentGrantOf(req))
|
|
339
|
-
return req.reject(403, 'an agent grant cannot issue grants');
|
|
340
|
-
const operatorId = req.user?.id;
|
|
341
|
-
if (!operatorId)
|
|
342
|
-
return req.reject(401, 'authentication required');
|
|
343
|
-
const rate = grantAdminRateLimiter.check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
|
|
344
|
-
if (!rate.allowed)
|
|
345
|
-
return req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
|
|
516
|
+
if (!checkGrantAdmin(req, 'issue'))
|
|
517
|
+
return;
|
|
518
|
+
const operatorId = String(req.user.id);
|
|
346
519
|
const data = (req.data ?? {});
|
|
347
520
|
let normalized;
|
|
348
521
|
try {
|
|
@@ -365,8 +538,8 @@ function registerAgentGrantHandlers(srv) {
|
|
|
365
538
|
};
|
|
366
539
|
});
|
|
367
540
|
srv.on('RevokeAgentGrant', async (req) => {
|
|
368
|
-
if (
|
|
369
|
-
return
|
|
541
|
+
if (!checkGrantAdmin(req, 'revoke'))
|
|
542
|
+
return;
|
|
370
543
|
const { grantId } = (req.data ?? {});
|
|
371
544
|
if (!grantId)
|
|
372
545
|
return req.reject(400, 'grantId is required', 'grantId');
|
|
@@ -375,6 +548,43 @@ function registerAgentGrantHandlers(srv) {
|
|
|
375
548
|
return req.reject(404, 'Grant not found or already revoked', 'grantId');
|
|
376
549
|
return true;
|
|
377
550
|
});
|
|
551
|
+
srv.on('RotateAgentGrantToken', async (req) => {
|
|
552
|
+
if (!checkGrantAdmin(req, 'rotate'))
|
|
553
|
+
return;
|
|
554
|
+
const { grantId } = (req.data ?? {});
|
|
555
|
+
if (!grantId)
|
|
556
|
+
return req.reject(400, 'grantId is required', 'grantId');
|
|
557
|
+
const rotated = await rotateAgentGrantToken(grantId, cds_1.default.tx(req));
|
|
558
|
+
if (!rotated)
|
|
559
|
+
return req.reject(404, 'Grant not found or already revoked', 'grantId');
|
|
560
|
+
return rotated;
|
|
561
|
+
});
|
|
562
|
+
srv.on('UpdateAgentGrant', async (req) => {
|
|
563
|
+
if (!checkGrantAdmin(req, 'update'))
|
|
564
|
+
return;
|
|
565
|
+
const data = (req.data ?? {});
|
|
566
|
+
if (!data.grantId)
|
|
567
|
+
return req.reject(400, 'grantId is required', 'grantId');
|
|
568
|
+
const immutable = exports.GRANT_IMMUTABLE_FIELDS.filter((f) => Object.prototype.hasOwnProperty.call(data, f));
|
|
569
|
+
if (immutable.length > 0) {
|
|
570
|
+
return req.reject(400, `${immutable.join(', ')} cannot be changed; issue a new grant for a different binding`, immutable[0]);
|
|
571
|
+
}
|
|
572
|
+
let result;
|
|
573
|
+
try {
|
|
574
|
+
result = await updateAgentGrant(data.grantId, data, cds_1.default.tx(req));
|
|
575
|
+
}
|
|
576
|
+
catch (err) {
|
|
577
|
+
if (err instanceof errors_1.BackendError)
|
|
578
|
+
return req.reject(err.statusCode, err.message, err.target);
|
|
579
|
+
throw err;
|
|
580
|
+
}
|
|
581
|
+
if (!result.ok) {
|
|
582
|
+
if (result.code)
|
|
583
|
+
return req.reject({ status: result.status, code: result.code, message: result.message });
|
|
584
|
+
return req.reject(result.status, result.message, 'grantId');
|
|
585
|
+
}
|
|
586
|
+
return { grantId: result.grantId, updated: result.updated };
|
|
587
|
+
});
|
|
378
588
|
// GetGrantStatus: the calling token's own grant, read fresh so the budget
|
|
379
589
|
// counter is current. An operator without a token lists AgentGrants instead.
|
|
380
590
|
srv.on('GetGrantStatus', async (req) => {
|
|
@@ -384,12 +594,33 @@ function registerAgentGrantHandlers(srv) {
|
|
|
384
594
|
const fresh = (await cds_1.default.tx(req).run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grant.ID })));
|
|
385
595
|
return toGrantStatus(fresh ?? grant);
|
|
386
596
|
});
|
|
597
|
+
// GetGrantUsage: an Admin sees any grant (revoked ones keep their history), a
|
|
598
|
+
// token only its own — the hook already narrowed it (404, non-leaking).
|
|
599
|
+
srv.on('GetGrantUsage', async (req) => {
|
|
600
|
+
const data = (req.data ?? {});
|
|
601
|
+
if (!data.grantId)
|
|
602
|
+
return req.reject(400, 'grantId is required', 'grantId');
|
|
603
|
+
const window = resolveUsageWindow(data.since, data.until);
|
|
604
|
+
if (!window.ok)
|
|
605
|
+
return req.reject(400, window.message, window.target);
|
|
606
|
+
const own = agentGrantOf(req);
|
|
607
|
+
if (own && own.ID !== data.grantId)
|
|
608
|
+
return req.reject(404, 'Grant not found', 'grantId');
|
|
609
|
+
if (!own && !userIs(req, 'Admin'))
|
|
610
|
+
return req.reject(403, "GetGrantUsage needs Admin or the grant's own token");
|
|
611
|
+
const tx = cds_1.default.tx(req);
|
|
612
|
+
const grant = (await tx.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: data.grantId })));
|
|
613
|
+
if (!grant)
|
|
614
|
+
return req.reject(404, 'Grant not found', 'grantId');
|
|
615
|
+
return getGrantUsage(grant, window, tx);
|
|
616
|
+
});
|
|
387
617
|
}
|
|
388
618
|
// ---------------------------------------------------------------------------
|
|
389
619
|
// Enforcement (before('*') on the six services)
|
|
390
620
|
// ---------------------------------------------------------------------------
|
|
391
621
|
function attachAgentGrantEnforcement(srv, runner) {
|
|
392
|
-
|
|
622
|
+
const serviceName = String(srv.name ?? 'unknown');
|
|
623
|
+
srv.before('*', (req) => enforceAgentGrant(req, runner, undefined, serviceName));
|
|
393
624
|
}
|
|
394
625
|
function budgetRunnerFor(req, injected, detached) {
|
|
395
626
|
if (injected)
|
|
@@ -413,7 +644,7 @@ async function runStmt(br, statement) {
|
|
|
413
644
|
* principals pass through untouched: this hook is a no-op without a grant.
|
|
414
645
|
* `runner` / `detached` are test seams; production picks them per request.
|
|
415
646
|
*/
|
|
416
|
-
async function enforceAgentGrant(req, runner, detached) {
|
|
647
|
+
async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
|
|
417
648
|
const grant = agentGrantOf(req);
|
|
418
649
|
if (!grant)
|
|
419
650
|
return;
|
|
@@ -426,6 +657,13 @@ async function enforceAgentGrant(req, runner, detached) {
|
|
|
426
657
|
const br = budgetRunnerFor(req, runner, detached);
|
|
427
658
|
const event = String(req.event ?? '');
|
|
428
659
|
if (exports.AGENT_ALWAYS_ALLOWED_EVENTS.has(event)) {
|
|
660
|
+
// The handler's Admin gate alone would answer for every grant: a token sees
|
|
661
|
+
// its own usage only, and a foreign id is not found (non-leaking, NIGHTGATE).
|
|
662
|
+
if (event === 'GetGrantUsage') {
|
|
663
|
+
const asked = String(req.data?.grantId ?? '');
|
|
664
|
+
if (asked !== grant.ID)
|
|
665
|
+
return req.reject(404, 'Grant not found', 'grantId');
|
|
666
|
+
}
|
|
429
667
|
await touchLastUsed(grant, br);
|
|
430
668
|
return;
|
|
431
669
|
}
|
|
@@ -453,31 +691,38 @@ async function enforceAgentGrant(req, runner, detached) {
|
|
|
453
691
|
// in the worker service, so a foreign job is a 404 there already.
|
|
454
692
|
}
|
|
455
693
|
}
|
|
694
|
+
let charge = null;
|
|
456
695
|
if (grant.maxJobsPerDay !== undefined && grant.maxJobsPerDay !== null) {
|
|
457
|
-
|
|
696
|
+
charge = await consumeDailyBudget(br, grant);
|
|
458
697
|
if (!charge.consumed) {
|
|
459
698
|
return req.reject(429, `agent grant daily budget exhausted (${grant.maxJobsPerDay}/day)`);
|
|
460
699
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
700
|
+
}
|
|
701
|
+
// Admitted: one usage unit on (grant, day, service, action), budgeted or not.
|
|
702
|
+
const usageDay = await recordGrantUsage(br, grant, serviceName, event);
|
|
703
|
+
// Detached writes: a request the handler refuses as invalid (400..428)
|
|
704
|
+
// admitted nothing, so give the budget unit back — in the window it was
|
|
705
|
+
// charged to, not in whatever day it is when the refund runs — and mark the
|
|
706
|
+
// usage unit refunded. 429 and every 5xx keep both (over-count, never
|
|
707
|
+
// under-count). Writes made inside the request's own transaction need none
|
|
708
|
+
// of this: its rollback undoes them.
|
|
709
|
+
if (br.detached) {
|
|
710
|
+
const chargedWindow = charge?.window ?? null;
|
|
711
|
+
req.on?.('failed', (err) => {
|
|
712
|
+
const e = err;
|
|
713
|
+
const status = Number(e?.status ?? e?.statusCode ?? e?.code);
|
|
714
|
+
if (Number.isInteger(status) && status >= 400 && status < 429) {
|
|
715
|
+
// Off the failing request's tick: its transaction is still rolling
|
|
716
|
+
// back when 'failed' fires, and a write on a second connection at
|
|
717
|
+
// that moment is the SQLite lock contention this module must never cause.
|
|
718
|
+
setImmediate(() => {
|
|
719
|
+
if (chargedWindow) {
|
|
476
720
|
void refundDailyBudget(br, grant, chargedWindow).catch((refundErr) => logger.warn(`daily budget refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
721
|
+
}
|
|
722
|
+
void refundGrantUsage(br, grant, serviceName, event, usageDay).catch((refundErr) => logger.warn(`usage refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
});
|
|
481
726
|
}
|
|
482
727
|
await touchLastUsed(grant, br);
|
|
483
728
|
}
|
|
@@ -515,6 +760,41 @@ async function refundDailyBudget(br, grant, window) {
|
|
|
515
760
|
.set({ jobsUsedToday: { '-=': 1 } })
|
|
516
761
|
.where({ ID: grant.ID, budgetWindow: window, jobsUsedToday: { '>': 0 } }));
|
|
517
762
|
}
|
|
763
|
+
/**
|
|
764
|
+
* One admitted call: `calls + 1` on (grant, UTC day, service, action). A
|
|
765
|
+
* conditional UPDATE first (the common path), an INSERT when the row does not
|
|
766
|
+
* exist yet, one more UPDATE when a racing request inserted it first. Runs on
|
|
767
|
+
* the hook's BudgetRunner and is AWAITED like every other write of the hook
|
|
768
|
+
* (see touchLastUsed), but never fails the request: usage is accounting, not
|
|
769
|
+
* admission. Returns the day the call was counted on (the refund names it).
|
|
770
|
+
*/
|
|
771
|
+
async function recordGrantUsage(br, grant, service, action, now = new Date()) {
|
|
772
|
+
const runner = 'runner' in br ? br : { runner: br, detached: true };
|
|
773
|
+
const day = utcDay(now);
|
|
774
|
+
const key = { grant_ID: grant.ID, day, service, action };
|
|
775
|
+
const bump = () => runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': 1 } }).where(key));
|
|
776
|
+
try {
|
|
777
|
+
if (Number(await bump()) > 0)
|
|
778
|
+
return day;
|
|
779
|
+
try {
|
|
780
|
+
await runStmt(runner, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: 1, refunded: 0 }));
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
await bump(); // lost the insert race: the row exists now
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
catch (err) {
|
|
787
|
+
logger.warn(`usage record for grant ${grant.ID} (${service}.${action}) failed: ${String(err?.message ?? err)}`);
|
|
788
|
+
}
|
|
789
|
+
return day;
|
|
790
|
+
}
|
|
791
|
+
/** `refunded + 1` on the row the call was counted on: a refused request admitted nothing. */
|
|
792
|
+
async function refundGrantUsage(br, grant, service, action, day) {
|
|
793
|
+
const runner = 'runner' in br ? br : { runner: br, detached: true };
|
|
794
|
+
await runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY)
|
|
795
|
+
.set({ refunded: { '+=': 1 } })
|
|
796
|
+
.where({ grant_ID: grant.ID, day, service, action }));
|
|
797
|
+
}
|
|
518
798
|
/**
|
|
519
799
|
* lastUsedAt, at most once a minute per grant. AWAITED, like the budget
|
|
520
800
|
* statements: every write this hook makes must be finished before the handler
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Liveness body for CardanoIndexerService.getLiveness() (unauthenticated,
|
|
3
|
+
* `@requires: 'any'`): process facts only. Never touches the app context, the
|
|
4
|
+
* backends or the DB, so it answers while those are still initializing or have
|
|
5
|
+
* failed — that is what a liveness probe is for; readiness stays with
|
|
6
|
+
* getStatus and the backend health entities, which remain authenticated.
|
|
7
|
+
*
|
|
8
|
+
* No secrets, no backend names, no API key state. Mirrors NIGHTGATE's
|
|
9
|
+
* `/api/v1/indexer/getLiveness()` (status 'alive', timestamp, uptime), plus the
|
|
10
|
+
* package version and the configured network.
|
|
11
|
+
*/
|
|
12
|
+
export interface Liveness {
|
|
13
|
+
status: 'alive';
|
|
14
|
+
timestamp: string;
|
|
15
|
+
/** Seconds since the process started. */
|
|
16
|
+
uptime: number;
|
|
17
|
+
/** @odatano/core version; '' when package.json is not where the in-place build puts it. */
|
|
18
|
+
version: string;
|
|
19
|
+
/** Configured network (cds.requires.odatano-core.network, NETWORK, default preview). */
|
|
20
|
+
network: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function buildLiveness(now?: Date): Liveness;
|
|
23
|
+
//# sourceMappingURL=liveness.d.ts.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Liveness body for CardanoIndexerService.getLiveness() (unauthenticated,
|
|
4
|
+
* `@requires: 'any'`): process facts only. Never touches the app context, the
|
|
5
|
+
* backends or the DB, so it answers while those are still initializing or have
|
|
6
|
+
* failed — that is what a liveness probe is for; readiness stays with
|
|
7
|
+
* getStatus and the backend health entities, which remain authenticated.
|
|
8
|
+
*
|
|
9
|
+
* No secrets, no backend names, no API key state. Mirrors NIGHTGATE's
|
|
10
|
+
* `/api/v1/indexer/getLiveness()` (status 'alive', timestamp, uptime), plus the
|
|
11
|
+
* package version and the configured network.
|
|
12
|
+
*/
|
|
13
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.buildLiveness = buildLiveness;
|
|
18
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
19
|
+
const path_1 = __importDefault(require("path"));
|
|
20
|
+
const processStartedAt = Date.now();
|
|
21
|
+
let cachedVersion = null;
|
|
22
|
+
function packageVersion() {
|
|
23
|
+
if (cachedVersion !== null)
|
|
24
|
+
return cachedVersion;
|
|
25
|
+
try {
|
|
26
|
+
// srv/utils → package root; the build compiles in place, so this holds in
|
|
27
|
+
// standalone and plugin mode alike.
|
|
28
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
29
|
+
const pkg = require(path_1.default.resolve(__dirname, '..', '..', 'package.json'));
|
|
30
|
+
cachedVersion = String(pkg.version ?? '');
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
cachedVersion = '';
|
|
34
|
+
}
|
|
35
|
+
return cachedVersion;
|
|
36
|
+
}
|
|
37
|
+
function buildLiveness(now = new Date()) {
|
|
38
|
+
const requires = (cds_1.default.env?.requires ?? {});
|
|
39
|
+
const core = (requires['odatano-core'] ?? {});
|
|
40
|
+
const network = String(core.network || process.env.NETWORK || 'preview');
|
|
41
|
+
return {
|
|
42
|
+
status: 'alive',
|
|
43
|
+
timestamp: now.toISOString(),
|
|
44
|
+
uptime: Math.max(0, Math.floor((now.getTime() - processStartedAt) / 1000)),
|
|
45
|
+
version: packageVersion(),
|
|
46
|
+
network,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=liveness.js.map
|