@mrsimpson/homelab-core-components 0.2.1 → 0.2.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"registry-secrets.js","sourceRoot":"","sources":["../src/registry-secrets.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,8DAgDC;AAeD,wEAwDC;AA5KD,wDAA0C;AAmB1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,SAAgB,yBAAyB,CACxC,IAA+B;IAE/B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,YAAY,CAAC;IAEjD,OAAO,IAAI,GAAG,CAAC,aAAa,CAAC,cAAc,CAC1C,oBAAoB,IAAI,CAAC,SAAS,EAAE,EACpC;QACC,UAAU,EAAE,6BAA6B;QACzC,IAAI,EAAE,gBAAgB;QACtB,QAAQ,EAAE;YACT,IAAI,EAAE,kBAAkB;YACxB,SAAS,EAAE,IAAI,CAAC,SAAS;SACzB;QACD,IAAI,EAAE;YACL,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE;gBACf,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,oBAAoB;aAC1B;YACD,MAAM,EAAE;gBACP,IAAI,EAAE,kBAAkB;gBACxB,cAAc,EAAE,OAAO;gBACvB,QAAQ,EAAE;oBACT,IAAI,EAAE,gCAAgC;oBACtC,IAAI,EAAE;wBACL,mBAAmB,EAAE,oKAAoK;qBACzL;iBACD;aACD;YACD,IAAI,EAAE;gBACL;oBACC,SAAS,EAAE,iBAAiB;oBAC5B,SAAS,EAAE;wBACV,GAAG,EAAE,iBAAiB;qBACtB;iBACD;gBACD;oBACC,SAAS,EAAE,cAAc;oBACzB,SAAS,EAAE;wBACV,GAAG,EAAE,cAAc;qBACnB;iBACD;aACD;SACD;KACD,EACD,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAC7B,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,8BAA8B,CAC7C,IAA+B;IAE/B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,YAAY,CAAC;IAEjD,OAAO,IAAI,GAAG,CAAC,aAAa,CAAC,cAAc,CAC1C,yBAAyB,IAAI,CAAC,SAAS,EAAE,EACzC;QACC,UAAU,EAAE,6BAA6B;QACzC,IAAI,EAAE,gBAAgB;QACtB,QAAQ,EAAE;YACT,IAAI,EAAE,uBAAuB;YAC7B,SAAS,EAAE,IAAI,CAAC,SAAS;SACzB;QACD,IAAI,EAAE;YACL,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE;gBACf,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,oBAAoB;aAC1B;YACD,MAAM,EAAE;gBACP,IAAI,EAAE,uBAAuB;gBAC7B,cAAc,EAAE,OAAO;gBACvB,QAAQ,EAAE;oBACT,IAAI,EAAE,gCAAgC;oBACtC,IAAI,EAAE;wBACL,mBAAmB,EAAE;;;;;;;;EAQ1B;qBACK;iBACD;aACD;YACD,IAAI,EAAE;gBACL;oBACC,SAAS,EAAE,oBAAoB;oBAC/B,SAAS,EAAE;wBACV,GAAG,EAAE,gCAAgC;qBACrC;iBACD;gBACD;oBACC,SAAS,EAAE,iBAAiB;oBAC5B,SAAS,EAAE;wBACV,GAAG,EAAE,6BAA6B;qBAClC;iBACD;aACD;SACD;KACD,EACD,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAC7B,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"registry-secrets.js","sourceRoot":"","sources":["../src/registry-secrets.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,8DAgDC;AAeD,wEAwDC;AA5KD,wDAA0C;AAmB1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,SAAgB,yBAAyB,CACvC,IAA+B;IAE/B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,YAAY,CAAC;IAEjD,OAAO,IAAI,GAAG,CAAC,aAAa,CAAC,cAAc,CACzC,oBAAoB,IAAI,CAAC,SAAS,EAAE,EACpC;QACE,UAAU,EAAE,6BAA6B;QACzC,IAAI,EAAE,gBAAgB;QACtB,QAAQ,EAAE;YACR,IAAI,EAAE,kBAAkB;YACxB,SAAS,EAAE,IAAI,CAAC,SAAS;SAC1B;QACD,IAAI,EAAE;YACJ,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE;gBACd,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,oBAAoB;aAC3B;YACD,MAAM,EAAE;gBACN,IAAI,EAAE,kBAAkB;gBACxB,cAAc,EAAE,OAAO;gBACvB,QAAQ,EAAE;oBACR,IAAI,EAAE,gCAAgC;oBACtC,IAAI,EAAE;wBACJ,mBAAmB,EAAE,oKAAoK;qBAC1L;iBACF;aACF;YACD,IAAI,EAAE;gBACJ;oBACE,SAAS,EAAE,iBAAiB;oBAC5B,SAAS,EAAE;wBACT,GAAG,EAAE,iBAAiB;qBACvB;iBACF;gBACD;oBACE,SAAS,EAAE,cAAc;oBACzB,SAAS,EAAE;wBACT,GAAG,EAAE,cAAc;qBACpB;iBACF;aACF;SACF;KACF,EACD,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAC9B,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,8BAA8B,CAC5C,IAA+B;IAE/B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,YAAY,CAAC;IAEjD,OAAO,IAAI,GAAG,CAAC,aAAa,CAAC,cAAc,CACzC,yBAAyB,IAAI,CAAC,SAAS,EAAE,EACzC;QACE,UAAU,EAAE,6BAA6B;QACzC,IAAI,EAAE,gBAAgB;QACtB,QAAQ,EAAE;YACR,IAAI,EAAE,uBAAuB;YAC7B,SAAS,EAAE,IAAI,CAAC,SAAS;SAC1B;QACD,IAAI,EAAE;YACJ,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE;gBACd,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,oBAAoB;aAC3B;YACD,MAAM,EAAE;gBACN,IAAI,EAAE,uBAAuB;gBAC7B,cAAc,EAAE,OAAO;gBACvB,QAAQ,EAAE;oBACR,IAAI,EAAE,gCAAgC;oBACtC,IAAI,EAAE;wBACJ,mBAAmB,EAAE;;;;;;;;EAQjC;qBACW;iBACF;aACF;YACD,IAAI,EAAE;gBACJ;oBACE,SAAS,EAAE,oBAAoB;oBAC/B,SAAS,EAAE;wBACT,GAAG,EAAE,gCAAgC;qBACtC;iBACF;gBACD;oBACE,SAAS,EAAE,iBAAiB;oBAC5B,SAAS,EAAE;wBACT,GAAG,EAAE,6BAA6B;qBACnC;iBACF;aACF;SACF;KACF,EACD,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAC9B,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrsimpson/homelab-core-components",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Reusable Pulumi components for secure homelab infrastructure",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -29,7 +29,7 @@
29
29
  "license": "MIT",
30
30
  "repository": {
31
31
  "type": "git",
32
- "url": "https://github.com/mrsimpson/homelab.git",
32
+ "url": "https://github.com/digitaleraluhut/homelab.git",
33
33
  "directory": "packages/core/components"
34
34
  },
35
35
  "publishConfig": {
@@ -0,0 +1,49 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ import { beforeAll, describe, expect, it } from "vitest";
3
+
4
+ // A PVC on a WaitForFirstConsumer storage class (longhorn-persistent) binds only once a
5
+ // pod uses it. If the Deployment waited for the PVC, neither would ever finish.
6
+ // The mock models that: the PVC never completes.
7
+ const created: Array<{ type: string; name: string; inputs: Record<string, unknown> }> = [];
8
+
9
+ beforeAll(async () => {
10
+ pulumi.runtime.setMocks(
11
+ {
12
+ newResource: (args) => {
13
+ created.push({ type: args.type, name: args.name, inputs: args.inputs });
14
+ if (args.type === "kubernetes:core/v1:PersistentVolumeClaim") {
15
+ return new Promise(() => {}) as never;
16
+ }
17
+ return { id: `${args.name}-id`, state: args.inputs };
18
+ },
19
+ call: (args) => args.inputs,
20
+ },
21
+ "homelab",
22
+ "test",
23
+ false
24
+ );
25
+ const { ExposedWebApp } = await import("./ExposedWebApp");
26
+ new ExposedWebApp("demo", {
27
+ image: "nginxinc/nginx-unprivileged:alpine",
28
+ domain: "demo.example.org",
29
+ port: 8080,
30
+ storage: { size: "1Gi", mountPath: "/data", storageClass: "longhorn-persistent" },
31
+ });
32
+ await new Promise((r) => setTimeout(r, 200));
33
+ });
34
+
35
+ describe("ExposedWebApp with storage", () => {
36
+ it("creates the Deployment without waiting for the PVC to bind", () => {
37
+ expect(created.some((c) => c.type === "kubernetes:core/v1:PersistentVolumeClaim")).toBe(true);
38
+ expect(created.some((c) => c.type === "kubernetes:apps/v1:Deployment")).toBe(true);
39
+ });
40
+
41
+ it("mounts the PVC by its fixed name", () => {
42
+ const dep = created.find((c) => c.type === "kubernetes:apps/v1:Deployment");
43
+ type Spec = {
44
+ template: { spec: { volumes: Array<{ persistentVolumeClaim?: { claimName: string } }> } };
45
+ };
46
+ const volumes = (dep?.inputs.spec as Spec).template.spec.volumes;
47
+ expect(volumes.map((v) => v.persistentVolumeClaim?.claimName)).toContain("demo-storage");
48
+ });
49
+ });
@@ -240,18 +240,12 @@ export class ExposedWebApp extends pulumi.ComponentResource {
240
240
  public readonly deployment: k8s.apps.v1.Deployment;
241
241
  public readonly service: k8s.core.v1.Service;
242
242
  /** Route resource(s): single HTTPRoute (Authelia/NONE) or IngressRoute[] (OAuth2-Proxy) */
243
- public readonly route:
244
- | k8s.apiextensions.CustomResource
245
- | k8s.apiextensions.CustomResource[];
243
+ public readonly route: k8s.apiextensions.CustomResource | k8s.apiextensions.CustomResource[];
246
244
  public readonly forwardAuthMiddleware?: k8s.apiextensions.CustomResource;
247
245
  public readonly dnsRecord?: cloudflare.Record;
248
246
  public readonly pvc?: k8s.core.v1.PersistentVolumeClaim;
249
247
 
250
- constructor(
251
- name: string,
252
- args: ExposedWebAppArgs,
253
- opts?: pulumi.ComponentResourceOptions,
254
- ) {
248
+ constructor(name: string, args: ExposedWebAppArgs, opts?: pulumi.ComponentResourceOptions) {
255
249
  super("homelab:ExposedWebApp", name, {}, opts);
256
250
 
257
251
  const childOpts = { parent: this };
@@ -263,7 +257,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
263
257
  // - "privileged": required when hostPath volumes are present (hostPath is
264
258
  // forbidden even in baseline per the K8s PSS spec)
265
259
  const hasHostPath = args.extraVolumes?.some(
266
- (v) => typeof v === "object" && v !== null && "hostPath" in v,
260
+ (v) => typeof v === "object" && v !== null && "hostPath" in v
267
261
  );
268
262
  const podSecurityLevel = hasHostPath
269
263
  ? "privileged"
@@ -287,7 +281,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
287
281
  },
288
282
  },
289
283
  },
290
- childOpts,
284
+ childOpts
291
285
  );
292
286
  this.namespace = namespace;
293
287
 
@@ -348,8 +342,8 @@ export class ExposedWebApp extends pulumi.ComponentResource {
348
342
  ],
349
343
  },
