29 Commits

Author SHA1 Message Date
4ab136be68 cleanup 2026-01-26 12:08:54 +01:00
0dbab431a0 support for file's content64 2026-01-25 21:42:22 +01:00
183099f7da boot: modules should always default to kernel version 2026-01-25 17:44:33 +01:00
47f695a8cd add functions to support new deployments 2026-01-25 11:23:47 +01:00
f57aa581f3 ui: don't inline style
It's used in other custom pages too
2026-01-25 11:22:11 +01:00
63a206f1ac ui fixes for config in json format 2026-01-25 10:28:23 +01:00
f2b23df97b add trunk dist under git 2026-01-22 17:55:23 +01:00
3085dac359 move ui to using trunk
cargo install trunk
2026-01-22 17:54:31 +01:00
2af7ff85c1 improve cert-signing ux 2026-01-19 17:57:15 +01:00
512177cab0 more semantic config upload 2025-12-16 14:43:59 +01:00
26d3d0faeb dir2config: support json output 2025-12-03 09:45:12 +01:00
834510760f add ${host_name} to CSRs 2025-10-11 09:21:33 +02:00
a2a970f93b cleanup install-on-metal.sh, assuming it's used from initrd v2 2025-10-01 18:02:45 +02:00
350e753ae0 dsa has been removed 2025-10-01 16:56:30 +02:00
436be67bfd move tls_dir to render context funcs because it needs template host IPs 2025-09-25 23:19:35 +02:00
8ae52501c9 add simple wireguard support 2025-09-03 16:04:43 +02:00
98eb601fd3 hack/docker-build: add GIT_TAG 2025-08-08 10:46:34 +02:00
8e87d406e4 log oops 2025-07-28 08:48:10 +02:00
f83b1eab23 render context: add asset_download_token 2025-07-27 13:08:59 +02:00
d03a7ab4ec dlset: allow globs in name, short kind 2025-07-27 12:49:28 +02:00
cd69d9234e cosmetic changes 2025-07-23 10:45:31 +02:00
5fa367949b feature: download set 2025-07-22 18:54:48 +02:00
cef4441208 download token: also render JSON 2025-07-22 11:58:18 +02:00
d4087d3534 download token: make a token page
- token page helps communicating a single link to multiple assets
- provide an extra layer in case of "miss click"
- ui: just link the page, not every asset of each download token.
2025-07-22 11:47:41 +02:00
ab6f0b6358 remove dep on udev
- remove the need to map host's /dev
- remove race issues or need to have a working `udevadm settle`
2025-07-22 11:00:33 +02:00
af2758dead compress initrds with zstd 2025-07-21 17:37:29 +02:00
899a0a9dab pull-through dist server 2025-07-08 22:20:26 +02:00
08cbccc756 allow download of .../dist assets 2025-07-08 21:45:33 +02:00
62882e78d8 darken inputs in dark mode 2025-07-08 14:50:14 +02:00
54 changed files with 18143 additions and 316 deletions

View File

@ -1,5 +1,6 @@
from novit.tech/direktil/dkl:bbea9b9 as dkl
# ------------------------------------------------------------------------
from golang:1.24.4-bookworm as build
from golang:1.25.5-trixie as build
run apt-get update && apt-get install -y git
@ -21,13 +22,14 @@ run \
hack/build ./...
# ------------------------------------------------------------------------
from debian:bookworm
from debian:trixie
entrypoint ["/bin/dkl-local-server"]
env _uncache=1
run apt-get update \
&& yes |apt-get install -y genisoimage gdisk dosfstools util-linux udev binutils systemd \
grub2 grub-pc-bin grub-efi-amd64-bin ca-certificates curl openssh-client qemu-utils \
grub2 grub-pc-bin grub-efi-amd64-bin ca-certificates curl openssh-client qemu-utils wireguard-tools \
&& apt-get clean
copy --from=dkl /bin/dkl /bin/dls /bin/
copy --from=build /src/dist/ /bin/

View File

