mirror of
https://github.com/morten-olsen/homelab-operator.git
synced 2026-02-08 01:36:28 +01:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83050d1eb1 |
2
.github/release-drafter-config.yml
vendored
2
.github/release-drafter-config.yml
vendored
@@ -1,5 +1,5 @@
|
|||||||
name-template: "$RESOLVED_VERSION 🌈"
|
name-template: "$RESOLVED_VERSION 🌈"
|
||||||
tag-template: "v$RESOLVED_VERSION"
|
tag-template: "$RESOLVED_VERSION"
|
||||||
categories:
|
categories:
|
||||||
- title: "🚀 Features"
|
- title: "🚀 Features"
|
||||||
labels:
|
labels:
|
||||||
|
|||||||
48
.github/workflows/main.yml
vendored
48
.github/workflows/main.yml
vendored
@@ -1,4 +1,4 @@
|
|||||||
name: Build, tag and release
|
name: Build and release
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -77,3 +77,49 @@ jobs:
|
|||||||
publish: true
|
publish: true
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
release:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
attestations: write
|
||||||
|
id-token: write
|
||||||
|
pages: write
|
||||||
|
name: Release
|
||||||
|
if: github.ref == 'refs/heads/main'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: update-release-draft
|
||||||
|
environment: release
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Log in to the Container registry
|
||||||
|
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
|
||||||
|
with:
|
||||||
|
registry: ${{ env.DOCKER_REGISTRY }}
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
||||||
|
with:
|
||||||
|
images: ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: push
|
||||||
|
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Generate artifact attestation
|
||||||
|
uses: actions/attest-build-provenance@v2
|
||||||
|
with:
|
||||||
|
subject-name: ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME}}
|
||||||
|
subject-digest: ${{ steps.push.outputs.digest }}
|
||||||
|
push-to-registry: true
|
||||||
65
.github/workflows/publish-tag.yml
vendored
65
.github/workflows/publish-tag.yml
vendored
@@ -1,65 +0,0 @@
|
|||||||
name: Publish tag
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- 'main'
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
|
|
||||||
env:
|
|
||||||
environment: test
|
|
||||||
release_channel: latest
|
|
||||||
DO_NOT_TRACK: "1"
|
|
||||||
NODE_VERSION: "23.x"
|
|
||||||
DOCKER_REGISTRY: ghcr.io
|
|
||||||
IMAGE_NAME: ${{ github.repository }}
|
|
||||||
PNPM_VERSION: 10.6.0
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
attestations: write
|
|
||||||
id-token: write
|
|
||||||
pages: write
|
|
||||||
name: Release
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Log in to the Container registry
|
|
||||||
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.DOCKER_REGISTRY }}
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Extract metadata (tags, labels) for Docker
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
|
||||||
with:
|
|
||||||
images: ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: push
|
|
||||||
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
push: true
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
||||||
|
|
||||||
- name: Generate artifact attestation
|
|
||||||
uses: actions/attest-build-provenance@v2
|
|
||||||
with:
|
|
||||||
subject-name: ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME}}
|
|
||||||
subject-digest: ${{ steps.push.outputs.digest }}
|
|
||||||
push-to-registry: true
|
|
||||||
277
README.md
277
README.md
@@ -1,282 +1,15 @@
|
|||||||
# homelab-operator
|
# homelab-operator
|
||||||
|
|
||||||
A Kubernetes operator designed for homelab environments that simplifies the
|
To install dependencies:
|
||||||
management of PostgreSQL databases and Kubernetes secrets. Built with TypeScript
|
|
||||||
and designed to run efficiently in resource-constrained environments.
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- **PostgreSQL Database Management**: Automatically create and manage PostgreSQL
|
|
||||||
databases and roles
|
|
||||||
- **Secret Management**: Generate and manage Kubernetes secrets with
|
|
||||||
configurable data
|
|
||||||
- **Owner References**: Automatic cleanup when resources are deleted
|
|
||||||
- **Status Tracking**: Comprehensive status conditions and error reporting
|
|
||||||
- **Lightweight**: Minimal resource footprint suitable for homelab environments
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
The operator manages two main Custom Resource Definitions (CRDs):
|
|
||||||
|
|
||||||
### PostgresDatabase
|
|
||||||
|
|
||||||
Manages PostgreSQL databases and their associated roles:
|
|
||||||
|
|
||||||
- Creates a PostgreSQL role with a secure random password
|
|
||||||
- Creates a database owned by that role
|
|
||||||
- Generates a Kubernetes secret containing database credentials
|
|
||||||
- Ensures proper cleanup through owner references
|
|
||||||
|
|
||||||
### SecretRequest
|
|
||||||
|
|
||||||
Generates Kubernetes secrets with configurable data:
|
|
||||||
|
|
||||||
- Supports custom secret names
|
|
||||||
- Configurable data fields with various encodings
|
|
||||||
- Automatic secret lifecycle management
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
- Kubernetes cluster (1.20+)
|
|
||||||
- PostgreSQL instance accessible from the cluster
|
|
||||||
- Helm 3.x (for chart-based installation)
|
|
||||||
|
|
||||||
### Using Helm Chart
|
|
||||||
|
|
||||||
1. Clone the repository:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <repository-url>
|
bun install
|
||||||
cd homelab-operator
|
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Install using Helm:
|
To run:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
helm install homelab-operator ./chart \
|
bun run index.ts
|
||||||
--set-string env.POSTGRES_HOST=<your-postgres-host> \
|
|
||||||
--set-string env.POSTGRES_USER=<admin-user> \
|
|
||||||
--set-string env.POSTGRES_PASSWORD=<admin-password>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using kubectl
|
This project was created using `bun init` in bun v1.2.16. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
||||||
|
|
||||||
1. Build and push the Docker image:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -t your-registry/homelab-operator:latest .
|
|
||||||
docker push your-registry/homelab-operator:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Apply the Kubernetes manifests:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
kubectl apply -f chart/templates/
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
The operator is configured through environment variables:
|
|
||||||
|
|
||||||
| Variable | Description | Required | Default |
|
|
||||||
| ------------------- | ---------------------------------------- | -------- | ------- |
|
|
||||||
| `POSTGRES_HOST` | PostgreSQL server hostname | Yes | - |
|
|
||||||
| `POSTGRES_USER` | PostgreSQL admin username | Yes | - |
|
|
||||||
| `POSTGRES_PASSWORD` | PostgreSQL admin password | Yes | - |
|
|
||||||
| `POSTGRES_PORT` | PostgreSQL server port | No | 5432 |
|
|
||||||
| `LOG_LEVEL` | Logging level (debug, info, warn, error) | No | info |
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
### PostgreSQL Database
|
|
||||||
|
|
||||||
Create a PostgreSQL database with an associated role:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
apiVersion: homelab.mortenolsen.pro/v1
|
|
||||||
kind: PostgresDatabase
|
|
||||||
metadata:
|
|
||||||
name: my-app-db
|
|
||||||
namespace: my-namespace
|
|
||||||
spec: {}
|
|
||||||
```
|
|
||||||
|
|
||||||
This will create:
|
|
||||||
|
|
||||||
- A PostgreSQL role named `my-app-db`
|
|
||||||
- A PostgreSQL database named `my-namespace_my-app-db` owned by the role
|
|
||||||
- A Kubernetes secret `postgres-database-my-app-db` containing:
|
|
||||||
- `name`: Base64-encoded database name
|
|
||||||
- `user`: Base64-encoded username
|
|
||||||
- `password`: Base64-encoded password
|
|
||||||
|
|
||||||
### Secret Request
|
|
||||||
|
|
||||||
Generate a Kubernetes secret with custom data:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
apiVersion: homelab.mortenolsen.pro/v1
|
|
||||||
kind: SecretRequest
|
|
||||||
metadata:
|
|
||||||
name: my-secret
|
|
||||||
namespace: my-namespace
|
|
||||||
spec:
|
|
||||||
secretName: app-config
|
|
||||||
data:
|
|
||||||
- key: api-key
|
|
||||||
value: "my-api-key"
|
|
||||||
encoding: base64
|
|
||||||
- key: database-url
|
|
||||||
value: "postgresql://user:pass@host:5432/db"
|
|
||||||
- key: random-token
|
|
||||||
length: 32
|
|
||||||
chars: "abcdefghijklmnopqrstuvwxyz0123456789"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Accessing Created Resources
|
|
||||||
|
|
||||||
To retrieve database credentials:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Get the secret
|
|
||||||
kubectl get secret postgres-database-my-app-db -o jsonpath='{.data.user}' | base64 -d
|
|
||||||
kubectl get secret postgres-database-my-app-db -o jsonpath='{.data.password}' | base64 -d
|
|
||||||
kubectl get secret postgres-database-my-app-db -o jsonpath='{.data.name}' | base64 -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
- [Bun](https://bun.sh/) runtime
|
|
||||||
- [pnpm](https://pnpm.io/) package manager
|
|
||||||
- Docker (for building images)
|
|
||||||
- Access to a Kubernetes cluster for testing
|
|
||||||
|
|
||||||
### Setup
|
|
||||||
|
|
||||||
1. Clone the repository:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone <repository-url>
|
|
||||||
cd homelab-operator
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Install dependencies:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm install
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Set up development environment:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp .env.example .env
|
|
||||||
# Edit .env with your PostgreSQL connection details
|
|
||||||
```
|
|
||||||
|
|
||||||
### Running Locally
|
|
||||||
|
|
||||||
For development, you can run the operator locally against a remote cluster:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Ensure kubectl is configured for your development cluster
|
|
||||||
export KUBECONFIG=~/.kube/config
|
|
||||||
|
|
||||||
# Set PostgreSQL connection environment variables
|
|
||||||
export POSTGRES_HOST=localhost
|
|
||||||
export POSTGRES_USER=postgres
|
|
||||||
export POSTGRES_PASSWORD=yourpassword
|
|
||||||
|
|
||||||
# Run the operator
|
|
||||||
bun run src/index.ts
|
|
||||||
```
|
|
||||||
|
|
||||||
### Development with Docker Compose
|
|
||||||
|
|
||||||
A development environment with PostgreSQL is provided:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker-compose -f docker-compose.dev.yaml up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
### Building
|
|
||||||
|
|
||||||
Build the Docker image:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -t homelab-operator:latest .
|
|
||||||
```
|
|
||||||
|
|
||||||
### Testing
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Run linting
|
|
||||||
pnpm run test:lint
|
|
||||||
|
|
||||||
# Apply test resources
|
|
||||||
kubectl apply -f test.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
1. Fork the repository
|
|
||||||
2. Create a feature branch: `git checkout -b feature/new-feature`
|
|
||||||
3. Make your changes and add tests
|
|
||||||
4. Run linting: `pnpm run test:lint`
|
|
||||||
5. Commit your changes: `git commit -am 'Add new feature'`
|
|
||||||
6. Push to the branch: `git push origin feature/new-feature`
|
|
||||||
7. Submit a pull request
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
├── chart/ # Helm chart for deployment
|
|
||||||
├── src/
|
|
||||||
│ ├── crds/ # Custom Resource Definitions
|
|
||||||
│ │ ├── postgres/ # PostgreSQL database management
|
|
||||||
│ │ └── secrets/ # Secret generation
|
|
||||||
│ ├── custom-resource/ # Base CRD framework
|
|
||||||
│ ├── database/ # Database migrations
|
|
||||||
│ ├── services/ # Core services
|
|
||||||
│ │ ├── config/ # Configuration management
|
|
||||||
│ │ ├── k8s.ts # Kubernetes API client
|
|
||||||
│ │ ├── log/ # Logging service
|
|
||||||
│ │ ├── postgres/ # PostgreSQL service
|
|
||||||
│ │ └── secrets/ # Secret management
|
|
||||||
│ └── utils/ # Utilities and constants
|
|
||||||
├── Dockerfile # Container build configuration
|
|
||||||
└── docker-compose.dev.yaml # Development environment
|
|
||||||
```
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
This project is licensed under the MIT License - see the LICENSE file for
|
|
||||||
details.
|
|
||||||
|
|
||||||
## Support
|
|
||||||
|
|
||||||
For support and questions:
|
|
||||||
|
|
||||||
- Create an issue in the GitHub repository
|
|
||||||
- Check existing issues for similar problems
|
|
||||||
- Review the logs using `kubectl logs -l app=homelab-operator`
|
|
||||||
|
|
||||||
## Status Monitoring
|
|
||||||
|
|
||||||
Monitor the operator status:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Check operator logs
|
|
||||||
kubectl logs -l app=homelab-operator -f
|
|
||||||
|
|
||||||
# Check CRD status
|
|
||||||
kubectl get postgresdatabases
|
|
||||||
kubectl get secretrequests
|
|
||||||
|
|
||||||
# Describe resources for detailed status
|
|
||||||
kubectl describe postgresdatabase my-app-db
|
|
||||||
kubectl describe secretrequest my-secret
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
|
|
||||||
image:
|
image:
|
||||||
repository: ghcr.io/morten-olsen/homelab-operator
|
repository: ghcr.io/morten-olsen/homelab-operator
|
||||||
pullPolicy: Always
|
pullPolicy: IfNotPresent
|
||||||
# Overrides the image tag whose default is the chart appVersion.
|
# Overrides the image tag whose default is the chart appVersion.
|
||||||
tag: main
|
tag: ""
|
||||||
|
|
||||||
imagePullSecrets: []
|
imagePullSecrets: []
|
||||||
nameOverride: ""
|
nameOverride: ""
|
||||||
|
|||||||
@@ -46,6 +46,6 @@ export default tseslint.config(
|
|||||||
},
|
},
|
||||||
...compat.extends('plugin:prettier/recommended'),
|
...compat.extends('plugin:prettier/recommended'),
|
||||||
{
|
{
|
||||||
ignores: ['**/node_modules/', '**/dist/', '**/.turbo/', '**/generated/', '**/clients/*.types.ts'],
|
ignores: ['**/node_modules/', '**/dist/', '**/.turbo/', '**/generated/'],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
15
package.json
15
package.json
@@ -4,8 +4,11 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/bun": "latest",
|
||||||
|
"nodemon": "^3.1.10",
|
||||||
"@eslint/eslintrc": "3.3.1",
|
"@eslint/eslintrc": "3.3.1",
|
||||||
"@eslint/js": "9.32.0",
|
"@eslint/js": "9.32.0",
|
||||||
|
"@pnpm/find-workspace-packages": "6.0.9",
|
||||||
"eslint": "9.32.0",
|
"eslint": "9.32.0",
|
||||||
"eslint-config-prettier": "10.1.8",
|
"eslint-config-prettier": "10.1.8",
|
||||||
"eslint-plugin-import": "2.32.0",
|
"eslint-plugin-import": "2.32.0",
|
||||||
@@ -18,23 +21,17 @@
|
|||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@goauthentik/api": "2025.6.3-1751754396",
|
|
||||||
"@kubernetes/client-node": "^1.3.0",
|
"@kubernetes/client-node": "^1.3.0",
|
||||||
"dotenv": "^17.2.1",
|
"@sinclair/typebox": "^0.34.38",
|
||||||
"knex": "^3.1.0",
|
"knex": "^3.1.0",
|
||||||
"pg": "^8.16.3",
|
"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",
|
"packageManager": "pnpm@10.6.0",
|
||||||
"pnpm": {
|
"pnpm": {
|
||||||
"onlyBuiltDependencies": [
|
"onlyBuiltDependencies": [
|
||||||
"sqlite3"
|
"sqlite3"
|
||||||
],
|
]
|
||||||
"patchedDependencies": {
|
|
||||||
"@kubernetes/client-node": "patches/@kubernetes__client-node.patch"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo 'No tests'",
|
"test": "echo 'No tests'",
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
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
8
postgres-database.ts
Normal file
8
postgres-database.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
apiVersion: 'homelab.mortenolsen.pro/v1';
|
||||||
|
kind: 'PostgresDatabase';
|
||||||
|
name: 'test2';
|
||||||
|
namespace: 'playground';
|
||||||
|
foo: 'bar';
|
||||||
|
foo: 'bar';
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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'),
|
|
||||||
);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
kubectl delete -f "$1"
|
|
||||||
kubectl apply -f "$1"
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
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
58661
src/clients/authentik/authentik.types.d.ts
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,58 +0,0 @@
|
|||||||
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';
|
|
||||||
|
|
||||||
const authentikClientSpec = z.object({
|
|
||||||
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 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 client = await authentikService.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 };
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
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 || 'homelab'}.svc.cluster.local`,
|
|
||||||
port: request.spec.destination.port,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
export { DomainEndpoint };
|
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { z } from 'zod';
|
import { Type } from '@sinclair/typebox';
|
||||||
|
import { ApiException, type V1Secret } from '@kubernetes/client-node';
|
||||||
|
|
||||||
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
|
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';
|
import { PostgresService } from '../../services/postgres/postgres.service.ts';
|
||||||
|
|
||||||
const postgresDatabaseSpecSchema = z.object({});
|
const postgresDatabaseSpecSchema = Type.Object({});
|
||||||
|
|
||||||
class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema> {
|
class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema> {
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -17,39 +20,99 @@ class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public update = async (options: CustomResourceHandlerOptions<typeof postgresDatabaseSpecSchema>) => {
|
#getVariables = async (request: CustomResourceRequest<typeof postgresDatabaseSpecSchema>) => {
|
||||||
const { request, services, ensureSecret } = options;
|
const { metadata, services } = request;
|
||||||
const variables = await ensureSecret({
|
const k8sService = services.get(K8sService);
|
||||||
name: `postgres-database-${request.metadata.name}`,
|
|
||||||
namespace: request.metadata.namespace ?? 'default',
|
const secretName = `postgres-database-${metadata.name}`;
|
||||||
schema: z.object({
|
let secret: V1Secret | undefined;
|
||||||
name: z.string(),
|
|
||||||
user: z.string(),
|
try {
|
||||||
password: z.string(),
|
secret = await k8sService.api.readNamespacedSecret({
|
||||||
}),
|
name: secretName,
|
||||||
generator: async () => ({
|
namespace: metadata.namespace ?? 'default',
|
||||||
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')}`,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
} 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 postgresService = services.get(PostgresService);
|
const postgresService = services.get(PostgresService);
|
||||||
await postgresService.upsertRole({
|
await postgresService.upsertRole({
|
||||||
name: variables.user,
|
name: Buffer.from(variables.user!, 'base64').toString('utf-8'),
|
||||||
password: variables.password,
|
password: Buffer.from(variables.password!, 'base64').toString('utf-8'),
|
||||||
});
|
});
|
||||||
|
|
||||||
await postgresService.upsertDatabase({
|
await postgresService.upsertDatabase({
|
||||||
name: variables.name,
|
name: Buffer.from(variables.name!, 'base64').toString('utf-8'),
|
||||||
owner: variables.user,
|
owner: Buffer.from(variables.user!, 'base64').toString('utf-8'),
|
||||||
});
|
});
|
||||||
|
|
||||||
await request.addEvent({
|
status.setCondition('Ready', {
|
||||||
type: 'Normal',
|
status: 'True',
|
||||||
reason: 'DatabaseUpserted',
|
reason: 'Ready',
|
||||||
message: 'Database has been upserted',
|
message: 'Role created',
|
||||||
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,18 +1,24 @@
|
|||||||
import { z } from 'zod';
|
import { Type } from '@sinclair/typebox';
|
||||||
|
import { ApiException, type V1Secret } from '@kubernetes/client-node';
|
||||||
|
|
||||||
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
|
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
|
||||||
|
import { K8sService } from '../../services/k8s.ts';
|
||||||
|
|
||||||
const stringValueSchema = z.object({
|
const stringValueSchema = Type.String({
|
||||||
key: z.string(),
|
key: Type.String(),
|
||||||
chars: z.string().optional(),
|
chars: Type.Optional(Type.String()),
|
||||||
length: z.number().optional(),
|
length: Type.Optional(Type.Number()),
|
||||||
encoding: z.enum(['utf-8', 'base64', 'base64url', 'hex']).optional(),
|
encoding: Type.Optional(
|
||||||
value: z.string().optional(),
|
Type.String({
|
||||||
|
enum: ['utf-8', 'base64', 'base64url', 'hex'],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
value: Type.Optional(Type.String()),
|
||||||
});
|
});
|
||||||
|
|
||||||
const secretRequestSpec = z.object({
|
const secretRequestSpec = Type.Object({
|
||||||
secretName: z.string().optional(),
|
secretName: Type.Optional(Type.String()),
|
||||||
data: z.array(stringValueSchema),
|
data: Type.Array(stringValueSchema),
|
||||||
});
|
});
|
||||||
|
|
||||||
class SecretRequest extends CustomResource<typeof secretRequestSpec> {
|
class SecretRequest extends CustomResource<typeof secretRequestSpec> {
|
||||||
@@ -27,18 +33,71 @@ class SecretRequest extends CustomResource<typeof secretRequestSpec> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public update = async (options: CustomResourceHandlerOptions<typeof secretRequestSpec>) => {
|
#createSecret = async (options: CustomResourceHandlerOptions<typeof secretRequestSpec>) => {
|
||||||
const { request, ensureSecret } = options;
|
const { request, services } = options;
|
||||||
const { secretName = request.metadata.name } = request.spec;
|
const { apiVersion, kind, spec, metadata } = request;
|
||||||
const { namespace = request.metadata.namespace ?? 'default' } = request.metadata;
|
const { secretName = metadata.name } = spec;
|
||||||
await ensureSecret({
|
const { namespace = 'default' } = metadata;
|
||||||
|
const k8sService = services.get(K8sService);
|
||||||
|
let current: V1Secret | undefined;
|
||||||
|
try {
|
||||||
|
current = await k8sService.api.readNamespacedSecret({
|
||||||
name: secretName,
|
name: secretName,
|
||||||
namespace,
|
namespace,
|
||||||
schema: z.object({}).passthrough(),
|
|
||||||
generator: async () => ({
|
|
||||||
hello: 'world',
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
} 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',
|
||||||
|
});
|
||||||
|
return await status.save();
|
||||||
|
} catch {
|
||||||
|
status.setCondition('Ready', {
|
||||||
|
status: 'False',
|
||||||
|
reason: 'SecretNotCreated',
|
||||||
|
message: 'Secret not created',
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +1,17 @@
|
|||||||
import { z, type ZodObject } from 'zod';
|
import { type TSchema } from '@sinclair/typebox';
|
||||||
|
|
||||||
import { GROUP } from '../utils/consts.ts';
|
import { GROUP } from '../utils/consts.ts';
|
||||||
import type { Services } from '../utils/service.ts';
|
import type { Services } from '../utils/service.ts';
|
||||||
import { noopAsync } from '../utils/types.ts';
|
|
||||||
|
|
||||||
import { customResourceStatusSchema, type CustomResourceRequest } from './custom-resource.request.ts';
|
import { statusSchema } from './custom-resource.status.ts';
|
||||||
|
import type { CustomResourceRequest } from './custom-resource.request.ts';
|
||||||
|
|
||||||
type EnsureSecretOptions<T extends ZodObject> = {
|
type CustomResourceHandlerOptions<TSpec extends TSchema> = {
|
||||||
schema: T;
|
|
||||||
name: string;
|
|
||||||
namespace: string;
|
|
||||||
generator: () => Promise<z.infer<T>>;
|
|
||||||
};
|
|
||||||
|
|
||||||
type CustomResourceHandlerOptions<TSpec extends ZodObject> = {
|
|
||||||
request: CustomResourceRequest<TSpec>;
|
request: CustomResourceRequest<TSpec>;
|
||||||
ensureSecret: <T extends ZodObject>(options: EnsureSecretOptions<T>) => Promise<z.infer<T>>;
|
|
||||||
services: Services;
|
services: Services;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CustomResourceConstructor<TSpec extends ZodObject> = {
|
type CustomResourceConstructor<TSpec extends TSchema> = {
|
||||||
kind: string;
|
kind: string;
|
||||||
spec: TSpec;
|
spec: TSpec;
|
||||||
names: {
|
names: {
|
||||||
@@ -28,7 +20,7 @@ type CustomResourceConstructor<TSpec extends ZodObject> = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
abstract class CustomResource<TSpec extends ZodObject> {
|
abstract class CustomResource<TSpec extends TSchema> {
|
||||||
#options: CustomResourceConstructor<TSpec>;
|
#options: CustomResourceConstructor<TSpec>;
|
||||||
|
|
||||||
constructor(options: CustomResourceConstructor<TSpec>) {
|
constructor(options: CustomResourceConstructor<TSpec>) {
|
||||||
@@ -89,16 +81,8 @@ abstract class CustomResource<TSpec extends ZodObject> {
|
|||||||
openAPIV3Schema: {
|
openAPIV3Schema: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
spec: {
|
spec: this.spec,
|
||||||
...z.toJSONSchema(this.spec.strict(), { io: 'input' }),
|
status: statusSchema,
|
||||||
$schema: undefined,
|
|
||||||
additionalProperties: undefined,
|
|
||||||
} as ExpectedAny,
|
|
||||||
status: {
|
|
||||||
...z.toJSONSchema(customResourceStatusSchema.strict(), { io: 'input' }),
|
|
||||||
$schema: undefined,
|
|
||||||
additionalProperties: undefined,
|
|
||||||
} as ExpectedAny,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -112,28 +96,4 @@ abstract class CustomResource<TSpec extends ZodObject> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const createCustomResource = <TSpec extends ZodObject>(
|
export { CustomResource, type CustomResourceConstructor, type CustomResourceHandlerOptions };
|
||||||
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 ?? noopAsync;
|
|
||||||
public create = options.create;
|
|
||||||
public delete = options.delete;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export {
|
|
||||||
CustomResource,
|
|
||||||
type CustomResourceConstructor,
|
|
||||||
type CustomResourceHandlerOptions,
|
|
||||||
type EnsureSecretOptions,
|
|
||||||
createCustomResource,
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,30 +1,15 @@
|
|||||||
import { ApiException, Watch } from '@kubernetes/client-node';
|
import { ApiException, Watch } from '@kubernetes/client-node';
|
||||||
import type { ZodObject } from 'zod';
|
|
||||||
|
|
||||||
import { K8sService } from '../services/k8s.ts';
|
import { K8sService } from '../services/k8s.ts';
|
||||||
import type { Services } from '../utils/service.ts';
|
import type { Services } from '../utils/service.ts';
|
||||||
|
|
||||||
import { type CustomResource, type EnsureSecretOptions } from './custom-resource.base.ts';
|
import { type CustomResource } from './custom-resource.base.ts';
|
||||||
import { CustomResourceRequest } from './custom-resource.request.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 {
|
class CustomResourceRegistry {
|
||||||
#services: Services;
|
#services: Services;
|
||||||
#resources = new Set<CustomResource<ExpectedAny>>();
|
#resources = new Set<CustomResource<any>>();
|
||||||
#watchers = new Map<string, AbortController>();
|
#watchers = new Map<string, AbortController>();
|
||||||
#cache = new Map<string, ManifestCacheItem>();
|
|
||||||
|
|
||||||
constructor(services: Services) {
|
constructor(services: Services) {
|
||||||
this.#services = services;
|
this.#services = services;
|
||||||
@@ -38,11 +23,11 @@ class CustomResourceRegistry {
|
|||||||
return Array.from(this.#resources).find((r) => r.kind === kind);
|
return Array.from(this.#resources).find((r) => r.kind === kind);
|
||||||
};
|
};
|
||||||
|
|
||||||
public register = (resource: CustomResource<ExpectedAny>) => {
|
public register = (resource: CustomResource<any>) => {
|
||||||
this.#resources.add(resource);
|
this.#resources.add(resource);
|
||||||
};
|
};
|
||||||
|
|
||||||
public unregister = (resource: CustomResource<ExpectedAny>) => {
|
public unregister = (resource: CustomResource<any>) => {
|
||||||
this.#resources.delete(resource);
|
this.#resources.delete(resource);
|
||||||
this.#watchers.forEach((controller, kind) => {
|
this.#watchers.forEach((controller, kind) => {
|
||||||
if (kind === resource.kind) {
|
if (kind === resource.kind) {
|
||||||
@@ -65,186 +50,46 @@ class CustomResourceRegistry {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
#ensureSecret =
|
#onResourceEvent = async (type: string, obj: any) => {
|
||||||
(request: CustomResourceRequest<ExpectedAny>) =>
|
const { kind } = obj;
|
||||||
async <T extends ZodObject>(options: EnsureSecretOptions<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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} 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 {
|
|
||||||
const response = await k8sService.api.createNamespacedSecret({
|
|
||||||
namespace,
|
|
||||||
body,
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
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,
|
|
||||||
});
|
|
||||||
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);
|
const crd = this.getByKind(kind);
|
||||||
if (!crd) {
|
if (!crd) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const input = { cacheKey, manifest, crd };
|
let handler = type === 'DELETED' ? crd.delete : crd.update;
|
||||||
|
const request = new CustomResourceRequest({
|
||||||
|
type: type as 'ADDED' | 'DELETED' | 'MODIFIED',
|
||||||
|
manifest: obj,
|
||||||
|
services: this.#services,
|
||||||
|
});
|
||||||
|
|
||||||
if (type === 'DELETE') {
|
const status = await request.getStatus();
|
||||||
await this.#onDelete(input);
|
if (status.observedGeneration === obj.metadata.generation) {
|
||||||
} else {
|
this.#services.log.debug('Skipping resource update', {
|
||||||
await this.#onResourceUpdated(type, input);
|
observedGeneration: status.observedGeneration,
|
||||||
|
generation: obj.metadata.generation,
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (type === 'ADDED' && crd.create) {
|
||||||
|
handler = crd.create;
|
||||||
|
}
|
||||||
|
|
||||||
|
await handler?.({
|
||||||
|
request,
|
||||||
|
services: this.#services,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
#onError = (error: ExpectedAny) => {
|
#onError = (error: any) => {
|
||||||
this.#services.log.error('Error watching resource', { error });
|
console.error(error);
|
||||||
};
|
};
|
||||||
|
|
||||||
public install = async (replace = false) => {
|
public install = async (replace = false) => {
|
||||||
const k8sService = this.#services.get(K8sService);
|
const k8sService = this.#services.get(K8sService);
|
||||||
for (const crd of this.#resources) {
|
for (const crd of this.#resources) {
|
||||||
this.#services.log.info('Installing CRD', { kind: crd.kind });
|
|
||||||
try {
|
|
||||||
const manifest = crd.toManifest();
|
const manifest = crd.toManifest();
|
||||||
try {
|
try {
|
||||||
await k8sService.extensionsApi.createCustomResourceDefinition({
|
await k8sService.extensionsApi.createCustomResourceDefinition({
|
||||||
@@ -262,12 +107,6 @@ class CustomResourceRegistry {
|
|||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof ApiException) {
|
|
||||||
throw new Error(`Failed to install ${crd.kind}: ${error.body}`);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,86 +1,85 @@
|
|||||||
import { z, type ZodObject } from 'zod';
|
import type { Static, TSchema } from '@sinclair/typebox';
|
||||||
import { setHeaderOptions } from '@kubernetes/client-node';
|
import { ApiException, PatchStrategy, setHeaderOptions } from '@kubernetes/client-node';
|
||||||
|
|
||||||
import type { Services } from '../utils/service.ts';
|
import type { Services } from '../utils/service.ts';
|
||||||
import { Manifest } from '../services/k8s/k8s.manifest.ts';
|
|
||||||
import { K8sService } from '../services/k8s.ts';
|
import { K8sService } from '../services/k8s.ts';
|
||||||
|
|
||||||
import { CustomResourceRegistry } from './custom-resource.registry.ts';
|
import { CustomResourceRegistry } from './custom-resource.registry.ts';
|
||||||
|
import { CustomResourceStatus, type CustomResourceStatusType } from './custom-resource.status.ts';
|
||||||
|
|
||||||
type CustomResourceRequestOptions = {
|
type CustomResourceRequestOptions = {
|
||||||
type: 'ADDED' | 'DELETED' | 'MODIFIED';
|
type: 'ADDED' | 'DELETED' | 'MODIFIED';
|
||||||
manifest: ExpectedAny;
|
manifest: any;
|
||||||
services: Services;
|
services: Services;
|
||||||
};
|
};
|
||||||
|
|
||||||
const customResourceStatusSchema = z.object({
|
type CustomResourceRequestMetadata = Record<string, string> & {
|
||||||
observedGeneration: z.number(),
|
name: string;
|
||||||
conditions: z.array(
|
namespace?: string;
|
||||||
z.object({
|
labels?: Record<string, string>;
|
||||||
type: z.string(),
|
annotations?: Record<string, string>;
|
||||||
status: z.enum(['True', 'False', 'Unknown']),
|
uid: string;
|
||||||
lastTransitionTime: z.string().datetime(),
|
resourceVersion: string;
|
||||||
reason: z.string().optional(),
|
creationTimestamp: string;
|
||||||
message: z.string().optional(),
|
generation: number;
|
||||||
}),
|
};
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
type CustomResourceStatus = z.infer<typeof customResourceStatusSchema>;
|
class CustomResourceRequest<TSpec extends TSchema> {
|
||||||
|
#options: CustomResourceRequestOptions;
|
||||||
|
|
||||||
class CustomResourceRequest<TSpec extends ZodObject> extends Manifest<z.infer<TSpec>> {
|
constructor(options: CustomResourceRequestOptions) {
|
||||||
#type: 'ADDED' | 'DELETED' | 'MODIFIED';
|
this.#options = options;
|
||||||
|
|
||||||
constructor({ type, ...options }: CustomResourceRequestOptions) {
|
|
||||||
super(options);
|
|
||||||
this.#type = type;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get schema() {
|
public get services(): Services {
|
||||||
return undefined as unknown as z.infer<TSpec>;
|
return this.#options.services;
|
||||||
}
|
}
|
||||||
|
|
||||||
public get type(): 'ADDED' | 'DELETED' | 'MODIFIED' {
|
public get type(): 'ADDED' | 'DELETED' | 'MODIFIED' {
|
||||||
return this.#type;
|
return this.#options.type;
|
||||||
}
|
}
|
||||||
|
|
||||||
public markSeen = async () => {
|
public get manifest() {
|
||||||
await this.setStatus({
|
return this.#options.manifest;
|
||||||
observedGeneration: this.manifest.metadata.generation,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
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 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 getStatus = async () => {
|
public setStatus = async (status: CustomResourceStatusType) => {
|
||||||
return this.manifest?.status as CustomResourceStatus | undefined;
|
const { manifest, services } = this.#options;
|
||||||
};
|
const { kind, metadata } = manifest;
|
||||||
|
const registry = services.get(CustomResourceRegistry);
|
||||||
public setStatus = async (status: Partial<CustomResourceStatus>) => {
|
|
||||||
const { kind, metadata } = this.manifest;
|
|
||||||
const registry = this.services.get(CustomResourceRegistry);
|
|
||||||
const crd = registry.getByKind(kind);
|
const crd = registry.getByKind(kind);
|
||||||
if (!crd) {
|
if (!crd) {
|
||||||
throw new Error(`Custom resource ${kind} not found`);
|
throw new Error(`Custom resource ${kind} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const current = await this.manifest;
|
const k8sService = services.get(K8sService);
|
||||||
const k8sService = this.services.get(K8sService);
|
|
||||||
|
|
||||||
const { namespace = 'default', name } = metadata;
|
const { namespace = 'default', name } = metadata;
|
||||||
|
|
||||||
@@ -91,23 +90,63 @@ class CustomResourceRequest<TSpec extends ZodObject> extends Manifest<z.infer<TS
|
|||||||
namespace,
|
namespace,
|
||||||
plural: crd.names.plural,
|
plural: crd.names.plural,
|
||||||
name,
|
name,
|
||||||
body: {
|
body: { status },
|
||||||
status: {
|
|
||||||
observedGeneration: this.manifest.metadata.generation,
|
|
||||||
conditions: current?.status?.conditions || [],
|
|
||||||
...current?.status,
|
|
||||||
...status,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
fieldValidation: 'Strict',
|
fieldValidation: 'Strict',
|
||||||
},
|
},
|
||||||
{
|
setHeaderOptions('Content-Type', PatchStrategy.MergePatch),
|
||||||
...setHeaderOptions('Content-Type', 'application/merge-patch+json'),
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
this.manifest = response;
|
|
||||||
return response;
|
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: [],
|
||||||
|
},
|
||||||
|
generation: 0,
|
||||||
|
save: this.setStatus,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new CustomResourceStatus({
|
||||||
|
status: { ...resource.status, observedGeneration: resource.status.observedGeneration },
|
||||||
|
generation: resource.metadata.generation,
|
||||||
|
save: this.setStatus,
|
||||||
|
});
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export { CustomResourceRequest, customResourceStatusSchema };
|
export { CustomResourceRequest };
|
||||||
|
|||||||
85
src/custom-resource/custom-resource.status.ts
Normal file
85
src/custom-resource/custom-resource.status.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
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 };
|
||||||
36
src/index.ts
36
src/index.ts
@@ -1,47 +1,11 @@
|
|||||||
import 'dotenv/config';
|
|
||||||
import { ApiException } from '@kubernetes/client-node';
|
|
||||||
|
|
||||||
import { CustomResourceRegistry } from './custom-resource/custom-resource.registry.ts';
|
import { CustomResourceRegistry } from './custom-resource/custom-resource.registry.ts';
|
||||||
import { Services } from './utils/service.ts';
|
import { Services } from './utils/service.ts';
|
||||||
import { SecretRequest } from './crds/secrets/secrets.request.ts';
|
import { SecretRequest } from './crds/secrets/secrets.request.ts';
|
||||||
import { PostgresDatabase } from './crds/postgres/postgres.database.ts';
|
import { PostgresDatabase } from './crds/postgres/postgres.database.ts';
|
||||||
import { AuthentikService } from './services/authentik/authentik.service.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';
|
|
||||||
|
|
||||||
const services = new Services();
|
const services = new Services();
|
||||||
|
|
||||||
//const authentikService = services.get(AuthentikService);
|
|
||||||
//await authentikService.ready();
|
|
||||||
|
|
||||||
const registry = services.get(CustomResourceRegistry);
|
const registry = services.get(CustomResourceRegistry);
|
||||||
registry.register(new SecretRequest());
|
registry.register(new SecretRequest());
|
||||||
registry.register(new PostgresDatabase());
|
registry.register(new PostgresDatabase());
|
||||||
registry.register(new AuthentikClient());
|
|
||||||
registry.register(new Domain());
|
|
||||||
registry.register(new DomainEndpoint());
|
|
||||||
await registry.install(true);
|
await registry.install(true);
|
||||||
await registry.watch();
|
await registry.watch();
|
||||||
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,237 +0,0 @@
|
|||||||
import type { Services } from '../../utils/service.ts';
|
|
||||||
import { createAuthentikClient, type AuthentikClient } from '../../clients/authentik/authentik.ts';
|
|
||||||
|
|
||||||
import type { UpsertClientRequest, UpsertGroupRequest } from './authentik.types.ts';
|
|
||||||
import { setupAuthentik } from './authentik.setup.ts';
|
|
||||||
|
|
||||||
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 AuthentikService {
|
|
||||||
#services: Services;
|
|
||||||
#init?: Promise<AuthentikClient>;
|
|
||||||
|
|
||||||
constructor(services: Services) {
|
|
||||||
this.#services = services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public getPublicUrl = async () => {
|
|
||||||
return '';
|
|
||||||
};
|
|
||||||
|
|
||||||
#getClient = () => {
|
|
||||||
if (!this.#init) {
|
|
||||||
this.#init = this.#create();
|
|
||||||
}
|
|
||||||
return this.#init;
|
|
||||||
};
|
|
||||||
|
|
||||||
#upsertApplication = async (request: UpsertClientRequest, provider: number, pk?: string) => {
|
|
||||||
const client = await this.#getClient();
|
|
||||||
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 = await this.#getClient();
|
|
||||||
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
#create = async () => {
|
|
||||||
const { url, token } = await setupAuthentik(this.#services);
|
|
||||||
return createAuthentikClient({
|
|
||||||
baseUrl: new URL('api/v3', url).toString(),
|
|
||||||
token: token,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
public getGroupFromName = async (name: string) => {
|
|
||||||
const client = await this.#getClient();
|
|
||||||
const groups = await client.core.coreGroupsList({
|
|
||||||
search: name,
|
|
||||||
});
|
|
||||||
return groups.results.find((group) => group.name === name);
|
|
||||||
};
|
|
||||||
|
|
||||||
public getScopePropertyMappings = async () => {
|
|
||||||
const client = await this.#getClient();
|
|
||||||
const mappings = await client.propertymappings.propertymappingsProviderScopeList({});
|
|
||||||
return mappings;
|
|
||||||
};
|
|
||||||
|
|
||||||
public getApplicationFromSlug = async (slug: string) => {
|
|
||||||
const client = await this.#getClient();
|
|
||||||
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 = await this.#getClient();
|
|
||||||
const providers = await client.providers.providersOauth2List({
|
|
||||||
clientId,
|
|
||||||
});
|
|
||||||
return providers.results.find((provider) => provider.clientId === clientId);
|
|
||||||
};
|
|
||||||
|
|
||||||
public getFlows = async () => {
|
|
||||||
const client = await this.#getClient();
|
|
||||||
const flows = await client.flows.flowsInstancesList();
|
|
||||||
return flows;
|
|
||||||
};
|
|
||||||
|
|
||||||
public upsertClient = async (request: UpsertClientRequest) => {
|
|
||||||
const url = await this.getPublicUrl();
|
|
||||||
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 = await this.#getClient();
|
|
||||||
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 = await this.#getClient();
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
public ready = async () => {
|
|
||||||
await this.#getClient();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export { AuthentikService };
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
import { NAMESPACE } from '../../utils/consts.ts';
|
|
||||||
import type { Services } from '../../utils/service.ts';
|
|
||||||
import { K8sService } from '../k8s.ts';
|
|
||||||
import { PostgresService } from '../postgres/postgres.service.ts';
|
|
||||||
|
|
||||||
const SECRET = 'WkE/MDsSCe7TyIPtx/16/rwQ3XyyY9QsM450mXZklhR545PZPFoXcfrBhnxYB5jzlIwTmkg7Opgm0FDl'; // TODO: Generate and store
|
|
||||||
const setupAuthentik = async (services: Services) => {
|
|
||||||
const namespace = NAMESPACE;
|
|
||||||
const db = {
|
|
||||||
name: 'homelab_authentik',
|
|
||||||
user: 'homelab_authentik',
|
|
||||||
password: 'sdf908sad0sdf7g98',
|
|
||||||
};
|
|
||||||
|
|
||||||
const k8sService = services.get(K8sService);
|
|
||||||
const postgresService = services.get(PostgresService);
|
|
||||||
|
|
||||||
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: `authentik-${command}`,
|
|
||||||
namespace: namespace,
|
|
||||||
labels: {
|
|
||||||
'app.kubernetes.io/name': `authentik-${command}`,
|
|
||||||
'argocd.argoproj.io/instance': 'homelab',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
spec: {
|
|
||||||
replicas: 1,
|
|
||||||
selector: {
|
|
||||||
matchLabels: {
|
|
||||||
'app.kubernetes.io/name': `authentik-${command}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
template: {
|
|
||||||
metadata: {
|
|
||||||
labels: {
|
|
||||||
'app.kubernetes.io/name': `authentik-${command}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
spec: {
|
|
||||||
containers: [
|
|
||||||
{
|
|
||||||
name: `authentik-${command}`,
|
|
||||||
image: 'ghcr.io/goauthentik/server:2025.6.4',
|
|
||||||
// imagePullPolicy: 'ifNot'
|
|
||||||
args: [command],
|
|
||||||
env: [
|
|
||||||
{ name: 'AUTHENTIK_SECRET_KEY', value: 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_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: 'authentik',
|
|
||||||
namespace,
|
|
||||||
labels: {
|
|
||||||
'app.kubernetes.io/name': 'authentik-server',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
spec: {
|
|
||||||
type: 'ClusterIP',
|
|
||||||
ports: [
|
|
||||||
{
|
|
||||||
port: 9000,
|
|
||||||
targetPort: 9000,
|
|
||||||
protocol: 'TCP',
|
|
||||||
name: 'http',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
selector: {
|
|
||||||
'app.kubernetes.io/name': 'authentik-server',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
url: '',
|
|
||||||
token: '',
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export { setupAuthentik };
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import type { ClientTypeEnum, SubModeEnum } from '@goauthentik/api';
|
|
||||||
|
|
||||||
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 { UpsertClientRequest, UpsertGroupRequest };
|
|
||||||
@@ -1,22 +1,4 @@
|
|||||||
class ConfigService {
|
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() {
|
public get postgres() {
|
||||||
const host = process.env.POSTGRES_HOST;
|
const host = process.env.POSTGRES_HOST;
|
||||||
const user = process.env.POSTGRES_USER;
|
const user = process.env.POSTGRES_USER;
|
||||||
|
|||||||
@@ -1,36 +1,17 @@
|
|||||||
import {
|
import { KubeConfig, CoreV1Api, ApiextensionsV1Api, CustomObjectsApi } from '@kubernetes/client-node';
|
||||||
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 {
|
class K8sService {
|
||||||
#services: Services;
|
|
||||||
#kc: KubeConfig;
|
#kc: KubeConfig;
|
||||||
#k8sApi: CoreV1Api;
|
#k8sApi: CoreV1Api;
|
||||||
#k8sExtensionsApi: ApiextensionsV1Api;
|
#k8sExtensionsApi: ApiextensionsV1Api;
|
||||||
#k8sCustomObjectsApi: CustomObjectsApi;
|
#k8sCustomObjectsApi: CustomObjectsApi;
|
||||||
#k8sEventsApi: EventsV1Api;
|
|
||||||
#k8sObjectsApi: KubernetesObjectApi;
|
|
||||||
|
|
||||||
constructor(services: Services) {
|
constructor() {
|
||||||
this.#services = services;
|
|
||||||
this.#kc = new KubeConfig();
|
this.#kc = new KubeConfig();
|
||||||
this.#kc.loadFromDefault();
|
this.#kc.loadFromDefault();
|
||||||
this.#k8sApi = this.#kc.makeApiClient(CoreV1Api);
|
this.#k8sApi = this.#kc.makeApiClient(CoreV1Api);
|
||||||
this.#k8sExtensionsApi = this.#kc.makeApiClient(ApiextensionsV1Api);
|
this.#k8sExtensionsApi = this.#kc.makeApiClient(ApiextensionsV1Api);
|
||||||
this.#k8sCustomObjectsApi = this.#kc.makeApiClient(CustomObjectsApi);
|
this.#k8sCustomObjectsApi = this.#kc.makeApiClient(CustomObjectsApi);
|
||||||
this.#k8sEventsApi = this.#kc.makeApiClient(EventsV1Api);
|
|
||||||
this.#k8sObjectsApi = this.#kc.makeApiClient(KubernetesObjectApi);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get config() {
|
public get config() {
|
||||||
@@ -48,92 +29,6 @@ class K8sService {
|
|||||||
public get customObjectsApi() {
|
public get customObjectsApi() {
|
||||||
return this.#k8sCustomObjectsApi;
|
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { K8sService };
|
export { K8sService };
|
||||||
|
|||||||
@@ -1,179 +0,0 @@
|
|||||||
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 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,10 +11,7 @@ class LogService {
|
|||||||
console.warn(message, data);
|
console.warn(message, data);
|
||||||
};
|
};
|
||||||
|
|
||||||
public error = (message: string, data?: Record<string, unknown>, root?: unknown) => {
|
public error = (message: string, data?: Record<string, unknown>) => {
|
||||||
if (root instanceof Error) {
|
|
||||||
console.log(root.stack);
|
|
||||||
}
|
|
||||||
console.error(message, data);
|
console.error(message, data);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,8 @@ import type { PostgresDatabase, PostgresRole } from './postgres.types.ts';
|
|||||||
|
|
||||||
class PostgresService {
|
class PostgresService {
|
||||||
#db: Knex;
|
#db: Knex;
|
||||||
#services: Services;
|
|
||||||
|
|
||||||
constructor(services: Services) {
|
constructor(services: Services) {
|
||||||
this.#services = services;
|
|
||||||
const configService = services.get(ConfigService);
|
const configService = services.get(ConfigService);
|
||||||
const config = configService.postgres;
|
const config = configService.postgres;
|
||||||
this.#db = knex({
|
this.#db = knex({
|
||||||
@@ -24,11 +22,6 @@ class PostgresService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public get config() {
|
|
||||||
const configService = this.#services.get(ConfigService);
|
|
||||||
return configService.postgres;
|
|
||||||
}
|
|
||||||
|
|
||||||
public upsertRole = async (role: PostgresRole) => {
|
public upsertRole = async (role: PostgresRole) => {
|
||||||
const existingRole = await this.#db.raw('SELECT 1 FROM pg_roles WHERE rolname = ?', [role.name]);
|
const existingRole = await this.#db.raw('SELECT 1 FROM pg_roles WHERE rolname = ?', [role.name]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
type ResourceRef = {
|
|
||||||
apiVersion: string;
|
|
||||||
kind: string;
|
|
||||||
name: string;
|
|
||||||
uid: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type { ResourceRef };
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
const GROUP = 'homelab.mortenolsen.pro';
|
const GROUP = 'homelab.mortenolsen.pro';
|
||||||
const NAMESPACE = 'homelab';
|
|
||||||
|
|
||||||
export { GROUP, NAMESPACE };
|
export { GROUP };
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
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 };
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
apiVersion: homelab.mortenolsen.pro/v1
|
|
||||||
kind: AuthentikClient
|
|
||||||
metadata:
|
|
||||||
name: foobas
|
|
||||||
spec:
|
|
||||||
redirectUris:
|
|
||||||
- url: http://localhost:3000/api/auth/callback
|
|
||||||
matchingMode: strict
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
apiVersion: 'homelab.mortenolsen.pro/v1'
|
|
||||||
kind: 'PostgresDatabase'
|
|
||||||
metadata:
|
|
||||||
name: 'test2'
|
|
||||||
namespace: 'playground'
|
|
||||||
@@ -16,8 +16,9 @@
|
|||||||
// Best practices
|
// Best practices
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
// "noUncheckedIndexedAccess": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
// "noImplicitOverride": true,
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
|
||||||
// Some stricter flags (disabled by default)
|
// Some stricter flags (disabled by default)
|
||||||
"noUnusedLocals": false,
|
"noUnusedLocals": false,
|
||||||
|
|||||||
Reference in New Issue
Block a user