@canopy-io/node 0.13.0 → 0.14.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,17 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 174f157: Machine clients. An OAuth client registered with `client_kind: machine` holds roles of its own and obtains tokens for itself with the `client_credentials` grant: `type: "service"`, `sub` and `client_id` set to its `client_id`, `gty: "client_credentials"`, and its organization's claims when it is pinned to one. `TokenVerifier` still accepts identity tokens only by default; `verify(token, { alsoAllow: ["service"] })` admits a service token on that one call, held to the new `serviceAudience` option (the audience your API answers to, which the token's `aud` names); without it a service token answers `token.audience_unverified`. In NestJS, `@AllowServiceTokens()` on a route or controller makes `CanopyTokenGuard` admit it there, and `CanopyGuard` then evaluates the client's own grants, chosen from the verified claims.
8
+
9
+ `LocalAuthorizer` reads a machine client's grants from `GET /api/v1/oauth-clients/:id/grants` when a check carries `principal_type: "service"`; `grantRoots`, `accessibleNodes`, `permissionsAt`, `permissionsAtMany` and `invalidate` take `{ principalType: "service" }`. A client and an identity are cached apart, and an assignment webhook naming a machine client carries its `client_id` (`data.metadata.client_id`) to invalidate by. The conformance bundle gains the `machine-clients` vector, replayed as service-token checks against each client's own grants.
10
+
11
+ `orgContext(claims)` returns `{ orgId, orgRoles, orgRoleIds }` and now requires `org_role_ids` beside `org_id` and `org_roles`, paired with the names position for position; a token missing it, or with lists of different lengths, answers `null`. A `CanopyGuard` denial reads "Caller does not hold" in place of "Identity does not hold".
12
+
13
+ The spec now has 157 operations. Generated types cover machine clients (`client_kind`, `organization_node_id`, `allowed_audiences`), their assignment and grant routes, and roles that belong to one organization.
14
+
3
15
  ## 0.13.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -117,6 +117,32 @@ staff (`platform`) and some API key flows (`api_key`) with the same keys and
117
117
  issuer, so they are refused with `token.type_not_allowed` unless you name them:
118
118
  `new TokenVerifier({ ..., allowedTypes: ["identity", "user"] })`.
119
119
 