@ -1,10 +1,12 @@
package main
import (
"encoding/json"
"flag"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"github.com/go-git/go-git/v5"
@ -127,12 +129,22 @@ func main() {
defer out.Close()
out.Write([]byte("# dkl-dir2config " + Version + "\n"))
switch ext := path.Ext(*outPath); ext {
case ".yaml":
out.Write([]byte("# dkl-dir2config " + Version + "\n"))
if err = yaml.NewEncoder(out).Encode(dst); err != nil {
log.Fatal("failed to render output: ", err)
if err = yaml.NewEncoder(out).Encode(dst); err != nil {
log.Fatal("failed to render output: ", err)
}
case ".json":
if err = json.NewEncoder(out).Encode(dst); err != nil {
log.Fatal("failed to render output: ", err)
}
default:
log.Fatal("unknown output file extension: ", ext)
}
}
func cfgPath(subPath string) string { return filepath.Join(*dir, subPath) }

View File

@ -8,6 +8,7 @@ import (
"math/rand"
"path"
"reflect"
"strconv"
"strings"
"github.com/cespare/xxhash"
@ -223,6 +224,7 @@ func (ctx *renderContext) templateFuncs(ctxMap map[string]any) map[string]any {
if err != nil {
return
}
reqJson := cleanJsonObject(buf.String())
key := name
if req.PerHost {
@ -235,11 +237,11 @@ func (ctx *renderContext) templateFuncs(ctxMap map[string]any) map[string]any {
dir := "/etc/tls/" + name
s = fmt.Sprintf("{{ %s %q %q %q %q %q %q %q }}", funcName,
dir, cluster, req.CA, key, req.Profile, req.Label, buf.String())
dir, cluster, req.CA, key, req.Profile, req.Label, reqJson)
default:
s = fmt.Sprintf("{{ %s %q %q %q %q %q %q }}", funcName,
cluster, req.CA, key, req.Profile, req.Label, buf.String())
cluster, req.CA, key, req.Profile, req.Label, reqJson)
}
return
}
@ -280,16 +282,24 @@ func (ctx *renderContext) templateFuncs(ctxMap map[string]any) map[string]any {
},
"ssh_user_ca": func(path string) (s string) {
return fmt.Sprintf("{{ ssh_user_ca %q %q}}",
return fmt.Sprintf("{{ ssh_user_ca %q %q }}",
path, cluster)
},
"ssh_host_keys": func(dir string) (s string) {
return fmt.Sprintf("{{ ssh_host_keys %q %q \"\"}}",
return fmt.Sprintf("{{ ssh_host_keys %q %q \"\" }}",
dir, cluster)
},
"host_download_token": func() (s string) {
return "{{ host_download_token }}"
},
"asset_download_token": func(args ...string) (s string) {
argsStr := new(strings.Builder)
for _, arg := range args {
argsStr.WriteByte(' ')
argsStr.WriteString(strconv.Quote(arg))
}
return "{{ asset_download_token" + argsStr.String() + " }}"
},
"hosts_of_group": func() (hosts []any) {
hosts = make([]any, 0)

View File

@ -29,7 +29,7 @@ func (ctx *renderContext) renderStaticPods() (pods []namePod) {
for n := 0; ; n++ {
str := buf.String()
podMap := map[string]interface{}{}
podMap := map[string]any{}
err := dec.Decode(podMap)
if err == io.EOF {
@ -46,7 +46,7 @@ func (ctx *renderContext) renderStaticPods() (pods []namePod) {
log.Fatalf("static pod %d: no metadata\n%s", n, buf.String())
}
md := podMap["metadata"].(map[interface{}]interface{})
md := podMap["metadata"].(map[any]any)
namespace := md["namespace"].(string)
name := md["name"].(string)

View File

@ -0,0 +1,15 @@
package main
import (
"encoding/json"
"fmt"
)
func cleanJsonObject(raw string) string {
v := map[string]any{}
if err := json.Unmarshal([]byte(raw), &v); err != nil {
panic(fmt.Errorf("invalid json: %w\n%s", err, raw))
}
clean, _ := json.Marshal(v)
return string(clean)
}

View File

@ -109,7 +109,7 @@ func qemuImgBootImg(format string) func(out io.Writer, ctx *renderContext) (err
var grubSupportVersion = flag.String("grub-support", "1.1.0", "GRUB support version")
func setupBootImage(bootImg *os.File, ctx *renderContext) (err error) {
path, err := ctx.distFetch("grub-support", *grubSupportVersion)
path, err := distFetch("grub-support", *grubSupportVersion)
if err != nil {
return
}
@ -148,6 +148,7 @@ func setupBootImage(bootImg *os.File, ctx *renderContext) (err error) {
}()
log.Print("device: ", dev)
syncSysToDev()
tempDir := bootImg.Name() + ".p1.mount"
@ -161,9 +162,10 @@ func setupBootImage(bootImg *os.File, ctx *renderContext) (err error) {
os.RemoveAll(tempDir)
}()
err = syscall.Mount(dev+"p1", tempDir, "vfat", 0, "")
devp1 := dev + "p1"
err = syscall.Mount(devp1, tempDir, "vfat", 0, "")
if err != nil {
return fmt.Errorf("failed to mount %s to %s: %v", dev+"p1", tempDir, err)
return fmt.Errorf("failed to mount %s to %s: %v", devp1, tempDir, err)
}
defer func() {

View File

@ -31,7 +31,7 @@ func buildBootTar(out io.Writer, ctx *renderContext) (err error) {
}
// kernel
kernelPath, err := ctx.distFetch("kernels", ctx.Host.Kernel)
kernelPath, err := distFetch("kernels", ctx.Host.Kernel)
if err != nil {
return
}
@ -92,7 +92,7 @@ func buildBootEFITar(out io.Writer, ctx *renderContext) (err error) {
}
// kernel
kernelPath, err := ctx.distFetch("kernels", ctx.Host.Kernel)
kernelPath, err := distFetch("kernels", ctx.Host.Kernel)
if err != nil {
return
}

View File

@ -11,6 +11,7 @@ import (
"net/http"
"os"
"github.com/klauspost/compress/zstd"
yaml "gopkg.in/yaml.v2"
"novit.tech/direktil/pkg/cpiocat"
@ -39,10 +40,15 @@ func buildInitrd(out io.Writer, ctx *renderContext) (err error) {
return
}
cat := cpiocat.New(out)
zout, err := zstd.NewWriter(out, zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(12)))
if err != nil {
return fmt.Errorf("zstd writer setup failed: %w", err)
}
cat := cpiocat.New(zout)
// initrd
initrdPath, err := ctx.distFetch("initrd", ctx.Host.Initrd)
initrdPath, err := distFetch("initrd", ctx.Host.Initrd)
if err != nil {
return
}
@ -52,9 +58,11 @@ func buildInitrd(out io.Writer, ctx *renderContext) (err error) {
for _, layer := range cfg.Layers {
switch layer {
case "modules":
layerVersion := ctx.Host.Versions[layer]
modulesPath, err := ctx.distFetch("layers", layer, layerVersion)
if layerVersion == "" {
layerVersion = ctx.Host.Kernel
}
modulesPath, err := distFetch("layers", layer, layerVersion)
if err != nil {
return err
}
@ -75,7 +83,7 @@ func buildInitrd(out io.Writer, ctx *renderContext) (err error) {
cat.AppendDir("/etc/ssh", 0o700)
// XXX do we want bootstrap-stage keys instead of the real host key?
for _, format := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
for _, format := range []string{"rsa", "ecdsa", "ed25519"} {
keyPath := "/etc/ssh/ssh_host_" + format + "_key"
cat.AppendBytes(cfg.FileContent(keyPath), keyPath, 0o600)
}
@ -88,7 +96,15 @@ func buildInitrd(out io.Writer, ctx *renderContext) (err error) {
cat.AppendBytes(userCA, "user_ca.pub", 0600)
return cat.Close()
if err = cat.Close(); err != nil {
return fmt.Errorf("cpio close failed: %w", err)
}
if err = zout.Close(); err != nil {
return fmt.Errorf("zstd close failed: %w", err)
}
return
}
func buildBootstrap(out io.Writer, ctx *renderContext) (err error) {
@ -165,7 +181,7 @@ func buildBootstrap(out io.Writer, ctx *renderContext) (err error) {
return fmt.Errorf("layer %q not mapped to a version", layer)
}
outPath, err := ctx.distFetch("layers", layer, layerVersion)
outPath, err := distFetch("layers", layer, layerVersion)
if err != nil {
return err
}

View File

@ -60,6 +60,14 @@ func templateFuncs(sslCfg *cfsslconfig.Config) map[string]any {
return map[string]any{
"quote": strconv.Quote,
"yaml": asYaml,
"indent": func(s, indent string) string {
buf := new(strings.Builder)
for _, line := range strings.Split(s, "\n") {
buf.WriteString(indent + line + "\n")
}
return buf.String()
},
"password": func(cluster, name, hashAlg string) (password string, err error) {
key := cluster + "/" + name
@ -170,40 +178,10 @@ func templateFuncs(sslCfg *cfsslconfig.Config) map[string]any {
s = string(kc.Cert)
return
},
"tls_dir": func(dir, cluster, caName, name, profile, label, reqJson string) (s string, err error) {
ca, err := getUsableClusterCA(cluster, caName)
if err != nil {
return
}
kc, err := getKeyCert(cluster, caName, name, profile, label, reqJson)
if err != nil {
return
}
return asYaml([]config.FileDef{
{
Path: path.Join(dir, "ca.crt"),
Mode: 0644,
Content: string(ca.Cert),
},
{
Path: path.Join(dir, "tls.crt"),
Mode: 0644,
Content: string(kc.Cert),
},
{
Path: path.Join(dir, "tls.key"),
Mode: 0600,
Content: string(kc.Key),
},
})
},
}
}
func asYaml(v interface{}) (string, error) {
func asYaml(v any) (string, error) {
ba, err := yaml.Marshal(v)
if err != nil {
return "", err

View File

@ -0,0 +1,15 @@
package main
func htmlHeader(title string) string {
return `<!doctype html>
<html>
<head>
<title>` + title + `</title>
<style>@import url('/ui/style.css');@import url('/ui/app.css');</style>
</head>
<body><h1>` + title + `</h1>
`
}
var htmlFooter = `</body>
</html>`

View File

@ -8,7 +8,7 @@ import (
)
func renderKernel(w http.ResponseWriter, r *http.Request, ctx *renderContext) error {
path, err := ctx.distFetch("kernels", ctx.Host.Kernel)
path, err := distFetch("kernels", ctx.Host.Kernel)
if err != nil {
return err
}
@ -19,7 +19,7 @@ func renderKernel(w http.ResponseWriter, r *http.Request, ctx *renderContext) er
}
func fetchKernel(out io.Writer, ctx *renderContext) (err error) {
path, err := ctx.distFetch("kernels", ctx.Host.Kernel)
path, err := distFetch("kernels", ctx.Host.Kernel)
if err != nil {
return err
}

View File

@ -72,6 +72,7 @@ func main() {
staticHandler := http.FileServer(http.FS(dlshtml.FS))
http.Handle("/favicon.ico", staticHandler)
http.Handle("/ui/", staticHandler)
http.Handle("/dist/", http.StripPrefix("/dist/", upstreamServer{}))
http.Handle("/public-state", streamsse.StreamHandler(wPublicState))
http.Handle("/state", requireAdmin(streamsse.StreamHandler(wState)))

View File

@ -4,7 +4,9 @@ import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
@ -13,9 +15,12 @@ import (
"os"
"path"
"path/filepath"
"strings"
"text/template"
"time"
cfsslconfig "github.com/cloudflare/cfssl/config"
"github.com/cloudflare/cfssl/csr"
restful "github.com/emicklei/go-restful"
yaml "gopkg.in/yaml.v2"
@ -27,6 +32,8 @@ import (
var cmdlineParam = restful.QueryParameter("cmdline", "Linux kernel cmdline addition")
var b64 = base64.StdEncoding.WithPadding(base64.NoPadding)
type renderContext struct {
Host *localconfig.Host
SSLConfig *cfsslconfig.Config
@ -97,6 +104,8 @@ func (ctx *renderContext) Config() (ba []byte, cfg *config.Config, err error) {
return
}
// log.Print("rendered config:\n", string(ba))
cfg = &config.Config{}
if err = yaml.Unmarshal(ba, cfg); err != nil {
return
@ -138,7 +147,7 @@ func (ctx *renderContext) render(templateText string) (ba []byte, err error) {
return
}
func (ctx *renderContext) distFilePath(path ...string) string {
func distFilePath(path ...string) string {
return filepath.Join(append([]string{*dataDir, "dist"}, path...)...)
}
@ -164,7 +173,26 @@ func (ctx *renderContext) Tag() (string, error) {
func (ctx *renderContext) TemplateFuncs() map[string]any {
funcs := templateFuncs(ctx.SSLConfig)
// FIXME duplicate from cluster-render-context
getKeyCert := func(cluster, caName, name, profile, label, reqJson string) (kc KeyCert, err error) {
certReq := &csr.CertificateRequest{
KeyRequest: csr.NewKeyRequest(),
}
err = json.Unmarshal([]byte(reqJson), certReq)
if err != nil {
log.Print("CSR unmarshal failed on: ", reqJson)
return
}
return getUsableKeyCert(cluster, caName, name, profile, label, certReq, ctx.SSLConfig)
}
for name, method := range map[string]any{
"base64": func(input string) string {
return b64.EncodeToString([]byte(input))
},
"host_ip": func() (s string) {
return ctx.Host.IPs[0]
},
@ -176,6 +204,39 @@ func (ctx *renderContext) TemplateFuncs() map[string]any {
return hex.EncodeToString(ba[:])
},
"tls_dir": func(dir, cluster, caName, name, profile, label, reqJson string) (s string, err error) {
ca, err := getUsableClusterCA(cluster, caName)
if err != nil {
return
}
reqJson = strings.ReplaceAll(reqJson, "${host_ip}", ctx.Host.IPs[0])
reqJson = strings.ReplaceAll(reqJson, "${host_name}", ctx.Host.Name)
kc, err := getKeyCert(cluster, caName, name, profile, label, reqJson)
if err != nil {
return
}
return asYaml([]config.FileDef{
{
Path: path.Join(dir, "ca.crt"),
Mode: 0644,
Content: string(ca.Cert),
},
{
Path: path.Join(dir, "tls.crt"),
Mode: 0644,
Content: string(kc.Cert),
},
{
Path: path.Join(dir, "tls.key"),
Mode: 0600,
Content: string(kc.Key),
},
})
},
"ssh_user_ca": func(path, cluster string) (s string, err error) {
userCA, err := sshCAPubKey(cluster)
return asYaml([]config.FileDef{{
@ -184,6 +245,10 @@ func (ctx *renderContext) TemplateFuncs() map[string]any {
Content: string(userCA),
}})
},
"ssh_user_ca_pub": func(cluster string) (s string, err error) {
userCA, err := sshCAPubKey(cluster)
return string(userCA), err
},
"ssh_host_keys": func(dir, cluster, host string) (s string, err error) {
if host == "" {
host = ctx.Host.Name
@ -218,6 +283,20 @@ func (ctx *renderContext) TemplateFuncs() map[string]any {
return asYaml(files)
},
"ssh_host_key": func(type_ string) (s string, err error) {
pair, err := ctx.sshHostKeyPair(type_)
if err != nil {
return
}
return pair.Private, nil
},
"ssh_host_pubkey": func(type_ string) (s string, err error) {
pair, err := ctx.sshHostKeyPair(type_)
if err != nil {
return
}
return pair.Public, nil
},
"host_download_token": func() (token string, err error) {
key := ctx.Host.Name
token, found, err := hostDownloadTokens.Get(key)
@ -239,9 +318,65 @@ func (ctx *renderContext) TemplateFuncs() map[string]any {
return
},
"asset_download_token": func(asset string, params ...string) (token string, err error) {
now := time.Now()
exp := now.Add(24 * time.Hour) // expire in 24h by default
if len(params) != 0 {
exp, err = parseCertDuration(params[0], now)
if err != nil {
return
}
}
set := DownloadSet{
Expiry: exp,
Items: []DownloadSetItem{
{
Kind: "host",
Name: ctx.Host.Name,
Assets: []string{asset},
},
},
}
privKey, _ := dlsSigningKeys()
token = set.Signed(privKey)
return
},
"wg_key": func(name string) (key string, err error) {
return wgKey(name + "/hosts/" + ctx.Host.Name)
},
"wg_psk": func(name, peerName string) (key string, err error) {
a := ctx.Host.Name
b := peerName
if a > b {
a, b = b, a
}
return wgKey(name + "/psks/" + a + " " + b)
},
"wg_pubkey": func(name, host string) (key string, err error) {
return wgKey(name + "/hosts/" + host)
},
} {
funcs[name] = method
}
return funcs
}
func (ctx *renderContext) sshHostKeyPair(type_ string) (kp SSHKeyPair, err error) {
pairs, err := getSSHKeyPairs(ctx.Host.Name)
if err != nil {
return
}
for _, pair := range pairs {
if pair.Type == type_ {
return pair, nil
}
}
err = fmt.Errorf("no key pair with type %q", type_)
return
}

View File

@ -1,6 +1,7 @@
package main
import (
"crypto/ed25519"
"encoding/json"
"errors"
"os"
@ -9,6 +10,7 @@ import (
"github.com/cloudflare/cfssl/certinfo"
"github.com/cloudflare/cfssl/config"
"github.com/cloudflare/cfssl/helpers/derhelpers"
"github.com/cloudflare/cfssl/log"
)
@ -73,3 +75,33 @@ func checkCertUsable(certPEM []byte) error {
return nil
}
func dlsSigningKeys() (ed25519.PrivateKey, ed25519.PublicKey) {
var signerDER []byte
if err := readSecret("signer", &signerDER); os.IsNotExist(err) {
_, key, err := ed25519.GenerateKey(nil)
if err != nil {
panic(err)
}
signerDER, err = derhelpers.MarshalEd25519PrivateKey(key)
if err != nil {
panic(err)
}
writeSecret("signer", signerDER)
} else if err != nil {
panic(err)
}
pkeyGeneric, err := derhelpers.ParseEd25519PrivateKey(signerDER)
if err != nil {
panic(err)
}
pkey := pkeyGeneric.(ed25519.PrivateKey)
pubkey := pkey.Public().(ed25519.PublicKey)
return pkey, pubkey
}

View File

@ -32,7 +32,6 @@ func getSSHKeyPairs(host string) (pairs []SSHKeyPair, err error) {
genLoop:
for _, keyType := range []string{
"rsa",
"dsa",
"ecdsa",
"ed25519",
} {
@ -157,28 +156,25 @@ func sshCASign(cluster string, userPubKey []byte, principal, validity string, op
return
}
_, identity, _, _, err := ssh.ParseAuthorizedKey(userPubKey)
pubkey, identity, _, _, err := ssh.ParseAuthorizedKey(bytes.TrimSpace(userPubKey))
if err != nil {
return
}
ak := ssh.MarshalAuthorizedKey(pubkey)
userPubKeyFile, err := os.CreateTemp("/tmp", "user.pub")
if err != nil {
return
}
defer os.Remove(userPubKeyFile.Name())
_, err = io.Copy(userPubKeyFile, bytes.NewBuffer(userPubKey))
_, err = io.Copy(userPubKeyFile, bytes.NewBuffer(ak))
userPubKeyFile.Close()
if err != nil {
return
}
err = os.WriteFile(userPubKeyFile.Name(), userPubKey, 0600)
if err != nil {
return
}
serial := strconv.FormatInt(time.Now().Unix(), 10)
cmd := exec.Command("ssh-keygen", "-q", "-s", "/dev/stdin", "-I", identity, "-z", serial, "-n", principal)

View File

@ -0,0 +1,63 @@
package main
import (
"bytes"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"golang.org/x/sys/unix"
)
// Simulate a udev run for our needs
func syncSysToDev() {
// loop devices
sysPaths, _ := filepath.Glob("/sys/devices/virtual/block/loop*/**/dev")
for _, sysPath := range sysPaths {
mknodBlk(sysPath)
}
}
func mknodBlk(sysPath string) {
devPath := "/dev/" + filepath.Base(filepath.Dir(sysPath))
if _, err := os.Stat(devPath); os.IsNotExist(err) {
// ok
} else if err != nil {
log.Printf("stat %s failed: %v", devPath, err)
return
} else {
return // exists
}
devBytes, err := os.ReadFile(sysPath)
if err != nil {
log.Printf("read %s failed: %v", sysPath, err)
return
}
devBytes = bytes.TrimSpace(devBytes)
// rust: let Some(dev) = devBytes.split_once(':').filter_map(|a,b| Some(mkdev(a.parse().ok()?, b.parse().ok()?)));
majorStr, minorStr, ok := strings.Cut(string(devBytes), ":")
if !ok {
log.Printf("%s: invalid dev string: %s", sysPath, string(devBytes))
return
}
major, err := strconv.ParseUint(majorStr, 10, 32)
if err != nil {
log.Printf("%s: invalid major: %q", sysPath, majorStr)
return
}
minor, err := strconv.ParseUint(minorStr, 10, 32)
if err != nil {
log.Printf("%s: invalid minor: %q", sysPath, minorStr)
return
}
devMajMin := int(unix.Mkdev(uint32(major), uint32(minor)))
log.Printf("mknod %s b %d %d", devPath, major, minor)
unix.Mknod(devPath, syscall.S_IFBLK|0o0600, devMajMin)
}

View File

@ -9,9 +9,11 @@ import (
"log"
"net/http"
"os"
"path"
gopath "path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
@ -22,8 +24,22 @@ var (
upstreamURL = flag.String("upstream", "https://dkl.novit.io/dist", "Upstream server for dist elements")
)
func (ctx *renderContext) distFetch(path ...string) (outPath string, err error) {
outPath = ctx.distFilePath(path...)
type upstreamServer struct{}
func (_ upstreamServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
path := path.Clean(req.URL.Path)
outPath, err := distFetch(strings.Split(path, "/")...)
if err != nil {
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte(err.Error() + "\n"))
return
}
http.ServeFile(w, req, outPath)
}
func distFetch(path ...string) (outPath string, err error) {
outPath = distFilePath(path...)
if _, err = os.Stat(outPath); err == nil {
return

View File

@ -0,0 +1,44 @@
package main
import (
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
var wgKeys = KVSecrets[string]{"wireguard"}
func wgKey(path string) (key string, err error) {
return wgKeys.GetOrCreate(path, func() (key string, err error) {
k, err := wgtypes.GeneratePrivateKey()
if err != nil {
return
}
key = k.String()
return
})
}
func wgPSKey(path string) (key string, err error) {
return wgKeys.GetOrCreate(path, func() (key string, err error) {
k, err := wgtypes.GenerateKey()
if err != nil {
return
}
key = k.String()
return
})
}
func wgPubKey(path string) (pubkey string, err error) {
key, err := wgKey(path)
if err != nil {
return
}
k, err := wgtypes.ParseKey(key)
if err != nil {
return
}
pubkey = k.PublicKey().String()
return
}

View File

@ -1,20 +1,32 @@
package main
import (
"bytes"
"compress/gzip"
"io"
"os"
"path/filepath"
restful "github.com/emicklei/go-restful"
"gopkg.in/yaml.v2"
"m.cluseau.fr/go/httperr"
"novit.tech/direktil/pkg/localconfig"
)
func wsUploadConfig(req *restful.Request, resp *restful.Response) {
body := req.Request.Body
cfg := &localconfig.Config{}
if err := req.ReadEntity(cfg); err != nil {
wsError(resp, httperr.BadRequest(err.Error()))
return
}
err := writeNewConfig(body)
body.Close()
cfgBytes, err := yaml.Marshal(cfg)
if err != nil {
wsError(resp, err)
return
}
err = writeNewConfig(cfgBytes)
if err != nil {
wsError(resp, err)
return
@ -23,7 +35,7 @@ func wsUploadConfig(req *restful.Request, resp *restful.Response) {
resp.WriteEntity(true)
}
func writeNewConfig(reader io.Reader) (err error) {
func writeNewConfig(cfgBytes []byte) (err error) {
out, err := os.CreateTemp(*dataDir, ".config-upload")
if err != nil {
return
@ -31,7 +43,7 @@ func writeNewConfig(reader io.Reader) (err error) {
defer os.Remove(out.Name())
_, err = io.Copy(out, reader)
_, err = io.Copy(out, bytes.NewReader(cfgBytes))
out.Close()
if err != nil {
return

View File

@ -0,0 +1,292 @@
package main
import (
"bytes"
"crypto/ed25519"
"encoding/base32"
"fmt"
"io"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
restful "github.com/emicklei/go-restful"
"github.com/pierrec/lz4"
"m.cluseau.fr/go/httperr"
)
func globMatch(pattern, value string) bool {
ok, _ := filepath.Match(pattern, value)
return ok
}
type DownloadSet struct {
Expiry time.Time
Items []DownloadSetItem
}
func (s DownloadSet) Contains(kind, name, asset string) bool {
for _, item := range s.Items {
if item.Kind == kind && globMatch(item.Name, name) &&
slices.Contains(item.Assets, asset) {
return true
}
}
return false
}
func (s DownloadSet) Encode() string {
buf := new(strings.Builder)
s.EncodeTo(buf)
return buf.String()
}
func (s DownloadSet) EncodeTo(buf *strings.Builder) {
buf.WriteString(strconv.FormatInt(s.Expiry.Unix(), 16))
for _, item := range s.Items {
buf.WriteByte('|')
item.EncodeTo(buf)
}
}
func (s *DownloadSet) Decode(encoded string) (err error) {
exp, rem, _ := strings.Cut(encoded, "|")
expUnix, err := strconv.ParseInt(exp, 16, 64)
if err != nil {
return
}
s.Expiry = time.Unix(expUnix, 0)
if rem == "" {
s.Items = nil
} else {
itemStrs := strings.Split(rem, "|")
s.Items = make([]DownloadSetItem, len(itemStrs))
for i, itemStr := range itemStrs {
s.Items[i].Decode(itemStr)
}
}
return
}
func (s DownloadSet) Signed(privKey ed25519.PrivateKey) string {
buf := new(bytes.Buffer)
{
setBytes := []byte(s.Encode())
w := lz4.NewWriter(buf)
w.Write(setBytes)
w.Close()
}
setBytes := buf.Bytes()
sig := ed25519.Sign(privKey, setBytes)
buf = bytes.NewBuffer(make([]byte, 0, 1+len(sig)+len(setBytes)))
buf.WriteByte(byte(len(sig)))
buf.Write(sig)
buf.Write(setBytes)
enc := base32.StdEncoding.WithPadding(base32.NoPadding)
return enc.EncodeToString(buf.Bytes())
}
type DownloadSetItem struct {
Kind string
Name string
Assets []string
}
func (i DownloadSetItem) EncodeTo(buf *strings.Builder) {
kind := i.Kind
switch kind {
case "host":
kind = "h"
case "cluster":
kind = "c"
}
buf.WriteString(kind)
buf.WriteByte(':')
buf.WriteString(i.Name)
for _, asset := range i.Assets {
buf.WriteByte(':')
buf.WriteString(asset)
}
}
func (i *DownloadSetItem) Decode(encoded string) {
rem := encoded
i.Kind, rem, _ = strings.Cut(rem, ":")
switch i.Kind {
case "h":
i.Kind = "host"
case "c":
i.Kind = "cluster"
}
i.Name, rem, _ = strings.Cut(rem, ":")
if rem == "" {
i.Assets = nil
} else {
i.Assets = strings.Split(rem, ":")
}
}
type DownloadSetReq struct {
Expiry string
Items []DownloadSetItem
}
func wsSignDownloadSet(req *restful.Request, resp *restful.Response) {
setReq := DownloadSetReq{}
if err := req.ReadEntity(&setReq); err != nil {
wsError(resp, err)
return
}
exp, err := parseCertDuration(setReq.Expiry, time.Now())
if err != nil {
wsError(resp, err)
return
}
set := DownloadSet{
Expiry: exp,
Items: setReq.Items,
}
privKey, _ := dlsSigningKeys()
resp.WriteEntity(set.Signed(privKey))
}
func getDlSet(req *restful.Request) (*DownloadSet, *httperr.Error) {
setStr := req.QueryParameter("set")
setBytes, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(setStr)
if err != nil {
err := httperr.BadRequest("invalid set")
return nil, &err
}
if len(setBytes) == 0 {
err := httperr.BadRequest("invalid set")
return nil, &err
}
sigLen := int(setBytes[0])
setBytes = setBytes[1:]
if len(setBytes) < sigLen {
err := httperr.BadRequest("invalid set")
return nil, &err
}
sig := setBytes[:sigLen]
setBytes = setBytes[sigLen:]
_, pubkey := dlsSigningKeys()
if !ed25519.Verify(pubkey, setBytes, sig) {
err := httperr.BadRequest("invalid signature")
return nil, &err
}
setBytes, err = io.ReadAll(lz4.NewReader(bytes.NewBuffer(setBytes)))
if err != nil {
err := httperr.BadRequest("invalid data")
return nil, &err
}
fmt.Println(string(setBytes))
set := DownloadSet{}
if err := set.Decode(string(setBytes)); err != nil {
err := httperr.BadRequest("invalid set: " + err.Error())
return nil, &err
}
if time.Now().After(set.Expiry) {
err := httperr.BadRequest("set expired")
return nil, &err
}
return &set, nil
}
func wsDownloadSetAsset(req *restful.Request, resp *restful.Response) {
set, err := getDlSet(req)
if err != nil {
wsError(resp, *err)
return
}
kind := req.PathParameter("kind")
name := req.PathParameter("name")
asset := req.PathParameter("asset")
if !set.Contains(kind, name, asset) {
wsNotFound(resp)
return
}
downloadAsset(req, resp, kind, name, asset)
}
func wsDownloadSet(req *restful.Request, resp *restful.Response) {
setStr := req.QueryParameter("set")
set, err := getDlSet(req)
if err != nil {
resp.WriteHeader(err.Status)
resp.Write([]byte(htmlHeader(err.Error())))
resp.Write([]byte(htmlFooter))
return
}
buf := new(bytes.Buffer)
buf.WriteString(htmlHeader("Download set"))
cfg, err2 := readConfig()
if err2 != nil {
wsError(resp, err2)
return
}
for _, item := range set.Items {
names := make([]string, 0)
switch item.Kind {
case "cluster":
for _, c := range cfg.Clusters {
if globMatch(item.Name, c.Name) {
names = append(names, c.Name)
}
}
case "host":
for _, h := range cfg.Hosts {
if globMatch(item.Name, h.Name) {
names = append(names, h.Name)
}
}
}
for _, name := range names {
fmt.Fprintf(buf, "<h2>%s %s</h2>", strings.Title(item.Kind), name)
fmt.Fprintf(buf, "<p class=\"download-links\">\n")
for _, asset := range item.Assets {
fmt.Fprintf(buf, " <a href=\"/public/download-set/%s/%s/%s?set=%s\" download>%s</a>\n", item.Kind, name, asset, setStr, asset)
}
fmt.Fprintf(buf, `</p>`)
}
}
buf.WriteString(htmlFooter)
buf.WriteTo(resp)
}

View File

@ -1,11 +1,14 @@
package main
import (
"bytes"
"crypto/rand"
"encoding/base32"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
restful "github.com/emicklei/go-restful"
@ -53,7 +56,7 @@ func wsAuthorizeDownload(req *restful.Request, resp *restful.Response) {
resp.WriteAsJson(token)
}
func wsDownload(req *restful.Request, resp *restful.Response) {
func wsDownloadAsset(req *restful.Request, resp *restful.Response) {
token := req.PathParameter("token")
asset := req.PathParameter("asset")
@ -102,6 +105,10 @@ func wsDownload(req *restful.Request, resp *restful.Response) {
log.Printf("download via token: %s %q asset %q", spec.Kind, spec.Name, asset)
downloadAsset(req, resp, spec.Kind, spec.Name, asset)
}
func downloadAsset(req *restful.Request, resp *restful.Response, kind, name, asset string) {
cfg, err := readConfig()
if err != nil {
wsError(resp, err)
@ -109,12 +116,12 @@ func wsDownload(req *restful.Request, resp *restful.Response) {
}
setHeader := func(ext string) {
resp.AddHeader("Content-Disposition", "attachment; filename="+strconv.Quote(spec.Kind+"_"+spec.Name+"_"+asset+ext))
resp.AddHeader("Content-Disposition", "attachment; filename="+strconv.Quote(kind+"_"+name+"_"+asset+ext))
}
switch spec.Kind {
switch kind {
case "cluster":
cluster := cfg.ClusterByName(spec.Name)
cluster := cfg.ClusterByName(name)
if cluster == nil {
wsNotFound(resp)
return
@ -130,7 +137,7 @@ func wsDownload(req *restful.Request, resp *restful.Response) {
}
case "host":
host := hostOrTemplate(cfg, spec.Name)
host := hostOrTemplate(cfg, name)
if host == nil {
wsNotFound(resp)
return
@ -149,3 +156,44 @@ func wsDownload(req *restful.Request, resp *restful.Response) {
wsNotFound(resp)
}
}
func wsDownload(req *restful.Request, resp *restful.Response) {
if strings.HasSuffix(req.Request.URL.Path, "/") {
wsDownloadPage(req, resp)
return
}
token := req.PathParameter("token")
spec, ok := wState.Get().Downloads[token]
if !ok {
wsNotFound(resp)
return
}
resp.WriteEntity(spec)
}
func wsDownloadPage(req *restful.Request, resp *restful.Response) {
token := req.PathParameter("token")
spec, ok := wState.Get().Downloads[token]
if !ok {
resp.WriteHeader(http.StatusNotFound)
resp.Write([]byte(htmlHeader("Token not found")))
resp.Write([]byte(htmlFooter))
return
}
buf := new(bytes.Buffer)
buf.WriteString(htmlHeader(fmt.Sprintf("Token assets: %s %s", spec.Kind, spec.Name)))
buf.WriteString("<ul>")
for _, asset := range spec.Assets {
fmt.Fprintf(buf, "<li><a href=\"%s\" download>%s</a></li>\n", asset, asset)
}
buf.WriteString("</ul>")
buf.WriteString(htmlFooter)
buf.WriteTo(resp)
}

View File

@ -28,7 +28,6 @@ func (hft HostFromTemplate) ClusterName(cfg *localconfig.Config) string {
func hostOrTemplate(cfg *localconfig.Config, name string) (host *localconfig.Host) {
host = cfg.Host(name)
if host != nil {
log.Print("no host named ", name)
return
}
@ -39,13 +38,13 @@ func hostOrTemplate(cfg *localconfig.Config, name string) (host *localconfig.Hos
}
if !found {
log.Print("no host from template named ", name)
log.Print("no host named ", name)
return
}
ht := cfg.HostTemplate(hft.Template)
if ht == nil {
log.Print("no host template named ", name)
log.Print("host ", name, " found but no template named ", hft.Template)
return
}

View File

@ -1,44 +0,0 @@
package main
import (
"net/http"
"os"
"path/filepath"
restful "github.com/emicklei/go-restful"
yaml "gopkg.in/yaml.v2"
)
type SSH_ACL struct {
Keys []string
Clusters []string
Groups []string
Hosts []string
}
func loadSSH_ACLs() (acls []SSH_ACL, err error) {
f, err := os.Open(filepath.Join(*dataDir, "ssh-acls.yaml"))
if err != nil {
return
}
defer f.Close()
err = yaml.NewDecoder(f).Decode(&acls)
return
}
func wsSSH_ACL_List(req *restful.Request, resp *restful.Response) {
// TODO
http.NotFound(resp.ResponseWriter, req.Request)
}
func wsSSH_ACL_Get(req *restful.Request, resp *restful.Response) {
// TODO
http.NotFound(resp.ResponseWriter, req.Request)
}
func wsSSH_ACL_Set(req *restful.Request, resp *restful.Response) {
// TODO
http.NotFound(resp.ResponseWriter, req.Request)
}

View File

@ -4,13 +4,12 @@ import (
"errors"
"fmt"
"log"
"net"
"net/http"
"strings"
"text/template"
cfsslconfig "github.com/cloudflare/cfssl/config"
"github.com/emicklei/go-restful"
"gopkg.in/yaml.v2"
"m.cluseau.fr/go/httperr"
"novit.tech/direktil/pkg/localconfig"
@ -37,10 +36,13 @@ func registerWS(rest *restful.Container) {
Route(ws.POST("/store.tar").To(wsStoreUpload).
Consumes(mime.TAR).
Doc("Upload an existing store")).
Route(ws.GET("/downloads/{token}/{asset}").To(wsDownload).
Route(ws.GET("/downloads/{token}").To(wsDownload)).
Route(ws.GET("/downloads/{token}/{asset}").To(wsDownloadAsset).
Param(ws.PathParameter("token", "the download token")).
Param(ws.PathParameter("asset", "the requested asset")).
Doc("Fetch an asset via a download token"))
Doc("Fetch an asset via a download token")).
Route(ws.GET("/download-set").To(wsDownloadSet)).
Route(ws.GET("/download-set/{kind}/{name}/{asset}").To(wsDownloadSetAsset))
rest.Add(ws)
}
@ -65,10 +67,14 @@ func registerWS(rest *restful.Container) {
Consumes(mime.JSON).Reads(DownloadSpec{}).
Produces(mime.JSON).
Doc("Create a download token for the given download"))
ws.Route(ws.POST("/sign-download-set").To(wsSignDownloadSet).
Consumes(mime.JSON).Reads(DownloadSetReq{}).
Produces(mime.JSON).
Doc("Sign a download set"))
// - configs API
ws.Route(ws.POST("/configs").To(wsUploadConfig).
Consumes(mime.YAML).Param(ws.BodyParameter("config", "The new full configuration")).
Consumes(mime.YAML, mime.JSON).Param(ws.BodyParameter("config", "The new full configuration")).
Produces(mime.JSON).Writes(true).
Doc("Upload a new current configuration, archiving the previous one"))
@ -144,10 +150,6 @@ func registerWS(rest *restful.Container) {
ws.Route(ws.GET("/hosts").To(wsListHosts).
Doc("List hosts"))
ws.Route(ws.GET("/ssh-acls").To(wsSSH_ACL_List))
ws.Route(ws.GET("/ssh-acls/{acl-name}").To(wsSSH_ACL_Get))
ws.Route(ws.PUT("/ssh-acls/{acl-name}").To(wsSSH_ACL_Set))
rest.Add(ws)
// Hosts API
@ -168,19 +170,6 @@ func registerWS(rest *restful.Container) {
rest.Add(ws)
// Detected host API
ws = (&restful.WebService{}).
Filter(requireSecStore).
Path("/me").
Param(ws.HeaderParameter("Authorization", "Host or admin bearer token"))
(&wsHost{
hostDoc: "detected host",
getHost: detectHost,
}).register(ws, func(rb *restful.RouteBuilder) {
rb.Notes("In this case, the host is detected from the remote IP")
})
// Hosts by token API
ws = (&restful.WebService{}).
Filter(requireSecStore).
@ -221,41 +210,6 @@ func requireSecStore(req *restful.Request, resp *restful.Response, chain *restfu
chain.ProcessFilter(req, resp)
}
func detectHost(req *restful.Request) (hostName string, err error) {
if !*allowDetectedHost {
return
}
r := req.Request
remoteAddr := r.RemoteAddr
if *trustXFF {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
remoteAddr = strings.Split(xff, ",")[0]
}
}
hostIP, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
hostIP = remoteAddr
}
cfg, err := readConfig()
if err != nil {
return
}
host := cfg.HostByIP(hostIP)
if host == nil {
log.Print("no host found for IP ", hostIP)
return
}
return host.Name, nil
}
func wsReadConfig(resp *restful.Response) *localconfig.Config {
cfg, err := readConfig()
if err != nil {
@ -300,3 +254,26 @@ func wsRender(resp *restful.Response, sslCfg *cfsslconfig.Config, tmplStr string
return
}
}
func init() {
restful.RegisterEntityAccessor(mime.YAML, yamlEntityAccessor{})
}
type yamlEntityAccessor struct{}
var _ restful.EntityReaderWriter = yamlEntityAccessor{}
func (_ yamlEntityAccessor) Read(req *restful.Request, v any) error {
decoder := yaml.NewDecoder(req.Request.Body)
return decoder.Decode(v)
}
func (_ yamlEntityAccessor) Write(resp *restful.Response, status int, v any) error {
if v == nil {
resp.WriteHeader(status)
// do not write a nil representation
return nil
}
resp.Header().Set("Content-Type", mime.YAML)
resp.WriteHeader(status)
return yaml.NewEncoder(resp.ResponseWriter).Encode(v)
}

6
go.mod
View File

@ -11,18 +11,21 @@ require (
github.com/emicklei/go-restful v2.16.0+incompatible
github.com/emicklei/go-restful-openapi v1.4.1
github.com/go-git/go-git/v5 v5.16.2
github.com/klauspost/compress v1.18.0
github.com/mcluseau/go-swagger-ui v0.0.0-20191019002626-fd9128c24a34
github.com/miolini/datacounter v1.0.3
github.com/oklog/ulid v1.3.1
github.com/pierrec/lz4 v2.6.1+incompatible
github.com/sergeymakinen/go-crypt v1.0.1
golang.org/x/crypto v0.39.0
golang.org/x/sys v0.33.0
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10
gopkg.in/src-d/go-billy.v4 v4.3.2
gopkg.in/src-d/go-git.v4 v4.13.1
gopkg.in/yaml.v2 v2.4.0
k8s.io/apimachinery v0.33.2
m.cluseau.fr/go v0.0.0-20230809064045-12c5a121c766
novit.tech/direktil/pkg v0.0.0-20250706092353-d857af8032a1
novit.tech/direktil/pkg v0.0.0-20260125193049-56f78e083a84
)
replace github.com/zmap/zlint/v3 => github.com/zmap/zlint/v3 v3.3.1
@ -70,7 +73,6 @@ require (
github.com/zmap/zlint/v3 v3.5.0 // indirect
golang.org/x/mod v0.25.0 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect

8
go.sum
View File

@ -128,6 +128,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kisielk/sqlstruct v0.0.0-20210630145711-dae28ed37023 h1:/pb3UJ+3ZtSEUKWnufwsoVF7f0AX5ytPULbTwHMgbq4=
github.com/kisielk/sqlstruct v0.0.0-20210630145711-dae28ed37023/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@ -309,6 +311,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10 h1:3GDAcqdIg1ozBNLgPy4SLT84nfcBjr6rhGtXYtrkWLU=
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10/go.mod h1:T97yPqesLiNrOYxkwmhMI0ZIlJDm+p0PMR8eRVeR5tQ=
gomodules.xyz/jsonpatch/v2 v2.5.0 h1:JELs8RLM12qJGXU4u/TO3V25KW8GreMKl9pdkk14RM0=
gomodules.xyz/jsonpatch/v2 v2.5.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
@ -342,5 +346,5 @@ k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 h1:hwvWFiBzdWw1FhfY1FooPn3kzWuJ8
k8s.io/utils v0.0.0-20250604170112-4c0f3b243397/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
m.cluseau.fr/go v0.0.0-20230809064045-12c5a121c766 h1:JRzMBDbUwrTTGDJaJSH0ap4vRL0Q9CN1bG8a6n49eaQ=
m.cluseau.fr/go v0.0.0-20230809064045-12c5a121c766/go.mod h1:BMv3aOSYpupuiiG3Ch3ND88aB5CfAks3YZuRLE8j1ls=
novit.tech/direktil/pkg v0.0.0-20250706092353-d857af8032a1 h1:hKj9qhbTAoTxYIj6KaMLJp9I+bvZfkSM/QwK8Bd496o=
novit.tech/direktil/pkg v0.0.0-20250706092353-d857af8032a1/go.mod h1:zjezU6tELE880oYHs/WAauGBupKIEQQ7KqWTB69RW10=
novit.tech/direktil/pkg v0.0.0-20260125193049-56f78e083a84 h1:eqLPaRpVth1WgdvprKKtc4CVF13dkxuKbo7bLzlYG6s=
novit.tech/direktil/pkg v0.0.0-20260125193049-56f78e083a84/go.mod h1:zjezU6tELE880oYHs/WAauGBupKIEQQ7KqWTB69RW10=

View File

@ -1,8 +1,11 @@
#! /bin/bash
set -ex
GIT_TAG=$(git describe --always --dirty)
case "$1" in
commit) tag=$(git describe --always --dirty) ;;
commit) tag=$GIT_TAG ;;
"") tag=latest ;;
*) tag=$1 ;;
esac
docker build -t novit.tech/direktil/local-server:$tag .
docker build -t novit.tech/direktil/local-server:$tag . --build-arg GIT_TAG=$GIT_TAG

View File

@ -2,5 +2,5 @@ package dlshtml
import "embed"
//go:embed favicon.ico ui
//go:embed ui
var FS embed.FS

View File

@ -0,0 +1,131 @@
const Cluster = {
components: { Downloads, GetCopy },
props: [ 'cluster', 'token', 'state' ],
data() {
return {
signReqValidity: "1d",
sshSignReq: {
PubKey: "",
Principal: "root",
},
sshUserCert: null,
kubeSignReq: {
CSR: "",
User: "",
Group: "system:masters",
},
kubeUserCert: null,
};
},
methods: {
sshCASign() {
event.preventDefault();
fetch(`/clusters/${this.cluster.Name}/ssh/user-ca/sign`, {
method: 'POST',
body: JSON.stringify({ ...this.sshSignReq, Validity: this.signReqValidity }),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => {
if (resp.ok) {
resp.blob().then((cert) => { this.sshUserCert = URL.createObjectURL(cert) })
} else {
resp.json().then((resp) => alert('failed to sign: '+resp.message))
}
})
.catch((e) => { alert('failed to sign: '+e); })
},
kubeCASign() {
event.preventDefault();
fetch(`/clusters/${this.cluster.Name}/kube/sign`, {
method: 'POST',
body: JSON.stringify({ ...this.kubeSignReq, Validity: this.signReqValidity }),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => {
if (resp.ok) {
resp.blob().then((cert) => { this.kubeUserCert = URL.createObjectURL(cert) })
} else {
resp.json().then((resp) => alert('failed to sign: '+resp.message))
}
})
.catch((e) => { alert('failed to sign: '+e); })
},
readFile(e, onload) {
const file = e.target.files[0];
if (!file) { return; }
const reader = new FileReader();
reader.onload = () => { onload(reader.result) };
reader.onerror = () => { alert("error reading file"); };
reader.readAsText(file);
},
loadPubKey(e) {
this.readFile(e, (v) => {
this.sshSignReq.PubKey = v;
});
},
loadCSR(e) {
this.readFile(e, (v) => {
this.kubeSignReq.CSR = v;
});
},
},
template: `
<h3>Access</h3>
<p>Allow cluster access from a public key</p>
<h4>Grant SSH access</h4>
<p>Validity: <input type="text" v-model="signReqValidity"/> <small>time range, ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</small></p>
<p>User: <input type="text" v-model="sshSignReq.Principal"/></p>
<p>Public key (OpenSSH format):<br/>
<span class="text-and-file"><textarea v-model="sshSignReq.PubKey" style="height:3lh"></textarea>
<input type="file" accept=".pub" @change="loadPubKey" /></span>
</p>
<p><button @click="sshCASign">Sign SSH access</button>
<template v-if="sshUserCert">
=&gt; <a :href="sshUserCert" download="ssh-cert.pub">Get certificate</a>
</template>
</p>
<h4>Grant Kubernetes API access</h4>
<p>Validity: <input type="text" v-model="signReqValidity"/> <small>time range, ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</small></p>
<p>User: <input type="text" v-model="kubeSignReq.User"/> (by default, from the CSR)</p>
<p>Group: <input type="text" v-model="kubeSignReq.Group"/></p>
<p>Certificate signing request (PEM format):<br/>
<span class="text-and-file"><textarea v-model="kubeSignReq.CSR" style="height:7lh;"></textarea>
<input type="file" accept=".csr" @change="loadCSR" /></span>
</p>
<p><button @click="kubeCASign">Sign Kubernetes API access</button>
<template v-if="kubeUserCert">
=&gt; <a :href="kubeUserCert" download="kube-cert.pub">Get certificate</a>
</template>
</p>
<h3>Tokens</h3>
<section class="links">
<GetCopy v-for="n in cluster.Tokens" :token="token" :name="n" :href="'/clusters/'+cluster.Name+'/tokens/'+n" />
</section>
<h3>Passwords</h3>
<section class="links">
<GetCopy v-for="n in cluster.Passwords" :token="token" :name="n" :href="'/clusters/'+cluster.Name+'/passwords/'+n" />
</section>
<h3>Downloads</h3>
<Downloads :token="token" :state="state" kind="cluster" :name="cluster.Name" />
<h3>CAs</h3>
<table><tr><th>Name</th><th>Certificate</th><th>Signed certificates</th></tr>
<tr v-for="ca in cluster.CAs">
<td>{{ ca.Name }}</td>
<td><GetCopy :token="token" name="cert" :href="'/clusters/'+cluster.Name+'/CAs/'+ca.Name+'/certificate'" /></td>
<td><template v-for="signed in ca.Signed">
{{" "}}
<GetCopy :token="token" :name="signed" :href="'/clusters/'+cluster.Name+'/CAs/'+ca.Name+'/signed?name='+signed" />
</template></td>
</tr></table>
`
}

View File

@ -0,0 +1,70 @@
const Downloads = {
props: [ 'kind', 'name', 'token', 'state' ],
data() {
return { createDisabled: false, selectedAssets: {} }
},
computed: {
availableAssets() {
return {
cluster: ['addons'],
host: [
"kernel",
"initrd",
"bootstrap.tar",
"boot.img.lz4",
"boot.img.gz",
"boot.qcow2",
"boot.vmdk",
"boot.img",
"boot.iso",
"boot.tar",
"boot-efi.tar",
"config",
"bootstrap-config",
"ipxe",
],
}[this.kind]
},
downloads() {
return Object.entries(this.state.Downloads)
.filter(e => { let d=e[1]; return d.Kind == this.kind && d.Name == this.name })
.map(e => {
const token= e[0];
return {
text: token.substring(0, 5) + '...',
url: '/public/downloads/'+token+"/",
}
})
},
assets() {
return this.availableAssets.filter(a => this.selectedAssets[a])
},
},
methods: {
createToken() {
event.preventDefault()
this.createDisabled = true
fetch('/authorize-download', {
method: 'POST',
body: JSON.stringify({Kind: this.kind, Name: this.name, Assets: this.assets}),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => resp.json())
.then((token) => { this.selectedAssets = {}; this.createDisabled = false })
.catch((e) => { alert('failed to create link'); this.createDisabled = false })
},
},
template: `
<h4>Available assets</h4>
<p class="downloads">
<template v-for="asset in availableAssets">
<label :class="{selected: selectedAssets[asset]}"><input type="checkbox" v-model="selectedAssets[asset]" />&nbsp;{{ asset }}</label>
{{" "}}
</template>
</p>
<p><button :disabled="createDisabled || assets.length==0" @click="createToken">Create link</button></p>
<template v-if="downloads.length">
<h4>Active links</h4>
<p class="download-links"><template v-for="d in downloads"><a :href="d.url" target="_blank">{{ d.text }}</a>{{" "}}</template></p>
</template>`
}

View File

@ -0,0 +1,32 @@
const GetCopy = {
props: [ 'name', 'href', 'token' ],
data() { return {showCopied: false} },
template: `<span class="notif"><div v-if="showCopied">copied!</div><a :href="href" @click="fetchAndSave()">{{name}}</a>&nbsp;<a href="#" class="copy" @click="fetchAndCopy()">&#x1F5D0;</a></span>`,
methods: {
fetch() {
event.preventDefault()
return fetch(this.href, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + this.token },
})
},
handleFetchError(e) {
console.log("failed to get value:", e)
alert('failed to get value')
},
fetchAndSave() {
this.fetch().then(resp => resp.blob()).then((value) => {
window.open(URL.createObjectURL(value), "_blank")
}).catch(this.handleFetchError)
},
fetchAndCopy() {
this.fetch()
.then((resp) => resp.headers.get("content-type") == "application/json" ? resp.json() : resp.text())
.then((value) => {
window.navigator.clipboard.writeText(value)
this.showCopied = true
setTimeout(() => { this.showCopied = false }, 1000)
}).catch(this.handleFetchError)
},
},
}

View File

@ -0,0 +1,14 @@
const Host = {
components: { Downloads },
props: [ 'host', 'token', 'state' ],
template: `
<p>Cluster: {{ host.Cluster }}<template v-if="host.Template"> ({{ host.Template }})</template></p>
<p>IPs:
<code v-for="ip in host.IPs">
{{ ip }}{{" "}}
</code>
</p>
<h3>Downloads</h3>
<Downloads :token="token" :state="state" kind="host" :name="host.Name" />
`
}

View File

@ -0,0 +1,267 @@
import { createApp } from './vue.esm-browser.js';
createApp({
components: { Cluster, Host },
data() {
return {
forms: {
store: {},
storeUpload: {},
delKey: {},
hostFromTemplate: {},
hostFromTemplateDel: "",
},
view: "",
viewFilter: "",
session: {},
error: null,
publicState: null,
serverVersion: null,
uiHash: null,
watchingState: false,
state: null,
}
},
mounted() {
this.session = JSON.parse(sessionStorage.state || "{}")
this.watchPublicState()
},
watch: {
session: {
deep: true,
handler(v) {
sessionStorage.state = JSON.stringify(v)
if (v.token && !this.watchingState) {
this.watchState()
this.watchingState = true
}
}
},
publicState: {
deep: true,
handler(v) {
if (v) {
this.serverVersion = v.ServerVersion
if (this.uiHash && v.UIHash != this.uiHash) {
console.log("reloading")
location.reload()
} else {
this.uiHash = v.UIHash
}
}
},
}
},
computed: {
views() {
var views = [{type: "actions", name: "admin", title: "Admin actions"}];
(this.state.Clusters||[]).forEach((c) => views.push({type: "cluster", name: c.Name, title: `Cluster ${c.Name}`}));
(this.state.Hosts ||[]).forEach((c) => views.push({type: "host", name: c.Name, title: `Host ${c.Name}`}));
return views.filter((v) => v.type != "host" || v.name.includes(this.viewFilter));
},
viewObj() {
if (this.view) {
if (this.view.type == "cluster") {
return this.state.Clusters.find((c) => c.Name == this.view.name);
}
if (this.view.type == "host") {
return this.state.Hosts.find((h) => h.Name == this.view.name);
}
}
return undefined;
},
hostsFromTemplate() {
return (this.state.Hosts||[]).filter((h) => h.Template);
},
},
methods: {
any(array) {
return array && array.length != 0;
},
copyText(text) {
event.preventDefault()
window.navigator.clipboard.writeText(text)
},
setToken() {
event.preventDefault()
this.session.token = this.forms.setToken
this.forms.setToken = null
},
uploadStore() {
event.preventDefault()
this.apiPost('/public/store.tar', this.$refs.storeUpload.files[0], (v) => {
this.forms.store = {}
}, "application/tar")
},
namedPassphrase(name, passphrase) {
return {Name: this.forms.store.name, Passphrase: btoa(this.forms.store.pass1)}
},
storeAddKey() {
this.apiPost('/store/add-key', this.namedPassphrase(), (v) => {
this.forms.store = {}
})
},
storeDelKey() {
event.preventDefault()
let name = this.forms.delKey.name
if (!confirm("Remove key named "+JSON.stringify(name)+"?")) {
return
}
this.apiPost('/store/delete-key', name , (v) => {
this.forms.delKey = {}
})
},
unlockStore() {
this.apiPost('/public/unlock-store', this.namedPassphrase(), (v) => {
this.forms.store = {}
if (v) {
this.session.token = v
if (!this.watchingState) {
this.watchState()
this.watchingState = true
}
}
})
},
uploadConfig() {
const file = this.$refs.configUpload.files[0];
let contentType = "text/vnd.yaml";
if (file.name.endsWith(".json")) {
contentType = "application/json";
}
this.apiPost('/configs', file, (v) => {}, contentType, true)
},
hostFromTemplateAdd() {
let v = this.forms.hostFromTemplate;
this.apiPost('/hosts-from-template/'+v.name, v, (v) => { this.forms.hostFromTemplate = {} });
},
hostFromTemplateDel() {
event.preventDefault()
let v = this.forms.hostFromTemplateDel;
if (!confirm("delete host template instance "+v+"?")) {
return
}
this.apiDelete('/hosts-from-template/'+v, (v) => { this.forms.hostFromTemplateDel = "" });
},
apiPost(action, data, onload, contentType = 'application/json', raw = false) {
event.preventDefault()
if (data === undefined) {
throw("action " + action + ": no data")
}
/* TODO
fetch(action, {
method: 'POST',
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((result) => onload)
// */
var xhr = new XMLHttpRequest()
xhr.responseType = 'json'
// TODO spinner, pending action notification, or something
xhr.onerror = () => {
// this.actionResults.splice(idx, 1, {...item, done: true, failed: true })
}
xhr.onload = (r) => {
if (xhr.status != 200) {
this.error = xhr.response
return
}
// this.actionResults.splice(idx, 1, {...item, done: true, resp: xhr.responseText})
this.error = null
if (onload) {
onload(xhr.response)
}
}
xhr.open("POST", action)
xhr.setRequestHeader('Accept', 'application/json')
xhr.setRequestHeader('Content-Type', contentType)
if (this.session.token) {
xhr.setRequestHeader('Authorization', 'Bearer '+this.session.token)
}
if (!raw && contentType == "application/json") {
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
}
},
apiDelete(action, data, onload) {
event.preventDefault()
var xhr = new XMLHttpRequest()
xhr.onload = (r) => {
if (xhr.status != 200) {
this.error = xhr.response
return
}
this.error = null
if (onload) {
onload(xhr.response)
}
}
xhr.open("DELETE", action)
xhr.setRequestHeader('Accept', 'application/json')
if (this.session.token) {
xhr.setRequestHeader('Authorization', 'Bearer '+this.session.token)
}
xhr.send()
},
download(url) {
event.target.target = '_blank'
event.target.href = this.downloadLink(url)
},
downloadLink(url) {
// TODO once-shot download link
return url + '?token=' + this.session.token
},
watchPublicState() {
this.watchStream('publicState', '/public-state')
},
watchState() {
this.watchStream('state', '/state', true)
},
watchStream(field, path, withToken) {
let evtSrc = new EventSource(path + (withToken ? '?token='+this.session.token : ''));
evtSrc.onmessage = (e) => {
let update = JSON.parse(e.data)
console.log("watch "+path+":", update)
if (update.err) {
console.log("watch error from server:", err)
}
if (update.set) {
this[field] = update.set
}
if (update.p) { // patch
new jsonpatch.JSONPatch(update.p, true).apply(this[field])
}
}
evtSrc.onerror = (e) => {
// console.log("event source " + path + " error:", e)
if (evtSrc) evtSrc.close()
this[field] = null
window.setTimeout(() => { this.watchStream(field, path, withToken) }, 1000)
}
},
}
}).mount('#app');

View File

@ -10,7 +10,7 @@
cursor: pointer;
}
.downloads {
.downloads, .download-links {
& > * {
display: inline-block;
margin-right: 1ex;
@ -20,18 +20,23 @@
border-radius: 1ex;
cursor: pointer;
}
}
.downloads, .view-links {
& > .selected {
color: blue;
color: var(--link);
}
}
.download-links a {
margin-right: 1ex;
}
.text-and-file {
position:relative;
@media (prefers-color-scheme: dark) {
.downloads > .selected,
.view-links > .selected {
color: #31b0fa;
textarea {
width: 64em;
}
input[type="file"] {
position:absolute;
bottom:0;right:0;
}
}

View File

Before

Width:  |  Height:  |  Size: 8.7 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

View File

@ -2,18 +2,25 @@
<html>
<head>
<title>Direktil Local Server</title>
<style>
@import url('./style.css');
@import url('./app.css');
</style>
<script src="js/jsonpatch.min.js" crossorigin="anonymous"></script>
<script src="js/app.js" type="module" defer></script>
<base href="/ui/" />
<link rel="icon" href="favicon.ico" />
<style>@import url('/ui/style.css');@import url('/ui/app.css');</style>
<script src="/ui/jsonpatch.min-942279a1c4209cc2.js" integrity="sha384-GcPrkRS12jtrElEkbJcrZ8asvvb9s3mc+CUq9UW/8bL4L0bpkmh9M+oFnWN6qLq2"></script>
<script src="/ui/app-7f4645e84eaae7ce.js" defer integrity="sha384-31uiQnXVSPLDq61o+chfyKRkSdkmzv023M7KafOo+0xRw5AM70BUFyYO6yo0kPiZ" type="module"></script>
<script src="/ui/Downloads-c9374f19f52c46d.js" integrity="sha384-WQIkCSxlUkvu4jFIWwS3bESMaazGwwnBn9dyvB7nItz3L8BmusRMsJACzfJa7sC4"></script>
<script src="/ui/GetCopy-7e3c9678f9647d40.js" integrity="sha384-LzxUXylxE/t25HyTch8y2qvKcehvP2nqCo37swIBGEKZZUzHVJVQrS5UJDWNskTA"></script>
<script src="/ui/Cluster-703dcdca97841304.js" integrity="sha384-ifGpq/GB1nDfqczm5clTRtcfnc9UMkT+SptMyS3UG9Di3xoKORtOGGjmK5RnJx+v"></script>
<script src="/ui/Host-61916516a854adff.js" integrity="sha384-/wh3KrC0sb4MT7ekO2U84rswxI42WSH/0jB4dbDaaGaGhX60xTEZHFsdQAf7UgTG"></script>
<body>
<div id="app">
<header>
<div id="logo">
<img src="/favicon.ico" />
<img src="favicon.ico" />
<span>Direktil Local Server</span>
</div>
<div class="utils">
@ -74,7 +81,7 @@
</template>
<template v-else>
<div style="float:right;"><input type="text" placeholder="Filter" v-model="viewFilter"/></div>
<div style="float:right;"><input type="search" placeholder="Filter" v-model="viewFilter"/></div>
<p class="view-links"><span v-for="v in views" @click="view = v" :class="{selected: view.type==v.type && view.name==v.name}">{{v.title}}</span></p>
<h2 v-if="view">{{view.title}}</h2>
@ -112,9 +119,9 @@
<template v-for="k,i in state.Store.KeyNames">{{i?", ":""}}<code @click="forms.delKey.name=k">{{k}}</code></template>.</p>
</form>
<template v-if="state.HostTemplates && state.HostTemplates.length">
<template v-if="any(state.HostTemplates) || any(hostsFromTemplate)">
<h3>Hosts from template</h3>
<form @submit="hostFromTemplateAdd" action="">
<form @submit="hostFromTemplateAdd" action="" v-if="any(state.HostTemplates)">
<p>Add a host from template instance:</p>
<input type="text" v-model="forms.hostFromTemplate.name" required placeholder="Name" />
<select v-model="forms.hostFromTemplate.Template" required>
@ -123,7 +130,7 @@
<input type="text" v-model="forms.hostFromTemplate.IP" required placeholder="IP" />
<input type="submit" value="add instance" />
</form>
<form @submit="hostFromTemplateDel" action="">
<form @submit="hostFromTemplateDel" action="" v-if="any(hostsFromTemplate)">
<p>Remove a host from template instance:</p>
<select v-model="forms.hostFromTemplateDel" required>
<option v-for="h in hostsFromTemplate" :value="h.Name">{{h.Name}}</option>
@ -134,6 +141,5 @@
</div>
</template>
</div>
</body>
</html>

View File

@ -1,5 +1,30 @@
:root {
--bg: #eee;
--color: black;
--bevel-dark: darkgray;
--bevel-light: lightgray;
--link: blue;
--input-bg: #ddd;
--input-text: white;
--btn-bg: #eee;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: black;
--color: orange;
--bevel-dark: #402900;
--bevel-light: #805300;
--link: #31b0fa;
--input-bg: #111;
--input-text: #ddd;
--btn-bg: #222;
}
}
body {
background: white;
background: var(--bg);
color: var(--color);
}
button[disabled] {
@ -8,7 +33,7 @@ button[disabled] {
a[href], a[href]:visited, button.link {
border: none;
color: blue;
color: var(--link);
background: none;
cursor: pointer;
text-decoration: none;
@ -37,20 +62,38 @@ th, tr:last-child > td {
.red { color: red; }
@media (prefers-color-scheme: dark) {
body {
background: black;
color: orange;
}
button, input[type=submit] {
background: #333;
color: #eee;
}
a[href], a[href]:visited, button.link {
border: none;
color: #31b0fa;
.red { color: #c00; }
}
textarea, select, input {
background: var(--input-bg);
color: var(--input-text);
border: solid 1pt;
border-color: var(--bevel-light);
border-top-color: var(--bevel-dark);
border-left-color: var(--bevel-dark);
margin: 1pt;
&:focus {
outline: solid 1pt var(--color);
}
}
.red { color: #c00; }
button, input[type=button], input[type=submit], ::file-selector-button {
background: var(--btn-bg);
color: var(--color);
border: solid 2pt;
border-color: var(--bevel-dark);
border-top-color: var(--bevel-light);
border-left-color: var(--bevel-light);
&:hover {
background: var(--bevel-dark);
}
&:active {
background: var(--bevel-dark);
border-color: var(--bevel-light);
}
}
header {

View File

@ -1,37 +1,23 @@
#! /bin/sh
if [ $# -ne 2 ]; then
echo "USAGE: $0 <device> <base url>"
echo "USAGE: $0 <device>"
fi
dev=$1
base_url=$2
: ${MP:=/mnt}
set -ex
mkdir -p $MP
zcat boot.img.gz | dd of=$dev
apk add sgdisk
[[ $dev =~ nvme ]] &&
devp=${dev}p ||
devp=${dev}
if vgdisplay storage; then
# the system is already installed, just upgrade
mount -t vfat ${devp}1 $MP
curl ${base_url}/boot.tar |tar xv -C $MP
umount $MP
sgdisk --move-second-header --new=3:0:0 $dev
else
sgdisk --clear $dev
pvcreate ${devp}3
vgcreate storage ${devp}3
curl ${base_url}/boot.img.lz4 |lz4cat >$dev
sgdisk --move-second-header --new=3:0:0 $dev
pvcreate ${devp}3
vgcreate storage ${devp}3
fi
while umount $MP; do true; done

View File

@ -2,7 +2,6 @@ package clustersconfig
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
@ -178,7 +177,7 @@ type dirStore struct {
// listDir
func (b *dirStore) listDir(prefix string) (subDirs []string, err error) {
entries, err := ioutil.ReadDir(filepath.Join(b.path, prefix))
entries, err := os.ReadDir(filepath.Join(b.path, prefix))
if err != nil {
return
}
@ -226,7 +225,7 @@ func (b *dirStore) List(prefix string) ([]string, error) {
// Load is part of the DataBackend interface
func (b *dirStore) Get(key string) (ba []byte, err error) {
ba, err = ioutil.ReadFile(filepath.Join(b.path, filepath.Join(path.Split(key))+".yaml"))
ba, err = os.ReadFile(filepath.Join(b.path, filepath.Join(path.Split(key))+".yaml"))
if os.IsNotExist(err) {
return nil, nil
}

24
ui/Trunk.toml Normal file
View File

@ -0,0 +1,24 @@
[build]
public_url = "/ui"
dist = "../html/ui"
[[proxy]]
backend = "http://localhost:7606/public-state"
[[proxy]]
backend = "http://localhost:7606/state"
[[proxy]]
backend = "http://localhost:7606/public"
[[proxy]]
backend = "http://localhost:7606/store"
[[proxy]]
backend = "http://localhost:7606/authorize-download"
[[proxy]]
backend = "http://localhost:7606/sign-download-set"
[[proxy]]
backend = "http://localhost:7606/configs"
[[proxy]]
backend = "http://localhost:7606/clusters"
[[proxy]]
backend = "http://localhost:7606/hosts-from-template"
[[proxy]]
backend = "http://localhost:7606/hosts"

42
ui/app.css Normal file
View File

@ -0,0 +1,42 @@
.view-links > span {
display: inline-block;
white-space: nowrap;
margin-right: 1ex;
margin-bottom: 1ex;
padding: 0.5ex;
border: 1pt solid;
border-radius: 1ex;
cursor: pointer;
}
.downloads, .download-links {
& > * {
display: inline-block;
margin-right: 1ex;
margin-bottom: 1ex;
padding: 0.5ex;
border: 1px solid;
border-radius: 1ex;
cursor: pointer;
}
}
.downloads, .view-links {
& > .selected {
color: var(--link);
}
}
.text-and-file {
position:relative;
textarea {
width: 64em;
}
input[type="file"] {
position:absolute;
bottom:0;right:0;
}
}

1
ui/build Executable file
View File

@ -0,0 +1 @@
trunk build --release

BIN
ui/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

145
ui/index.html Normal file
View File

@ -0,0 +1,145 @@
<!doctype html>
<html>
<head>
<title>Direktil Local Server</title>
<base data-trunk-public-url />
<link data-trunk rel="copy-file" href="favicon.ico" />
<link rel="icon" href="favicon.ico" />
<link data-trunk rel="copy-file" href="js/vue.esm-browser.js" />
<link data-trunk rel="copy-file" href="style.css" />
<link data-trunk rel="copy-file" href="app.css" />
<style>@import url('/ui/style.css');@import url('/ui/app.css');</style>
<script data-trunk src="js/jsonpatch.min.js"></script>
<script data-trunk src="js/app.js" type="module" defer></script>
<script data-trunk src="js/Downloads.js"></script>
<script data-trunk src="js/GetCopy.js"></script>
<script data-trunk src="js/Cluster.js"></script>
<script data-trunk src="js/Host.js"></script>
<body>
<div id="app">
<header>
<div id="logo">
<img src="favicon.ico" />
<span>Direktil Local Server</span>
</div>
<div class="utils">
<span id="login-hdr" v-if="session.token">
Logged in
<button class="link" @click="copyText(session.token)">&#x1F5D0;</button>
</span>
<span>server <code>{{ serverVersion || '-----' }}</code></span>
<span>ui <code>{{ uiHash || '-----' }}</code></span>
<span :class="publicState ? 'green' : 'red'">&#x1F5F2;</span>
</div>
</header>
<div class="error" v-if="error">
<button class="btn-close" @click="error=null">&times;</button>
<div class="code" v-if="error.code">{{ error.code }}</div>
<div class="message">{{ error.message }}</div>
</div>
<template v-if="!publicState">
<p>Not connected.</p>
</template>
<template v-else-if="publicState.Store.New">
<p>Store is new.</p>
<p>Option 1: initialize a new store</p>
<form @submit="unlockStore">
<input type="text" v-model="forms.store.name" name="name" placeholder="Name" /><br/>
<input type="password" v-model="forms.store.pass1" name="passphrase" required placeholder="Passphrase" />
<input type="password" v-model="forms.store.pass2" required placeholder="Passphrase confirmation" />
<input type="submit" value="initialize" :disabled="!forms.store.pass1 || forms.store.pass1 != forms.store.pass2" />
</form>
<p>Option 2: upload a previously downloaded store</p>
<form @submit="uploadStore">
<input type="file" ref="storeUpload" />
<input type="submit" value="upload" />
</form>
</template>
<template v-else-if="!publicState.Store.Open">
<p>Store is not open.</p>
<form @submit="unlockStore">
<input type="password" name="passphrase" v-model="forms.store.pass1" required placeholder="Passphrase" />
<input type="submit" value="unlock" :disabled="!forms.store.pass1" />
</form>
</template>
<template v-else-if="!state">
<p v-if="!session.token">Not logged in.</p>
<p v-else>Invalid token</p>
<form @submit="unlockStore">
<input type="password" v-model="forms.store.pass1" required placeholder="Passphrase" />
<input type="submit" value="log in"/>
</form>
</template>
<template v-else>
<div style="float:right;"><input type="search" placeholder="Filter" v-model="viewFilter"/></div>
<p class="view-links"><span v-for="v in views" @click="view = v" :class="{selected: view.type==v.type && view.name==v.name}">{{v.title}}</span></p>
<h2 v-if="view">{{view.title}}</h2>
<div v-if="view.type == 'cluster'" id="clusters">
<Cluster :cluster="viewObj" :token="session.token" :state="state" />
</div>
<div v-if="view.type == 'host'" id="hosts">
<Host :host="viewObj" :token="session.token" :state="state" />
</div>
<div v-if="view.type == 'actions' && view.name == 'admin'">
<h3>Config</h3>
<form @submit="uploadConfig">
<input type="file" ref="configUpload" required />
<input type="submit" value="upload config" />
</form>
<h3>Store</h3>
<p><a :href="'/public/store.tar?token='+state.Store.DownloadToken" target="_blank">Download</a></p>
<form @submit="storeAddKey" action="/store/add-key">
<p>Add an unlock phrase:</p>
<input type="text" v-model="forms.store.name" name="name" required placeholder="Name" /><br/>
<input type="password" v-model="forms.store.pass1" name="passphrase" autocomplete="new-password" required placeholder="Phrase" />
<input type="password" v-model="forms.store.pass2" autocomplete="new-password" required placeholder="Phrase confirmation" />
<input type="submit" value="add unlock phrase" :disabled="!forms.store.pass1 || forms.store.pass1 != forms.store.pass2" />
</form>
<form @submit="storeDelKey" action="/store/delete-key">
<p>Remove an unlock phrase:</p>
<input type="text" v-model="forms.delKey.name" name="name" required placeholder="Name" />
<input type="submit" value="remove unlock phrase" />
<p v-if="state.Store.KeyNames">Available names:
<template v-for="k,i in state.Store.KeyNames">{{i?", ":""}}<code @click="forms.delKey.name=k">{{k}}</code></template>.</p>
</form>
<template v-if="any(state.HostTemplates) || any(hostsFromTemplate)">
<h3>Hosts from template</h3>
<form @submit="hostFromTemplateAdd" action="" v-if="any(state.HostTemplates)">
<p>Add a host from template instance:</p>
<input type="text" v-model="forms.hostFromTemplate.name" required placeholder="Name" />
<select v-model="forms.hostFromTemplate.Template" required>
<option v-for="name in state.HostTemplates" :value="name">{{name}}</option>
</select>
<input type="text" v-model="forms.hostFromTemplate.IP" required placeholder="IP" />
<input type="submit" value="add instance" />
</form>
<form @submit="hostFromTemplateDel" action="" v-if="any(hostsFromTemplate)">
<p>Remove a host from template instance:</p>
<select v-model="forms.hostFromTemplateDel" required>
<option v-for="h in hostsFromTemplate" :value="h.Name">{{h.Name}}</option>
</select>
<input type="submit" value="delete instance" :disabled="!forms.hostFromTemplateDel" />
</form>
</template>
</div>
</template>
</div>
</body>
</html>

View File

@ -1,8 +1,4 @@
import Downloads from './Downloads.js';
import GetCopy from './GetCopy.js';
export default {
const Cluster = {
components: { Downloads, GetCopy },
props: [ 'cluster', 'token', 'state' ],
data() {
@ -15,8 +11,8 @@ export default {
sshUserCert: null,
kubeSignReq: {
CSR: "",
User: "anonymous",
Group: "",
User: "",
Group: "system:masters",
},
kubeUserCert: null,
};
@ -28,8 +24,13 @@ export default {
method: 'POST',
body: JSON.stringify({ ...this.sshSignReq, Validity: this.signReqValidity }),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => resp.blob())
.then((cert) => { this.sshUserCert = URL.createObjectURL(cert) })
}).then((resp) => {
if (resp.ok) {
resp.blob().then((cert) => { this.sshUserCert = URL.createObjectURL(cert) })
} else {
resp.json().then((resp) => alert('failed to sign: '+resp.message))
}
})
.catch((e) => { alert('failed to sign: '+e); })
},
kubeCASign() {
@ -38,12 +39,70 @@ export default {
method: 'POST',
body: JSON.stringify({ ...this.kubeSignReq, Validity: this.signReqValidity }),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => resp.blob())
.then((cert) => { this.kubeUserCert = URL.createObjectURL(cert) })
}).then((resp) => {
if (resp.ok) {
resp.blob().then((cert) => { this.kubeUserCert = URL.createObjectURL(cert) })
} else {
resp.json().then((resp) => alert('failed to sign: '+resp.message))
}
})
.catch((e) => { alert('failed to sign: '+e); })
},
readFile(e, onload) {
const file = e.target.files[0];
if (!file) { return; }
const reader = new FileReader();
reader.onload = () => { onload(reader.result) };
reader.onerror = () => { alert("error reading file"); };
reader.readAsText(file);
},
loadPubKey(e) {
this.readFile(e, (v) => {
this.sshSignReq.PubKey = v;
});
},
loadCSR(e) {
this.readFile(e, (v) => {
this.kubeSignReq.CSR = v;
});
},
},
template: `
<h3>Access</h3>
<p>Allow cluster access from a public key</p>
<h4>Grant SSH access</h4>
<p>Validity: <input type="text" v-model="signReqValidity"/> <small>time range, ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</small></p>
<p>User: <input type="text" v-model="sshSignReq.Principal"/></p>
<p>Public key (OpenSSH format):<br/>
<span class="text-and-file"><textarea v-model="sshSignReq.PubKey" style="height:3lh"></textarea>
<input type="file" accept=".pub" @change="loadPubKey" /></span>
</p>
<p><button @click="sshCASign">Sign SSH access</button>
<template v-if="sshUserCert">
=&gt; <a :href="sshUserCert" download="ssh-cert.pub">Get certificate</a>
</template>
</p>
<h4>Grant Kubernetes API access</h4>
<p>Validity: <input type="text" v-model="signReqValidity"/> <small>time range, ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</small></p>
<p>User: <input type="text" v-model="kubeSignReq.User"/> (by default, from the CSR)</p>
<p>Group: <input type="text" v-model="kubeSignReq.Group"/></p>
<p>Certificate signing request (PEM format):<br/>
<span class="text-and-file"><textarea v-model="kubeSignReq.CSR" style="height:7lh;"></textarea>
<input type="file" accept=".csr" @change="loadCSR" /></span>
</p>
<p><button @click="kubeCASign">Sign Kubernetes API access</button>
<template v-if="kubeUserCert">
=&gt; <a :href="kubeUserCert" download="kube-cert.pub">Get certificate</a>
</template>
</p>
<h3>Tokens</h3>
<section class="links">
<GetCopy v-for="n in cluster.Tokens" :token="token" :name="n" :href="'/clusters/'+cluster.Name+'/tokens/'+n" />
@ -68,34 +127,5 @@ export default {
</template></td>
</tr></table>
<h3>Access</h3>
<p>Allow cluster access from a public key</p>
<p>Certificate time validity: <input type="text" v-model="signReqValidity"/> <small>ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</p>
<h4>Grant SSH access</h4>
<p>Public key (OpenSSH format):<br/>
<textarea v-model="sshSignReq.PubKey" style="width:64em;height:2lh"></textarea>
</p>
<p>Principal: <input type="text" v-model="sshSignReq.Principal"/></p>
<p><button @click="sshCASign">Sign SSH access request</button></p>
<p v-if="sshUserCert">
<a :href="sshUserCert" download="ssh-cert.pub">Get certificate</a>
</p>
<h4>Grant Kubernetes API access</h4>
<p>Certificate signing request (PEM format):<br/>
<textarea v-model="kubeSignReq.CSR" style="width:64em;height:7lh;"></textarea>
</p>
<p>User: <input type="text" v-model="kubeSignReq.User"/></p>
<p>Group: <input type="text" v-model="kubeSignReq.Group"/></p>
<p><button @click="kubeCASign">Sign Kubernetes API access request</button></p>
<p v-if="kubeUserCert">
<a :href="kubeUserCert" download="kube-cert.pub">Get certificate</a>
</p>
`
}

View File

@ -1,5 +1,4 @@
export default {
const Downloads = {
props: [ 'kind', 'name', 'token', 'state' ],
data() {
return { createDisabled: false, selectedAssets: {} }
@ -27,16 +26,15 @@ export default {
}[this.kind]
},
downloads() {
let ret = []
Object.entries(this.state.Downloads)
return Object.entries(this.state.Downloads)
.filter(e => { let d=e[1]; return d.Kind == this.kind && d.Name == this.name })
.forEach(e => {
let token= e[0], d = e[1]
d.Assets.forEach(asset => {
ret.push({name: asset, url: '/public/downloads/'+token+'/'+asset})
})
.map(e => {
const token= e[0];
return {
text: token.substring(0, 5) + '...',
url: '/public/downloads/'+token+"/",
}
})
return ret
},
assets() {
return this.availableAssets.filter(a => this.selectedAssets[a])
@ -64,9 +62,9 @@ export default {
{{" "}}
</template>
</p>
<p><button :disabled="createDisabled || assets.length==0" @click="createToken">Create links</button></p>
<p><button :disabled="createDisabled || assets.length==0" @click="createToken">Create link</button></p>
<template v-if="downloads.length">
<h4>Active links</h4>
<p class="download-links"><template v-for="d in downloads"><a :href="d.url" download>{{ d.name }}</a>{{" "}}</template></p>
<p class="download-links"><template v-for="d in downloads"><a :href="d.url" target="_blank">{{ d.text }}</a>{{" "}}</template></p>
</template>`
}

View File

@ -1,4 +1,4 @@
export default {
const GetCopy = {
props: [ 'name', 'href', 'token' ],
data() { return {showCopied: false} },
template: `<span class="notif"><div v-if="showCopied">copied!</div><a :href="href" @click="fetchAndSave()">{{name}}</a>&nbsp;<a href="#" class="copy" @click="fetchAndCopy()">&#x1F5D0;</a></span>`,

View File

@ -1,7 +1,4 @@
import Downloads from './Downloads.js';
export default {
const Host = {
components: { Downloads },
props: [ 'host', 'token', 'state' ],
template: `

View File

@ -1,9 +1,6 @@
import { createApp } from './vue.esm-browser.js';
import Cluster from './Cluster.js';
import Host from './Host.js';
createApp({
components: { Cluster, Host },
data() {
@ -65,7 +62,7 @@ createApp({
(this.state.Clusters||[]).forEach((c) => views.push({type: "cluster", name: c.Name, title: `Cluster ${c.Name}`}));
(this.state.Hosts ||[]).forEach((c) => views.push({type: "host", name: c.Name, title: `Host ${c.Name}`}));
return views.filter((v) => v.name.includes(this.viewFilter));
return views.filter((v) => v.type != "host" || v.name.includes(this.viewFilter));
},
viewObj() {
if (this.view) {
@ -79,11 +76,14 @@ createApp({
return undefined;
},
hostsFromTemplate() {
return (this.state.Hosts||[]).filter((h) => h.Template)
return (this.state.Hosts||[]).filter((h) => h.Template);
},
},
methods: {
any(array) {
return array && array.length != 0;
},
copyText(text) {
event.preventDefault()
window.navigator.clipboard.writeText(text)
@ -133,7 +133,12 @@ createApp({
})
},
uploadConfig() {
this.apiPost('/configs', this.$refs.configUpload.files[0], (v) => {}, "text/vnd.yaml")
const file = this.$refs.configUpload.files[0];
let contentType = "text/vnd.yaml";
if (file.name.endsWith(".json")) {
contentType = "application/json";
}
this.apiPost('/configs', file, (v) => {}, contentType, true)
},
hostFromTemplateAdd() {
let v = this.forms.hostFromTemplate;
@ -148,7 +153,7 @@ createApp({
}
this.apiDelete('/hosts-from-template/'+v, (v) => { this.forms.hostFromTemplateDel = "" });
},
apiPost(action, data, onload, contentType = 'application/json') {
apiPost(action, data, onload, contentType = 'application/json', raw = false) {
event.preventDefault()
if (data === undefined) {
@ -190,7 +195,7 @@ createApp({
xhr.setRequestHeader('Authorization', 'Bearer '+this.session.token)
}
if (contentType == "application/json") {
if (!raw && contentType == "application/json") {
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
@ -259,5 +264,4 @@ createApp({
},
}
}).mount('#app')
}).mount('#app');

36
ui/js/jsonpatch.min.js vendored Normal file

File diff suppressed because one or more lines are too long

16172
ui/js/vue.esm-browser.js Normal file

File diff suppressed because it is too large Load Diff

195
ui/style.css Normal file
View File

@ -0,0 +1,195 @@
:root {
--bg: #eee;
--color: black;
--bevel-dark: darkgray;
--bevel-light: lightgray;
--link: blue;
--input-bg: #ddd;
--input-text: white;
--btn-bg: #eee;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: black;
--color: orange;
--bevel-dark: #402900;
--bevel-light: #805300;
--link: #31b0fa;
--input-bg: #111;
--input-text: #ddd;
--btn-bg: #222;
}
}
body {
background: var(--bg);
color: var(--color);
}
button[disabled] {
opacity: 0.5;
}
a[href], a[href]:visited, button.link {
border: none;
color: var(--link);
background: none;
cursor: pointer;
text-decoration: none;
}
table {
border-collapse: collapse;
}
th, td {
border-left: dotted 1pt;
border-right: dotted 1pt;
border-bottom: dotted 1pt;
padding: 2pt 4pt;
}
tr:first-child > th {
border-top: dotted 1pt;
}
th, tr:last-child > td {
border-bottom: solid 1pt;
}
.flat > * { margin-left: 1ex; }
.flat > *:first-child { margin-left: 0; }
.green { color: green; }
.red { color: red; }
@media (prefers-color-scheme: dark) {
.red { color: #c00; }
}
textarea, select, input {
background: var(--input-bg);
color: var(--input-text);
border: solid 1pt;
border-color: var(--bevel-light);
border-top-color: var(--bevel-dark);
border-left-color: var(--bevel-dark);
margin: 1pt;
&:focus {
outline: solid 1pt var(--color);
}
}
button, input[type=button], input[type=submit], ::file-selector-button {
background: var(--btn-bg);
color: var(--color);
border: solid 2pt;
border-color: var(--bevel-dark);
border-top-color: var(--bevel-light);
border-left-color: var(--bevel-light);
&:hover {
background: var(--bevel-dark);
}
&:active {
background: var(--bevel-dark);
border-color: var(--bevel-light);
}
}
header {
display: flex;
align-items: center;
border-bottom: 2pt solid;
margin: 0 0 1em 0;
padding: 1ex;
justify-content: space-between;
}
#logo > img {
vertical-align: middle;
}
header .utils > * {
margin-left: 1ex;
}
.error {
display: flex;
position: relative;
background: rgba(255,0,0,0.2);
border: 1pt solid red;
justify-content: space-between;
align-items: center;
}
.error .btn-close,
.error .code {
background: #600;
color: white;
font-weight: bold;
border: none;
align-self: stretch;
padding: 1ex 1em;
}
.error .code {
order: 1;
display: flex;
align-items: center;
text-align: center;
}
.error .message {
order: 2;
padding: 1ex 2em;
}
.error .btn-close {
order: 3;
}
.sheets {
display: flex;
align-items: stretch;
}
.sheets > div {
margin: 0 1ex;
border: 1pt solid;
border-radius: 6pt;
}
.sheets .title {
text-align: center;
font-weight: bold;
font-size: large;
padding: 2pt 6pt;
background: rgba(127,127,127,0.5);
}
.sheets .section {
padding: 2pt 6pt 2pt 6pt;
font-weight: bold;
border-top: 1px dotted;
}
.sheets section {
margin: 2pt 6pt 6pt 6pt;
}
.sheets > *:last-child > table:last-child > tr:last-child > td {
border-bottom: none;
}
.notif {
display: inline-block;
position: relative;
}
.notif > div:first-child {
position: absolute;
min-width: 100%; height: 100%;
background: white;
opacity: 75%;
text-align: center;
}
.links > * { margin-left: 1ex; }
.links > *:first-child { margin-left: 0; }
@media (prefers-color-scheme: dark) {
.notif > div:first-child {
background: black;
}
}
.copy { font-size: small; }