@canopy-io/node 0.15.0 → 0.17.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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.17.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3b4bc7f: Generated types follow the API as Canopy now publishes it. The spec has 199 operations.
8
+
9
+ - Access previews are stored: the node move and delete, role permission and organization node previews answer an `id` and `expires_at` with their counts and no longer carry `people`. The people are read from `GET /api/v1/access-previews/{previewId}/people`, or as CSV from `.../people.csv`, by the principal that made the preview. Code that read `people` from a preview's type reads the new route instead.
10
+ - Identities can be created with a password hash: `password_hash` and `password_hash_algorithm` on create and bulk create. The request schemas are now `ApiCreateIdentityDto` and `ApiBulkCreateIdentitiesDto` in `components["schemas"]`, so a reference to `CreateIdentityDto` or `BulkCreateIdentitiesDto` takes the new name.
11
+ - 5de853f: Webhooks reach the `LocalAuthorizer` cache, so a revocation lands on the next local check instead of waiting out `ttlMs`.
12
+
13
+ - `verifyWebhookSignature({ headers, rawBody, secret })` checks a delivery's `X-Canopy-Signature`: HMAC-SHA256 over `{id}.{timestamp}.{raw body}`, compared in constant time on Web Crypto, so it runs in edge workers as well as Node. It accepts either signature while a rotation's window is open, takes several secrets while you roll one out, and refuses a timestamp more than five minutes from the clock (`toleranceSeconds`). It resolves `false`, never rejects.
14
+ - `authorizer.applyEvent(delivery)` drops what a webhook delivery or change-feed entry makes stale and answers what it dropped: the subjects an assignment, membership, identity-status, single-person deny or machine-client change names; everything for a role, permission, node, schema, organization creation or deletion, role deny or directory group mapping; nothing for a change that moves no one's access. An event this version does not know drops everything.
15
+ - `authorizer.replayChanges({ cursor })` reads `GET /api/v1/changes` to the newest change, applies each, and answers the cursor to resume from: for catching up after a restart, or polled on every instance in place of webhooks.
16
+ - `invalidate` now also discards a read already in flight, so a check that began before a change cannot put the access it revoked back in the cache for a whole window.
17
+
18
+ ## 0.16.0
19
+
20
+ ### Minor Changes
21
+
22
+ - 7d31f2f: `LocalAuthorizer` understands authorization model version 2, which Canopy answers in an Environment that holds a deny. A deny refuses a permission to an identity, a machine client or a role's holders at a node and everything beneath it, whatever the grants allow. The grants read carries the subject's deny roots beside its grant roots, already resolved by Canopy (the roles it holds, the exception roles that spare it), and the authorizer applies them from the same cache and TTL:
23
+
24
+ - `evaluate` refuses with the new reason `denied` when a deny root for the permission is at the node or above it, before any grant is looked at. An `app_wide` check holds while one grant in effect stands clear of every deny, and is `denied` when none does. A check on a permission with a deny reads the tree even for a grant at the node itself.
25
+ - `grantRoots` and `accessibleNodes` leave out a root a deny refuses and name `excludedRoots`, the deny roots beneath a root, each cutting out its subtree. `accessibleNodes` leaves those subtrees out of `nodes`, and `envWide` is false while anything is excluded. A filter by roots must exclude `excludedRoots` too.
26
+ - `holdsAnywhereUnder` answers `{ held, roots, excludedRoots }`; a deny at the subtree's root or above it refuses the whole subtree.
27
+ - `permissionsAt` and `permissionsAtMany` leave out a permission a deny refuses at the node.
28
+
29
+ `LocalDenialReason` gains `denied`, so an exhaustive `switch` over it needs the new case. A version 1 answer, from a Canopy without denies, carries none and is read as before. The conformance bundle gains the `denies` vector, which the authorizer answers, and is published at model version 2.
30
+
31
+ The spec now has 197 operations. Generated types cover the Denies routes (`/api/v1/denies`: list, get, create, preview, reach, remove), unwrapped like the other management routes, `deny_id` on an evaluation refused by a deny, and the reads and previews released beside them.
32
+
3
33
  ## 0.15.0
4
34
 
5
35
  ### Minor Changes
package/README.md CHANGED
@@ -26,6 +26,7 @@ Despite the name, it is not Node-only: the client is `fetch` and nothing else, s
26
26
  - **Typed errors.** `CanopyError` carries a stable `code`, `CanopyConnectionError` marks a transport failure, `CanopyTokenError` a rejected token, `CanopyAuthorizerError` a check that could not be decided — each with a type guard.