350
344
  },
351
- { ...childOpts, dependsOn: externalSecretDeps },
352
- ),
345
+ { ...childOpts, dependsOn: externalSecretDeps }
346
+ )
353
347
  );
354
348
  } else if (pullSecret.name === "dockerhub-pull-secret") {
355
349
  pullSecretResources.push(
@@ -402,8 +396,8 @@ export class ExposedWebApp extends pulumi.ComponentResource {
402
396
  ],
403
397
  },
404
398
  },
405
- { ...childOpts, dependsOn: externalSecretDeps },
406
- ),
399
+ { ...childOpts, dependsOn: externalSecretDeps }
400
+ )
407
401
  );
408
402
  }
409
403
  });
@@ -428,7 +422,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
428
422
  },
429
423
  },
430
424
  },
431
- childOpts,
425
+ childOpts
432
426
  );
433
427
  }
434
428
 
@@ -498,7 +492,10 @@ export class ExposedWebApp extends pulumi.ComponentResource {
498
492
  volumes.push({
499
493
  name: "storage",
500
494
  persistentVolumeClaim: {
501
- claimName: this.pvc.metadata.name,
495
+ // The fixed name, not this.pvc.metadata.name: an output would make the Deployment
496
+ // wait for the PVC, which on WaitForFirstConsumer classes binds only once a pod
497
+ // uses it (deadlock). The pod waits for the claim by itself.
498
+ claimName: `${name}-storage`,
502
499
  },
503
500
  });
504
501
  }
