335 lines
10 KiB
Go
335 lines
10 KiB
Go
package app
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"unicode/utf16"
|
|
|
|
"github.com/Nwflower/reims-go/internal/atomicfile"
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
|
)
|
|
|
|
const (
|
|
secretPlaceholder = "{{secret}}"
|
|
secretTemplateMaxBytes = 1 << 20
|
|
secretMaxBytes = 4096
|
|
materializedSecretsDoc = "materialized-secrets.json"
|
|
)
|
|
|
|
// materializedSecret is one file the host wrote for a driver and must delete
|
|
// when the driver discards it or the VM goes away.
|
|
type materializedSecret struct {
|
|
VMKey string `json:"vm_key"`
|
|
PluginID string `json:"plugin_id"`
|
|
Setting string `json:"setting"`
|
|
Path string `json:"path"`
|
|
}
|
|
|
|
type materializedSecretsFile struct {
|
|
Entries []materializedSecret `json:"entries"`
|
|
}
|
|
|
|
var materializedMu sync.Mutex
|
|
|
|
// secretSource returns the decrypted value of one secret setting. Only the
|
|
// host calls it; the value never goes back to a plugin.
|
|
type secretSource func(pluginID, vmKey, setting string) (string, error)
|
|
|
|
func (a *App) secretHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
|
if mgr == nil || mgr.Broker() == nil {
|
|
return nil
|
|
}
|
|
broker := mgr.Broker()
|
|
source := func(pid, vmKey, setting string) (string, error) {
|
|
value, err := mgr.SecretSetting(pid, vmKey, setting)
|
|
if err != nil {
|
|
// A secret declared at app scope serves every VM.
|
|
if appValue, appErr := mgr.SecretSetting(pid, "", setting); appErr == nil {
|
|
return appValue, nil
|
|
}
|
|
}
|
|
return value, err
|
|
}
|
|
return map[string]plugin.RPCRequestHandler{
|
|
"host/secret.materialize": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
|
|
return a.materializeSecret(mgr, broker, source, pluginID, raw)
|
|
}),
|
|
"host/secret.discard": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
|
|
return a.discardSecret(mgr, broker, pluginID, raw)
|
|
}),
|
|
}
|
|
}
|
|
|
|
func encodeSecret(secret, format string) (string, error) {
|
|
switch format {
|
|
case "", "raw":
|
|
return secret, nil
|
|
case "xml":
|
|
var buf bytes.Buffer
|
|
if err := xml.EscapeText(&buf, []byte(secret)); err != nil {
|
|
return "", err
|
|
}
|
|
return buf.String(), nil
|
|
case "base64-utf16le":
|
|
units := utf16.Encode([]rune(secret))
|
|
raw := make([]byte, 0, len(units)*2)
|
|
for _, u := range units {
|
|
raw = append(raw, byte(u), byte(u>>8))
|
|
}
|
|
return base64.StdEncoding.EncodeToString(raw), nil
|
|
}
|
|
return "", fmt.Errorf("unsupported secret format %q (use raw, xml or base64-utf16le)", format)
|
|
}
|
|
|
|
// materializeSecret fills template with a secret setting and writes the
|
|
// result into the VM's folder. The plugin gets back only the path.
|
|
func (a *App) materializeSecret(kernel hostMethodHost, broker *plugin.Broker, source secretSource, pluginID string, raw json.RawMessage) (any, error) {
|
|
req, err := decodeHostParams[pluginproto.SecretMaterializeParams](kernel, pluginID, "host/secret.materialize", raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if strings.TrimSpace(req.Setting) == "" {
|
|
return nil, errors.New("secret setting name is required")
|
|
}
|
|
if len(req.Template) == 0 || len(req.Template) > secretTemplateMaxBytes || !strings.Contains(req.Template, secretPlaceholder) {
|
|
return nil, fmt.Errorf("template must hold %s and be at most %d bytes", secretPlaceholder, secretTemplateMaxBytes)
|
|
}
|
|
driverID, err := broker.ResolveRefDriver(pluginID, req.Ref.DriverID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if driverID == "" {
|
|
return nil, fmt.Errorf("plugin %q declares no driver", pluginID)
|
|
}
|
|
vm, err := a.resolveVMInfo(driverID, strings.TrimSpace(req.Ref.Name))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if driver.CanonicalDriverID(vm.DriverID) != driver.CanonicalDriverID(driverID) {
|
|
return nil, fmt.Errorf("VM %q does not belong to driver %q", vm.Name, driverID)
|
|
}
|
|
if strings.TrimSpace(vm.Directory) == "" {
|
|
return nil, fmt.Errorf("VM %q has no folder to write into", vm.Name)
|
|
}
|
|
dest := strings.TrimSpace(req.Dest)
|
|
if dest == "" {
|
|
return nil, errors.New("dest is required")
|
|
}
|
|
if !filepath.IsAbs(dest) {
|
|
dest = filepath.Join(vm.Directory, dest)
|
|
}
|
|
dest = filepath.Clean(dest)
|
|
if !pathInside(vm.Directory, dest) {
|
|
return nil, errors.New("dest must stay inside the VM folder")
|
|
}
|
|
if st, err := os.Lstat(dest); err == nil && (st.Mode()&os.ModeSymlink != 0 || st.IsDir()) {
|
|
return nil, errors.New("dest must be a plain file path")
|
|
}
|
|
secret, err := source(pluginID, vm.Ref().Key(), req.Setting)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { secret = "" }()
|
|
if len(secret) == 0 || len(secret) > secretMaxBytes {
|
|
return nil, fmt.Errorf("secret must hold between 1 and %d bytes", secretMaxBytes)
|
|
}
|
|
encoded, err := encodeSecret(secret, req.Format)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
content := strings.ReplaceAll(req.Template, secretPlaceholder, encoded)
|
|
// Record the file first: a crash in between leaves a record without a file,
|
|
// never a secret file nobody cleans up.
|
|
if err := a.trackMaterializedSecret(materializedSecret{VMKey: vm.Ref().Key(), PluginID: pluginID, Setting: req.Setting, Path: dest}); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := writeSecretFile(dest, []byte(content)); err != nil {
|
|
return nil, err
|
|
}
|
|
// The audit line names the setting and its size, never the value.
|
|
broker.Audit(pluginID, "SECRET_MATERIALIZE", fmt.Sprintf("vm=%s setting=%s bytes=%d", vm.Ref().Key(), req.Setting, len(secret)))
|
|
return pluginproto.SecretMaterializeResult{Path: dest}, nil
|
|
}
|
|
|
|
func writeSecretFile(dest string, content []byte) error {
|
|
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
|
return err
|
|
}
|
|
return atomicfile.Write(dest, content, 0o600)
|
|
}
|
|
|
|
func (a *App) materializedSecretsPath() string {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
if a.cfg == nil {
|
|
return ""
|
|
}
|
|
return filepath.Join(a.cfg.DataRoot, "plugins", materializedSecretsDoc)
|
|
}
|
|
|
|
func loadMaterializedSecrets(path string) (materializedSecretsFile, error) {
|
|
var doc materializedSecretsFile
|
|
raw, err := os.ReadFile(path)
|
|
if os.IsNotExist(err) {
|
|
return doc, nil
|
|
}
|
|
if err != nil {
|
|
return doc, err
|
|
}
|
|
if err := json.Unmarshal(raw, &doc); err != nil {
|
|
return materializedSecretsFile{}, fmt.Errorf("read %s: %w", materializedSecretsDoc, err)
|
|
}
|
|
return doc, nil
|
|
}
|
|
|
|
func saveMaterializedSecrets(path string, doc materializedSecretsFile) error {
|
|
if len(doc.Entries) == 0 {
|
|
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
return err
|
|
}
|
|
return atomicfile.WriteJSON(path, doc, 0o600)
|
|
}
|
|
|
|
func samePath(a, b string) bool { return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) }
|
|
|
|
// trackMaterializedSecret records entry. It refuses a file that already exists
|
|
// without a record of the same VM and plugin: the host would later delete it.
|
|
func (a *App) trackMaterializedSecret(entry materializedSecret) error {
|
|
path := a.materializedSecretsPath()
|
|
if path == "" {
|
|
return errors.New("data folder is unavailable")
|
|
}
|
|
materializedMu.Lock()
|
|
defer materializedMu.Unlock()
|
|
doc, err := loadMaterializedSecrets(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for i := range doc.Entries {
|
|
if samePath(doc.Entries[i].Path, entry.Path) {
|
|
if doc.Entries[i].VMKey != entry.VMKey || doc.Entries[i].PluginID != entry.PluginID {
|
|
return errors.New("dest holds a secret file of another VM or plugin")
|
|
}
|
|
doc.Entries[i] = entry
|
|
return saveMaterializedSecrets(path, doc)
|
|
}
|
|
}
|
|
if _, err := os.Lstat(entry.Path); err == nil {
|
|
return errors.New("dest already exists")
|
|
} else if !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
doc.Entries = append(doc.Entries, entry)
|
|
return saveMaterializedSecrets(path, doc)
|
|
}
|
|
|
|
// wipeFile overwrites a secret file and deletes it. A missing file is fine.
|
|
func wipeFile(path string) error {
|
|
st, err := os.Lstat(path)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if st.Mode().IsRegular() {
|
|
f, err := os.OpenFile(path, os.O_WRONLY, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = f.Write(make([]byte, st.Size()))
|
|
if err := errors.Join(err, f.Close()); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return os.Remove(path)
|
|
}
|
|
|
|
// removeMaterialized deletes the tracked files chosen by match and drops
|
|
// their records. A file it cannot delete keeps its record for the next try.
|
|
// It returns how many files it deleted.
|
|
func (a *App) removeMaterialized(match func(materializedSecret) bool) (int, error) {
|
|
path := a.materializedSecretsPath()
|
|
if path == "" {
|
|
return 0, nil
|
|
}
|
|
materializedMu.Lock()
|
|
defer materializedMu.Unlock()
|
|
doc, err := loadMaterializedSecrets(path)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
kept := doc.Entries[:0:0]
|
|
removed := 0
|
|
var errs []error
|
|
for _, e := range doc.Entries {
|
|
if match(e) {
|
|
err := wipeFile(e.Path)
|
|
if err == nil {
|
|
removed++
|
|
continue
|
|
}
|
|
errs = append(errs, err)
|
|
}
|
|
kept = append(kept, e)
|
|
}
|
|
if removed > 0 {
|
|
doc.Entries = kept
|
|
errs = append(errs, saveMaterializedSecrets(path, doc))
|
|
}
|
|
return removed, errors.Join(errs...)
|
|
}
|
|
|
|
// discardSecret deletes the files a plugin materialized for one VM, or just
|
|
// the one named by path.
|
|
func (a *App) discardSecret(kernel hostMethodHost, broker *plugin.Broker, pluginID string, raw json.RawMessage) (any, error) {
|
|
req, err := decodeHostParams[pluginproto.SecretDiscardParams](kernel, pluginID, "host/secret.discard", raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
driverID, err := broker.ResolveRefDriver(pluginID, req.Ref.DriverID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if driverID == "" {
|
|
return nil, fmt.Errorf("plugin %q declares no driver", pluginID)
|
|
}
|
|
vmKey := driver.NewVMRef(driverID, strings.TrimSpace(req.Ref.Name)).Key()
|
|
path := strings.TrimSpace(req.Path)
|
|
n, err := a.removeMaterialized(func(e materializedSecret) bool {
|
|
return e.PluginID == pluginID && e.VMKey == vmKey && (path == "" || samePath(e.Path, path))
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
broker.Audit(pluginID, "SECRET_DISCARD", fmt.Sprintf("vm=%s files=%d", vmKey, n))
|
|
return pluginproto.SecretDiscardResult{Removed: n}, nil
|
|
}
|
|
|
|
// discardMaterializedSecretsForVM deletes every secret file of a VM that is
|
|
// being deleted or has disappeared.
|
|
func (a *App) discardMaterializedSecretsForVM(vmKey string) {
|
|
if strings.TrimSpace(vmKey) == "" {
|
|
return
|
|
}
|
|
if _, err := a.removeMaterialized(func(e materializedSecret) bool { return e.VMKey == vmKey }); err != nil {
|
|
a.emitLog("plugin", "Could not clean up secret files of "+vmKey+": "+err.Error())
|
|
}
|
|
}
|