keyctl/cmd/keyctl/main.go

131 lines
3 KiB
Go

// Copyright (C) 2023 Marius Schellenberger
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"git.giftfish.de/ston1th/godrop/v2"
"git.giftfish.de/ston1th/keyctl/pkg/api"
"git.giftfish.de/ston1th/keyctl/pkg/cli"
"git.giftfish.de/ston1th/keyctl/pkg/db"
"git.giftfish.de/ston1th/keyctl/pkg/ssh"
"github.com/go-logr/logr"
)
var (
version string
listen string
socket string
path string
log logr.Logger
)
func usage() {
fmt.Printf(`keyctl %s:
supported subcommands:
keyctl server - starts a keyctl server
keyctl get - retrieve a key from the server
keyctl new - generates a new key (admin)
keyctl ls - list configured keys (admin)
keyctl req - list current key requests (admin)
keyctl approve - approve a key request (admin)
keyctl reject - reject a key request (admin)
keyctl del - delete a key (admin)
keyctl ssh login - request ssh access
keyctl ssh req - list current ssh requests (admin)
keyctl ssh approve - approve ssh access (admin)
keyctl ssh reject - reject ssh access (admin)
keyctl help - show this usage
`, version)
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
usage() // does not return
}
arg := os.Args[1]
switch arg {
case "new", "get", "ls", "req", "approve", "reject", "del":
cli.Run(arg) // does not return
case "server":
server() // does not return
case "ssh":
if len(os.Args) < 3 {
usage() // does not return
}
ssh.Run(os.Args[2]) // does not return
default:
usage() // does not return
}
}
func fatal(msg string, err error) {
log.Error(err, msg)
os.Exit(1)
}
func trimPath(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
s := a.Value.Any().(*slog.Source)
s.File = filepath.Base(s.File)
}
return a
}
func server() {
fs := flag.NewFlagSet("", flag.ExitOnError)
fs.StringVar(&listen, "listen", ":7070", "listen ip:port")
fs.StringVar(&socket, "socket", "keyctl.sock", "listen unix domain socket")
fs.StringVar(&path, "path", "/var/keyctl", "db storage dir")
fs.Parse(os.Args[2:])
h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
AddSource: true,
ReplaceAttr: trimPath,
})
l := logr.FromSlogHandler(h)
log = l.WithName("main")
log.Info("starting keyctl", "version", version)
err := godrop.PledgePromises("stdio rpath wpath cpath inet fattr flock unix unveil")
if err != nil {
fatal("init failed", err)
}
dbstore, err := db.New(l.WithName("db"), path)
if err != nil {
fatal("init failed", err)
}
srv, err := api.NewServer(l.WithName("srv"), listen, filepath.Join(path, socket), dbstore)
if err != nil {
fatal("init failed", err)
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
log.Info("keyctl shutdown initiated")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
srv.Shutdown(ctx)
cancel()
err = dbstore.Close()
exit := 0
if err != nil {
log.Error(err, "error closing db")
exit = 1
}
log.Info("keyctl shutdown completed")
os.Exit(exit)
}