@@ -508,10 +505,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
508
505
 
509
506
  // Create Deployment
510
507
  // Build deployment dependencies - include pull secrets if we created them
511
- const deploymentDeps: pulumi.Resource[] = [
512
- namespace,
513
- ...pullSecretResources,
514
- ];
508
+ const deploymentDeps: pulumi.Resource[] = [namespace, ...pullSecretResources];
515
509
 
516
510
  this.deployment = new k8s.apps.v1.Deployment(
517
511
  `${name}-deployment`,
@@ -543,9 +537,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
543
537
  nodeSelector: args.nodeSelector,
544
538
  securityContext: {
545
539
  // Only enforce runAsNonRoot when the image supports it (opt-out via allowRoot)
546
- ...(args.securityContext?.allowRoot
547
- ? {}
548
- : { runAsNonRoot: true }),
540
+ ...(args.securityContext?.allowRoot ? {} : { runAsNonRoot: true }),
549
541
  // When allowRoot is true, omit runAsUser/runAsGroup to let the image use its own UID
550
542
  ...(args.securityContext?.allowRoot
551
543
  ? {}
@@ -559,8 +551,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
559
551
  },
560
552
  containers: [
561
553
  appContainer,
562
- ...((args.extraContainers ??
563
- []) as k8s.types.input.core.v1.Container[]),
554
+ ...((args.extraContainers ?? []) as k8s.types.input.core.v1.Container[]),
564
555
  ],
565
556
  initContainers: args.initContainers as
566
557
  | k8s.types.input.core.v1.Container[]
@@ -570,7 +561,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
570
561
  },
571
562
  },
