mirror of
https://github.com/morten-olsen/homelab-operator.git
synced 2026-02-08 01:36:28 +01:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
daf0ea21bb | ||
|
|
26b58a59c0 | ||
|
|
a25e0b9ffb | ||
|
|
5782d59f71 | ||
|
|
34bba171ef | ||
|
|
85d043aec3 | ||
|
|
523637d40f | ||
|
|
dd1e5a8124 |
2
.github/workflows/publish-tag.yml
vendored
2
.github/workflows/publish-tag.yml
vendored
@@ -5,7 +5,7 @@ on:
|
||||
branches:
|
||||
- 'main'
|
||||
tags:
|
||||
- "v[0-9]+.[0-9]+.[0-9]+"
|
||||
- "v*"
|
||||
|
||||
env:
|
||||
environment: test
|
||||
|
||||
@@ -31,6 +31,67 @@ spec:
|
||||
{{- toYaml .Values.securityContext | nindent 12 }}
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
env:
|
||||
# PostgreSQL Host
|
||||
- name: POSTGRES_HOST
|
||||
{{- if .Values.config.postgres.host.fromSecret.enabled }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.postgres.host.fromSecret.secretName }}
|
||||
key: {{ .Values.config.postgres.host.fromSecret.key }}
|
||||
{{- else }}
|
||||
value: {{ .Values.config.postgres.host.value | quote }}
|
||||
{{- end }}
|
||||
# PostgreSQL Port
|
||||
- name: POSTGRES_PORT
|
||||
{{- if .Values.config.postgres.port.fromSecret.enabled }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.postgres.port.fromSecret.secretName }}
|
||||
key: {{ .Values.config.postgres.port.fromSecret.key }}
|
||||
{{- else }}
|
||||
value: {{ .Values.config.postgres.port.value | quote }}
|
||||
{{- end }}
|
||||
# PostgreSQL User
|
||||
- name: POSTGRES_USER
|
||||
{{- if .Values.config.postgres.user.fromSecret.enabled }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.postgres.user.fromSecret.secretName }}
|
||||
key: {{ .Values.config.postgres.user.fromSecret.key }}
|
||||
{{- else }}
|
||||
value: {{ .Values.config.postgres.user.value | quote }}
|
||||
{{- end }}
|
||||
# PostgreSQL Password
|
||||
- name: POSTGRES_PASSWORD
|
||||
{{- if .Values.config.postgres.password.fromSecret.enabled }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.postgres.password.fromSecret.secretName }}
|
||||
key: {{ .Values.config.postgres.password.fromSecret.key }}
|
||||
{{- else }}
|
||||
value: {{ .Values.config.postgres.password.value | quote }}
|
||||
{{- end }}
|
||||
# Certificate Manager
|
||||
- name: CERT_MANAGER
|
||||
{{- if .Values.config.certManager.fromSecret.enabled }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.certManager.fromSecret.secretName }}
|
||||
key: {{ .Values.config.certManager.fromSecret.key }}
|
||||
{{- else }}
|
||||
value: {{ .Values.config.certManager.value | quote }}
|
||||
{{- end }}
|
||||
# Istio Gateway
|
||||
- name: ISTIO_GATEWAY
|
||||
{{- if .Values.config.istioGateway.fromSecret.enabled }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.istioGateway.fromSecret.secretName }}
|
||||
key: {{ .Values.config.istioGateway.fromSecret.key }}
|
||||
{{- else }}
|
||||
value: {{ .Values.config.istioGateway.value | quote }}
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.resources | nindent 12 }}
|
||||
{{- with .Values.nodeSelector }}
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
image:
|
||||
repository: ghcr.io/morten-olsen/homelab-operator
|
||||
pullPolicy: IfNotPresent
|
||||
pullPolicy: Always
|
||||
# Overrides the image tag whose default is the chart appVersion.
|
||||
tag: ""
|
||||
tag: main
|
||||
|
||||
imagePullSecrets: []
|
||||
nameOverride: ""
|
||||
@@ -51,3 +51,53 @@ nodeSelector: {}
|
||||
tolerations: []
|
||||
|
||||
affinity: {}
|
||||
|
||||
# Configuration for the homelab operator
|
||||
config:
|
||||
# PostgreSQL database configuration
|
||||
postgres:
|
||||
host:
|
||||
# Direct value (used when fromSecret.enabled is false)
|
||||
value: "127.0.0.1"
|
||||
# Secret reference (used when fromSecret.enabled is true)
|
||||
fromSecret:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
key: "POSTGRES_HOST"
|
||||
|
||||
port:
|
||||
value: "5432"
|
||||
fromSecret:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
key: "POSTGRES_PORT"
|
||||
|
||||
user:
|
||||
value: "postgres"
|
||||
fromSecret:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
key: "POSTGRES_USER"
|
||||
|
||||
password:
|
||||
value: ""
|
||||
fromSecret:
|
||||
enabled: true # Default to secret for sensitive data
|
||||
secretName: "postgres-secret"
|
||||
key: "POSTGRES_PASSWORD"
|
||||
|
||||
# Certificate manager configuration
|
||||
certManager:
|
||||
value: "letsencrypt-prod"
|
||||
fromSecret:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
key: "CERT_MANAGER"
|
||||
|
||||
# Istio gateway configuration
|
||||
istioGateway:
|
||||
value: "istio-ingress"
|
||||
fromSecret:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
key: "ISTIO_GATEWAY"
|
||||
|
||||
@@ -46,6 +46,6 @@ export default tseslint.config(
|
||||
},
|
||||
...compat.extends('plugin:prettier/recommended'),
|
||||
{
|
||||
ignores: ['**/node_modules/', '**/dist/', '**/.turbo/', '**/generated/'],
|
||||
ignores: ['**/node_modules/', '**/dist/', '**/.turbo/', '**/generated/', '**/clients/*.types.ts'],
|
||||
},
|
||||
);
|
||||
|
||||
15
package.json
15
package.json
@@ -4,11 +4,8 @@
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"nodemon": "^3.1.10",
|
||||
"@eslint/eslintrc": "3.3.1",
|
||||
"@eslint/js": "9.32.0",
|
||||
"@pnpm/find-workspace-packages": "6.0.9",
|
||||
"eslint": "9.32.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-plugin-import": "2.32.0",
|
||||
@@ -21,17 +18,23 @@
|
||||
"typescript": "^5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@goauthentik/api": "2025.6.3-1751754396",
|
||||
"@kubernetes/client-node": "^1.3.0",
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"dotenv": "^17.2.1",
|
||||
"knex": "^3.1.0",
|
||||
"pg": "^8.16.3",
|
||||
"sqlite3": "^5.1.7"
|
||||
"sqlite3": "^5.1.7",
|
||||
"yaml": "^2.8.0",
|
||||
"zod": "^4.0.14"
|
||||
},
|
||||
"packageManager": "pnpm@10.6.0",
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"sqlite3"
|
||||
]
|
||||
],
|
||||
"patchedDependencies": {
|
||||
"@kubernetes/client-node": "patches/@kubernetes__client-node.patch"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo 'No tests'",
|
||||
|
||||
14
patches/@kubernetes__client-node.patch
Normal file
14
patches/@kubernetes__client-node.patch
Normal file
@@ -0,0 +1,14 @@
|
||||
diff --git a/dist/gen/models/ObjectSerializer.js b/dist/gen/models/ObjectSerializer.js
|
||||
index 1d798b6a2d7c059165d1df9fbb77b89a8317ebca..c8bacfdc95be0f0146c6505f89a9372e013afea4 100644
|
||||
--- a/dist/gen/models/ObjectSerializer.js
|
||||
+++ b/dist/gen/models/ObjectSerializer.js
|
||||
@@ -2216,6 +2216,9 @@ export class ObjectSerializer {
|
||||
return transformedData;
|
||||
}
|
||||
else if (type === "Date") {
|
||||
+ if (typeof data === "string") {
|
||||
+ return data;
|
||||
+ }
|
||||
if (format == "date") {
|
||||
let month = data.getMonth() + 1;
|
||||
month = month < 10 ? "0" + month.toString() : month.toString();
|
||||
1316
pnpm-lock.yaml
generated
1316
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,8 +0,0 @@
|
||||
apiVersion: 'homelab.mortenolsen.pro/v1';
|
||||
kind: 'PostgresDatabase';
|
||||
name: 'test2';
|
||||
namespace: 'playground';
|
||||
foo: 'bar';
|
||||
foo: 'bar';
|
||||
{
|
||||
}
|
||||
24
scripts/create-clients.ts
Normal file
24
scripts/create-clients.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import fs from 'node:fs';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
|
||||
import YAML from 'yaml';
|
||||
import openapiTS, { astToString } from 'openapi-typescript';
|
||||
|
||||
const schemaRequest = await fetch('https://authentik.olsen.cloud/api/v3/schema/');
|
||||
if (!schemaRequest.ok) {
|
||||
console.error(schemaRequest.status, schemaRequest.statusText);
|
||||
throw new Error('Failed to fetch schema');
|
||||
}
|
||||
const schemaYaml = await schemaRequest.text();
|
||||
const schema = YAML.parse(schemaYaml);
|
||||
|
||||
const ast = await openapiTS(schema);
|
||||
const contents = astToString(ast);
|
||||
|
||||
const targetLocation = resolve(import.meta.dirname, '..', 'src', 'clients', 'authentik', 'authentik.types.d.ts');
|
||||
await mkdir(dirname(targetLocation), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
targetLocation,
|
||||
['// This file is generated by scripts/create-clients.ts', '/* eslint-disable */', contents].join('\n'),
|
||||
);
|
||||
2
scripts/recreate.bash
Executable file
2
scripts/recreate.bash
Executable file
@@ -0,0 +1,2 @@
|
||||
kubectl delete -f "$1"
|
||||
kubectl apply -f "$1"
|
||||
33
src/clients/authentik/authentik.ts
Normal file
33
src/clients/authentik/authentik.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
Configuration,
|
||||
CoreApi,
|
||||
FlowsApi,
|
||||
PropertymappingsApi,
|
||||
ProvidersApi,
|
||||
instanceOfErrorDetail,
|
||||
} from '@goauthentik/api';
|
||||
|
||||
type CreateAuthentikClientOptions = {
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
};
|
||||
const createAuthentikClient = ({ baseUrl, token }: CreateAuthentikClientOptions) => {
|
||||
const config = new Configuration({
|
||||
basePath: baseUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
const client = {
|
||||
core: new CoreApi(config),
|
||||
providers: new ProvidersApi(config),
|
||||
propertymappings: new PropertymappingsApi(config),
|
||||
flows: new FlowsApi(config),
|
||||
};
|
||||
|
||||
return client;
|
||||
};
|
||||
|
||||
type AuthentikClient = ReturnType<typeof createAuthentikClient>;
|
||||
|
||||
export { createAuthentikClient, type AuthentikClient, instanceOfErrorDetail };
|
||||
58661
src/clients/authentik/authentik.types.d.ts
vendored
Normal file
58661
src/clients/authentik/authentik.types.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
111
src/crds/authentik/client/client.ts
Normal file
111
src/crds/authentik/client/client.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { SubModeEnum } from '@goauthentik/api';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { CustomResource, type CustomResourceHandlerOptions } from '../../../custom-resource/custom-resource.base.ts';
|
||||
import { AuthentikService } from '../../../services/authentik/authentik.service.ts';
|
||||
import { K8sService } from '../../../services/k8s.ts';
|
||||
import { GROUP } from '../../../utils/consts.ts';
|
||||
|
||||
const authentikClientSpec = z.object({
|
||||
authentik: z.object({
|
||||
name: z.string(),
|
||||
namespace: z.string().optional(),
|
||||
}),
|
||||
subMode: z.enum(SubModeEnum).optional(),
|
||||
clientType: z.enum(['confidential', 'public']).optional(),
|
||||
redirectUris: z.array(
|
||||
z.object({
|
||||
url: z.string(),
|
||||
matchingMode: z.enum(['strict', 'regex']),
|
||||
}),
|
||||
),
|
||||
});
|
||||
const authentikClientSecret = z.object({
|
||||
clientSecret: z.string(),
|
||||
});
|
||||
|
||||
class AuthentikClient extends CustomResource<typeof authentikClientSpec> {
|
||||
constructor() {
|
||||
super({
|
||||
kind: 'AuthentikClient',
|
||||
names: {
|
||||
singular: 'authentikclient',
|
||||
plural: 'authentikclients',
|
||||
},
|
||||
spec: authentikClientSpec,
|
||||
});
|
||||
}
|
||||
|
||||
public update = async (options: CustomResourceHandlerOptions<typeof authentikClientSpec>) => {
|
||||
const { request, services, ensureSecret } = options;
|
||||
const k8s = services.get(K8sService);
|
||||
const { spec } = request;
|
||||
|
||||
const serverNamespace = spec.authentik.namespace ?? request.metadata.namespace ?? 'default';
|
||||
|
||||
const server = await k8s.get<ExpectedAny>({
|
||||
apiVersion: `${GROUP}/v1`,
|
||||
kind: 'AuthentikServer',
|
||||
namespace: serverNamespace,
|
||||
name: spec.authentik.name,
|
||||
});
|
||||
|
||||
if (!server) {
|
||||
throw new Error(`AuthentikServer ${spec.authentik.name} not found in namespace ${serverNamespace}`);
|
||||
}
|
||||
|
||||
const serverSecret = await k8s.getSecret<{
|
||||
token: string;
|
||||
}>(spec.authentik.name, spec.authentik.namespace);
|
||||
if (!serverSecret) {
|
||||
throw new Error(
|
||||
`Secret for AuthentikServer ${spec.authentik.name} not found in namespace ${spec.authentik.namespace}`,
|
||||
);
|
||||
}
|
||||
|
||||
const domainNamespace = server.spec.domain.namespace || server.metadata.namespace || 'default';
|
||||
|
||||
const domain = await k8s.get<ExpectedAny>({
|
||||
apiVersion: `${GROUP}/v1`,
|
||||
kind: 'Domain',
|
||||
name: server.spec.domain.name,
|
||||
namespace: domainNamespace,
|
||||
});
|
||||
|
||||
if (!domain) {
|
||||
throw new Error(`Domain ${server.spec.domain.name} not found in namespace ${domainNamespace}`);
|
||||
}
|
||||
|
||||
const internalUrl = `http://${server.metadata.name}.${spec.authentik.namespace || 'default'}.svc.cluster.local:9000`;
|
||||
const externalUrl = `https://${server.spec.subdomain}.${domain.spec.domain}`;
|
||||
const authentikService = services.get(AuthentikService);
|
||||
const { clientSecret } = await ensureSecret({
|
||||
name: `authentik-client-${request.metadata.name}`,
|
||||
namespace: request.metadata.namespace ?? 'default',
|
||||
schema: authentikClientSecret,
|
||||
generator: async () => ({
|
||||
clientSecret: crypto.randomUUID(),
|
||||
}),
|
||||
});
|
||||
const authentik = await authentikService.get({
|
||||
url: {
|
||||
internal: internalUrl,
|
||||
external: externalUrl,
|
||||
},
|
||||
token: serverSecret.token,
|
||||
});
|
||||
const client = await authentik.upsertClient({
|
||||
name: request.metadata.name,
|
||||
secret: clientSecret,
|
||||
subMode: request.spec.subMode,
|
||||
clientType: request.spec.clientType,
|
||||
redirectUris: request.spec.redirectUris.map((rule) => ({
|
||||
url: rule.url,
|
||||
matchingMode: rule.matchingMode ?? 'strict',
|
||||
})),
|
||||
});
|
||||
console.log(client.config);
|
||||
};
|
||||
}
|
||||
|
||||
export { AuthentikClient };
|
||||
13
src/crds/authentik/server/server.schema.ts
Normal file
13
src/crds/authentik/server/server.schema.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const authentikServerSpecSchema = z.object({
|
||||
domain: z.object({
|
||||
name: z.string(),
|
||||
namespace: z.string().optional(),
|
||||
}),
|
||||
subdomain: z.string(),
|
||||
});
|
||||
|
||||
type AuthentikServerSpec = z.infer<typeof authentikServerSpecSchema>;
|
||||
|
||||
export { authentikServerSpecSchema, type AuthentikServerSpec };
|
||||
250
src/crds/authentik/server/server.setup.ts
Normal file
250
src/crds/authentik/server/server.setup.ts
Normal file
@@ -0,0 +1,250 @@
|
||||
import z from 'zod';
|
||||
|
||||
import type { CustomResourceHandlerOptions } from '../../../custom-resource/custom-resource.base.ts';
|
||||
import { K8sService } from '../../../services/k8s.ts';
|
||||
import { PostgresService } from '../../../services/postgres/postgres.service.ts';
|
||||
import { FIELDS, GROUP } from '../../../utils/consts.ts';
|
||||
|
||||
import type { authentikServerSpecSchema } from './server.schema.ts';
|
||||
|
||||
const toPostgresSafeName = (inputString: string): string => {
|
||||
let safeName = inputString.toLowerCase();
|
||||
safeName = safeName.replace(/[^a-z0-9_]/g, '_');
|
||||
safeName = safeName.replace(/^_+|_+$/g, '');
|
||||
if (safeName === '') {
|
||||
return 'default_name'; // Or throw new Error("Input resulted in an empty safe name.");
|
||||
}
|
||||
|
||||
if (/^[0-9]/.test(safeName)) {
|
||||
safeName = '_' + safeName;
|
||||
}
|
||||
|
||||
const MAX_PG_IDENTIFIER_LENGTH = 63;
|
||||
if (safeName.length > MAX_PG_IDENTIFIER_LENGTH) {
|
||||
safeName = safeName.substring(0, MAX_PG_IDENTIFIER_LENGTH);
|
||||
}
|
||||
|
||||
return safeName;
|
||||
};
|
||||
|
||||
const setupAuthentik = async ({
|
||||
services,
|
||||
request,
|
||||
ensureSecret,
|
||||
}: CustomResourceHandlerOptions<typeof authentikServerSpecSchema>) => {
|
||||
const { name, namespace } = request.metadata;
|
||||
|
||||
const k8sService = services.get(K8sService);
|
||||
const postgresService = services.get(PostgresService);
|
||||
|
||||
const domainNamespace = request.spec.domain.namespace || namespace || 'default';
|
||||
|
||||
const domain = await k8sService.get<ExpectedAny>({
|
||||
apiVersion: `${GROUP}/v1`,
|
||||
kind: 'Domain',
|
||||
name: request.spec.domain.name,
|
||||
namespace: domainNamespace,
|
||||
});
|
||||
|
||||
if (!domain) {
|
||||
throw new Error(`Domain ${request.spec.domain.name} not found in namespace ${domainNamespace || 'default'}`);
|
||||
}
|
||||
|
||||
const secretData = await ensureSecret({
|
||||
name: name,
|
||||
namespace: namespace || 'default',
|
||||
schema: z.object({
|
||||
secret: z.string(),
|
||||
token: z.string(),
|
||||
password: z.string(),
|
||||
}),
|
||||
generator: async () => ({
|
||||
secret: Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex'),
|
||||
token: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('hex'),
|
||||
password: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('hex'),
|
||||
}),
|
||||
});
|
||||
|
||||
const hostname = `${request.spec.subdomain}.${domain.spec.domain}`;
|
||||
|
||||
const db = {
|
||||
name: toPostgresSafeName(`${namespace}_${name}`),
|
||||
user: toPostgresSafeName(`${namespace}_${name}_user`),
|
||||
password: 'sdf908sad0sdf7g98',
|
||||
};
|
||||
|
||||
await postgresService.upsertRole({
|
||||
name: db.user,
|
||||
password: db.password,
|
||||
});
|
||||
|
||||
await postgresService.upsertDatabase({
|
||||
name: db.name,
|
||||
owner: db.user,
|
||||
});
|
||||
|
||||
const createManifest = (command: string) => ({
|
||||
apiVersion: 'apps/v1',
|
||||
kind: 'Deployment',
|
||||
metadata: {
|
||||
name: `${name}-${command}`,
|
||||
namespace: namespace,
|
||||
labels: {
|
||||
'app.kubernetes.io/name': `${name}-${command}`,
|
||||
'argocd.argoproj.io/instance': 'homelab',
|
||||
},
|
||||
annotations: {
|
||||
[FIELDS.domain.domainId]: domain.dependencyId,
|
||||
},
|
||||
ownerReferences: [request.objectRef],
|
||||
},
|
||||
spec: {
|
||||
replicas: 1,
|
||||
selector: {
|
||||
matchLabels: {
|
||||
'app.kubernetes.io/name': `${name}-${command}`,
|
||||
},
|
||||
},
|
||||
template: {
|
||||
metadata: {
|
||||
labels: {
|
||||
'app.kubernetes.io/name': `${name}-${command}`,
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
containers: [
|
||||
{
|
||||
name: `${name}-${command}`,
|
||||
image: 'ghcr.io/goauthentik/server:2025.6.4',
|
||||
// imagePullPolicy: 'ifNot'
|
||||
args: [command],
|
||||
env: [
|
||||
{ name: 'AUTHENTIK_SECRET_KEY', value: secretData.secret },
|
||||
{ name: 'AUTHENTIK_POSTGRESQL__HOST', value: 'postgres-postgresql.postgres.svc.cluster.local' },
|
||||
{
|
||||
name: 'AUTHENTIK_POSTGRESQL__PORT',
|
||||
value: '5432',
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_POSTGRESQL__NAME',
|
||||
value: db.name,
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_POSTGRESQL__USER',
|
||||
value: db.user,
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_POSTGRESQL__PASSWORD',
|
||||
value: db.password,
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_REDIS__HOST',
|
||||
value: 'redis.redis.svc.cluster.local',
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_BOOTSTRAP_PASSWORD',
|
||||
value: secretData.password,
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_BOOTSTRAP_TOKEN',
|
||||
value: secretData.token,
|
||||
},
|
||||
{
|
||||
name: 'AUTHENTIK_BOOTSTRAP_EMAIL',
|
||||
value: `admin@${hostname}`,
|
||||
},
|
||||
// {
|
||||
// name: 'AUTHENTIK_REDIS__PORT',
|
||||
// value: ''
|
||||
// }
|
||||
],
|
||||
ports: [
|
||||
{
|
||||
name: 'http',
|
||||
containerPort: 9000,
|
||||
protocol: 'TCP',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await k8sService.upsert(createManifest('server'));
|
||||
await k8sService.upsert(createManifest('worker'));
|
||||
await k8sService.upsert({
|
||||
apiVersion: 'v1',
|
||||
kind: 'Service',
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
labels: {
|
||||
'app.kubernetes.io/name': `${name}-server`,
|
||||
},
|
||||
ownerReferences: [request.objectRef],
|
||||
},
|
||||
spec: {
|
||||
type: 'ClusterIP',
|
||||
ports: [
|
||||
{
|
||||
port: 9000,
|
||||
targetPort: 9000,
|
||||
protocol: 'TCP',
|
||||
name: 'http',
|
||||
},
|
||||
],
|
||||
selector: {
|
||||
'app.kubernetes.io/name': `${name}-server`,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await k8sService.upsert({
|
||||
apiVersion: 'networking.istio.io/v1',
|
||||
kind: 'DestinationRule',
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
labels: {
|
||||
'app.kubernetes.io/name': `${name}-server`,
|
||||
},
|
||||
ownerReferences: [request.objectRef],
|
||||
},
|
||||
spec: {
|
||||
host: `${name}.${namespace || 'default'}.svc.cluster.local`,
|
||||
trafficPolicy: {
|
||||
tls: {
|
||||
mode: 'DISABLE',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await k8sService.upsert({
|
||||
apiVersion: `${GROUP}/v1`,
|
||||
kind: 'DomainEndpoint',
|
||||
metadata: {
|
||||
name: request.metadata.name,
|
||||
namespace: request.metadata.namespace ?? 'default',
|
||||
labels: {
|
||||
'app.kubernetes.io/name': `${name}-domain-endpoint`,
|
||||
},
|
||||
ownerReferences: [request.objectRef],
|
||||
},
|
||||
spec: {
|
||||
domain: 'homelab/homelab',
|
||||
subdomain: request.spec.subdomain,
|
||||
destination: {
|
||||
name,
|
||||
namespace: namespace ?? 'default',
|
||||
port: {
|
||||
number: 9000,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export { setupAuthentik };
|
||||
18
src/crds/authentik/server/server.ts
Normal file
18
src/crds/authentik/server/server.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { createCustomResource } from '../../../custom-resource/custom-resource.base.ts';
|
||||
|
||||
import { authentikServerSpecSchema } from './server.schema.ts';
|
||||
import { setupAuthentik } from './server.setup.ts';
|
||||
|
||||
const AuthentikServer = createCustomResource({
|
||||
kind: 'AuthentikServer',
|
||||
names: {
|
||||
plural: 'authentikservers',
|
||||
singular: 'authentikserver',
|
||||
},
|
||||
spec: authentikServerSpecSchema,
|
||||
update: async (options) => {
|
||||
await setupAuthentik(options);
|
||||
},
|
||||
});
|
||||
|
||||
export { AuthentikServer };
|
||||
24
src/crds/backup/backup-report/backup-report.ts
Normal file
24
src/crds/backup/backup-report/backup-report.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { createCustomResource } from '../../../custom-resource/custom-resource.base.ts';
|
||||
|
||||
const backupReportSchema = z.object({
|
||||
spec: z.object({
|
||||
startedAt: z.string().datetime(),
|
||||
finishedAt: z.string().datetime(),
|
||||
status: z.enum(['success', 'failed', 'in-progress']),
|
||||
error: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
const BackupReport = createCustomResource({
|
||||
kind: 'BackupReport',
|
||||
spec: backupReportSchema,
|
||||
names: {
|
||||
plural: 'backupreports',
|
||||
singular: 'backupreport',
|
||||
},
|
||||
});
|
||||
|
||||
export { BackupReport };
|
||||
0
src/crds/backup/backup/backup.ts
Normal file
0
src/crds/backup/backup/backup.ts
Normal file
133
src/crds/domain/domain/domain.ts
Normal file
133
src/crds/domain/domain/domain.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
import z from 'zod';
|
||||
|
||||
import { createCustomResource } from '../../../custom-resource/custom-resource.base.ts';
|
||||
import { K8sService } from '../../../services/k8s.ts';
|
||||
import { ConfigService } from '../../../services/config/config.ts';
|
||||
import { CustomResourceRegistry } from '../../../custom-resource/custom-resource.registry.ts';
|
||||
import { GROUP } from '../../../utils/consts.ts';
|
||||
|
||||
const Domain = createCustomResource({
|
||||
kind: 'Domain',
|
||||
names: {
|
||||
singular: 'domain',
|
||||
plural: 'domains',
|
||||
},
|
||||
spec: z.object({
|
||||
domain: z.string(),
|
||||
}),
|
||||
update: async ({ request, services }) => {
|
||||
const k8s = services.get(K8sService);
|
||||
const config = services.get(ConfigService);
|
||||
const secretName = `certificate-${request.metadata.name}`;
|
||||
|
||||
request.addEvent({
|
||||
type: 'Normal',
|
||||
message: 'Creating certificate',
|
||||
reason: 'CreateCertificate',
|
||||
action: 'Create',
|
||||
});
|
||||
await k8s.upsert({
|
||||
apiVersion: 'cert-manager.io/v1',
|
||||
kind: 'Certificate',
|
||||
metadata: {
|
||||
name: request.metadata.name,
|
||||
namespace: 'istio-ingress',
|
||||
},
|
||||
spec: {
|
||||
secretName,
|
||||
dnsNames: [`*.${request.spec.domain}`],
|
||||
issuerRef: {
|
||||
name: config.certManager,
|
||||
kind: 'ClusterIssuer',
|
||||
},
|
||||
},
|
||||
});
|
||||
request.addEvent({
|
||||
type: 'Normal',
|
||||
message: 'Created certificate',
|
||||
reason: 'CreatedCertificate',
|
||||
action: 'Create',
|
||||
});
|
||||
|
||||
request.addEvent({
|
||||
type: 'Normal',
|
||||
message: 'Creating gateway',
|
||||
reason: 'CreateGateway',
|
||||
action: 'Create',
|
||||
});
|
||||
await k8s.upsert({
|
||||
apiVersion: 'networking.istio.io/v1alpha3',
|
||||
kind: 'Gateway',
|
||||
metadata: {
|
||||
name: request.metadata.name,
|
||||
namespace: request.metadata.namespace,
|
||||
ownerReferences: [request.objectRef],
|
||||
},
|
||||
spec: {
|
||||
selector: {
|
||||
app: config.istio.gateway,
|
||||
},
|
||||
servers: [
|
||||
{
|
||||
port: {
|
||||
number: 80,
|
||||
name: 'http',
|
||||
protocol: 'HTTP',
|
||||
},
|
||||
hosts: [`*.${request.spec.domain}`],
|
||||
tls: {
|
||||
httpsRedirect: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
port: {
|
||||
number: 443,
|
||||
name: 'https',
|
||||
protocol: 'HTTPS',
|
||||
},
|
||||
hosts: [`*.${request.spec.domain}`],
|
||||
tls: {
|
||||
mode: 'SIMPLE',
|
||||
credentialName: secretName,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
request.addEvent({
|
||||
type: 'Normal',
|
||||
message: 'Created gateway',
|
||||
reason: 'CreatedGateway',
|
||||
action: 'Create',
|
||||
});
|
||||
const registryService = services.get(CustomResourceRegistry);
|
||||
const endpoints = registryService.objects.filter(
|
||||
(obj) =>
|
||||
obj.manifest.kind === 'DomainEndpoint' &&
|
||||
obj.manifest.apiVersion === `${GROUP}/v1` &&
|
||||
obj.manifest.spec.domain === `${request.metadata.namespace}/${request.metadata.name}`,
|
||||
);
|
||||
const expectedDomainId = [request.metadata.uid, request.metadata.generation].join('.');
|
||||
for (const endpoint of endpoints) {
|
||||
const domainId = endpoint.manifest.metadata[`${GROUP}/domain-id`];
|
||||
if (domainId === expectedDomainId) {
|
||||
continue;
|
||||
}
|
||||
request.addEvent({
|
||||
type: 'Normal',
|
||||
message: `Updating dependent endpoint: ${endpoint.manifest.metadata.namespace}/${endpoint.manifest.metadata.name}`,
|
||||
reason: 'UpdateDependant',
|
||||
action: 'Update',
|
||||
});
|
||||
await endpoint.manifest.patch({
|
||||
metadata: {
|
||||
annotations: {
|
||||
[`${GROUP}/generation`]: expectedDomainId,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export { Domain };
|
||||
80
src/crds/domain/endpoint/endpoint.ts
Normal file
80
src/crds/domain/endpoint/endpoint.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import z from 'zod';
|
||||
|
||||
import { createCustomResource } from '../../../custom-resource/custom-resource.base.ts';
|
||||
import { K8sService } from '../../../services/k8s.ts';
|
||||
import { getWithNamespace } from '../../../utils/naming.ts';
|
||||
import { GROUP } from '../../../utils/consts.ts';
|
||||
|
||||
const DomainEndpoint = createCustomResource({
|
||||
kind: 'DomainEndpoint',
|
||||
names: {
|
||||
plural: 'domainendpoints',
|
||||
singular: 'domainendpoint',
|
||||
},
|
||||
spec: z.object({
|
||||
domain: z.string(),
|
||||
subdomain: z.string(),
|
||||
destination: z.object({
|
||||
name: z.string(),
|
||||
namespace: z.string().optional(),
|
||||
port: z.object({
|
||||
number: z.number(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
update: async ({ request, services }) => {
|
||||
const k8s = services.get(K8sService);
|
||||
const domainName = getWithNamespace(request.spec.domain);
|
||||
const domain = await k8s.get<ExpectedAny>({
|
||||
apiVersion: `${GROUP}/v1`,
|
||||
kind: 'Domain',
|
||||
name: domainName.name,
|
||||
namespace: domainName.namespace,
|
||||
});
|
||||
if (!domain) {
|
||||
throw new Error(`Domain ${request.spec.domain} could not be found`);
|
||||
}
|
||||
const host = `${request.spec.subdomain}.${domain.spec.domain}`;
|
||||
await k8s.upsert({
|
||||
apiVersion: 'networking.istio.io/v1alpha3',
|
||||
kind: 'VirtualService',
|
||||
metadata: {
|
||||
name: request.metadata.name,
|
||||
namespace: request.metadata.namespace,
|
||||
ownerReferences: [request.objectRef],
|
||||
labels: {
|
||||
app: request.spec.destination.name,
|
||||
},
|
||||
annotations: {
|
||||
[`${GROUP}/domain-id`]: [domain.metadata.uid, domain.metadata.generation].join('.'),
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
hosts: [host],
|
||||
gateways: [`${domain.metadata.namespace}/${domain.metadata.name}`],
|
||||
http: [
|
||||
{
|
||||
match: [
|
||||
{
|
||||
uri: {
|
||||
prefix: '/',
|
||||
},
|
||||
},
|
||||
],
|
||||
route: [
|
||||
{
|
||||
destination: {
|
||||
host: `${request.spec.destination.name}.${request.spec.destination.namespace || request.metadata.namespace || 'default'}.svc.cluster.local`,
|
||||
protocol: 'HTTP',
|
||||
port: request.spec.destination.port,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export { DomainEndpoint };
|
||||
@@ -1,12 +1,9 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { ApiException, type V1Secret } from '@kubernetes/client-node';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
|
||||
import { K8sService } from '../../services/k8s.ts';
|
||||
import type { CustomResourceRequest } from '../../custom-resource/custom-resource.request.ts';
|
||||
import { PostgresService } from '../../services/postgres/postgres.service.ts';
|
||||
|
||||
const postgresDatabaseSpecSchema = Type.Object({});
|
||||
const postgresDatabaseSpecSchema = z.object({});
|
||||
|
||||
class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema> {
|
||||
constructor() {
|
||||
@@ -20,99 +17,39 @@ class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema>
|
||||
});
|
||||
}
|
||||
|
||||
#getVariables = async (request: CustomResourceRequest<typeof postgresDatabaseSpecSchema>) => {
|
||||
const { metadata, services } = request;
|
||||
const k8sService = services.get(K8sService);
|
||||
|
||||
const secretName = `postgres-database-${metadata.name}`;
|
||||
let secret: V1Secret | undefined;
|
||||
|
||||
try {
|
||||
secret = await k8sService.api.readNamespacedSecret({
|
||||
name: secretName,
|
||||
namespace: metadata.namespace ?? 'default',
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiException && error.code === 404)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (secret && request.isOwnerOf(secret) && secret.data) {
|
||||
services.log.debug('PostgresRole secret found', { secret });
|
||||
return secret.data;
|
||||
}
|
||||
|
||||
if (secret && !request.isOwnerOf(secret)) {
|
||||
throw new Error('The secret is not owned by this resource');
|
||||
}
|
||||
|
||||
const data = {
|
||||
name: Buffer.from(`${metadata.namespace}_${metadata.name}`).toString('base64'),
|
||||
user: Buffer.from(metadata.name).toString('base64'),
|
||||
password: Buffer.from(crypto.randomUUID()).toString('base64'),
|
||||
};
|
||||
const namespace = metadata.namespace ?? 'default';
|
||||
|
||||
services.log.debug('Creating secret', { data });
|
||||
const response = await k8sService.api.createNamespacedSecret({
|
||||
namespace,
|
||||
body: {
|
||||
kind: 'Secret',
|
||||
metadata: {
|
||||
name: secretName,
|
||||
namespace,
|
||||
ownerReferences: [
|
||||
{
|
||||
apiVersion: request.apiVersion,
|
||||
kind: request.kind,
|
||||
name: metadata.name,
|
||||
uid: metadata.uid,
|
||||
},
|
||||
],
|
||||
},
|
||||
type: 'Opaque',
|
||||
data,
|
||||
},
|
||||
});
|
||||
services.log.debug('Secret created', { response });
|
||||
return response.data!;
|
||||
};
|
||||
|
||||
public update = async (options: CustomResourceHandlerOptions<typeof postgresDatabaseSpecSchema>) => {
|
||||
const { request, services } = options;
|
||||
const status = await request.getStatus();
|
||||
|
||||
try {
|
||||
const variables = await this.#getVariables(request);
|
||||
const { request, services, ensureSecret } = options;
|
||||
const variables = await ensureSecret({
|
||||
name: `postgres-database-${request.metadata.name}`,
|
||||
namespace: request.metadata.namespace ?? 'default',
|
||||
schema: z.object({
|
||||
name: z.string(),
|
||||
user: z.string(),
|
||||
password: z.string(),
|
||||
}),
|
||||
generator: async () => ({
|
||||
name: `${request.metadata.namespace || 'default'}_${request.metadata.name}`,
|
||||
user: `${request.metadata.namespace || 'default'}_${request.metadata.name}`,
|
||||
password: `password_${Buffer.from(crypto.getRandomValues(new Uint8Array(12))).toString('hex')}`,
|
||||
}),
|
||||
});
|
||||
const postgresService = services.get(PostgresService);
|
||||
await postgresService.upsertRole({
|
||||
name: Buffer.from(variables.user!, 'base64').toString('utf-8'),
|
||||
password: Buffer.from(variables.password!, 'base64').toString('utf-8'),
|
||||
name: variables.user,
|
||||
password: variables.password,
|
||||
});
|
||||
|
||||
await postgresService.upsertDatabase({
|
||||
name: Buffer.from(variables.name!, 'base64').toString('utf-8'),
|
||||
owner: Buffer.from(variables.user!, 'base64').toString('utf-8'),
|
||||
name: variables.name,
|
||||
owner: variables.user,
|
||||
});
|
||||
|
||||
status.setCondition('Ready', {
|
||||
status: 'True',
|
||||
reason: 'Ready',
|
||||
message: 'Role created',
|
||||
await request.addEvent({
|
||||
type: 'Normal',
|
||||
reason: 'DatabaseUpserted',
|
||||
message: 'Database has been upserted',
|
||||
action: 'UPSERT',
|
||||
});
|
||||
services.log.info('PostgresRole updated', { status });
|
||||
return await status.save();
|
||||
} catch (error) {
|
||||
const status = await request.getStatus();
|
||||
status.setCondition('Ready', {
|
||||
status: 'False',
|
||||
reason: 'Error',
|
||||
message: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
services.log.error('Error updating PostgresRole', { error });
|
||||
return await status.save();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { ApiException, type V1Secret } from '@kubernetes/client-node';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
|
||||
import { K8sService } from '../../services/k8s.ts';
|
||||
|
||||
const stringValueSchema = Type.String({
|
||||
key: Type.String(),
|
||||
chars: Type.Optional(Type.String()),
|
||||
length: Type.Optional(Type.Number()),
|
||||
encoding: Type.Optional(
|
||||
Type.String({
|
||||
enum: ['utf-8', 'base64', 'base64url', 'hex'],
|
||||
}),
|
||||
),
|
||||
value: Type.Optional(Type.String()),
|
||||
const stringValueSchema = z.object({
|
||||
key: z.string(),
|
||||
chars: z.string().optional(),
|
||||
length: z.number().optional(),
|
||||
encoding: z.enum(['utf-8', 'base64', 'base64url', 'hex']).optional(),
|
||||
value: z.string().optional(),
|
||||
});
|
||||
|
||||
const secretRequestSpec = Type.Object({
|
||||
secretName: Type.Optional(Type.String()),
|
||||
data: Type.Array(stringValueSchema),
|
||||
const secretRequestSpec = z.object({
|
||||
secretName: z.string().optional(),
|
||||
data: z.array(stringValueSchema),
|
||||
});
|
||||
|
||||
class SecretRequest extends CustomResource<typeof secretRequestSpec> {
|
||||
@@ -33,71 +27,18 @@ class SecretRequest extends CustomResource<typeof secretRequestSpec> {
|
||||
});
|
||||
}
|
||||
|
||||
#createSecret = async (options: CustomResourceHandlerOptions<typeof secretRequestSpec>) => {
|
||||
const { request, services } = options;
|
||||
const { apiVersion, kind, spec, metadata } = request;
|
||||
const { secretName = metadata.name } = spec;
|
||||
const { namespace = 'default' } = metadata;
|
||||
const k8sService = services.get(K8sService);
|
||||
let current: V1Secret | undefined;
|
||||
try {
|
||||
current = await k8sService.api.readNamespacedSecret({
|
||||
name: secretName,
|
||||
namespace,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiException && error.code === 404)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (current) {
|
||||
services.log.debug('secret already exists', { current });
|
||||
// TODO: Add update logic
|
||||
return;
|
||||
}
|
||||
await k8sService.api.createNamespacedSecret({
|
||||
namespace,
|
||||
body: {
|
||||
kind: 'Secret',
|
||||
metadata: {
|
||||
name: secretName,
|
||||
namespace,
|
||||
ownerReferences: [
|
||||
{
|
||||
apiVersion,
|
||||
kind,
|
||||
name: metadata.name,
|
||||
uid: metadata.uid,
|
||||
},
|
||||
],
|
||||
},
|
||||
type: 'Opaque',
|
||||
data: {
|
||||
// TODO: generate data from spec
|
||||
test: 'test',
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
public update = async (options: CustomResourceHandlerOptions<typeof secretRequestSpec>) => {
|
||||
const { request } = options;
|
||||
const status = await request.getStatus();
|
||||
try {
|
||||
await this.#createSecret(options);
|
||||
status.setCondition('Ready', {
|
||||
status: 'True',
|
||||
reason: 'SecretCreated',
|
||||
message: 'Secret created',
|
||||
const { request, ensureSecret } = options;
|
||||
const { secretName = request.metadata.name } = request.spec;
|
||||
const { namespace = request.metadata.namespace ?? 'default' } = request.metadata;
|
||||
await ensureSecret({
|
||||
name: secretName,
|
||||
namespace,
|
||||
schema: z.object({}).passthrough(),
|
||||
generator: async () => ({
|
||||
hello: 'world',
|
||||
}),
|
||||
});
|
||||
return await status.save();
|
||||
} catch {
|
||||
status.setCondition('Ready', {
|
||||
status: 'False',
|
||||
reason: 'SecretNotCreated',
|
||||
message: 'Secret not created',
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
import { type TSchema } from '@sinclair/typebox';
|
||||
import { z, type ZodObject } from 'zod';
|
||||
|
||||
import { GROUP } from '../utils/consts.ts';
|
||||
import type { Services } from '../utils/service.ts';
|
||||
|
||||
import { statusSchema } from './custom-resource.status.ts';
|
||||
import type { CustomResourceRequest } from './custom-resource.request.ts';
|
||||
import { customResourceStatusSchema, type CustomResourceRequest } from './custom-resource.request.ts';
|
||||
|
||||
type CustomResourceHandlerOptions<TSpec extends TSchema> = {
|
||||
type EnsureSecretOptions<T extends ZodObject> = {
|
||||
schema: T;
|
||||
name: string;
|
||||
namespace: string;
|
||||
generator: () => Promise<z.infer<T>>;
|
||||
};
|
||||
|
||||
type CustomResourceHandlerOptions<TSpec extends ZodObject> = {
|
||||
request: CustomResourceRequest<TSpec>;
|
||||
ensureSecret: <T extends ZodObject>(options: EnsureSecretOptions<T>) => Promise<z.infer<T>>;
|
||||
services: Services;
|
||||
};
|
||||
|
||||
type CustomResourceConstructor<TSpec extends TSchema> = {
|
||||
type CustomResourceConstructor<TSpec extends ZodObject> = {
|
||||
kind: string;
|
||||
spec: TSpec;
|
||||
names: {
|
||||
@@ -20,7 +27,7 @@ type CustomResourceConstructor<TSpec extends TSchema> = {
|
||||
};
|
||||
};
|
||||
|
||||
abstract class CustomResource<TSpec extends TSchema> {
|
||||
abstract class CustomResource<TSpec extends ZodObject> {
|
||||
#options: CustomResourceConstructor<TSpec>;
|
||||
|
||||
constructor(options: CustomResourceConstructor<TSpec>) {
|
||||
@@ -53,9 +60,10 @@ abstract class CustomResource<TSpec extends TSchema> {
|
||||
return this.#options.names;
|
||||
}
|
||||
|
||||
public abstract update(options: CustomResourceHandlerOptions<TSpec>): Promise<void>;
|
||||
public update?(options: CustomResourceHandlerOptions<TSpec>): Promise<void>;
|
||||
public create?(options: CustomResourceHandlerOptions<TSpec>): Promise<void>;
|
||||
public delete?(options: CustomResourceHandlerOptions<TSpec>): Promise<void>;
|
||||
public reconcile?(options: CustomResourceHandlerOptions<TSpec>): Promise<void>;
|
||||
|
||||
public toManifest = () => {
|
||||
return {
|
||||
@@ -81,8 +89,16 @@ abstract class CustomResource<TSpec extends TSchema> {
|
||||
openAPIV3Schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
spec: this.spec,
|
||||
status: statusSchema,
|
||||
spec: {
|
||||
...z.toJSONSchema(this.spec.strict(), { io: 'input' }),
|
||||
$schema: undefined,
|
||||
additionalProperties: undefined,
|
||||
} as ExpectedAny,
|
||||
status: {
|
||||
...z.toJSONSchema(customResourceStatusSchema.strict(), { io: 'input' }),
|
||||
$schema: undefined,
|
||||
additionalProperties: undefined,
|
||||
} as ExpectedAny,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -96,4 +112,28 @@ abstract class CustomResource<TSpec extends TSchema> {
|
||||
};
|
||||
}
|
||||
|
||||
export { CustomResource, type CustomResourceConstructor, type CustomResourceHandlerOptions };
|
||||
const createCustomResource = <TSpec extends ZodObject>(
|
||||
options: CustomResourceConstructor<TSpec> & {
|
||||
update?: (options: CustomResourceHandlerOptions<TSpec>) => Promise<void>;
|
||||
create?: (options: CustomResourceHandlerOptions<TSpec>) => Promise<void>;
|
||||
delete?: (options: CustomResourceHandlerOptions<TSpec>) => Promise<void>;
|
||||
},
|
||||
) => {
|
||||
return class extends CustomResource<TSpec> {
|
||||
constructor() {
|
||||
super(options);
|
||||
}
|
||||
|
||||
public update = options.update;
|
||||
public create = options.create;
|
||||
public delete = options.delete;
|
||||
};
|
||||
};
|
||||
|
||||
export {
|
||||
CustomResource,
|
||||
type CustomResourceConstructor,
|
||||
type CustomResourceHandlerOptions,
|
||||
type EnsureSecretOptions,
|
||||
createCustomResource,
|
||||
};
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
import { ApiException, Watch } from '@kubernetes/client-node';
|
||||
import type { z, ZodObject } from 'zod';
|
||||
|
||||
import { K8sService } from '../services/k8s.ts';
|
||||
import type { Services } from '../utils/service.ts';
|
||||
|
||||
import { type CustomResource } from './custom-resource.base.ts';
|
||||
import { type CustomResource, type EnsureSecretOptions } from './custom-resource.base.ts';
|
||||
import { CustomResourceRequest } from './custom-resource.request.ts';
|
||||
|
||||
type ManifestCacheItem = {
|
||||
kind: string;
|
||||
namespace?: string;
|
||||
name?: string;
|
||||
manifest: CustomResourceRequest<ExpectedAny>;
|
||||
};
|
||||
|
||||
type ManifestChangeOptions = {
|
||||
crd: CustomResource<ExpectedAny>;
|
||||
cacheKey: string;
|
||||
manifest: ExpectedAny;
|
||||
};
|
||||
|
||||
class CustomResourceRegistry {
|
||||
#services: Services;
|
||||
#resources = new Set<CustomResource<any>>();
|
||||
#resources = new Set<CustomResource<ExpectedAny>>();
|
||||
#watchers = new Map<string, AbortController>();
|
||||
#cache = new Map<string, ManifestCacheItem>();
|
||||
|
||||
constructor(services: Services) {
|
||||
this.#services = services;
|
||||
@@ -23,11 +38,11 @@ class CustomResourceRegistry {
|
||||
return Array.from(this.#resources).find((r) => r.kind === kind);
|
||||
};
|
||||
|
||||
public register = (resource: CustomResource<any>) => {
|
||||
public register = (resource: CustomResource<ExpectedAny>) => {
|
||||
this.#resources.add(resource);
|
||||
};
|
||||
|
||||
public unregister = (resource: CustomResource<any>) => {
|
||||
public unregister = (resource: CustomResource<ExpectedAny>) => {
|
||||
this.#resources.delete(resource);
|
||||
this.#watchers.forEach((controller, kind) => {
|
||||
if (kind === resource.kind) {
|
||||
@@ -50,46 +65,191 @@ class CustomResourceRegistry {
|
||||
}
|
||||
};
|
||||
|
||||
#onResourceEvent = async (type: string, obj: any) => {
|
||||
const { kind } = obj;
|
||||
#ensureSecret =
|
||||
(request: CustomResourceRequest<ExpectedAny>) =>
|
||||
async <T extends ZodObject>(options: EnsureSecretOptions<T>): Promise<z.infer<T>> => {
|
||||
const { schema, name, namespace, generator } = options;
|
||||
const { metadata } = request;
|
||||
const k8sService = this.#services.get(K8sService);
|
||||
let exists = false;
|
||||
try {
|
||||
const secret = await k8sService.api.readNamespacedSecret({
|
||||
name,
|
||||
namespace,
|
||||
});
|
||||
|
||||
exists = true;
|
||||
if (secret?.data) {
|
||||
const decoded = Object.fromEntries(
|
||||
Object.entries(secret.data).map(([key, value]) => [key, Buffer.from(value, 'base64').toString('utf-8')]),
|
||||
);
|
||||
if (schema.safeParse(decoded).success) {
|
||||
return decoded as z.infer<T>;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiException && error.code === 404)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const value = await generator();
|
||||
const data = Object.fromEntries(
|
||||
Object.entries(value).map(([key, value]) => [key, Buffer.from(value as string).toString('base64')]),
|
||||
);
|
||||
const body = {
|
||||
kind: 'Secret',
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
ownerReferences: [
|
||||
{
|
||||
apiVersion: request.apiVersion,
|
||||
kind: request.kind,
|
||||
name: metadata.name,
|
||||
uid: metadata.uid,
|
||||
},
|
||||
],
|
||||
},
|
||||
type: 'Opaque',
|
||||
data,
|
||||
};
|
||||
if (exists) {
|
||||
await k8sService.api.replaceNamespacedSecret({
|
||||
name,
|
||||
namespace,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await k8sService.api.createNamespacedSecret({
|
||||
namespace,
|
||||
body,
|
||||
});
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
public get objects() {
|
||||
return Array.from(this.#cache.values());
|
||||
}
|
||||
|
||||
#onResourceUpdated = async (type: string, options: ManifestChangeOptions) => {
|
||||
const { cacheKey, manifest, crd } = options;
|
||||
const { kind, metadata } = manifest;
|
||||
const request = new CustomResourceRequest({
|
||||
type: type as 'ADDED' | 'MODIFIED',
|
||||
manifest: manifest,
|
||||
services: this.#services,
|
||||
});
|
||||
this.#cache.set(cacheKey, {
|
||||
kind,
|
||||
manifest: request,
|
||||
});
|
||||
const status = await request.getStatus();
|
||||
if (status && (type === 'ADDED' || type === 'MODIFIED')) {
|
||||
if (status.observedGeneration === metadata.generation) {
|
||||
this.#services.log.debug('Skipping resource update', {
|
||||
kind,
|
||||
name: metadata.name,
|
||||
namespace: metadata.namespace,
|
||||
observedGeneration: status.observedGeneration,
|
||||
generation: metadata.generation,
|
||||
});
|
||||
await crd.reconcile?.({
|
||||
request,
|
||||
services: this.#services,
|
||||
ensureSecret: this.#ensureSecret(request) as ExpectedAny,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.#services.log.debug('Updating resource', {
|
||||
type,
|
||||
kind,
|
||||
name: metadata.name,
|
||||
namespace: metadata.namespace,
|
||||
observedGeneration: status?.observedGeneration,
|
||||
generation: metadata.generation,
|
||||
});
|
||||
await request.markSeen();
|
||||
const handler = type === 'ADDED' && crd.create ? crd.create : crd.update;
|
||||
try {
|
||||
await handler?.({
|
||||
request,
|
||||
services: this.#services,
|
||||
ensureSecret: this.#ensureSecret(request) as ExpectedAny,
|
||||
});
|
||||
if (type === 'ADDED' || type === 'MODIFIED') {
|
||||
await request.setCondition({
|
||||
type: 'Ready',
|
||||
status: 'True',
|
||||
message: 'Resource created',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
let message = 'Unknown error';
|
||||
|
||||
if (error instanceof ApiException) {
|
||||
message = error.body;
|
||||
this.#services.log.error('Error handling resource', { reason: error.body }, error);
|
||||
} else if (error instanceof Error) {
|
||||
message = error.message;
|
||||
this.#services.log.error('Error handling resource', { reason: error.message }, error);
|
||||
} else {
|
||||
message = String(error);
|
||||
this.#services.log.error('Error handling resource', { reason: String(error) }, error);
|
||||
}
|
||||
if (type === 'ADDED' || type === 'MODIFIED') {
|
||||
await request.setCondition({
|
||||
type: 'Ready',
|
||||
status: 'False',
|
||||
reason: 'Error',
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#onDelete = async (options: ManifestChangeOptions) => {
|
||||
const { manifest, cacheKey } = options;
|
||||
const { kind, metadata } = manifest;
|
||||
|
||||
this.#services.log.debug('Deleting resource', {
|
||||
kind,
|
||||
name: metadata.name,
|
||||
namespace: metadata.namespace,
|
||||
observedGeneration: manifest.status?.observedGeneration,
|
||||
generation: metadata.generation,
|
||||
});
|
||||
this.#cache.delete(cacheKey);
|
||||
};
|
||||
|
||||
#onResourceEvent = async (type: string, manifest: ExpectedAny) => {
|
||||
const { kind, metadata } = manifest;
|
||||
const { name, namespace } = metadata;
|
||||
const cacheKey = [kind, name, namespace].join('___');
|
||||
const crd = this.getByKind(kind);
|
||||
if (!crd) {
|
||||
return;
|
||||
}
|
||||
|
||||
let handler = type === 'DELETED' ? crd.delete : crd.update;
|
||||
const request = new CustomResourceRequest({
|
||||
type: type as 'ADDED' | 'DELETED' | 'MODIFIED',
|
||||
manifest: obj,
|
||||
services: this.#services,
|
||||
});
|
||||
const input = { cacheKey, manifest, crd };
|
||||
|
||||
const status = await request.getStatus();
|
||||
if (status.observedGeneration === obj.metadata.generation) {
|
||||
this.#services.log.debug('Skipping resource update', {
|
||||
observedGeneration: status.observedGeneration,
|
||||
generation: obj.metadata.generation,
|
||||
});
|
||||
return;
|
||||
if (type === 'DELETE') {
|
||||
await this.#onDelete(input);
|
||||
} else {
|
||||
await this.#onResourceUpdated(type, input);
|
||||
}
|
||||
|
||||
if (type === 'ADDED' && crd.create) {
|
||||
handler = crd.create;
|
||||
}
|
||||
|
||||
await handler?.({
|
||||
request,
|
||||
services: this.#services,
|
||||
});
|
||||
};
|
||||
|
||||
#onError = (error: any) => {
|
||||
console.error(error);
|
||||
#onError = (error: ExpectedAny) => {
|
||||
this.#services.log.error('Error watching resource', { error });
|
||||
};
|
||||
|
||||
public install = async (replace = false) => {
|
||||
const k8sService = this.#services.get(K8sService);
|
||||
for (const crd of this.#resources) {
|
||||
this.#services.log.info('Installing CRD', { kind: crd.kind });
|
||||
try {
|
||||
const manifest = crd.toManifest();
|
||||
try {
|
||||
await k8sService.extensionsApi.createCustomResourceDefinition({
|
||||
@@ -107,6 +267,12 @@ class CustomResourceRegistry {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiException) {
|
||||
throw new Error(`Failed to install ${crd.kind}: ${error.body}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,85 +1,86 @@
|
||||
import type { Static, TSchema } from '@sinclair/typebox';
|
||||
import { ApiException, PatchStrategy, setHeaderOptions } from '@kubernetes/client-node';
|
||||
import { z, type ZodObject } from 'zod';
|
||||
import { setHeaderOptions } from '@kubernetes/client-node';
|
||||
|
||||
import type { Services } from '../utils/service.ts';
|
||||
import { Manifest } from '../services/k8s/k8s.manifest.ts';
|
||||
import { K8sService } from '../services/k8s.ts';
|
||||
|
||||
import { CustomResourceRegistry } from './custom-resource.registry.ts';
|
||||
import { CustomResourceStatus, type CustomResourceStatusType } from './custom-resource.status.ts';
|
||||
|
||||
type CustomResourceRequestOptions = {
|
||||
type: 'ADDED' | 'DELETED' | 'MODIFIED';
|
||||
manifest: any;
|
||||
manifest: ExpectedAny;
|
||||
services: Services;
|
||||
};
|
||||
|
||||
type CustomResourceRequestMetadata = Record<string, string> & {
|
||||
name: string;
|
||||
namespace?: string;
|
||||
labels?: Record<string, string>;
|
||||
annotations?: Record<string, string>;
|
||||
uid: string;
|
||||
resourceVersion: string;
|
||||
creationTimestamp: string;
|
||||
generation: number;
|
||||
};
|
||||
const customResourceStatusSchema = z.object({
|
||||
observedGeneration: z.number(),
|
||||
conditions: z.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
status: z.enum(['True', 'False', 'Unknown']),
|
||||
lastTransitionTime: z.string().datetime(),
|
||||
reason: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
class CustomResourceRequest<TSpec extends TSchema> {
|
||||
#options: CustomResourceRequestOptions;
|
||||
type CustomResourceStatus = z.infer<typeof customResourceStatusSchema>;
|
||||
|
||||
constructor(options: CustomResourceRequestOptions) {
|
||||
this.#options = options;
|
||||
class CustomResourceRequest<TSpec extends ZodObject> extends Manifest<z.infer<TSpec>> {
|
||||
#type: 'ADDED' | 'DELETED' | 'MODIFIED';
|
||||
|
||||
constructor({ type, ...options }: CustomResourceRequestOptions) {
|
||||
super(options);
|
||||
this.#type = type;
|
||||
}
|
||||
|
||||
public get services(): Services {
|
||||
return this.#options.services;
|
||||
public get schema() {
|
||||
return undefined as unknown as z.infer<TSpec>;
|
||||
}
|
||||
|
||||
public get type(): 'ADDED' | 'DELETED' | 'MODIFIED' {
|
||||
return this.#options.type;
|
||||
return this.#type;
|
||||
}
|
||||
|
||||
public get manifest() {
|
||||
return this.#options.manifest;
|
||||
}
|
||||
|
||||
public get kind(): string {
|
||||
return this.#options.manifest.kind;
|
||||
}
|
||||
|
||||
public get apiVersion(): string {
|
||||
return this.#options.manifest.apiVersion;
|
||||
}
|
||||
|
||||
public get spec(): Static<TSpec> {
|
||||
return this.#options.manifest.spec;
|
||||
}
|
||||
|
||||
public get metadata(): CustomResourceRequestMetadata {
|
||||
return this.#options.manifest.metadata;
|
||||
}
|
||||
|
||||
public isOwnerOf = (manifest: any) => {
|
||||
const ownerRef = manifest?.metadata?.ownerReferences || [];
|
||||
return ownerRef.some(
|
||||
(ref: any) =>
|
||||
ref.apiVersion === this.apiVersion &&
|
||||
ref.kind === this.kind &&
|
||||
ref.name === this.metadata.name &&
|
||||
ref.uid === this.metadata.uid,
|
||||
);
|
||||
public markSeen = async () => {
|
||||
await this.setStatus({
|
||||
observedGeneration: this.manifest.metadata.generation,
|
||||
});
|
||||
};
|
||||
|
||||
public setStatus = async (status: CustomResourceStatusType) => {
|
||||
const { manifest, services } = this.#options;
|
||||
const { kind, metadata } = manifest;
|
||||
const registry = services.get(CustomResourceRegistry);
|
||||
public setCondition = async (condition: Omit<CustomResourceStatus['conditions'][number], 'lastTransitionTime'>) => {
|
||||
const fullCondition = {
|
||||
...condition,
|
||||
lastTransitionTime: new Date().toISOString(),
|
||||
};
|
||||
const conditions: CustomResourceStatus['conditions'] = this.manifest?.status?.conditions || [];
|
||||
const index = conditions.findIndex((c) => c.type === condition.type);
|
||||
if (index === -1) {
|
||||
conditions.push(fullCondition);
|
||||
} else {
|
||||
conditions[index] = fullCondition;
|
||||
}
|
||||
await this.setStatus({
|
||||
conditions,
|
||||
});
|
||||
};
|
||||
|
||||
public getStatus = async () => {
|
||||
return this.manifest?.status as CustomResourceStatus | undefined;
|
||||
};
|
||||
|
||||
public setStatus = async (status: Partial<CustomResourceStatus>) => {
|
||||
const { kind, metadata } = this.manifest;
|
||||
const registry = this.services.get(CustomResourceRegistry);
|
||||
const crd = registry.getByKind(kind);
|
||||
if (!crd) {
|
||||
throw new Error(`Custom resource ${kind} not found`);
|
||||
}
|
||||
|
||||
const k8sService = services.get(K8sService);
|
||||
const current = await this.manifest;
|
||||
const k8sService = this.services.get(K8sService);
|
||||
|
||||
const { namespace = 'default', name } = metadata;
|
||||
|
||||
@@ -90,63 +91,23 @@ class CustomResourceRequest<TSpec extends TSchema> {
|
||||
namespace,
|
||||
plural: crd.names.plural,
|
||||
name,
|
||||
body: { status },
|
||||
body: {
|
||||
status: {
|
||||
observedGeneration: this.manifest.metadata.generation,
|
||||
conditions: current?.status?.conditions || [],
|
||||
...current?.status,
|
||||
...status,
|
||||
},
|
||||
},
|
||||
fieldValidation: 'Strict',
|
||||
},
|
||||
setHeaderOptions('Content-Type', PatchStrategy.MergePatch),
|
||||
);
|
||||
return response;
|
||||
};
|
||||
|
||||
public getCurrent = async () => {
|
||||
const { manifest, services } = this.#options;
|
||||
const k8sService = services.get(K8sService);
|
||||
const registry = services.get(CustomResourceRegistry);
|
||||
const crd = registry.getByKind(manifest.kind);
|
||||
if (!crd) {
|
||||
throw new Error(`Custom resource ${manifest.kind} not found`);
|
||||
}
|
||||
try {
|
||||
const resource = await k8sService.customObjectsApi.getNamespacedCustomObject({
|
||||
group: crd.group,
|
||||
version: crd.version,
|
||||
plural: crd.names.plural,
|
||||
namespace: manifest.metadata.namespace,
|
||||
name: manifest.metadata.name,
|
||||
});
|
||||
return resource as {
|
||||
apiVersion: string;
|
||||
kind: string;
|
||||
metadata: CustomResourceRequestMetadata;
|
||||
spec: Static<TSpec>;
|
||||
status: CustomResourceStatusType;
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof ApiException && error.code === 404) {
|
||||
return undefined;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
public getStatus = async () => {
|
||||
const resource = await this.getCurrent();
|
||||
if (!resource || !resource.status) {
|
||||
return new CustomResourceStatus({
|
||||
status: {
|
||||
observedGeneration: 0,
|
||||
conditions: [],
|
||||
{
|
||||
...setHeaderOptions('Content-Type', 'application/merge-patch+json'),
|
||||
},
|
||||
generation: 0,
|
||||
save: this.setStatus,
|
||||
});
|
||||
}
|
||||
return new CustomResourceStatus({
|
||||
status: { ...resource.status, observedGeneration: resource.status.observedGeneration },
|
||||
generation: resource.metadata.generation,
|
||||
save: this.setStatus,
|
||||
});
|
||||
);
|
||||
this.manifest = response;
|
||||
return response;
|
||||
};
|
||||
}
|
||||
|
||||
export { CustomResourceRequest };
|
||||
export { CustomResourceRequest, customResourceStatusSchema };
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
|
||||
type CustomResourceStatusType = Static<typeof statusSchema>;
|
||||
|
||||
const statusSchema = Type.Object({
|
||||
observedGeneration: Type.Number(),
|
||||
conditions: Type.Array(
|
||||
Type.Object({
|
||||
type: Type.String(),
|
||||
status: Type.String({
|
||||
enum: ['True', 'False', 'Unknown'],
|
||||
}),
|
||||
lastTransitionTime: Type.String(),
|
||||
reason: Type.String(),
|
||||
message: Type.String(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
type CustomResourceStatusOptions = {
|
||||
status?: CustomResourceStatusType;
|
||||
generation: number;
|
||||
save: (status: CustomResourceStatusType) => Promise<void>;
|
||||
};
|
||||
|
||||
class CustomResourceStatus {
|
||||
#status: CustomResourceStatusType;
|
||||
#generation: number;
|
||||
#save: (status: CustomResourceStatusType) => Promise<void>;
|
||||
|
||||
constructor(options: CustomResourceStatusOptions) {
|
||||
this.#save = options.save;
|
||||
this.#status = {
|
||||
observedGeneration: options.status?.observedGeneration ?? 0,
|
||||
conditions: options.status?.conditions ?? [],
|
||||
};
|
||||
this.#generation = options.generation;
|
||||
}
|
||||
|
||||
public get generation() {
|
||||
return this.#generation;
|
||||
}
|
||||
|
||||
public get observedGeneration() {
|
||||
return this.#status.observedGeneration;
|
||||
}
|
||||
|
||||
public set observedGeneration(observedGeneration: number) {
|
||||
this.#status.observedGeneration = observedGeneration;
|
||||
}
|
||||
|
||||
public getCondition = (type: string) => {
|
||||
return this.#status.conditions?.find((condition) => condition.type === type)?.status;
|
||||
};
|
||||
|
||||
public setCondition = (
|
||||
type: string,
|
||||
condition: Omit<CustomResourceStatusType['conditions'][number], 'type' | 'lastTransitionTime'>,
|
||||
) => {
|
||||
const currentCondition = this.getCondition(type);
|
||||
const newCondition = {
|
||||
...condition,
|
||||
type,
|
||||
lastTransitionTime: new Date().toISOString(),
|
||||
};
|
||||
if (currentCondition) {
|
||||
this.#status.conditions = this.#status.conditions.map((c) => (c.type === type ? newCondition : c));
|
||||
} else {
|
||||
this.#status.conditions.push(newCondition);
|
||||
}
|
||||
};
|
||||
|
||||
public save = async () => {
|
||||
await this.#save({
|
||||
...this.#status,
|
||||
observedGeneration: this.#generation,
|
||||
});
|
||||
};
|
||||
|
||||
public toJSON = () => {
|
||||
return this.#status;
|
||||
};
|
||||
}
|
||||
|
||||
export { CustomResourceStatus, statusSchema, type CustomResourceStatusType };
|
||||
35
src/index.ts
35
src/index.ts
@@ -1,11 +1,46 @@
|
||||
import 'dotenv/config';
|
||||
import { ApiException } from '@kubernetes/client-node';
|
||||
|
||||
import { CustomResourceRegistry } from './custom-resource/custom-resource.registry.ts';
|
||||
import { Services } from './utils/service.ts';
|
||||
import { SecretRequest } from './crds/secrets/secrets.request.ts';
|
||||
import { PostgresDatabase } from './crds/postgres/postgres.database.ts';
|
||||
import { AuthentikClient } from './crds/authentik/client/client.ts';
|
||||
import { Domain } from './crds/domain/domain/domain.ts';
|
||||
import { DomainEndpoint } from './crds/domain/endpoint/endpoint.ts';
|
||||
import { AuthentikServer } from './crds/authentik/server/server.ts';
|
||||
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.log('UNCAUGHT EXCEPTION');
|
||||
if (error instanceof ApiException) {
|
||||
return console.error(error.body);
|
||||
}
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (error) => {
|
||||
console.log('UNHANDLED REJECTION');
|
||||
if (error instanceof Error) {
|
||||
// show stack trace
|
||||
console.error(error.stack);
|
||||
}
|
||||
if (error instanceof ApiException) {
|
||||
return console.error(error.body);
|
||||
}
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
const services = new Services();
|
||||
const registry = services.get(CustomResourceRegistry);
|
||||
|
||||
registry.register(new SecretRequest());
|
||||
registry.register(new PostgresDatabase());
|
||||
registry.register(new AuthentikServer());
|
||||
registry.register(new AuthentikClient());
|
||||
registry.register(new Domain());
|
||||
registry.register(new DomainEndpoint());
|
||||
|
||||
await registry.install(true);
|
||||
await registry.watch();
|
||||
|
||||
225
src/services/authentik/authentik.instance.ts
Normal file
225
src/services/authentik/authentik.instance.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import { createAuthentikClient, type AuthentikClient } from '../../clients/authentik/authentik.ts';
|
||||
import type { Services } from '../../utils/service.ts';
|
||||
|
||||
import type { AuthentikServerInfo, UpsertClientRequest, UpsertGroupRequest } from './authentik.types.ts';
|
||||
|
||||
type AuthentikInstanceOptions = {
|
||||
info: AuthentikServerInfo;
|
||||
services: Services;
|
||||
};
|
||||
|
||||
const DEFAULT_AUTHORIZATION_FLOW = 'default-provider-authorization-implicit-consent';
|
||||
const DEFAULT_INVALIDATION_FLOW = 'default-invalidation-flow';
|
||||
const DEFAULT_SCOPES = ['openid', 'email', 'profile', 'offline_access'];
|
||||
|
||||
class AuthentikInstance {
|
||||
#options: AuthentikInstanceOptions;
|
||||
#client: AuthentikClient;
|
||||
|
||||
constructor(options: AuthentikInstanceOptions) {
|
||||
this.#options = options;
|
||||
const baseUrl = new URL('/api/v3', options.info.url.internal).toString();
|
||||
options.services.log.debug('Using Authentik base URL', { baseUrl });
|
||||
this.#client = createAuthentikClient({
|
||||
baseUrl,
|
||||
token: options.info.token,
|
||||
});
|
||||
}
|
||||
|
||||
#upsertApplication = async (request: UpsertClientRequest, provider: number, pk?: string) => {
|
||||
const client = this.#client;
|
||||
if (!pk) {
|
||||
return await client.core.coreApplicationsCreate({
|
||||
applicationRequest: {
|
||||
name: request.name,
|
||||
slug: request.name,
|
||||
provider,
|
||||
},
|
||||
});
|
||||
}
|
||||
return await client.core.coreApplicationsUpdate({
|
||||
slug: request.name,
|
||||
applicationRequest: {
|
||||
name: request.name,
|
||||
slug: request.name,
|
||||
provider,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
#upsertProvider = async (request: UpsertClientRequest, pk?: number) => {
|
||||
const flows = await this.getFlows();
|
||||
const authorizationFlow = flows.results.find(
|
||||
(flow) => flow.slug === (request.flows?.authorization ?? DEFAULT_AUTHORIZATION_FLOW),
|
||||
);
|
||||
const invalidationFlow = flows.results.find(
|
||||
(flow) => flow.slug === (request.flows?.invalidation ?? DEFAULT_INVALIDATION_FLOW),
|
||||
);
|
||||
if (!authorizationFlow || !invalidationFlow) {
|
||||
throw new Error('Authorization and invalidation flows not found');
|
||||
}
|
||||
const scopes = await this.getScopePropertyMappings();
|
||||
const scopePropertyMapping = (request.scopes ?? DEFAULT_SCOPES)
|
||||
.map((scope) => scopes.results.find((mapping) => mapping.scopeName === scope)?.pk)
|
||||
.filter(Boolean) as string[];
|
||||
|
||||
const client = this.#client;
|
||||
|
||||
if (!pk) {
|
||||
return await client.providers.providersOauth2Create({
|
||||
oAuth2ProviderRequest: {
|
||||
name: request.name,
|
||||
clientId: request.name,
|
||||
clientSecret: request.secret,
|
||||
redirectUris: request.redirectUris,
|
||||
authorizationFlow: authorizationFlow.pk,
|
||||
invalidationFlow: invalidationFlow.pk,
|
||||
propertyMappings: scopePropertyMapping,
|
||||
clientType: request.clientType,
|
||||
subMode: request.subMode,
|
||||
accessCodeValidity: request.timing?.accessCodeValidity,
|
||||
accessTokenValidity: request.timing?.accessTokenValidity,
|
||||
refreshTokenValidity: request.timing?.refreshTokenValidity,
|
||||
},
|
||||
});
|
||||
}
|
||||
return await client.providers.providersOauth2Update({
|
||||
id: pk,
|
||||
oAuth2ProviderRequest: {
|
||||
name: request.name,
|
||||
clientId: request.name,
|
||||
clientSecret: request.secret,
|
||||
redirectUris: request.redirectUris,
|
||||
authorizationFlow: authorizationFlow.pk,
|
||||
invalidationFlow: invalidationFlow.pk,
|
||||
propertyMappings: scopePropertyMapping,
|
||||
clientType: request.clientType,
|
||||
subMode: request.subMode,
|
||||
accessCodeValidity: request.timing?.accessCodeValidity,
|
||||
accessTokenValidity: request.timing?.accessTokenValidity,
|
||||
refreshTokenValidity: request.timing?.refreshTokenValidity,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
public getGroupFromName = async (name: string) => {
|
||||
const client = this.#client;
|
||||
const groups = await client.core.coreGroupsList({
|
||||
search: name,
|
||||
});
|
||||
return groups.results.find((group) => group.name === name);
|
||||
};
|
||||
|
||||
public getScopePropertyMappings = async () => {
|
||||
const client = this.#client;
|
||||
const mappings = await client.propertymappings.propertymappingsProviderScopeList({});
|
||||
return mappings;
|
||||
};
|
||||
|
||||
public getApplicationFromSlug = async (slug: string) => {
|
||||
const client = this.#client;
|
||||
const applications = await client.core.coreApplicationsList({
|
||||
search: slug,
|
||||
});
|
||||
const application = applications.results.find((app) => app.slug === slug);
|
||||
return application;
|
||||
};
|
||||
|
||||
public getProviderFromClientId = async (clientId: string) => {
|
||||
const client = this.#client;
|
||||
|
||||
const providers = await client.providers.providersOauth2List({
|
||||
clientId,
|
||||
});
|
||||
return providers.results.find((provider) => provider.clientId === clientId);
|
||||
};
|
||||
|
||||
public getFlows = async () => {
|
||||
const client = this.#client;
|
||||
const flows = await client.flows.flowsInstancesList();
|
||||
return flows;
|
||||
};
|
||||
|
||||
public upsertClient = async (request: UpsertClientRequest) => {
|
||||
const url = this.#options.info.url.external;
|
||||
try {
|
||||
let provider = await this.getProviderFromClientId(request.name);
|
||||
provider = await this.#upsertProvider(request, provider?.pk);
|
||||
let application = await this.getApplicationFromSlug(request.name);
|
||||
application = await this.#upsertApplication(request, provider.pk, application?.pk);
|
||||
const config = {
|
||||
provider: {
|
||||
id: provider.pk,
|
||||
name: provider.name,
|
||||
clientId: provider.clientId,
|
||||
clientSecret: provider.clientSecret,
|
||||
clientType: provider.clientType,
|
||||
subMode: provider.subMode,
|
||||
redirectUris: provider.redirectUris,
|
||||
scopes: provider.propertyMappings,
|
||||
timing: {
|
||||
accessCodeValidity: provider.accessCodeValidity,
|
||||
accessTokenValidity: provider.accessTokenValidity,
|
||||
refreshTokenValidity: provider.refreshTokenValidity,
|
||||
},
|
||||
},
|
||||
application: {
|
||||
id: application.pk,
|
||||
name: application.name,
|
||||
slug: application.slug,
|
||||
provider: provider.pk,
|
||||
},
|
||||
urls: {
|
||||
configuration: new URL(`/application/o/${provider.name}/.well-known/openid-configuration`, url).toString(),
|
||||
configurationIssuer: new URL(`/application/o/${provider.name}/`, url).toString(),
|
||||
authorization: new URL(`/application/o/${provider.name}/authorize/`, url).toString(),
|
||||
token: new URL(`/application/o/${provider.name}/token/`, url).toString(),
|
||||
userinfo: new URL(`/application/o/${provider.name}/userinfo/`, url).toString(),
|
||||
endSession: new URL(`/application/o/${provider.name}/end-session/`, url).toString(),
|
||||
jwks: new URL(`/application/o/${provider.name}/jwks/`, url).toString(),
|
||||
},
|
||||
};
|
||||
return { provider, application, config };
|
||||
} catch (error: ExpectedAny) {
|
||||
if ('response' in error) {
|
||||
throw new Error(await error.response.text());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
public deleteClient = async (name: string) => {
|
||||
const provider = await this.getProviderFromClientId(name);
|
||||
const client = this.#client;
|
||||
if (provider) {
|
||||
await client.providers.providersOauth2Destroy({ id: provider.pk });
|
||||
}
|
||||
const application = await this.getApplicationFromSlug(name);
|
||||
if (application) {
|
||||
await client.core.coreApplicationsDestroy({ slug: application.name });
|
||||
}
|
||||
};
|
||||
|
||||
public upsertGroup = async (request: UpsertGroupRequest) => {
|
||||
const group = await this.getGroupFromName(request.name);
|
||||
const client = this.#client;
|
||||
if (!group) {
|
||||
await client.core.coreGroupsCreate({
|
||||
groupRequest: {
|
||||
name: request.name,
|
||||
attributes: request.attributes,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await client.core.coreGroupsUpdate({
|
||||
groupUuid: group.pk,
|
||||
groupRequest: {
|
||||
name: request.name,
|
||||
attributes: request.attributes,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export { AuthentikInstance, type AuthentikInstanceOptions };
|
||||
21
src/services/authentik/authentik.service.ts
Normal file
21
src/services/authentik/authentik.service.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { Services } from '../../utils/service.ts';
|
||||
|
||||
import type { AuthentikServerInfo } from './authentik.types.ts';
|
||||
import { AuthentikInstance } from './authentik.instance.ts';
|
||||
|
||||
class AuthentikService {
|
||||
#services: Services;
|
||||
|
||||
constructor(services: Services) {
|
||||
this.#services = services;
|
||||
}
|
||||
|
||||
public get = async (info: AuthentikServerInfo) => {
|
||||
return new AuthentikInstance({
|
||||
info,
|
||||
services: this.#services,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export { AuthentikService };
|
||||
37
src/services/authentik/authentik.types.ts
Normal file
37
src/services/authentik/authentik.types.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { ClientTypeEnum, SubModeEnum } from '@goauthentik/api';
|
||||
|
||||
type AuthentikServerInfo = {
|
||||
url: {
|
||||
internal: string;
|
||||
external: string;
|
||||
};
|
||||
token: string;
|
||||
};
|
||||
|
||||
type UpsertClientRequest = {
|
||||
name: string;
|
||||
secret: string;
|
||||
scopes?: string[];
|
||||
flows?: {
|
||||
authorization: string;
|
||||
invalidation: string;
|
||||
};
|
||||
clientType?: ClientTypeEnum;
|
||||
subMode?: SubModeEnum;
|
||||
redirectUris: {
|
||||
url: string;
|
||||
matchingMode: 'strict' | 'regex';
|
||||
}[];
|
||||
timing?: {
|
||||
accessCodeValidity?: string;
|
||||
accessTokenValidity?: string;
|
||||
refreshTokenValidity?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type UpsertGroupRequest = {
|
||||
name: string;
|
||||
attributes?: Record<string, string[]>;
|
||||
};
|
||||
|
||||
export type { AuthentikServerInfo, UpsertClientRequest, UpsertGroupRequest };
|
||||
@@ -1,4 +1,22 @@
|
||||
class ConfigService {
|
||||
public get istio() {
|
||||
const gateway = process.env.ISTIO_GATEWAY;
|
||||
if (!gateway) {
|
||||
throw new Error('ISTIO_GATEWAY must be set');
|
||||
}
|
||||
return {
|
||||
gateway: process.env.ISTIO_GATEWAY,
|
||||
};
|
||||
}
|
||||
|
||||
public get certManager() {
|
||||
const certManager = process.env.CERT_MANAGER;
|
||||
if (!certManager) {
|
||||
throw new Error('CERT_MANAGER must be set');
|
||||
}
|
||||
return certManager;
|
||||
}
|
||||
|
||||
public get postgres() {
|
||||
const host = process.env.POSTGRES_HOST;
|
||||
const user = process.env.POSTGRES_USER;
|
||||
|
||||
@@ -1,17 +1,36 @@
|
||||
import { KubeConfig, CoreV1Api, ApiextensionsV1Api, CustomObjectsApi } from '@kubernetes/client-node';
|
||||
import {
|
||||
KubeConfig,
|
||||
CoreV1Api,
|
||||
ApiextensionsV1Api,
|
||||
CustomObjectsApi,
|
||||
EventsV1Api,
|
||||
KubernetesObjectApi,
|
||||
ApiException,
|
||||
PatchStrategy,
|
||||
} from '@kubernetes/client-node';
|
||||
|
||||
import type { Services } from '../utils/service.ts';
|
||||
|
||||
import { Manifest } from './k8s/k8s.manifest.ts';
|
||||
|
||||
class K8sService {
|
||||
#services: Services;
|
||||
#kc: KubeConfig;
|
||||
#k8sApi: CoreV1Api;
|
||||
#k8sExtensionsApi: ApiextensionsV1Api;
|
||||
#k8sCustomObjectsApi: CustomObjectsApi;
|
||||
#k8sEventsApi: EventsV1Api;
|
||||
#k8sObjectsApi: KubernetesObjectApi;
|
||||
|
||||
constructor() {
|
||||
constructor(services: Services) {
|
||||
this.#services = services;
|
||||
this.#kc = new KubeConfig();
|
||||
this.#kc.loadFromDefault();
|
||||
this.#k8sApi = this.#kc.makeApiClient(CoreV1Api);
|
||||
this.#k8sExtensionsApi = this.#kc.makeApiClient(ApiextensionsV1Api);
|
||||
this.#k8sCustomObjectsApi = this.#kc.makeApiClient(CustomObjectsApi);
|
||||
this.#k8sEventsApi = this.#kc.makeApiClient(EventsV1Api);
|
||||
this.#k8sObjectsApi = this.#kc.makeApiClient(KubernetesObjectApi);
|
||||
}
|
||||
|
||||
public get config() {
|
||||
@@ -29,6 +48,111 @@ class K8sService {
|
||||
public get customObjectsApi() {
|
||||
return this.#k8sCustomObjectsApi;
|
||||
}
|
||||
|
||||
public get eventsApi() {
|
||||
return this.#k8sEventsApi;
|
||||
}
|
||||
|
||||
public get objectsApi() {
|
||||
return this.#k8sObjectsApi;
|
||||
}
|
||||
|
||||
public exists = async (options: { apiVersion: string; kind: string; name: string; namespace?: string }) => {
|
||||
try {
|
||||
await this.objectsApi.read({
|
||||
apiVersion: options.apiVersion,
|
||||
kind: options.kind,
|
||||
metadata: {
|
||||
name: options.name,
|
||||
namespace: options.namespace,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (!(err instanceof ApiException && err.code === 404)) {
|
||||
throw err;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
public get = async <T>(options: { apiVersion: string; kind: string; name: string; namespace?: string }) => {
|
||||
try {
|
||||
const manifest = await this.objectsApi.read({
|
||||
apiVersion: options.apiVersion,
|
||||
kind: options.kind,
|
||||
metadata: {
|
||||
name: options.name,
|
||||
namespace: options.namespace,
|
||||
},
|
||||
});
|
||||
return new Manifest<T>({
|
||||
manifest,
|
||||
services: this.#services,
|
||||
});
|
||||
} catch (err) {
|
||||
if (!(err instanceof ApiException && err.code === 404)) {
|
||||
throw err;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
public upsert = async (obj: ExpectedAny) => {
|
||||
let current: unknown;
|
||||
try {
|
||||
current = await this.objectsApi.read({
|
||||
apiVersion: obj.apiVersion,
|
||||
kind: obj.kind,
|
||||
metadata: {
|
||||
name: obj.metadata.name,
|
||||
namespace: obj.metadata.namespace,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiException && error.code === 404)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (current) {
|
||||
return new Manifest({
|
||||
manifest: await this.objectsApi.patch(
|
||||
obj,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
PatchStrategy.MergePatch,
|
||||
),
|
||||
services: this.#services,
|
||||
});
|
||||
} else {
|
||||
return new Manifest({
|
||||
manifest: await this.objectsApi.create(obj),
|
||||
services: this.#services,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
public getSecret = async <T extends Record<string, string>>(name: string, namespace?: string) => {
|
||||
const current = await this.get<ExpectedAny>({
|
||||
apiVersion: 'v1',
|
||||
kind: 'Secret',
|
||||
name,
|
||||
namespace,
|
||||
});
|
||||
|
||||
if (!current) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { data } = current.manifest || {};
|
||||
const decodedData = Object.fromEntries(
|
||||
Object.entries(data).map(([key, value]) => [key, Buffer.from(String(value), 'base64').toString('utf-8')]),
|
||||
);
|
||||
return decodedData as T;
|
||||
};
|
||||
}
|
||||
|
||||
export { K8sService };
|
||||
|
||||
183
src/services/k8s/k8s.manifest.ts
Normal file
183
src/services/k8s/k8s.manifest.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import { ApiException, PatchStrategy, V1MicroTime } from '@kubernetes/client-node';
|
||||
|
||||
import type { Services } from '../../utils/service.ts';
|
||||
import { K8sService } from '../k8s.ts';
|
||||
import { GROUP } from '../../utils/consts.ts';
|
||||
import { CustomResourceRegistry } from '../../custom-resource/custom-resource.registry.ts';
|
||||
|
||||
type ManifestOptions = {
|
||||
manifest: ExpectedAny;
|
||||
services: Services;
|
||||
};
|
||||
|
||||
type ManifestMetadata = Record<string, string> & {
|
||||
name: string;
|
||||
namespace?: string;
|
||||
labels?: Record<string, string>;
|
||||
annotations?: Record<string, string>;
|
||||
uid: string;
|
||||
resourceVersion: string;
|
||||
creationTimestamp: string;
|
||||
generation: number;
|
||||
};
|
||||
|
||||
type EventOptions = {
|
||||
reason: string;
|
||||
message: string;
|
||||
action: string;
|
||||
type: 'Normal' | 'Warning' | 'Error';
|
||||
};
|
||||
|
||||
class Manifest<TSpec> {
|
||||
#options: ManifestOptions;
|
||||
|
||||
constructor(options: ManifestOptions) {
|
||||
this.#options = {
|
||||
...options,
|
||||
manifest: options.manifest,
|
||||
};
|
||||
}
|
||||
|
||||
public get objectRef() {
|
||||
return {
|
||||
apiVersion: this.apiVersion,
|
||||
kind: this.kind,
|
||||
name: this.metadata.name,
|
||||
uid: this.metadata.uid,
|
||||
namespace: this.metadata.namespace,
|
||||
};
|
||||
}
|
||||
|
||||
public get services(): Services {
|
||||
return this.#options.services;
|
||||
}
|
||||
|
||||
public get manifest() {
|
||||
return this.#options.manifest;
|
||||
}
|
||||
|
||||
protected set manifest(obj: ExpectedAny) {
|
||||
this.#options.manifest = obj;
|
||||
}
|
||||
|
||||
public get dependencyId() {
|
||||
return `${this.metadata.uid}-${this.metadata.generation}`;
|
||||
}
|
||||
|
||||
public get kind(): string {
|
||||
return this.#options.manifest.kind;
|
||||
}
|
||||
|
||||
public get apiVersion(): string {
|
||||
return this.#options.manifest.apiVersion;
|
||||
}
|
||||
|
||||
public get spec(): TSpec {
|
||||
return this.#options.manifest.spec;
|
||||
}
|
||||
|
||||
public get metadata(): ManifestMetadata {
|
||||
return this.#options.manifest.metadata;
|
||||
}
|
||||
|
||||
public isOwnerOf = (manifest: ExpectedAny) => {
|
||||
const ownerRef = manifest?.metadata?.ownerReferences || [];
|
||||
return ownerRef.some(
|
||||
(ref: ExpectedAny) =>
|
||||
ref.apiVersion === this.apiVersion &&
|
||||
ref.kind === this.kind &&
|
||||
ref.name === this.metadata.name &&
|
||||
ref.uid === this.metadata.uid,
|
||||
);
|
||||
};
|
||||
|
||||
public addEvent = async (event: EventOptions) => {
|
||||
const { manifest, services } = this.#options;
|
||||
const k8sService = services.get(K8sService);
|
||||
|
||||
await k8sService.eventsApi.createNamespacedEvent({
|
||||
namespace: manifest.metadata.namespace,
|
||||
body: {
|
||||
kind: 'Event',
|
||||
metadata: {
|
||||
name: `${manifest.metadata.name}-${Date.now()}-${Buffer.from(crypto.getRandomValues(new Uint8Array(8))).toString('hex')}`,
|
||||
namespace: manifest.metadata.namespace,
|
||||
},
|
||||
eventTime: new V1MicroTime(),
|
||||
note: event.message,
|
||||
action: event.action,
|
||||
reason: event.reason,
|
||||
type: event.type,
|
||||
reportingController: GROUP,
|
||||
reportingInstance: manifest.metadata.name,
|
||||
regarding: {
|
||||
apiVersion: manifest.apiVersion,
|
||||
resourceVersion: manifest.metadata.resourceVersion,
|
||||
kind: manifest.kind,
|
||||
name: manifest.metadata.name,
|
||||
namespace: manifest.metadata.namespace,
|
||||
uid: manifest.metadata.uid,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
public patch = async (manifest: ExpectedAny) => {
|
||||
const { services } = this.#options;
|
||||
const k8sService = services.get(K8sService);
|
||||
this.manifest = await k8sService.objectsApi.patch(
|
||||
{
|
||||
apiVersion: this.apiVersion,
|
||||
kind: this.kind,
|
||||
metadata: {
|
||||
name: this.metadata.name,
|
||||
namespace: this.metadata.namespace,
|
||||
ownerReferences: this.metadata.ownerReferences,
|
||||
...manifest.metadata,
|
||||
labels: {
|
||||
...this.metadata.labels,
|
||||
...(manifest.metadata?.label || {}),
|
||||
},
|
||||
annotations: {
|
||||
...this.metadata.annotations,
|
||||
...(manifest.metadata?.annotations || {}),
|
||||
},
|
||||
},
|
||||
spec: manifest.spec || this.spec,
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
PatchStrategy.MergePatch,
|
||||
);
|
||||
};
|
||||
|
||||
public update = async () => {
|
||||
const { manifest, services } = this.#options;
|
||||
const k8sService = services.get(K8sService);
|
||||
const registry = services.get(CustomResourceRegistry);
|
||||
const crd = registry.getByKind(manifest.kind);
|
||||
if (!crd) {
|
||||
throw new Error(`Custom resource ${manifest.kind} not found`);
|
||||
}
|
||||
try {
|
||||
const resource = await k8sService.objectsApi.read({
|
||||
apiVersion: this.apiVersion,
|
||||
kind: this.kind,
|
||||
metadata: {
|
||||
name: this.metadata.name,
|
||||
namespace: this.metadata.namespace,
|
||||
},
|
||||
});
|
||||
this.#options.manifest = resource;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiException && error.code === 404) {
|
||||
return undefined;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export { Manifest };
|
||||
@@ -11,7 +11,19 @@ class LogService {
|
||||
console.warn(message, data);
|
||||
};
|
||||
|
||||
public error = (message: string, data?: Record<string, unknown>) => {
|
||||
public error = (message: string, data?: Record<string, unknown>, root?: unknown) => {
|
||||
if (root instanceof AggregateError) {
|
||||
for (const error of root.errors) {
|
||||
if (error instanceof Error) {
|
||||
console.error(error.stack);
|
||||
} else {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (root instanceof Error) {
|
||||
console.log(root.stack);
|
||||
}
|
||||
console.error(message, data);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,8 +7,10 @@ import type { PostgresDatabase, PostgresRole } from './postgres.types.ts';
|
||||
|
||||
class PostgresService {
|
||||
#db: Knex;
|
||||
#services: Services;
|
||||
|
||||
constructor(services: Services) {
|
||||
this.#services = services;
|
||||
const configService = services.get(ConfigService);
|
||||
const config = configService.postgres;
|
||||
this.#db = knex({
|
||||
@@ -22,6 +24,11 @@ class PostgresService {
|
||||
});
|
||||
}
|
||||
|
||||
public get config() {
|
||||
const configService = this.#services.get(ConfigService);
|
||||
return configService.postgres;
|
||||
}
|
||||
|
||||
public upsertRole = async (role: PostgresRole) => {
|
||||
const existingRole = await this.#db.raw('SELECT 1 FROM pg_roles WHERE rolname = ?', [role.name]);
|
||||
|
||||
|
||||
8
src/types/kubernetes.ts
Normal file
8
src/types/kubernetes.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
type ResourceRef = {
|
||||
apiVersion: string;
|
||||
kind: string;
|
||||
name: string;
|
||||
uid: string;
|
||||
};
|
||||
|
||||
export type { ResourceRef };
|
||||
@@ -1,3 +1,10 @@
|
||||
const GROUP = 'homelab.mortenolsen.pro';
|
||||
const NAMESPACE = 'homelab';
|
||||
|
||||
export { GROUP };
|
||||
const FIELDS = {
|
||||
domain: {
|
||||
domainId: `${GROUP}/domain-id`,
|
||||
},
|
||||
};
|
||||
|
||||
export { GROUP, NAMESPACE, FIELDS };
|
||||
|
||||
13
src/utils/naming.ts
Normal file
13
src/utils/naming.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
const getWithNamespace = (input: string) => {
|
||||
const result = input.split('/');
|
||||
const first = result.pop();
|
||||
if (!first) {
|
||||
throw new Error(`${input} could not be parsed as a namespace`);
|
||||
}
|
||||
return {
|
||||
name: first,
|
||||
namespace: result.join('/'),
|
||||
};
|
||||
};
|
||||
|
||||
export { getWithNamespace };
|
||||
12
src/utils/types.ts
Normal file
12
src/utils/types.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type ExpectedAny = any;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
const noop = () => {};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
const noopAsync = async () => {};
|
||||
|
||||
export { noop, noopAsync };
|
||||
8
test-manifests/authentik-client.yaml
Normal file
8
test-manifests/authentik-client.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
apiVersion: homelab.mortenolsen.pro/v1
|
||||
kind: AuthentikClient
|
||||
metadata:
|
||||
name: foobas
|
||||
spec:
|
||||
redirectUris:
|
||||
- url: http://localhost:3000/api/auth/callback
|
||||
matchingMode: strict
|
||||
5
test-manifests/postgres-database.yaml
Normal file
5
test-manifests/postgres-database.yaml
Normal file
@@ -0,0 +1,5 @@
|
||||
apiVersion: 'homelab.mortenolsen.pro/v1'
|
||||
kind: 'PostgresDatabase'
|
||||
metadata:
|
||||
name: 'test2'
|
||||
namespace: 'playground'
|
||||
@@ -16,9 +16,8 @@
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
// "noUncheckedIndexedAccess": true,
|
||||
// "noImplicitOverride": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
|
||||
Reference in New Issue
Block a user