BlueGit

timfa bluegit

Files

bluegit / internal / backupserver / protocol / protocol.go

protocol.go

protocol.go 4.0 KiB Download Raw
1// Package protocol is het draadformaat tussen BlueGit en bluegit-backup.
2// Het moet gelijk blijven aan internal/backup in BlueGit (docs/BACKUP.md).
3package protocol
4
5import (
6 "crypto/hmac"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "net/http"
11 "path"
12 "strconv"
13 "strings"
14 "time"
15)
16
17// KeyPrefix staat voor elke Backupserver-Key.
18const KeyPrefix = "bgbk_"
19
20// Koppen van een ondertekend verzoek van BlueGit.
21const (
22 HeaderInstance = "X-BlueGit-Instance"
23 HeaderTimestamp = "X-BlueGit-Timestamp"
24 HeaderSignature = "X-BlueGit-Signature"
25)
26
27// MaxSkew is hoe ver de klokken uit elkaar mogen lopen.
28const MaxSkew = 5 * time.Minute
29
30// DBPath is het logische pad van de databasekopie.
31const DBPath = "state/bluegit.db"
32
33// Entry is één bestand in het manifest van BlueGit.
34type Entry struct {
35 Path string `json:"path"`
36 Size int64 `json:"size"`
37 MTime int64 `json:"mtime"`
38 Mode uint32 `json:"mode"`
39 SHA256 string `json:"sha256,omitempty"`
40}
41
42// Manifest is de volledige lijst op één moment.
43type Manifest struct {
44 Instance string `json:"instance_id"`
45 CreatedAt time.Time `json:"created_at"`
46 Files []Entry `json:"files"`
47}
48
49// Info is GET /api/v1/backup/info.
50type Info struct {
51 InstanceID string `json:"instance_id"`
52 BaseURL string `json:"base_url"`
53 ServerURL string `json:"server_url"`
54 ServerID string `json:"server_id"`
55 HasStorage bool `json:"has_storage"`
56}
57
58// SigningSecret leidt het HMAC-geheim af uit de key.
59func SigningSecret(key string) string {
60 s := sha256.Sum256([]byte("bluegit-backup-sign:" + key))
61 return hex.EncodeToString(s[:])
62}
63
64// Signature is hex(HMAC-SHA256(secret, METHOD \n PATH \n TS \n sha256hex(body))).
65func Signature(secret, method, p, ts string, body []byte) string {
66 sum := sha256.Sum256(body)
67 mac := hmac.New(sha256.New, []byte(secret))
68 mac.Write([]byte(strings.ToUpper(method) + "\n" + p + "\n" + ts + "\n" + hex.EncodeToString(sum[:])))
69 return hex.EncodeToString(mac.Sum(nil))
70}
71
72// Sign zet de koppen op een uitgaand verzoek (gebruikt in tests en door
73// BlueGit zelf).
74func Sign(req *http.Request, secret, instance string, body []byte, now time.Time) {
75 ts := strconv.FormatInt(now.Unix(), 10)
76 req.Header.Set(HeaderInstance, instance)
77 req.Header.Set(HeaderTimestamp, ts)
78 req.Header.Set(HeaderSignature, Signature(secret, req.Method, req.URL.Path, ts, body))
79}
80
81// Verify controleert een binnenkomend ondertekend verzoek.
82func Verify(r *http.Request, secret string, body []byte, now time.Time) error {
83 ts := r.Header.Get(HeaderTimestamp)
84 n, err := strconv.ParseInt(ts, 10, 64)
85 if err != nil {
86 return errors.New("timestamp ontbreekt")
87 }
88 d := now.Sub(time.Unix(n, 0))
89 if d < 0 {
90 d = -d
91 }
92 if d > MaxSkew {
93 return errors.New("timestamp te oud of in de toekomst")
94 }
95 want := Signature(secret, r.Method, r.URL.Path, ts, body)
96 if !hmac.Equal([]byte(want), []byte(r.Header.Get(HeaderSignature))) {
97 return errors.New("handtekening klopt niet")
98 }
99 return nil
100}
101
102var (
103 stateFiles = []string{"bluegit.db", "secret.key"}
104 stateDirs = []string{"ssh", "logos", "avatars"}
105 dataDirs = []string{"repos", "releases", "artifacts"}
106)
107
108// CleanLogical controleert een logisch pad zoals BlueGit dat doet. Een pad
109// buiten de bekende mappen komt nooit in de kopie.
110func CleanLogical(p string) (string, bool) {
111 if p == "" || strings.Contains(p, "\\") || strings.ContainsRune(p, 0) || strings.HasPrefix(p, "/") {
112 return "", false
113 }
114 c := path.Clean(p)
115 if c != p || c == "." {
116 return "", false
117 }
118 parts := strings.Split(c, "/")
119 for _, part := range parts {
120 if part == ".." || part == "." || part == "" {
121 return "", false
122 }
123 }
124 if len(parts) < 2 {
125 return "", false
126 }
127 switch parts[0] {
128 case "state":
129 if len(parts) == 2 && has(stateFiles, parts[1]) {
130 return c, true
131 }
132 if len(parts) >= 3 && has(stateDirs, parts[1]) {
133 return c, true
134 }
135 case "data":
136 if len(parts) >= 3 && has(dataDirs, parts[1]) && parts[2] != ".incoming" {
137 return c, true
138 }
139 }
140 return "", false
141}
142
143func has(list []string, v string) bool {
144 for _, x := range list {
145 if x == v {
146 return true
147 }
148 }
149 return false
150}