572
563
  },
573
- { ...childOpts, dependsOn: deploymentDeps },
564
+ { ...childOpts, dependsOn: deploymentDeps }
574
565
  );
575
566
 
576
567
  // Create Service
@@ -596,7 +587,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
596
587
  ],
597
588
  },
598
589
  },
599
- { ...childOpts, dependsOn: [this.deployment] },
590
+ { ...childOpts, dependsOn: [this.deployment] }
600
591
  );
601
592
 
602
593
  // --- Routing & Authentication ---
@@ -635,7 +626,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
635
626
  },
636
627
  },
637
628
  },
638
- { ...childOpts, dependsOn: [this.service] },
629
+ { ...childOpts, dependsOn: [this.service] }
639
630
  );
640
631
 
641
632
  // Use shared redirect service from oauth2-proxy namespace
@@ -664,7 +655,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
664
655
  },
665
656
  },
666
657
  },
667
- { ...childOpts, dependsOn: [this.service] },
658
+ { ...childOpts, dependsOn: [this.service] }
668
659
  );
669
660
 
670
661
  // Chain middleware - errors wraps forwardauth
@@ -689,7 +680,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
689
680
  {
690
681
  ...childOpts,
691
682
  dependsOn: [errorsMiddleware, this.forwardAuthMiddleware],
692
- },
683
+ }
693
684
  );
694
685
 
695
686
  // IngressRoute 1: /oauth2/* → oauth2-proxy (unprotected, handles sign-in flow)
@@ -720,7 +711,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
720
711
  ],
721
712
  },
722
713
  },
723
- { ...childOpts, dependsOn: [namespace] },
714
+ { ...childOpts, dependsOn: [namespace] }
724
715
  );
725
716
 
726
717
  // IngressRoute 2: /* → app backend (protected by middleware chain)
@@ -759,7 +750,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
759
750
  {
760
751
  ...childOpts,
761
752
  dependsOn: [this.service, chainMiddleware, signinRoute],
762
- },
753
+ }
763
754
  );
764
755
 
765
756
  this.route = [signinRoute, appRoute];
@@ -767,8 +758,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
767
758
  // --- Authelia / NONE: Gateway API HTTPRoute ---
768
759
 
769
760
  const gatewayName = args.gatewayApi?.gatewayName || "homelab-gateway";
770
- const gatewayNamespace =
771
- args.gatewayApi?.gatewayNamespace || "traefik-system";
761
+ const gatewayNamespace = args.gatewayApi?.gatewayNamespace || "traefik-system";
772
762
 
773
763
  // Build Gateway API dependencies
774
764
  const httpRouteDeps: pulumi.Resource[] = [this.service];
