summaryrefslogtreecommitdiff
path: root/stdlib/backups/borg/server.go
blob: 29794d83bc70e61242aebb8f29d1299deb946853 (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
96
97
98
99
100
101
102
103
104
105
106
107
package borg

import (
	"log/slog"
	"path/filepath"

	gonf "git.adyxax.org/adyxax/gonf/v2/pkg"
)

type BorgServer struct {
	chain   []gonf.Promise
	clients map[string][]byte // name -> publicKey
	path    string
	user    string
	status  gonf.Status
}

var borgServer *BorgServer = nil

func (b *BorgServer) IfRepaired(p ...gonf.Promise) gonf.Promise {
	b.chain = append(b.chain, p...)
	return b
}

func (b *BorgServer) Promise() *BorgServer {
	if b.status == gonf.DECLARED {
		b.status = gonf.PROMISED
		gonf.MakeCustomPromise(b).Promise()
	}
	return b
}

func (b *BorgServer) Resolve() {
	b.status = gonf.KEPT
	// Borg user
	user := gonf.User(gonf.UserData{
		HomeDir: b.path,
		Name:    "borg",
		System:  true,
	})
	user.Resolve()
	switch user.Status() {
	case gonf.BROKEN:
		b.status = gonf.BROKEN
		return
	case gonf.REPAIRED:
		b.status = gonf.REPAIRED
	}
	// borg package
	switch installBorgPackage() {
	case gonf.BROKEN:
		b.status = gonf.BROKEN
		return
	case gonf.REPAIRED:
		b.status = gonf.REPAIRED
	}
	// authorized_keys
	borgDir := gonf.ModeUserGroup(0700, "borg", "borg")
	borgRO := gonf.ModeUserGroup(0400, "borg", "borg")
	file := gonf.File(filepath.Join(b.path, ".ssh/authorized_keys")).
		DirectoriesPermissions(borgDir).
		Permissions(borgRO)
	authorizedKeys := ""
	// we sort the names so that the file contents are stable
	names := make([]string, len(b.clients)-1)
	for name := range b.clients {
		names = append(names, name)
	}
	for _, name := range names {
		key := b.clients[name]
		authorizedKeys += "command=\"borg serve --restrict-to-path " + filepath.Join(b.path, name) + "\",restrict " + string(key) + "\n"
	}
	file.Contents(authorizedKeys).Resolve()
	switch file.Status() {
	case gonf.BROKEN:
		b.status = gonf.BROKEN
		return
	case gonf.REPAIRED:
		b.status = gonf.REPAIRED
	}
}

func (b BorgServer) Status() gonf.Status {
	return b.status
}

func Server() *BorgServer {
	if borgServer == nil {
		borgServer = &BorgServer{
			chain:   nil,
			clients: make(map[string][]byte),
			path:    "/srv/borg/",
			user:    "borg",
			status:  gonf.DECLARED,
		}
	}
	return borgServer
}

func (b *BorgServer) Add(name string, publicKey []byte) *BorgServer {
	if _, ok := b.clients[name]; ok {
		slog.Debug("Duplicate name for BorgServer", "name", name)
		panic("Duplicate name for BorgServer")
	}
	b.clients[name] = publicKey
	return b
}