@spechtlabs/backstage-plugin-tailscale-backend 0.0.0-stage → 0.1.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.
@@ -0,0 +1,878 @@
1
+ 'use strict';
2
+
3
+ var catalogModel = require('@backstage/catalog-model');
4
+ var graph = require('./graph.cjs.js');
5
+ var hujson = require('./hujson.cjs.js');
6
+ var backstagePluginTailscaleCommon = require('@spechtlabs/backstage-plugin-tailscale-common');
7
+
8
+ const titleOf = (e) => e.spec?.profile?.displayName ?? e.metadata.title ?? e.metadata.name;
9
+ class Directory {
10
+ groups = /* @__PURE__ */ new Map();
11
+ // by tailnet name
12
+ groupsByRef = /* @__PURE__ */ new Map();
13
+ users = /* @__PURE__ */ new Map();
14
+ // by ref
15
+ usersByLogin = /* @__PURE__ */ new Map();
16
+ constructor(entities) {
17
+ for (const e of entities) {
18
+ const ref = catalogModel.stringifyEntityRef(e);
19
+ if (e.kind === "User") {
20
+ const login = e.metadata.annotations?.[backstagePluginTailscaleCommon.ANNOTATION_TAILNET_LOGIN];
21
+ const user = { ref, login, title: titleOf(e) };
22
+ this.users.set(ref, user);
23
+ if (login) this.usersByLogin.set(login, user);
24
+ }
25
+ }
26
+ for (const e of entities) {
27
+ if (e.kind !== "Group") continue;
28
+ const ref = catalogModel.stringifyEntityRef(e);
29
+ const annotation = e.metadata.annotations?.[backstagePluginTailscaleCommon.ANNOTATION_TAILNET_GROUP];
30
+ const group = {
31
+ ref,
32
+ name: annotation ?? `group:${e.metadata.name}`,
33
+ title: titleOf(e),
34
+ description: e.metadata.description,
35
+ memberRefs: (e.relations ?? []).filter((r) => r.type === catalogModel.RELATION_HAS_MEMBER).map((r) => r.targetRef).sort(),
36
+ annotated: !!annotation
37
+ };
38
+ this.groupsByRef.set(ref, group);
39
+ if (annotation || !this.groups.has(group.name)) {
40
+ if (!this.groups.get(group.name)?.annotated) {
41
+ this.groups.set(group.name, group);
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
47
+ const ADDRESS = /^(\d{1,3}(\.\d{1,3}){3}(\/\d+)?|[0-9a-f]*:[0-9a-f:]*(\/\d+)?)$/i;
48
+ const byName = (a, b) => a.metadata.name.localeCompare(b.metadata.name);
49
+ const refOf = (e) => catalogModel.stringifyEntityRef(e);
50
+ function stringsIn(value, out = []) {
51
+ if (typeof value === "string") out.push(value);
52
+ else if (Array.isArray(value)) value.forEach((v) => stringsIn(v, out));
53
+ else if (value && typeof value === "object") {
54
+ Object.values(value).forEach((v) => stringsIn(v, out));
55
+ }
56
+ return out;
57
+ }
58
+ const unique = (refs) => [...new Set(refs.map((r) => catalogModel.parseEntityRef(r).name))].sort();
59
+ function shortRef(ref) {
60
+ const { kind, namespace, name } = catalogModel.parseEntityRef(ref);
61
+ return namespace === "default" ? `${kind}:${name}` : ref;
62
+ }
63
+ class PolicyCompiler {
64
+ constructor(dir, policy, parts) {
65
+ this.dir = dir;
66
+ this.policy = policy;
67
+ this.parts = parts;
68
+ this.hosts = policy.spec.hosts ?? {};
69
+ this.ipsets = new Set(
70
+ Object.keys(policy.spec.settings?.ipsets ?? {})
71
+ );
72
+ for (const tag of this.of("tag")) {
73
+ const existing = this.tagEntities.get(tag.spec.tag);
74
+ if (existing) {
75
+ this.error(
76
+ `${tag.spec.tag} is already declared by ${refOf(existing)}`,
77
+ tag
78
+ );
79
+ } else {
80
+ this.tagEntities.set(tag.spec.tag, tag);
81
+ }
82
+ }
83
+ }
84
+ dir;
85
+ policy;
86
+ parts;
87
+ diagnostics = [];
88
+ usedGroups = /* @__PURE__ */ new Map();
89
+ tagUsage = /* @__PURE__ */ new Map();
90
+ tagEntities = /* @__PURE__ */ new Map();
91
+ hosts;
92
+ ipsets;
93
+ of(type) {
94
+ return this.parts.filter((p) => p.spec.type === type).sort(byName);
95
+ }
96
+ error(message, entity) {
97
+ this.diagnostics.push({
98
+ severity: "error",
99
+ message,
100
+ entityRef: typeof entity === "string" ? entity : entity && refOf(entity)
101
+ });
102
+ }
103
+ warn(message, entity) {
104
+ this.diagnostics.push({
105
+ severity: "warning",
106
+ message,
107
+ entityRef: typeof entity === "string" ? entity : entity && refOf(entity)
108
+ });
109
+ }
110
+ useGroup(name) {
111
+ this.usedGroups.set(name, (this.usedGroups.get(name) ?? 0) + 1);
112
+ }
113
+ /** What a source, destination, owner or approver stands for. */
114
+ resolve(value, where, field) {
115
+ const fail = (message) => {
116
+ this.error(`${field}: ${message}`, where);
117
+ return { value, name: value, kind: "host" };
118
+ };
119
+ if (value === "*") return { value, name: "*", kind: "any" };
120
+ if (value.startsWith("group:")) {
121
+ const group = value.includes("/") ? this.dir.groupsByRef.get(
122
+ catalogModel.stringifyEntityRef(
123
+ catalogModel.parseEntityRef(value, { defaultNamespace: "default" })
124
+ )
125
+ ) : this.dir.groups.get(value) ?? this.dir.groupsByRef.get(`group:default/${value.slice(6)}`);
126
+ if (!group) {
127
+ return fail(
128
+ `${value} is no group: no Backstage Group has ${backstagePluginTailscaleCommon.ANNOTATION_TAILNET_GROUP}: ${value}`
129
+ );
130
+ }
131
+ this.useGroup(group.name);
132
+ return {
133
+ value,
134
+ name: group.name,
135
+ kind: "group",
136
+ entityRef: group.ref,
137
+ title: group.title
138
+ };
139
+ }
140
+ if (value.startsWith("user:")) {
141
+ const ref = catalogModel.stringifyEntityRef(
142
+ catalogModel.parseEntityRef(value, { defaultNamespace: "default" })
143
+ );
144
+ const user = this.dir.users.get(ref);
145
+ if (!user) return fail(`${value} is not a User in the catalog`);
146
+ if (!user.login) {
147
+ return fail(`${value} has no ${backstagePluginTailscaleCommon.ANNOTATION_TAILNET_LOGIN} annotation`);
148
+ }
149
+ return {
150
+ value,
151
+ name: user.login,
152
+ kind: "user",
153
+ entityRef: user.ref,
154
+ title: user.title
155
+ };
156
+ }
157
+ if (value.startsWith("tag:")) {
158
+ const tag = this.tagEntities.get(value);
159
+ this.tagUsage.set(value, (this.tagUsage.get(value) ?? 0) + 1);
160
+ if (!tag) {
161
+ this.error(
162
+ `${field}: ${value} is not declared: no Tailscale tag entity in this policy has tag: ${value}`,
163
+ where
164
+ );
165
+ }
166
+ return {
167
+ value,
168
+ name: value,
169
+ kind: "tag",
170
+ entityRef: tag && refOf(tag),
171
+ title: tag?.metadata.title
172
+ };
173
+ }
174
+ if (value.startsWith("svc:"))
175
+ return { value, name: value, kind: "service" };
176
+ if (value.startsWith("autogroup:")) {
177
+ return { value, name: value, kind: "autogroup" };
178
+ }
179
+ if (value.startsWith("ipset:")) {
180
+ if (!this.ipsets.has(value)) {
181
+ return fail(`${value} is not in the policy's settings.ipsets`);
182
+ }
183
+ return { value, name: value, kind: "ipset" };
184
+ }
185
+ if (value.includes("@")) {
186
+ const user = this.dir.usersByLogin.get(value);
187
+ return {
188
+ value,
189
+ name: value,
190
+ kind: "user",
191
+ entityRef: user?.ref,
192
+ title: user?.title
193
+ };
194
+ }
195
+ if (ADDRESS.test(value)) return { value, name: value, kind: "address" };
196
+ if (value in this.hosts) {
197
+ return { value, name: value, kind: "host", title: this.hosts[value] };
198
+ }
199
+ return fail(`${value} is neither a host of this policy nor a selector`);
200
+ }
201
+ resolveAll(values, where, field) {
202
+ return (values ?? []).map((v) => this.resolve(v, where, field));
203
+ }
204
+ /** Groups named inside capability values (tsidp's users) count as used. */
205
+ scanApp(app) {
206
+ for (const s of stringsIn(app)) {
207
+ if (s.startsWith("group:") && this.dir.groups.has(s)) this.useGroup(s);
208
+ }
209
+ }
210
+ meta(e) {
211
+ return {
212
+ entityRef: refOf(e),
213
+ title: e.metadata.title,
214
+ description: e.metadata.description
215
+ };
216
+ }
217
+ compile(catalogEntities, baseUrl) {
218
+ const tags = this.of("tag").filter((t) => this.tagEntities.get(t.spec.tag) === t).map((t) => ({
219
+ id: refOf(t),
220
+ ...this.meta(t),
221
+ tag: t.spec.tag,
222
+ owners: this.resolveAll(t.spec.owners, t, "owners"),
223
+ appliesTo: (t.spec.appliesTo ?? []).map(
224
+ (r) => catalogModel.stringifyEntityRef(
225
+ catalogModel.parseEntityRef(r, {
226
+ defaultKind: "component",
227
+ defaultNamespace: t.metadata.namespace ?? "default"
228
+ })
229
+ )
230
+ ),
231
+ usage: 0
232
+ }));
233
+ const grants = this.of("grant").map((g) => {
234
+ const src = this.resolveAll(g.spec.src, g, "src");
235
+ for (const s of src) {
236
+ if (s.kind === "service") {
237
+ this.error(
238
+ `src: ${s.value} is a Service; Services are destinations`,
239
+ g
240
+ );
241
+ }
242
+ }
243
+ if (!g.spec.ip?.length && !g.spec.app) {
244
+ this.error("a grant needs ip, app or both", g);
245
+ }
246
+ this.scanApp(g.spec.app);
247
+ return {
248
+ id: refOf(g),
249
+ ...this.meta(g),
250
+ origin: "entity",
251
+ src,
252
+ dst: this.resolveAll(g.spec.dst, g, "dst"),
253
+ ip: g.spec.ip ?? [],
254
+ app: g.spec.app,
255
+ via: g.spec.via && this.resolveAll(g.spec.via, g, "via"),
256
+ srcPosture: g.spec.srcPosture
257
+ };
258
+ });
259
+ const ssh = this.of("ssh").map((s) => ({
260
+ id: refOf(s),
261
+ ...this.meta(s),
262
+ action: s.spec.action,
263
+ src: this.resolveAll(s.spec.src, s, "src"),
264
+ dst: this.resolveAll(s.spec.dst, s, "dst"),
265
+ users: s.spec.users,
266
+ checkPeriod: s.spec.checkPeriod,
267
+ acceptEnv: s.spec.acceptEnv,
268
+ recorder: s.spec.recorder && this.resolveAll(s.spec.recorder, s, "recorder"),
269
+ enforceRecorder: s.spec.enforceRecorder
270
+ }));
271
+ const nodeAttrs = this.of("nodeAttr").map(
272
+ (n) => {
273
+ this.scanApp(n.spec.app);
274
+ return {
275
+ id: refOf(n),
276
+ ...this.meta(n),
277
+ nodes: this.resolveAll(n.spec.nodes, n, "nodes"),
278
+ attr: n.spec.attr ?? [],
279
+ app: n.spec.app,
280
+ ipPool: n.spec.ipPool
281
+ };
282
+ }
283
+ );
284
+ const autoApprovers = this.of(
285
+ "autoApprovers"
286
+ ).flatMap((a) => {
287
+ const rules = [];
288
+ const add = (kind, target, list) => rules.push({
289
+ id: `${refOf(a)}#${kind}/${target}`,
290
+ ...this.meta(a),
291
+ kind,
292
+ target,
293
+ approvers: this.resolveAll(list, a, `${kind} ${target}`)
294
+ });
295
+ for (const [svc, list] of Object.entries(a.spec.services ?? {})) {
296
+ add("service", svc, list);
297
+ }
298
+ for (const [cidr, list] of Object.entries(a.spec.routes ?? {})) {
299
+ add("route", cidr, list);
300
+ }
301
+ if (a.spec.exitNode?.length)
302
+ add("exitNode", "exit node", a.spec.exitNode);
303
+ return rules;
304
+ });
305
+ const tests = this.of("test").flatMap((t) => {
306
+ const destination = (entry, field) => {
307
+ const at = entry.lastIndexOf(":");
308
+ if (at <= 0) return entry;
309
+ const target = this.resolve(entry.slice(0, at), t, field);
310
+ return `${target.name}${entry.slice(at)}`;
311
+ };
312
+ const acl = backstagePluginTailscaleCommon.asList(t.spec.tests).map(
313
+ (test, i) => ({
314
+ id: `${refOf(t)}#tests/${i}`,
315
+ ...this.meta(t),
316
+ kind: "acl",
317
+ src: this.resolve(test.src, t, "tests src"),
318
+ proto: test.proto,
319
+ accept: (test.accept ?? []).map((d) => destination(d, "tests accept")),
320
+ deny: (test.deny ?? []).map((d) => destination(d, "tests deny")),
321
+ check: []
322
+ })
323
+ );
324
+ const sshTests = backstagePluginTailscaleCommon.asList(t.spec.sshTests).map(
325
+ (test, i) => ({
326
+ id: `${refOf(t)}#sshTests/${i}`,
327
+ ...this.meta(t),
328
+ kind: "ssh",
329
+ src: this.resolve(test.src, t, "sshTests src"),
330
+ dst: this.resolveAll(test.dst, t, "sshTests dst"),
331
+ accept: test.accept ?? [],
332
+ deny: test.deny ?? [],
333
+ check: test.check ?? []
334
+ })
335
+ );
336
+ return [...acl, ...sshTests];
337
+ });
338
+ const catalog = this.catalogGrants(catalogEntities, grants);
339
+ grants.push(...catalog.grants);
340
+ this.checkPorts(grants);
341
+ for (const tag of tags) tag.usage = this.tagUsage.get(tag.tag) ?? 0;
342
+ const groups = [...this.dir.groups.values()].filter((g) => g.annotated || this.usedGroups.has(g.name)).sort((a, b) => a.name.localeCompare(b.name)).map((g) => ({
343
+ name: g.name,
344
+ entityRef: g.ref,
345
+ title: g.title,
346
+ description: g.description,
347
+ usage: this.usedGroups.get(g.name) ?? 0,
348
+ members: g.memberRefs.map((ref) => {
349
+ const user = this.dir.users.get(ref);
350
+ if (!user?.login) {
351
+ this.error(
352
+ `${ref} is in ${g.name} but has no ${backstagePluginTailscaleCommon.ANNOTATION_TAILNET_LOGIN} annotation`,
353
+ ref
354
+ );
355
+ }
356
+ return { entityRef: ref, login: user?.login, title: user?.title };
357
+ })
358
+ }));
359
+ const hosts = Object.entries(this.hosts).map(
360
+ ([name, address]) => ({ name, address })
361
+ );
362
+ const settings = this.policy.spec.settings ?? {};
363
+ const reserved = /* @__PURE__ */ new Set([
364
+ "groups",
365
+ "hosts",
366
+ "tagOwners",
367
+ "nodeAttrs",
368
+ "autoApprovers",
369
+ "ssh",
370
+ "grants",
371
+ "acls",
372
+ "tests",
373
+ "sshTests"
374
+ ]);
375
+ for (const key of Object.keys(settings)) {
376
+ if (reserved.has(key)) {
377
+ this.error(
378
+ `settings.${key}: ${key} comes from Tailscale entities, not settings`,
379
+ this.policy
380
+ );
381
+ }
382
+ }
383
+ const view = {
384
+ entityRef: refOf(this.policy),
385
+ name: this.policy.metadata.name,
386
+ title: this.policy.metadata.title,
387
+ description: this.policy.metadata.description,
388
+ tailnet: this.policy.spec.tailnet,
389
+ owner: this.policy.spec.owner,
390
+ publish: this.policy.spec.publish,
391
+ renderedAt: (/* @__PURE__ */ new Date()).toISOString(),
392
+ text: "",
393
+ spans: [],
394
+ parts: [],
395
+ groups,
396
+ hosts,
397
+ tags,
398
+ grants,
399
+ ssh,
400
+ nodeAttrs,
401
+ autoApprovers,
402
+ tests,
403
+ settings: Object.keys(settings).filter((k) => !reserved.has(k)),
404
+ catalog: catalog.info,
405
+ destinations: this.destinations(grants, autoApprovers),
406
+ diagnostics: this.diagnostics
407
+ };
408
+ render(view, settings, baseUrl, this.parts.length + 1);
409
+ view.parts = [this.policy, ...this.parts].map((p) => {
410
+ const ref = refOf(p);
411
+ return {
412
+ entityRef: ref,
413
+ type: p.spec.type,
414
+ name: p.metadata.name,
415
+ title: p.metadata.title,
416
+ description: p.metadata.description,
417
+ lines: view.spans.filter((s) => s.entityRef === ref).map((s) => s.lines)
418
+ };
419
+ }).sort((a, b) => a.name.localeCompare(b.name));
420
+ return view;
421
+ }
422
+ /**
423
+ * Ports that say less than they could: a grant with capabilities on every
424
+ * port, and a grant to a Service on every port.
425
+ */
426
+ checkPorts(grants) {
427
+ for (const g of grants.filter((x) => x.ip.includes("*"))) {
428
+ const where = g.entityRef ?? g.edges?.[0]?.api;
429
+ if (g.app) {
430
+ this.warn(
431
+ `carries ${Object.keys(g.app).join(
432
+ ", "
433
+ )} on every port: name the port the app listens on`,
434
+ where
435
+ );
436
+ }
437
+ const services = g.dst.filter((d) => d.kind === "service").map((d) => d.name);
438
+ if (services.length) {
439
+ this.warn(
440
+ `reaches every port of ${services.join(
441
+ ", "
442
+ )}: name the ports. On some hosts a Service's address passes every port through to the device, not just those it serves`,
443
+ where
444
+ );
445
+ }
446
+ }
447
+ }
448
+ /** Every grant destination, and what it is; a device without a reason is a problem. */
449
+ destinations(grants, approvers) {
450
+ const views = /* @__PURE__ */ new Map();
451
+ for (const g of grants) {
452
+ for (const d of g.dst) {
453
+ const view = views.get(d.name) ?? {
454
+ name: d.name,
455
+ class: "device",
456
+ entityRef: d.kind === "tag" ? d.entityRef : void 0,
457
+ grants: [],
458
+ serves: []
459
+ };
460
+ view.grants.push(g.id);
461
+ views.set(d.name, view);
462
+ }
463
+ }
464
+ const reachedBy = (name) => grants.filter((g) => g.dst.some((d) => d.name === name));
465
+ for (const view of views.values()) {
466
+ const tag = view.name.startsWith("tag:") ? this.tagEntities.get(view.name) : void 0;
467
+ view.reason = tag?.metadata.annotations?.[backstagePluginTailscaleCommon.ANNOTATION_DEVICE_REASON]?.trim() || void 0;
468
+ view.serves = approvers.filter(
469
+ (a) => a.kind === "service" && a.approvers.some((p) => p.name === view.name)
470
+ ).map((a) => a.target);
471
+ const grantsTo = reachedBy(view.name);
472
+ if (view.name === "*") view.class = "any";
473
+ else if (view.name.startsWith("svc:")) view.class = "service";
474
+ else if (view.name.startsWith("autogroup:")) view.class = "autogroup";
475
+ else if (grants.some(
476
+ (g) => g.src.some((s) => s.name === view.name) && g.dst.some((d) => d.name === view.name)
477
+ )) {
478
+ view.class = "mesh";
479
+ } else if (grantsTo.some((g) => g.app)) view.class = "capability";
480
+ else view.class = "device";
481
+ if (view.class === "device" && view.entityRef && // an undeclared tag is an error already
482
+ !view.reason) {
483
+ const by = grantsTo.map((g) => g.entityRef ?? g.title ?? g.id);
484
+ this.warn(
485
+ `${view.name} is reached as a device, not a Service (${by.join(
486
+ ", "
487
+ )})${view.serves.length ? `, though it serves ${view.serves.join(", ")}` : ""}: move the traffic to a Service, or say why on its tag entity (${backstagePluginTailscaleCommon.ANNOTATION_DEVICE_REASON})`,
488
+ view.entityRef
489
+ );
490
+ }
491
+ }
492
+ const order = [
493
+ "service",
494
+ "mesh",
495
+ "capability",
496
+ "autogroup",
497
+ "device",
498
+ "any"
499
+ ];
500
+ return [...views.values()].sort(
501
+ (a, b) => order.indexOf(a.class) - order.indexOf(b.class) || a.name.localeCompare(b.name)
502
+ );
503
+ }
504
+ /**
505
+ * Grants from the catalog: a Component consuming an API across the
506
+ * tailnet, and whoever an API's tailnet-allow names. Flows to the same
507
+ * destination and ports share a grant; grants with the same sources and
508
+ * destinations are then merged. A flow an entity grant already allows by
509
+ * name gets none; one only a "*" destination allows still gets its own,
510
+ * so the policy doesn't hang on a break-glass grant.
511
+ */
512
+ catalogGrants(entities, declared) {
513
+ const info = {
514
+ enabled: !!this.policy.spec.catalogGrants,
515
+ covered: [],
516
+ local: [],
517
+ missingSource: [],
518
+ invalid: []
519
+ };
520
+ if (!info.enabled) return { grants: [], info };
521
+ const graph$1 = graph.buildTailnetGraph(entities);
522
+ info.local = graph$1.local;
523
+ info.missingSource = graph$1.missingSource;
524
+ info.invalid = graph$1.invalid;
525
+ const coveredBy = (src, dst, port) => declared.filter(
526
+ (g) => g.src.some(
527
+ (s) => s.name === src || s.name === "*" || s.name === "autogroup:tagged" && src.startsWith("tag:")
528
+ ) && g.dst.some((d) => d.name === dst) && g.ip.some((p) => {
529
+ const range = backstagePluginTailscaleCommon.parsePort(p);
530
+ return range && backstagePluginTailscaleCommon.portCovers(range, port);
531
+ })
532
+ ).map((g) => g.id);
533
+ const byPorts = /* @__PURE__ */ new Map();
534
+ for (const edge of graph$1.edges) {
535
+ const view = {
536
+ consumer: edge.consumer,
537
+ api: edge.api,
538
+ providers: edge.providers,
539
+ via: edge.via,
540
+ src: edge.src,
541
+ dst: edge.dst,
542
+ ports: edge.ports.map(backstagePluginTailscaleCommon.formatPort)
543
+ };
544
+ const flows = edge.src.flatMap(
545
+ (s) => edge.dst.flatMap((d) => edge.ports.map((p) => coveredBy(s, d, p)))
546
+ );
547
+ if (flows.every((ids) => ids.length)) {
548
+ info.covered.push({ ...view, coveredBy: [...new Set(flows.flat())] });
549
+ continue;
550
+ }
551
+ const dst = [...edge.dst].sort();
552
+ const ip = view.ports.slice().sort();
553
+ const key = `${dst.join(",")}|${ip.join(",")}`;
554
+ const entry = byPorts.get(key) ?? { dst, ip, edges: [] };
555
+ entry.edges.push(view);
556
+ byPorts.set(key, entry);
557
+ }
558
+ const merged = /* @__PURE__ */ new Map();
559
+ for (const entry of byPorts.values()) {
560
+ const src = [...new Set(entry.edges.flatMap((e) => e.src))].sort();
561
+ const key = `${src.join(",")}>${entry.dst.join(",")}`;
562
+ const into = merged.get(key) ?? {
563
+ src,
564
+ dst: entry.dst,
565
+ ip: [],
566
+ edges: []
567
+ };
568
+ into.ip = [.../* @__PURE__ */ new Set([...into.ip, ...entry.ip])].sort(byPort);
569
+ for (const e of entry.edges) {
570
+ if (!into.edges.includes(e)) into.edges.push(e);
571
+ }
572
+ merged.set(key, into);
573
+ }
574
+ const grants = [...merged.values()].sort(
575
+ (a, b) => a.dst.join(",").localeCompare(b.dst.join(",")) || a.src.join(",").localeCompare(b.src.join(","))
576
+ ).map((entry) => {
577
+ const consumers = entry.edges.filter((e) => e.via === "consumesApi");
578
+ const allowed = entry.edges.filter((e) => e.via === "tailnet-allow");
579
+ const said = [
580
+ consumers.length ? `Consumed by ${unique(consumers.map((e) => e.consumer)).join(
581
+ ", "
582
+ )}.` : "",
583
+ allowed.length ? `Used by ${[...new Set(allowed.flatMap((e) => e.src))].join(
584
+ ", "
585
+ )} (tailnet-allow).` : ""
586
+ ];
587
+ return {
588
+ id: `catalog:${entry.src.join(",")}>${entry.dst.join(
589
+ ","
590
+ )}|${entry.ip.join(",")}`,
591
+ origin: "catalog",
592
+ title: `From the catalog: ${unique(entry.edges.map((e) => e.api)).join(
593
+ ", "
594
+ )}`,
595
+ description: said.filter(Boolean).join(" "),
596
+ src: entry.src.map((s) => {
597
+ const edge = entry.edges.find((e) => e.src.includes(s));
598
+ return this.resolve(
599
+ s,
600
+ edge.consumer,
601
+ edge.via === "consumesApi" ? "specht-labs.de/tailnet-src" : "specht-labs.de/tailnet-allow"
602
+ );
603
+ }),
604
+ dst: entry.dst.map(
605
+ (d) => this.resolve(d, entry.edges[0].api, "specht-labs.de/tailnet-dst")
606
+ ),
607
+ ip: entry.ip,
608
+ edges: entry.edges
609
+ };
610
+ });
611
+ return { grants, info };
612
+ }
613
+ }
614
+ function byPort(a, b) {
615
+ const pa = backstagePluginTailscaleCommon.parsePort(a);
616
+ const pb = backstagePluginTailscaleCommon.parsePort(b);
617
+ return (pa?.proto ?? "").localeCompare(pb?.proto ?? "") || (pa?.from ?? 0) - (pb?.from ?? 0);
618
+ }
619
+ const names = (list) => list?.map((p) => p.name);
620
+ function render(view, settings, baseUrl, entityCount) {
621
+ const w = new hujson.HujsonWriter();
622
+ const spans = [];
623
+ const mark = (rule, section2, lines) => {
624
+ rule.lines = lines;
625
+ if (rule.entityRef)
626
+ spans.push({ entityRef: rule.entityRef, section: section2, lines });
627
+ };
628
+ let commented;
629
+ const comment = (rule, depth) => {
630
+ if (rule.entityRef && rule.entityRef === commented) return;
631
+ commented = rule.entityRef;
632
+ w.comment(
633
+ [rule.title, rule.description].filter(Boolean).join("\n\n"),
634
+ depth
635
+ );
636
+ };
637
+ const item = (rule, section2, key, value, depth = 2) => {
638
+ const from = w.next;
639
+ comment(rule, depth);
640
+ const [, to] = w.value(key, value, depth);
641
+ mark(rule, section2, [from, to]);
642
+ };
643
+ const policyUrl = baseUrl && `${baseUrl}/catalog/${catalogModel.parseEntityRef(view.entityRef).namespace}/tailscale/${view.name}`;
644
+ w.comment(
645
+ `${view.title ?? view.name}${view.tailnet ? ` (${view.tailnet})` : ""}. Rendered by Backstage from ${entityCount} Tailscale entities and the catalog's users and groups; change those, not this file.`,
646
+ 0
647
+ );
648
+ if (policyUrl) w.raw(`// ${policyUrl}`);
649
+ w.raw("{");
650
+ const section = (key, open, body) => {
651
+ commented = void 0;
652
+ w.blank();
653
+ w.raw(`${JSON.stringify(key)}: ${open}`, 1);
654
+ body();
655
+ w.raw(open === "{" ? "}," : "],", 1);
656
+ };
657
+ if (view.groups.length) {
658
+ section("groups", "{", () => {
659
+ for (const group of view.groups) {
660
+ const from = w.next;
661
+ w.comment(group.title ?? group.description, 2);
662
+ w.raw(`${JSON.stringify(group.name)}: [`, 2);
663
+ for (const member of group.members) {
664
+ const line = w.next;
665
+ w.raw(`${JSON.stringify(member.login ?? member.entityRef)},`, 3);
666
+ spans.push({
667
+ entityRef: member.entityRef,
668
+ section: "groups",
669
+ lines: [line, line]
670
+ });
671
+ }
672
+ w.raw("],", 2);
673
+ group.lines = [from, w.next - 1];
674
+ spans.push({
675
+ entityRef: group.entityRef,
676
+ section: "groups",
677
+ lines: group.lines
678
+ });
679
+ }
680
+ });
681
+ }
682
+ if (view.hosts.length) {
683
+ section("hosts", "{", () => {
684
+ const width = Math.max(
685
+ ...view.hosts.map((h) => JSON.stringify(h.name).length)
686
+ );
687
+ for (const host of view.hosts) {
688
+ const line = w.next;
689
+ w.raw(
690
+ `${`${JSON.stringify(host.name)}:`.padEnd(width + 2)}${JSON.stringify(
691
+ host.address
692
+ )},`,
693
+ 2
694
+ );
695
+ host.lines = [line, line];
696
+ spans.push({
697
+ entityRef: view.entityRef,
698
+ section: "hosts",
699
+ lines: host.lines
700
+ });
701
+ }
702
+ });
703
+ }
704
+ if (view.tags.length) {
705
+ section("tagOwners", "{", () => {
706
+ for (const tag of view.tags)
707
+ item(tag, "tagOwners", tag.tag, names(tag.owners));
708
+ });
709
+ }
710
+ if (view.nodeAttrs.length) {
711
+ section("nodeAttrs", "[", () => {
712
+ for (const n of view.nodeAttrs) {
713
+ item(n, "nodeAttrs", void 0, {
714
+ target: names(n.nodes),
715
+ attr: n.attr.length ? n.attr : void 0,
716
+ app: n.app,
717
+ ipPool: n.ipPool
718
+ });
719
+ }
720
+ });
721
+ }
722
+ if (view.autoApprovers.length) {
723
+ section("autoApprovers", "{", () => {
724
+ const groupsOf = (kind) => {
725
+ const merged = /* @__PURE__ */ new Map();
726
+ for (const rule of view.autoApprovers.filter((r) => r.kind === kind)) {
727
+ const entry = merged.get(rule.target) ?? { rules: [], approvers: [] };
728
+ entry.rules.push(rule);
729
+ for (const a of rule.approvers) {
730
+ if (!entry.approvers.includes(a.name)) entry.approvers.push(a.name);
731
+ }
732
+ merged.set(rule.target, entry);
733
+ }
734
+ return merged;
735
+ };
736
+ const block = (key, kind) => {
737
+ const merged = groupsOf(kind);
738
+ if (!merged.size) return;
739
+ w.raw(`${JSON.stringify(key)}: {`, 2);
740
+ const written = /* @__PURE__ */ new Map();
741
+ for (const rule of view.autoApprovers.filter((r) => r.kind === kind)) {
742
+ const done = written.get(rule.target);
743
+ if (done) {
744
+ mark(rule, "autoApprovers", done);
745
+ continue;
746
+ }
747
+ const from = w.next;
748
+ comment(rule, 3);
749
+ const [, to] = w.value(
750
+ rule.target,
751
+ merged.get(rule.target).approvers,
752
+ 3
753
+ );
754
+ written.set(rule.target, [from, to]);
755
+ mark(rule, "autoApprovers", [from, to]);
756
+ }
757
+ w.raw("},", 2);
758
+ };
759
+ block("routes", "route");
760
+ block("services", "service");
761
+ const exit = groupsOf("exitNode").get("exit node");
762
+ if (exit) {
763
+ const from = w.next;
764
+ const [, to] = w.value("exitNode", exit.approvers, 2);
765
+ for (const r of exit.rules) mark(r, "autoApprovers", [from, to]);
766
+ }
767
+ });
768
+ }
769
+ if (view.ssh.length) {
770
+ section("ssh", "[", () => {
771
+ for (const s of view.ssh) {
772
+ item(s, "ssh", void 0, {
773
+ action: s.action,
774
+ checkPeriod: s.checkPeriod,
775
+ src: names(s.src),
776
+ dst: names(s.dst),
777
+ users: s.users,
778
+ acceptEnv: s.acceptEnv,
779
+ recorder: names(s.recorder),
780
+ enforceRecorder: s.enforceRecorder
781
+ });
782
+ }
783
+ });
784
+ }
785
+ if (view.grants.length) {
786
+ section("grants", "[", () => {
787
+ for (const g of view.grants) {
788
+ item(g, "grants", void 0, {
789
+ src: names(g.src),
790
+ dst: names(g.dst),
791
+ ip: g.ip.length ? g.ip : void 0,
792
+ via: names(g.via),
793
+ srcPosture: g.srcPosture,
794
+ app: g.app
795
+ });
796
+ }
797
+ });
798
+ }
799
+ const testsOf = (kind) => view.tests.filter((t) => t.kind === kind);
800
+ if (testsOf("acl").length) {
801
+ section("tests", "[", () => {
802
+ for (const t of testsOf("acl")) {
803
+ item(t, "tests", void 0, {
804
+ src: t.src.name,
805
+ proto: t.proto,
806
+ accept: t.accept.length ? t.accept : void 0,
807
+ deny: t.deny.length ? t.deny : void 0
808
+ });
809
+ }
810
+ });
811
+ }
812
+ if (testsOf("ssh").length) {
813
+ section("sshTests", "[", () => {
814
+ for (const t of testsOf("ssh")) {
815
+ item(t, "sshTests", void 0, {
816
+ src: t.src.name,
817
+ dst: names(t.dst),
818
+ accept: t.accept.length ? t.accept : void 0,
819
+ check: t.check.length ? t.check : void 0,
820
+ deny: t.deny.length ? t.deny : void 0
821
+ });
822
+ }
823
+ });
824
+ }
825
+ for (const key of view.settings) {
826
+ w.blank();
827
+ const [from, to] = w.value(key, settings[key], 1);
828
+ spans.push({ entityRef: view.entityRef, section: key, lines: [from, to] });
829
+ }
830
+ w.raw("}");
831
+ view.text = w.toString();
832
+ view.spans = spans;
833
+ }
834
+ function compileAll(entities, baseUrl) {
835
+ const dir = new Directory(entities);
836
+ const tailscale = entities.filter(backstagePluginTailscaleCommon.isTailscale).filter((e) => {
837
+ return backstagePluginTailscaleCommon.validateTailscaleSpec(e.spec).length === 0;
838
+ });
839
+ const policies = tailscale.filter(
840
+ (e) => e.spec.type === "policy"
841
+ );
842
+ const byRef = new Map(policies.map((p) => [refOf(p), p]));
843
+ const parts = new Map(
844
+ policies.map((p) => [refOf(p), []])
845
+ );
846
+ const orphans = [];
847
+ for (const part of tailscale.filter((e) => e.spec.type !== "policy")) {
848
+ const target = catalogModel.stringifyEntityRef(
849
+ catalogModel.parseEntityRef(part.spec.target, {
850
+ defaultKind: "tailscale",
851
+ defaultNamespace: part.metadata.namespace ?? "default"
852
+ })
853
+ );
854
+ if (!byRef.has(target)) {
855
+ orphans.push({
856
+ severity: "error",
857
+ entityRef: refOf(part),
858
+ message: `its target ${part.spec.target} is not a Tailscale policy in the catalog`
859
+ });
860
+ continue;
861
+ }
862
+ parts.get(target).push(part);
863
+ }
864
+ return {
865
+ renderedAt: (/* @__PURE__ */ new Date()).toISOString(),
866
+ orphans,
867
+ policies: policies.sort(byName).map(
868
+ (p) => new PolicyCompiler(dir, p, parts.get(refOf(p))).compile(
869
+ entities,
870
+ baseUrl
871
+ )
872
+ )
873
+ };
874
+ }
875
+
876
+ exports.compileAll = compileAll;
877
+ exports.shortRef = shortRef;
878
+ //# sourceMappingURL=compile.cjs.js.map