@@ -787,13 +777,12 @@ export class ExposedWebApp extends pulumi.ComponentResource {
787
777
  apiVersion: "traefik.io/v1alpha1",
788
778
  kind: "Middleware",
789
779
  metadata: {
790
- name: `forwardauth`,
780
+ name: "forwardauth",
791
781
  namespace: namespace.metadata.name,
792
782
  },
793
783
  spec: {
794
784
  forwardAuth: {
795
- address:
796
- "http://authelia.authelia.svc.cluster.local:9091/api/authz/auth-request",
785
+ address: "http://authelia.authelia.svc.cluster.local:9091/api/authz/auth-request",
797
786
  trustForwardHeader: true,
798
787
  authRequestHeaders: [
799
788
  "X-Original-URL",
@@ -817,7 +806,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
817
806
  {
818
807
  ...childOpts,
819
808
  dependsOn: httpRouteDeps,
820
- },
809
+ }
821
810
  );
822
811
 
823
812
  httpRouteDeps.push(this.forwardAuthMiddleware);
@@ -905,7 +894,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
905
894
  {
906
895
  ...childOpts,
907
896
  dependsOn: httpRouteDeps,
908
- },
897
+ }
909
898
  );
910
899
  }
911
900
 
@@ -926,7 +915,7 @@ export class ExposedWebApp extends pulumi.ComponentResource {
926
915
  // or when the Pulumi URN changes due to refactoring).
927
916
  allowOverwrite: true,
928
917
  },
929
- childOpts,
918
+ childOpts
930
919
  );
931
920
  }
932
921
 
@@ -0,0 +1,54 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ import { beforeAll, describe, expect, it } from "vitest";
3
+
4
+ const created: Array<{ type: string; name: string; inputs: Record<string, unknown> }> = [];
5
+
6
+ beforeAll(async () => {
7
+ pulumi.runtime.setMocks(
8
+ {
9
+ newResource: (args) => {
10
+ created.push({ type: args.type, name: args.name, inputs: args.inputs });
11
+ return { id: `${args.name}-id`, state: args.inputs };
12
+ },
13
+ call: (args) => args.inputs,
14
+ },
15
+ "app",
16
+ "test",
17
+ false
18
+ );
19
+ const { createAppNamespace } = await import("./app-namespace");
20
+ createAppNamespace("gitea");
21
+ await new Promise((r) => setTimeout(r, 50));
22
+ });
23
+
24
+ const of = (type: string) => created.find((c) => c.type === type);
25
+
26
+ describe("createAppNamespace", () => {
27
+ it("creates the namespace owned by the CI, pod-security restricted", () => {
28
+ const meta = of("kubernetes:core/v1:Namespace")?.inputs.metadata as {
29
+ name: string;
30
+ labels: Record<string, string>;
31
+ };
32
+ expect(meta.name).toBe("gitea");
33
+ expect(meta.labels["homelab/deployer"]).toBe("homelab-apps");
34
+ for (const mode of ["enforce", "audit", "warn"]) {
35
+ expect(meta.labels[`pod-security.kubernetes.io/${mode}`]).toBe("restricted");
36
+ }
37
+ });
38
+
39
+ it("binds the deployer role to the CI ServiceAccount in that namespace", () => {
40
+ const rb = of("kubernetes:rbac.authorization.k8s.io/v1:RoleBinding")?.inputs as {
41
+ metadata: { namespace: string };
42
+ roleRef: { kind: string; name: string };
43
+ subjects: Array<{ name: string; namespace: string }>;
44
+ };
45
+ expect(rb.metadata.namespace).toBe("gitea");
46
+ expect(rb.roleRef).toMatchObject({
47
+ kind: "ClusterRole",
48
+ name: "ci-access:homelab-apps:deployer",
49
+ });
50
+ expect(rb.subjects).toEqual([
51
+ { kind: "ServiceAccount", name: "homelab-apps", namespace: "ci-access" },
52
+ ]);
53
+ });
54
+ });
@@ -0,0 +1,45 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import type * as pulumi from "@pulumi/pulumi";
3
+
4
+ /**
5
+ * The namespace contract between the homelab-apps CI and the cluster.
6
+ * The homelab stack (core-infrastructure ci-access) admits CI-created namespaces and
7
+ * RoleBindings only if they follow it; apps create theirs with createAppNamespace().
8
+ */
9
+ export const APP_NAMESPACE_LABEL = "homelab/deployer";
10
+ export const APP_NAMESPACE_OWNER = "homelab-apps";
11
+ export const DEPLOYER_ROLE = "ci-access:homelab-apps:deployer";
12
+ export const CI_SUBJECT = { kind: "ServiceAccount", name: "homelab-apps", namespace: "ci-access" };
13
+
14
+ /**
15
+ * Creates an app's namespace (pod-security restricted, owned by the CI) and grants the CI
16
+ * its deployer rights there. Make the app's other resources depend on `binding`.
17
+ */
18
+ export function createAppNamespace(name: string, opts?: pulumi.CustomResourceOptions) {
19
+ const namespace = new k8s.core.v1.Namespace(
20
+ `${name}-ns`,
21
+ {
22
+ metadata: {
23
+ name,
24
+ labels: {
25
+ [APP_NAMESPACE_LABEL]: APP_NAMESPACE_OWNER,
26
+ "app.kubernetes.io/name": name,
27
+ "pod-security.kubernetes.io/enforce": "restricted",
28
+ "pod-security.kubernetes.io/audit": "restricted",
29
+ "pod-security.kubernetes.io/warn": "restricted",
30
+ },
31
+ },
32
+ },
33
+ opts
34
+ );
35
+ const binding = new k8s.rbac.v1.RoleBinding(
36
+ `${name}-deployer`,
37
+ {
38
+ metadata: { name: "homelab-apps:deployer", namespace: name },
39
+ roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "ClusterRole", name: DEPLOYER_ROLE },
40
+ subjects: [CI_SUBJECT],
41
+ },
42
+ { ...opts, dependsOn: [namespace] }
43
+ );
44
+ return { namespace, binding };
45
+ }
@@ -1,10 +1,6 @@
1
- import * as pulumi from "@pulumi/pulumi";
1
+ import type * as pulumi from "@pulumi/pulumi";
2
+ import type { ExternalSecretsConfig, GatewayApiConfig, TLSConfig } from "./ExposedWebApp";
2
3
  import { HomelabContext } from "./homelab-context";