27
27
  - **Local access-token verification.** `TokenVerifier` checks Canopy's RS256 signatures against the published key set: one JWKS fetch, then no network on any verification after it.
28
28
  - **Local authorization.** `LocalAuthorizer` answers permission checks in-process from an identity's grant roots and a shared copy of your hierarchy, so a check costs a walk up the tree rather than a round trip.
29
+ - **Webhooks wired to the cache.** `verifyWebhookSignature` checks a delivery in constant time, `authorizer.applyEvent` drops exactly what the change made stale, and `authorizer.replayChanges` catches up from the change feed.
29
30
  - **Conditional reads.** `requestConditional` sends the validator you already hold and tells you whether anything changed, so something expensive can be held and revalidated cheaply.
30
31
  - **Deadlines and cancellation.** A per-attempt timeout and a caller's own `AbortSignal`, settable client-wide or per call.
31
32
  - **Types generated from the published spec**, with CI failing on drift.
@@ -203,8 +204,8 @@ beneath the organization. Authorize by evaluating, never by the list.
203
204
  A grant inside an organization counts only while the membership is active.
204
205
  The grants `LocalAuthorizer` caches already apply that: a deactivated
205
206
  membership drops every grant inside the organization from the next read, so
206
- the authorizer sees it within the cache TTL, and sooner on
207
- `invalidate(identityId)` when an `organization.member.removed` webhook arrives.
207
+ the authorizer sees it within the cache TTL, and at once when the
208
+ `organization.member.removed` webhook is passed to `authorizer.applyEvent`.
208
209
 
209
210
  Tokens also carry `amr`, how the session was proven (`pwd`, `otp` or `sso`,
210
211
  plus `mfa` once a second factor was verified), so a backend can insist on