120
+ A **machine client** (an OAuth client registered with `client_kind: machine`)
121
+ obtains tokens for itself with the `client_credentials` grant. Its token's
122
+ `type` is `service`, its `sub` and `client_id` are the client's `client_id`,
123
+ and `gty` is `client_credentials`. Its `aud` names the API it was minted for
124
+ (the `audience` the client asked for, or the Environment's default audience),
125
+ so name yours as `serviceAudience`; `audience` stays the OAuth client a
126
+ person's token is for. Admit service tokens on the one call that serves
127
+ machines rather than on the whole verifier, so routes built for people keep
128
+ refusing them:
129
+
130
+ ```ts
131
+ const verifier = new TokenVerifier({
132
+ environmentId: process.env.CANOPY_ENVIRONMENT_ID,
133
+ serviceAudience: "https://api.example.com",
134
+ });
135
+
136
+ const claims = await verifier.verify(bearerToken, { alsoAllow: ["service"] });
137
+
138
+ if (claims.type === "service") {
139
+ claims.sub; // the machine client's client_id
140
+ }
141
+ ```
142
+
143
+ A machine client pinned to an organization carries that organization's claims,
144
+ read through `orgContext` like a person's.
145
+
120
146
  If Canopy cannot be reached when the cached keys are due for a refresh, the
121
147
  verifier keeps verifying with the keys it holds; only a verifier that has never
122
148
  loaded a key set, or a token signed by a key it has never seen, answers
@@ -144,9 +170,10 @@ mistakenly accepted.
144
170
 
145
171
  With an Environment's **organizations** container on, an identity token also
146
172
  names the organization the session is acting in and the roles held at that
147
- organization's node. Read the pair through `orgContext` rather than off the raw
148
- claims — Canopy mints the two together, and the helper refuses a half-present
149
- pair:
173
+ organization's node, by name and by id. Read them through `orgContext` rather
174
+ than off the raw claims: Canopy mints `org_id`, `org_roles` and `org_role_ids`
175
+ together, and the helper refuses a partial set or names and ids that do not
176
+ pair up:
150
177
 
151
178
  ```ts
152
179
  import { orgContext } from "@canopy-io/node";
@@ -156,6 +183,7 @@ const org = orgContext(claims);
156
183
  if (org) {
157
184
  org.orgId; // the organization — also a hierarchy node id
158
185
  org.orgRoles; // the roles held at its node, by name; [] for a member holding none there
186
+ org.orgRoleIds; // the same roles' ids, in the same order
159
187
  }
160
188
  ```
161
189
 
@@ -298,6 +326,25 @@ TTL is dropped at its boundary, not at the next expiry. `onDecision` and
298
326
  never able to change it, for audit trails and alerting without a fork of the
299
327
  guard.
300
328
 
329
+ A machine client's grants are its own, read from
330
+ `GET /api/v1/oauth-clients/:id/grants`. Pass `principal_type: "service"` with
331
+ the client's `client_id` as `identity_id`; the list reads and `invalidate` take
332
+ `{ principalType: "service" }`. The two kinds are cached apart, so a client
333
+ never answers from a person's grants. An assignment webhook naming a machine
334
+ client carries its `client_id` in `data.metadata.client_id`, the id to
335
+ invalidate:
336
+
337
+ ```ts
338
+ await authorizer.evaluate({
339
+ identity_id: claims.sub,
340
+ principal_type: claims.type === "service" ? "service" : "identity",
341
+ permission: "orders.import",
342
+ node_id: nodeId,
343
+ });
344
+
345
+ authorizer.invalidate(clientId, { principalType: "service" });
346
+ ```
347
+
301
348
  ```ts
302
349
  const authorizer = new LocalAuthorizer(canopy.client, {
303
350
  onDenied: ({ query, decision }) =>
package/dist/index.cjs CHANGED
@@ -1187,7 +1187,8 @@ function understood(page, path) {
1187
1187
  }
1188
1188
  return page;
1189
1189
  }
1190
- var GRANTS_PATH = (identityId) => `/api/v1/identities/${encodeURIComponent(identityId)}/grants`;
1190
+ var GRANTS_PATH = (type, id) => type === "service" ? `/api/v1/oauth-clients/${encodeURIComponent(id)}/grants` : `/api/v1/identities/${encodeURIComponent(id)}/grants`;
1191
+ var subjectKey = (type, id) => `${type}:${id}`;
1191
1192
  var PARENTS_PATH = "/api/v1/nodes/parents";
1192
1193
  function inEffect(window, now) {
1193
1194
  return (window.from === null || window.from <= now) && (window.to === null || window.to > now);
@@ -1296,9 +1297,12 @@ var LocalAuthorizer = class {
1296
1297
  * root the readable hierarchy does not contain raises
1297
1298
  * `authorizer.hierarchy_incomplete`, as a check at such a node does.
1298
1299
  */
1299
- async grantRoots(identityId, permission) {
1300
+ async grantRoots(identityId, permission, subject = {}) {
1300
1301
  const now = this.now();
1301
- const held = (await this.grantRootsFor(identityId)).get(permission) ?? [];
1302
+ const held = (await this.grantRootsFor(
1303
+ identityId,
1304
+ subject.principalType ?? "identity"
1305
+ )).get(permission) ?? [];
1302
1306
  const granted = new Set(
1303
1307
  held.filter((window) => inEffect(window, now)).map((w) => w.node)
1304
1308
  );
@@ -1345,7 +1349,9 @@ var LocalAuthorizer = class {
1345
1349
  */
1346
1350
  async accessibleNodes(identityId, permission, options = {}) {
1347
1351
  const cap = options.maxNodes ?? this.maxNodes;
1348
- const { roots, envWide } = await this.grantRoots(identityId, permission);
1352
+ const { roots, envWide } = await this.grantRoots(identityId, permission, {
1353
+ ...options.principalType ? { principalType: options.principalType } : {}
1354
+ });
1349
1355
  if (envWide) {
1350
1356
  return { roots, envWide: true, nodes: null, complete: true };
1351
1357
  }
@@ -1375,8 +1381,8 @@ var LocalAuthorizer = class {
1375
1381
  * inheritance: the list a screen renders its controls from, answered from
1376
1382
  * the same cached grant roots and tree a check uses.
1377
1383
  */
1378
- async permissionsAt(identityId, nodeId) {
1379
- const answers = await this.permissionsAtMany(identityId, [nodeId]);
1384
+ async permissionsAt(identityId, nodeId, subject = {}) {
1385
+ const answers = await this.permissionsAtMany(identityId, [nodeId], subject);
1380
1386
  return answers.get(nodeId) ?? [];
1381
1387
  }
1382
1388
  /**
@@ -1384,9 +1390,12 @@ var LocalAuthorizer = class {
1384
1390
  * the rows of a list each with their own controls, answered from one read
1385
1391
  * of the grant roots and one walk per node.
1386
1392
  */
1387
- async permissionsAtMany(identityId, nodeIds) {
1393
+ async permissionsAtMany(identityId, nodeIds, subject = {}) {
1388
1394
  const now = this.now();
1389
- const roots = await this.grantRootsFor(identityId);
1395
+ const roots = await this.grantRootsFor(
1396
+ identityId,
1397
+ subject.principalType ?? "identity"
1398
+ );
1390
1399
  const answers = /* @__PURE__ */ new Map();
1391
1400
  for (const nodeId of new Set(nodeIds)) {
1392
1401
  const path = await this.lineageOf(nodeId);
@@ -1404,9 +1413,10 @@ var LocalAuthorizer = class {
1404
1413
  }
1405
1414
  async decide(query) {
1406
1415
  const now = this.now();
1407
- const held = (await this.grantRootsFor(query.identity_id)).get(
1408
- query.permission
1409
- );
1416
+ const held = (await this.grantRootsFor(
1417
+ query.identity_id,
1418
+ query.principal_type ?? "identity"
1419
+ )).get(query.permission);
1410
1420
  if (!held || held.length === 0) {
1411
1421
  return { allowed: false, reason: "permission_not_held" };
1412
1422
  }
@@ -1442,6 +1452,8 @@ var LocalAuthorizer = class {
1442
1452
  * cached hierarchy and every other identity's entries stay warm. This is
1443
1453
  * the shape an assignment webhook wants: the event names the identity
1444
1454
  * whose authority moved, and nothing else needs to pay a refetch for it.
1455
+ * An event naming a machine client (`oauth_client_id`, with `identity_id`
1456
+ * null) passes that client's `client_id` with `principalType: "service"`.
1445
1457
  *
1446
1458
  * With no argument, everything goes: grants and the hierarchy tree. Not
1447
1459
  * needed in normal operation, where entries expire on their own; useful in
@@ -1457,9 +1469,11 @@ var LocalAuthorizer = class {
1457
1469
  * the TTL, and webhook-driven invalidation is a latency optimization on
1458
1470
  * top of it — size the TTL to the revocation latency you can promise.
1459
1471
  */
1460
- invalidate(identityId) {
1472
+ invalidate(identityId, subject = {}) {
1461
1473
  if (identityId !== void 0) {
1462
- this.grants.delete(identityId);
1474
+ this.grants.delete(
1475
+ subjectKey(subject.principalType ?? "identity", identityId)
1476
+ );
1463
1477
  return;
1464
1478
  }
1465
1479
  this.grants.clear();
@@ -1502,19 +1516,20 @@ var LocalAuthorizer = class {
1502
1516
  `The hierarchy this client can read does not contain node "${nodeId}", so authorization at that node cannot be decided. A scoped API key needs the \`hierarchy.view\` scope to read the tree.`
1503
1517
  );