3
- import type {
4
- ExternalSecretsConfig,
5
- GatewayApiConfig,
6
- TLSConfig,
7
- } from "./ExposedWebApp";
8
4
 
9
5
  /**
10
6
  * Optional overrides for infrastructure configuration that cannot be derived
@@ -1,5 +1,5 @@
1
- import * as k8s from "@pulumi/kubernetes";
2
- import * as pulumi from "@pulumi/pulumi";
1
+ import type * as k8s from "@pulumi/kubernetes";
2
+ import type * as pulumi from "@pulumi/pulumi";
3
3
  import type {
4
4
  CloudflareConfig,
5
5
  ExposedWebAppArgs,
package/src/index.ts CHANGED
@@ -5,6 +5,13 @@
5
5
  */
6
6
 
7
7
  export { ExposedWebApp, AuthType } from "./ExposedWebApp";
8
+ export {
9
+ APP_NAMESPACE_LABEL,
10
+ APP_NAMESPACE_OWNER,
11
+ CI_SUBJECT,
12
+ createAppNamespace,
13
+ DEPLOYER_ROLE,
14
+ } from "./app-namespace";
8
15
  export { HomelabContext } from "./homelab-context";
9
16
  export { createHomelabContextFromStack } from "./createHomelabContextFromStack";
10
17
  export type { HomelabContextFromStackOptions } from "./createHomelabContextFromStack";
@@ -22,3 +29,5 @@ export type {
22
29
  } from "./ExposedWebApp";
23
30
  export type { HomelabContextConfig } from "./homelab-context";
24
31
  export type { CreateImagePullSecretArgs } from "./registry-secrets";