@@ -260,29 +261,64 @@ const { token, base_url } = await canopy.organizations.mintDirectoryToken(
260
261
 
261
262
  ### Handling webhooks
262
263
 
264
+ Check every delivery's signature before acting on it, over the body exactly
265
+ as it arrived, then hand it to the authorizer and to your own handlers.
263
266
  Every webhook event has a published schema, and the SDK types deliveries from
264
- it. Narrow by event name and read that event's `metadata` without a cast; a
265
- field the API adds arrives with the next `npm run generate`.
267
+ it: narrow by event name and read that event's `metadata` without a cast.
266
268
 
267
269
  ```ts
268
- import { isWebhookEvent, type WebhookDelivery } from "@canopy-io/node";
270
+ import express from "express";
271
+ import {
272
+ isWebhookEvent,
273
+ verifyWebhookSignature,
274
+ type WebhookDelivery,
275
+ } from "@canopy-io/node";
276
+
277
+ app.post(
278
+ "/webhooks/canopy",
279
+ express.raw({ type: "application/json" }),
280
+ async (req, res) => {
281
+ const valid = await verifyWebhookSignature({
282
+ headers: req.headers,
283
+ rawBody: req.body,
284
+ secret: process.env.CANOPY_WEBHOOK_SECRET,
285
+ });
286
+
287
+ if (!valid) {
288
+ return res.sendStatus(401);
289
+ }
290
+
291
+ const delivery = JSON.parse(req.body.toString()) as WebhookDelivery;
292
+
293
+ authorizer.applyEvent(delivery);
294
+
295
+ if (isWebhookEvent(delivery, "organization.member.added")) {
296
+ const { identity_id, role_id } = delivery.data.metadata;
297
+ // ...
298
+ }
299
+
300
+ res.sendStatus(204);
301
+ },
302
+ );
303
+ ```
269
304
 
270
- app.post("/webhooks/canopy", (req, res) => {
271
- const delivery = req.body as WebhookDelivery;
305
+ `verifyWebhookSignature` resolves `false` for a missing header, a signature
306
+ that matches no secret, or an `X-Canopy-Timestamp` more than five minutes
307
+ from this machine's clock (`toleranceSeconds` changes it). For a while after
308
+ you rotate the secret the header carries two signatures, the new secret's
309
+ first, so a receiver still holding the old secret keeps verifying. To roll
310
+ the new secret out without a gap, pass both: `secret: [newSecret, oldSecret]`.
311
+ It runs on Web Crypto, so it works in edge workers as well as Node.
272
312
 
273
- if (isWebhookEvent(delivery, "organization.member.added")) {
274
- const { identity_id, role_id } = delivery.data.metadata;
275
- // ...
276
- }
277
-
278
- res.sendStatus(204);
279
- });
280
- ```
313
+ Deliveries are at least once. `X-Canopy-Webhook-Id` is the same across
314
+ retries: use it as an idempotency key for your own handlers. `applyEvent` is
315
+ safe to repeat.
281
316
 
282
317
  `WebhookEvent<"assignment.updated">` is the delivery of one event, and
283
318
  `WebhookEventName` is every event a subscription can receive. The API's
284
319
  `GET /api/v1/webhooks/event-types` names each event's schema in
285
- `payload_schema`.
320
+ `payload_schema`. A field the API adds arrives with the next
321
+ `npm run generate`.
286
322
 
287
323
  ### Authorizing without a call per request
288
324
 
@@ -320,27 +356,40 @@ and read again if the hierarchy changed while its pages were being read. At
320
356
  50,000 nodes a rebuild is 501 requests, and a revalidation is one.
321
357
 
322
358
  Both are held for at most 60 seconds, which is the delay between an access
323
- change and it taking effect, including a moved node. Set `ttlMs` to change it,
359
+ change and it taking effect, including a moved node, unless a webhook or the
360
+ change feed drops them sooner (see "Revoking before the window lapses"). Set `ttlMs` to change it,
324
361
  up to five minutes (`300_000`); a longer value throws when the authorizer is
325
362
  created. Shortening it below the gap between a user's requests saves nothing:
326
363
  every request then finds the cache expired and refetches.
327
364
 
328
365
  Each answer carries a reason when it is no, from what the grant roots and the
329
366
  tree can say: `permission_not_held`, `outside_grants`, `expired`,
330
- `not_yet_effective`, or `node_missing` for a `node` check with no node. The
367
+ `not_yet_effective`, `denied`, or `node_missing` for a `node` check with no
368
+ node. The
331
369
  grant roots are read with their windows, so a grant that ends sooner than the
332
370
  TTL is dropped at its boundary, not at the next expiry. `onDecision` and
333
371
  `onDenied` hooks hear every verdict after it is reached, never awaited and
334
372
  never able to change it, for audit trails and alerting without a fork of the
335
373
  guard.
336
374
 
375
+ A deny refuses a permission at a node and everything beneath it, whatever the
376
+ grants allow. The grants read carries the identity's deny roots beside its
377
+ grant roots, already resolved by Canopy (the roles it holds, the exception
378
+ roles that spare it), so a check refuses with `denied` when a deny root for
379
+ the permission is at the node or above it, before any grant is looked at. An
380
+ `app_wide` check holds while one grant in effect stands clear of every deny.
381
+ Denies ride the same cache and TTL as grants: a deny created or deleted
382
+ reaches this authorizer within `ttlMs`, and at once through `applyEvent`,
383
+ which drops the one person a deny names and everything for a deny on a role,
384
+ since a deny on a role binds everyone holding it.
385
+
337
386
  A machine client's grants are its own, read from
338
387
  `GET /api/v1/oauth-clients/:id/grants`. Pass `principal_type: "service"` with
339
388
  the client's `client_id` as `identity_id`; the list reads and `invalidate` take
340
389
  `{ principalType: "service" }`. The two kinds are cached apart, so a client
341
390
  never answers from a person's grants. An assignment webhook naming a machine
342
- client carries its `client_id` in `data.metadata.client_id`, the id to
343
- invalidate:
391
+ client carries its `client_id` in `data.metadata.client_id`, the id it is
392
+ cached under; `applyEvent` reads it from there. By hand:
344
393
 
345
394
  ```ts
346
395
  await authorizer.evaluate({
@@ -363,13 +412,15 @@ const authorizer = new LocalAuthorizer(canopy.client, {
363
412
  A list needs the other direction: which nodes may this identity see. The same
364
413
  cache answers it, in the shape your query wants. `grantRoots` names the nodes
365
414
  the permission is granted at, in effect now, minus the ones another root
366
- already covers, and says whether one is the Environment's root (`envWide`:
367
- every node qualifies, so no filter). `accessibleNodes` expands those roots
368
- through their descendants into a `Set` for an `IN (...)` filter, capped at
369
- `maxNodes` (10,000 by default, per authorizer or per call); past the cap it
370
- hands back the roots with `nodes: null` and `complete: false`, so an
371
- application with a closure table or a materialised path filters by "beneath a
372
- root" instead. `permissionsAt` lists what the identity holds at one node, for
415
+ already covers or a deny refuses, and says whether one is the Environment's
416
+ root (`envWide`: every node qualifies, so no filter). `excludedRoots` names
417
+ the deny roots beneath those roots; each cuts out its subtree, and `envWide`
418
+ is false while there are any. `accessibleNodes` expands the roots through
419
+ their descendants, leaving the excluded subtrees out, into a `Set` for an
420
+ `IN (...)` filter, capped at `maxNodes` (10,000 by default, per authorizer or
421
+ per call); past the cap it hands back the roots with `nodes: null` and
422
+ `complete: false`, so an application with a closure table or a materialised
423
+ path filters by "beneath a root and not beneath an excluded root" instead. `permissionsAt` lists what the identity holds at one node, for
373
424
  rendering a screen's controls, and `permissionsAtMany` answers several nodes
374
425
  from one read, for the rows of a list.
375
426
 
@@ -381,7 +432,8 @@ if (access.envWide) {
381
432
  }
382
433
 
383
434
  if (!access.complete) {
384
- // Too large for an IN (...) list: filter beneath access.roots instead.
435
+ // Too large for an IN (...) list: filter beneath access.roots, and not
436
+ // beneath access.excludedRoots, instead.
385
437
  }
386
438
 
387
439
  return db.reports.findMany({ where: { nodeId: { in: [...access.nodes] } } });
@@ -392,7 +444,9 @@ hold the permission anywhere in it? `app_wide` cannot say, since it covers the
392
444
  whole Environment, so a grant in another organization would show the menu
393
445
  here too. `holdsAnywhereUnder` answers for one subtree, with `roots` as the
394
446
  subtree root alone when a grant at or above it reaches all of it, and
395
- otherwise the topmost granted nodes inside it:
447
+ otherwise the topmost granted nodes inside it, with `excludedRoots` as the
448
+ deny roots inside those. A deny at the subtree's root or above it refuses the
449
+ whole subtree:
396
450
 
397
451
  ```ts
398
452
  const { held, roots } = await authorizer.holdsAnywhereUnder(
@@ -414,10 +468,52 @@ authorizer, as `canopy.identities.accessibleNodes(id, { permission })`.
414
468
 
415
469
  `canopy.permissions.evaluate` remains for a decision with no staleness at all.
416
470
 
417
- `authorizer.invalidate(identityId)` drops one identity's cached grants, so
418
- the next check reads them fresh. It reaches only this process: with several
419
- instances behind a load balancer, each keeps its own cache until its TTL runs
420
- out or it is told to invalidate too.
471
+ #### Revoking before the window lapses
472
+
473
+ `authorizer.applyEvent(delivery)` takes a webhook delivery and drops what
474
+ it makes stale, and answers what it dropped:
475
+
476
+ - A change naming whose access moved (an assignment, an Environment or
477
+ organization membership, an identity's status, a deny on one person, a
478
+ machine client disabled or deleted) drops those subjects' grants and keeps
479
+ everyone else's, and the hierarchy, warm.
480
+ - A change whose reach it cannot name (a role, a permission, a node, the
481
+ hierarchy schema, an organization created or deleted, a deny on a role, a
482
+ directory group mapped) drops everything.
483
+ - A change that moves no one's access (a profile edit, a sign-in policy, a
484
+ session revoked) drops nothing. An event this version does not know drops
485
+ everything, since guessing it harmless is the unsafe direction.
486
+
487
+ A check already reading from Canopy when the change lands answers from what
488
+ it read, but what it read is not kept, so the next check sees the change.
489
+
490
+ `authorizer.replayChanges({ cursor })` reads `GET /api/v1/changes` from
491
+ `cursor` to the newest change, applies each one the same way, and answers the
492
+ cursor to keep for next time. Run it at startup to catch up on what a process
493
+ missed while it was down, or on an interval in place of webhooks:
494
+
495
+ ```ts
496
+ let cursor: string | null = await loadCursor();
497
+
498
+ setInterval(async () => {
499
+ ({ cursor } = await authorizer.replayChanges({ cursor }));
500
+ await saveCursor(cursor);
501
+ }, 15_000);
502
+ ```
503
+
504
+ With no cursor it starts at the oldest change Canopy still retains, so the
505
+ first replay walks that window once.
506
+
507
+ A webhook reaches one process. With several instances behind a load
508
+ balancer, `applyEvent` drops the cache of the one that received it, and the
509
+ others keep theirs until their own TTL runs out. Either fan the delivery out
510
+ to every instance over your own pub/sub, or have every instance run
511
+ `replayChanges` on an interval shorter than `ttlMs`. Otherwise the TTL stays
512
+ the fleet-wide revocation guarantee.
513
+
514
+ `authorizer.invalidate(identityId)` remains for a change your own backend
515
+ makes and knows about: it drops one identity's cached grants, and with no
516
+ argument everything.
421
517
 
422
518
  A failed check (Canopy unreachable, a credential that cannot read the
423
519
  hierarchy, an identity not in the Environment, or a Canopy serving an