1504
1518
  }
1505
- async grantRootsFor(identityId) {
1506
- const cached = this.grants.get(identityId);
1519
+ async grantRootsFor(identityId, type) {
1520
+ const key = subjectKey(type, identityId);
1521
+ const cached = this.grants.get(key);
1507
1522
  if (cached && cached.expiresAt > this.now()) {
1508
1523
  return cached.roots;
1509
1524
  }
1510
- const pending = this.pendingGrants.get(identityId);
1525
+ const pending = this.pendingGrants.get(key);
1511
1526
  if (pending) {
1512
1527
  return pending;
1513
1528
  }
1514
- const read = this.fetchGrantRoots(identityId).finally(() => {
1515
- this.pendingGrants.delete(identityId);
1529
+ const read = this.fetchGrantRoots(identityId, type).finally(() => {
1530
+ this.pendingGrants.delete(key);
1516
1531
  });
1517
- this.pendingGrants.set(identityId, read);
1532
+ this.pendingGrants.set(key, read);
1518
1533
  return read;
1519
1534
  }
1520
1535
  /**
@@ -1532,9 +1547,9 @@ var LocalAuthorizer = class {
1532
1547
  * window boundary when that comes before the TTL, so a grant takes effect
1533
1548
  * or ends on time rather than up to `ttlMs` late.
1534
1549
  */
1535
- async fetchGrantRoots(identityId) {
1550
+ async fetchGrantRoots(identityId, type) {
1536
1551
  this.stats.grantFetches += 1;
1537
- const path = GRANTS_PATH(identityId);
1552
+ const path = GRANTS_PATH(type, identityId);
1538
1553
  const rows = paginate(
1539
1554
  (query) => {
1540
1555
  this.stats.grantPages += 1;
@@ -1567,7 +1582,7 @@ var LocalAuthorizer = class {
1567
1582
  roots.set(row.permission, [window]);
1568
1583
  }
1569
1584
  }
1570
- this.grants.set(identityId, {
1585
+ this.grants.set(subjectKey(type, identityId), {
1571
1586
  roots,
1572
1587
  expiresAt: Math.min(now + this.ttlMs, boundary)
1573
1588
  });
@@ -1754,7 +1769,13 @@ var HOSTED_ORIGIN = "https://auth.canopy-io.com";
1754
1769
  var DEFAULT_JWKS_CACHE_MAX_AGE_MS = 10 * 60 * 1e3;
1755
1770
  var DEFAULT_JWKS_MIN_REFETCH_INTERVAL_MS = 30 * 1e3;
1756
1771
  var DEFAULT_JWKS_TIMEOUT_MS = 5e3;
1757
- var PRINCIPAL_TYPES = /* @__PURE__ */ new Set(["user", "identity", "api_key", "platform"]);
1772
+ var PRINCIPAL_TYPES = /* @__PURE__ */ new Set([
1773
+ "user",
1774
+ "identity",
1775
+ "service",
1776
+ "api_key",
1777
+ "platform"
1778
+ ]);
1758
1779
  var DEFAULT_CLOCK_TOLERANCE_SEC = 60;
1759
1780
  function resolveIssuer(options) {
1760
1781
  const { environmentId, issuer } = options;
@@ -1774,11 +1795,16 @@ function resolveIssuer(options) {
1774
1795
  );
1775
1796
  }
1776
1797
  function orgContext(claims) {
1777
- const { org_id, org_roles } = claims;
1778
- if (typeof org_id !== "string" || org_id === "" || !Array.isArray(org_roles) || org_roles.some((role) => typeof role !== "string" || role === "")) {
1798
+ const { org_id, org_roles, org_role_ids } = claims;
1799
+ const isNameList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry !== "");
1800
+ if (typeof org_id !== "string" || org_id === "" || !isNameList(org_roles) || !isNameList(org_role_ids) || org_role_ids.length !== org_roles.length) {
1779
1801
  return null;
1780
1802
  }
1781
- return { orgId: org_id, orgRoles: [...org_roles] };
1803
+ return {
1804
+ orgId: org_id,
1805
+ orgRoles: [...org_roles],
1806
+ orgRoleIds: [...org_role_ids]
1807
+ };
1782
1808
  }
1783
1809
  function decodeBase64Url(value) {
1784
1810
  const padded = value.replace(/-/g, "+").replace(/_/g, "/");
@@ -1803,6 +1829,7 @@ function decodeJsonSegment(segment, what) {
1803
1829
  var TokenVerifier = class {
1804
1830
  issuer;
1805
1831
  audience;
1832
+ serviceAudience;
1806
1833
  jwksUri;
1807
1834
  jwksCacheMaxAgeMs;
1808
1835
  jwksMinRefetchIntervalMs;
@@ -1822,6 +1849,7 @@ var TokenVerifier = class {
1822
1849
  constructor(options = {}) {
1823
1850
  this.issuer = resolveIssuer(options);
1824
1851
  this.audience = options.audience;
1852
+ this.serviceAudience = options.serviceAudience;
1825
1853
  this.jwksUri = options.jwksUri ?? `${this.issuer}/.well-known/jwks.json`;
1826
1854
  this.jwksCacheMaxAgeMs = options.jwksCacheMaxAgeMs ?? DEFAULT_JWKS_CACHE_MAX_AGE_MS;
1827
1855
  this.jwksMinRefetchIntervalMs = options.jwksMinRefetchIntervalMs ?? DEFAULT_JWKS_MIN_REFETCH_INTERVAL_MS;
@@ -1844,7 +1872,7 @@ var TokenVerifier = class {
1844
1872
  * Order matters: the signature is checked before any claim is believed, so
1845
1873
  * nothing downstream ever reads an unverified payload.
1846
1874
  */
1847
- async verify(token) {
1875
+ async verify(token, options = {}) {
1848
1876
  const parts = token.split(".");
1849
1877
  if (parts.length !== 3) {
1850
1878
  throw new CanopyTokenError(
@@ -1889,11 +1917,11 @@ var TokenVerifier = class {
1889
1917
  encodedPayload,
1890
1918
  "payload"
1891
1919
  );
1892
- this.assertClaims(claims);
1920
+ this.assertClaims(claims, options);
1893
1921
  return claims;
1894
1922
  }
1895
1923
  /** Everything checked after the signature is known good. */
1896
- assertClaims(claims) {
1924
+ assertClaims(claims, options) {
1897
1925
  if (typeof claims.sub !== "string" || claims.sub === "") {
1898
1926
  throw new CanopyTokenError(
1899
1927
  "token.malformed",
@@ -1906,11 +1934,15 @@ var TokenVerifier = class {
1906
1934
  `Token has an unrecognised \`type\` claim: ${JSON.stringify(claims.type)}.`
1907
1935
  );
1908
1936
  }
1909
- if (!this.allowedTypes.has(claims.type)) {
1937
+ const accepted = /* @__PURE__ */ new Set([
1938
+ ...this.allowedTypes,
1939
+ ...options.alsoAllow ?? []
1940
+ ]);
1941
+ if (!accepted.has(claims.type)) {
1910
1942
  throw new CanopyTokenError(
1911
1943
  "token.type_not_allowed",
1912
1944
  `Token is for a "${claims.type}" principal; this verifier accepts ${[
1913
- ...this.allowedTypes
1945
+ ...accepted
1914
1946
  ].map((type) => `"${type}"`).join(", ")}. Set \`allowedTypes\` to accept another.`
1915
1947
  );
1916
1948
  }
@@ -1952,9 +1984,27 @@ var TokenVerifier = class {
1952
1984
  * token being verified by something that never said which client it is, and
1953
1985
  * ignoring it would accept a token minted for a different client. So it
1954
1986
  * throws and names the option.
1987
+ *
1988
+ * A service token names the API it was minted for, never a client, so it
1989
+ * is held to `serviceAudience` alone, which it must name.
1955
1990
  */
1956
1991
  assertAudience(claims) {
1957
1992
  const audiences = claims.aud === void 0 ? [] : Array.isArray(claims.aud) ? claims.aud : [claims.aud];
1993
+ if (claims.type === "service") {
1994
+ if (this.serviceAudience === void 0) {
1995
+ throw new CanopyTokenError(
1996
+ "token.audience_unverified",
1997
+ "This is a machine client's service token, and the verifier has no `serviceAudience` configured. Set `serviceAudience` to the audience your API answers to."
1998
+ );
1999
+ }
2000
+ if (!audiences.includes(this.serviceAudience)) {
2001
+ throw new CanopyTokenError(
2002
+ "token.audience_mismatch",
2003
+ `Token audience does not include "${this.serviceAudience}".`
2004
+ );
2005
+ }
2006
+ return;
2007
+ }
1958
2008
  if (this.audience === void 0) {
1959
2009
  if (audiences.length > 0) {
1960
2010
  throw new CanopyTokenError(