32
+ export { PostgresInstance } from "./postgres/PostgresInstance";
33
+ export type { PostgresInstanceArgs } from "./postgres/PostgresInstance";
@@ -0,0 +1,229 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import * as pulumi from "@pulumi/pulumi";
3
+
4
+ /**
5
+ * PostgresInstance — per-app PostgreSQL backed by the CloudNativePG (CNPG) operator.
6
+ *
7
+ * Creates a CNPG `Cluster` CRD and an adapter `Secret` that exposes the generated
8
+ * credentials under canonical env var names (`POSTGRES_DB`, `POSTGRES_USER`,
9
+ * `POSTGRES_PASSWORD`, `DATABASE_URL`).
10
+ *
11
+ * See docs/howto/deploy-database.md for usage and the restore runbook.
12
+ */
13
+
14
+ // CNPG webhook rejects tags that don't start with the PG major version (e.g. "latest-pg18").
15
+ const DEFAULT_IMAGE = "postgres:18";
16
+ const DEFAULT_USERNAME = "app"; // CNPG convention: app user owns the app database
17
+ const DEFAULT_STORAGE_SIZE = "5Gi";
18
+ const DEFAULT_STORAGE_CLASS = "longhorn-persistent";
19
+ const DEFAULT_INSTANCES = 1;
20
+ const PG_PORT = 5432;
21
+ // Official postgres image (Debian) uses UID/GID 26 — matches CNPG's own default.
22
+ // Override at call site for non-standard images (paradedb uses 999).
23
+ const DEFAULT_POSTGRES_UID = 26;
24
+ const DEFAULT_POSTGRES_GID = 26;
25
+ export interface PostgresInstanceArgs {
26
+ /** Pre-created Kubernetes namespace to deploy into */
27
+ namespace: k8s.core.v1.Namespace;
28
+
29
+ /** Name of the database to create */
30
+ databaseName: pulumi.Input<string>;
31
+
32
+ /**
33
+ * Container image for Postgres.
34
+ * Must start with the PG major version (e.g. `18`) — CNPG's webhook rejects `latest`.
35
+ * @default "postgres:18"
36
+ */
37
+ image?: pulumi.Input<string>;
38
+
39
+ /** @default "app" — CNPG convention */
40
+ username?: pulumi.Input<string>;
41
+
42
+ /** @default "5Gi" */
43
+ storageSize?: pulumi.Input<string>;
44
+
45
+ /**
46
+ * @default "longhorn-persistent" — daily R2 backup, 7-day retention
47
+ */
48
+ storageClass?: pulumi.Input<string>;
49
+
50
+ /**
51
+ * Primary + hot-standby count. Set to 3 for HA — CNPG handles promotion automatically.
52
+ * @default 1
53
+ */
54
+ instances?: number;
55
+
56
+ /**
57
+ * UID/GID for the postgres OS user. Official postgres image uses 26; paradedb uses 999.
58
+ * **Immutable** — changing requires cluster deletion and recreation.
59
+ * @default 26
60
+ */
61
+ postgresUID?: number;
62
+ postgresGID?: number;
63
+
64
+ /**
65
+ * Libraries for `shared_preload_libraries`. Required for extensions that cannot load
66
+ * on demand (e.g. `pg_search`, `pg_cron`).
67
+ * @default []
68
+ */
69
+ sharedPreloadLibraries?: string[];
70
+
71
+ /**
72
+ * SQL run as superuser in the app database at bootstrap — before the app user connects.
73
+ * Use to pre-install superuser-only extensions so app migrations are no-ops.
74
+ * Only runs once at cluster creation; not re-applied on updates.
75
+ * @default []
76
+ */
77
+ postInitApplicationSQL?: string[];
78
+
79
+ /**
80
+ * CNPG operator Helm Release. Pass `baseInfra.cnpg.operator` to ensure the webhook
81
+ * is ready before the `Cluster` CRD is applied.
82
+ */
83
+ cnpgOperator?: pulumi.Resource;
84
+ }
85
+
86
+ export class PostgresInstance extends pulumi.ComponentResource {
87
+ /** Read-write (primary) service name: `<name>-postgres-rw` */
88
+ readonly serviceName: pulumi.Output<string>;
89
+
90
+ /** In-cluster hostname: `<service>.<namespace>.svc.cluster.local` */
91
+ readonly host: pulumi.Output<string>;
92
+
93
+ readonly port: pulumi.Output<number>;
94
+
95
+ /** Full connection string — treat as secret. */
96
+ readonly connectionString: pulumi.Output<string>;
97
+
98
+ /**
99
+ * Adapter Secret name containing `POSTGRES_DB`, `POSTGRES_USER`,
100
+ * `POSTGRES_PASSWORD`, `DATABASE_URL`.
101
+ *
102
+ * ```typescript
103
+ * envFrom: [{ secretRef: { name: db.credentialsSecretName } }]
104
+ * ```
105
+ */
106
+ readonly credentialsSecretName: pulumi.Output<string>;
107
+
108
+ constructor(name: string, args: PostgresInstanceArgs, opts?: pulumi.ComponentResourceOptions) {
109
+ super("homelab:components:PostgresInstance", name, args, opts);
110
+
111
+ const childOpts: pulumi.ComponentResourceOptions = { parent: this };
112
+
113
+ const namespaceName = args.namespace.metadata.name as pulumi.Output<string>;
114
+
115
+ const image = args.image ?? DEFAULT_IMAGE;
116
+ const username = args.username ?? DEFAULT_USERNAME;
117
+ const storageSize = args.storageSize ?? DEFAULT_STORAGE_SIZE;
118
+ const storageClass = args.storageClass ?? DEFAULT_STORAGE_CLASS;
119
+ const instances = args.instances ?? DEFAULT_INSTANCES;
120
+ const postgresUID = args.postgresUID ?? DEFAULT_POSTGRES_UID;
121
+ const postgresGID = args.postgresGID ?? DEFAULT_POSTGRES_GID;
122
+ const sharedPreloadLibraries = args.sharedPreloadLibraries ?? [];
123
+ const postInitApplicationSQL = args.postInitApplicationSQL ?? [];
124
+
125
+ // CNPG names its objects as "<cluster-name>-<suffix>"
126
+ const clusterName = `${name}-postgres`;
127
+ const cnpgSecretName = `${clusterName}-app`;
128
+ const adapterSecretName = `${name}-postgres-credentials`;
129
+ const serviceName = `${clusterName}-rw`;
130
+
131
+ const clusterDependsOn: pulumi.Resource[] = [args.namespace];
132
+ if (args.cnpgOperator) clusterDependsOn.push(args.cnpgOperator);
133
+
134
+ const cluster = new k8s.apiextensions.CustomResource(
135
+ clusterName,
136
+ {
137
+ apiVersion: "postgresql.cnpg.io/v1",
138
+ kind: "Cluster",
139
+ metadata: {
140
+ name: clusterName,
141
+ namespace: namespaceName,
142
+ labels: {
143
+ app: name,
144
+ "app.kubernetes.io/managed-by": "pulumi",
145
+ },
146
+ },
147
+ spec: {
148
+ instances,
149
+ imageName: image,
150
+ postgresUID,
151
+ postgresGID,
152
+ bootstrap: {
153
+ initdb: {
154
+ database: args.databaseName,
155
+ owner: username,
156
+ postInitApplicationSQL,
157
+ },
158
+ },
159
+ postgresql: {
160
+ shared_preload_libraries: sharedPreloadLibraries,
161
+ },
162
+ storage: {
163
+ size: storageSize,
164
+ storageClass,
165
+ },
166
+ },
167
+ },
168
+ { ...childOpts, dependsOn: clusterDependsOn }
169
+ );
170
+
171
+ // CNPG auto-creates `<cluster>-app` after bootstrap. We read it to project its
172
+ // base64-encoded fields into our canonical adapter secret.
173
+ const cnpgSecret = k8s.core.v1.Secret.get(
174
+ cnpgSecretName,
175
+ pulumi.interpolate`${namespaceName}/${cnpgSecretName}`,
176
+ { ...childOpts, dependsOn: [cluster] }
177
+ );
178
+
179
+ const cnpgData = cnpgSecret.data;
180
+ const b64decode = (v: pulumi.Output<string>): pulumi.Output<string> =>
181
+ v.apply((s) => Buffer.from(s, "base64").toString("utf-8"));
182
+
183
+ const decodedUsername = b64decode(cnpgData.apply((d) => d.username ?? ""));
184
+ const decodedPassword = b64decode(cnpgData.apply((d) => d.password ?? ""));
185
+ const decodedDbname = b64decode(cnpgData.apply((d) => d.dbname ?? ""));
186
+ const decodedUri = b64decode(cnpgData.apply((d) => d.uri ?? ""));
187
+
188
+ new k8s.core.v1.Secret(
189
+ adapterSecretName,
190
+ {
191
+ metadata: {
192
+ name: adapterSecretName,
193
+ namespace: namespaceName,
194
+ labels: {
195
+ app: name,
196
+ "app.kubernetes.io/managed-by": "pulumi",
197
+ },
198
+ annotations: {
199
+ "homelab/cnpg-source-secret": cnpgSecretName,
200
+ },
201
+ },
202
+ type: "Opaque",
203
+ stringData: {
204
+ POSTGRES_DB: decodedDbname,
205
+ POSTGRES_USER: decodedUsername,
206
+ POSTGRES_PASSWORD: decodedPassword,
207
+ DATABASE_URL: decodedUri,
208
+ },
209
+ },
210
+ { ...childOpts, dependsOn: [cnpgSecret] }
211
+ );
212
+
213
+ const host = pulumi.interpolate`${serviceName}.${namespaceName}.svc.cluster.local`;
214
+
215
+ this.serviceName = pulumi.output(serviceName);
216
+ this.host = host;
217
+ this.port = pulumi.output(PG_PORT);
218
+ this.connectionString = decodedUri;
219
+ this.credentialsSecretName = pulumi.output(adapterSecretName);
220
+
221
+ this.registerOutputs({
222
+ serviceName: this.serviceName,
223
+ host: this.host,
224
+ port: this.port,
225
+ connectionString: this.connectionString,
226
+ credentialsSecretName: this.credentialsSecretName,
227
+ });
228
+ }
229
+ }