aboutsummaryrefslogtreecommitdiff
path: root/server/wkfs/vaultfs/vault.go
blob: f7c136035a01493a95bb6f889db8e8a830ede2e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package vaultfs

import (
	"bytes"
	"errors"
	"os"
	"path"
	"time"

	"github.com/nsheridan/cashier/server/config"
	"github.com/nsheridan/cashier/server/helpers/vault"
	"go4.org/wkfs"
)

// Register the /vault/ filesystem as a well-known filesystem.
func Register(vc *config.Vault) {
	if vc == nil {
		registerBrokenFS(errors.New("no vault configuration found"))
		return
	}
	client, err := vault.NewClient(vc.Address, vc.Token)
	if err != nil {
		registerBrokenFS(err)
		return
	}
	wkfs.RegisterFS("/vault/", &vaultFS{
		client: client,
	})
}

func registerBrokenFS(err error) {
	wkfs.RegisterFS("/vault/", &vaultFS{
		err: err,
	})
}

type vaultFS struct {
	err    error
	client *vault.Client
}

// Open opens the named file for reading.
func (fs *vaultFS) Open(name string) (wkfs.File, error) {
	secret, err := fs.client.Read(name)
	if err != nil {
		return nil, err
	}
	return &file{
		name:   name,
		Reader: bytes.NewReader([]byte(secret)),
	}, nil
}

func (fs *vaultFS) Stat(name string) (os.FileInfo, error) { return fs.Lstat(name) }
func (fs *vaultFS) Lstat(name string) (os.FileInfo, error) {
	secret, err := fs.client.Read(name)
	if err != nil {
		return nil, err
	}
	return &statInfo{
		name: path.Base(name),
		size: int64(len(secret)),
	}, nil
}

func (fs *vaultFS) MkdirAll(path string, perm os.FileMode) error { return nil }

func (fs *vaultFS) OpenFile(name string, flag int, perm os.FileMode) (wkfs.FileWriter, error) {
	return nil, errors.New("not implemented")
}

type statInfo struct {
	name    string
	size    int64
	isDir   bool
	modtime time.Time
}

func (si *statInfo) IsDir() bool        { return si.isDir }
func (si *statInfo) ModTime() time.Time { return si.modtime }
func (si *statInfo) Mode() os.FileMode  { return 0644 }
func (si *statInfo) Name() string       { return path.Base(si.name) }
func (si *statInfo) Size() int64        { return si.size }
func (si *statInfo) Sys() interface{}   { return nil }

type file struct {
	name string
	*bytes.Reader
}

func (*file) Close() error   { return nil }
func (f *file) Name() string { return path.Base(f.name) }
func (f *file) Stat() (os.FileInfo, error) {
	return nil, errors.New("Stat not implemented on /vault/ files")
}