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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
|
// rss-parrot-wrapper is the hosty ExecStart entrypoint for the rss-parrot app.
//
// rss-parrot is not configured via environment variables: it reads two JSONC
// files whose paths come from $CONFIG and $SECRETS, and it serves its web
// templates/assets from a "www/" directory resolved relative to the process
// working directory.
//
// This wrapper bridges the hosty model (env vars + a FUSE-backed mutable
// filesystem at $HOSTY_FS whose contents live in the app's SQLite database)
// onto rss-parrot's expectations:
//
// - Persistent state (secrets, birb identity keypair, blocked-feeds list,
// profiles, log) is kept under $HOSTY_FS, so it survives restarts and is
// stored inside the .hosty SQLite database.
// - On first run it generates the birb ActivityPub RSA keypair (encrypted
// with a generated passphrase) exactly the way rss-parrot's key_store does,
// plus random API/metrics secrets.
// - config.json and secrets.json are (re)generated on every start from the
// hosty env vars and the persisted state.
// - Finally it chdirs into the image directory that contains www/ (so the
// relative template/asset lookups work) and execs the real rss_parrot
// binary with CONFIG/SECRETS pointing at the generated files.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
// persistedIdentity is stored as JSON in $HOSTY_FS so the birb keypair and
// secrets remain stable across restarts.
type persistedIdentity struct {
BirbPrivKeyPass string `json:"birb_privkey_passphrase"`
MetricsAuth string `json:"metrics_auth"`
APIKey string `json:"api_key"`
BirbPubKey string `json:"birb_pub_key"`
BirbPrivKey string `json:"birb_priv_key"`
BirbPublished string `json:"birb_published"`
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "rss-parrot-wrapper: %v\n", err)
os.Exit(1)
}
}
func run() error {
port := os.Getenv("HOSTY_PORT")
if port == "" {
return fmt.Errorf("HOSTY_PORT not set")
}
portNum, err := strconv.ParseUint(port, 10, 32)
if err != nil {
return fmt.Errorf("HOSTY_PORT %q is not a number: %w", port, err)
}
dbFile := os.Getenv("HOSTY_DB")
if dbFile == "" {
return fmt.Errorf("HOSTY_DB not set")
}
fsDir := os.Getenv("HOSTY_FS")
if fsDir == "" {
return fmt.Errorf("HOSTY_FS not set")
}
// HOST is the public domain baked into all ActivityPub URLs.
host := os.Getenv("HOST")
if host == "" {
return fmt.Errorf("HOST config value not set (public domain for federation, e.g. parrot.example.com)")
}
logLevel := os.Getenv("LOG_LEVEL")
if logLevel == "" {
logLevel = "Info"
}
birbUser := os.Getenv("BIRB_USER")
if birbUser == "" {
birbUser = "birb"
}
// ALLOWED_REQUESTERS: optional comma/newline/space-separated list of fediverse
// monikers (@user@host) permitted to request new feeds. Empty = open to all.
allowedRequesters := os.Getenv("ALLOWED_REQUESTERS")
// Paths into the image are configured image-absolute (/usr/bin/rss_parrot)
// and resolved against $HOSTY_ROOT, which hosty sets to the image location:
// the extracted tree on the host in user mode, and "" in system mode, where
// RootDirectory= already makes the image the filesystem root. Resolving
// relative to the working directory instead would only work in user mode,
// since system mode sets no WorkingDirectory=.
hostyRoot := os.Getenv("HOSTY_ROOT")
wwwRoot := os.Getenv("RSS_PARROT_WWW_ROOT")
if wwwRoot == "" {
return fmt.Errorf("RSS_PARROT_WWW_ROOT not set (image dir containing www/)")
}
wwwRoot = imagePath(hostyRoot, wwwRoot)
rssParrotBin := os.Getenv("RSS_PARROT_BIN")
if rssParrotBin == "" {
return fmt.Errorf("RSS_PARROT_BIN not set (path to rss_parrot binary)")
}
// Must be absolute before the chdir below, since exec happens afterwards.
rssParrotBin, err = filepath.Abs(imagePath(hostyRoot, rssParrotBin))
if err != nil {
return fmt.Errorf("resolving RSS_PARROT_BIN: %w", err)
}
// Directories under $HOSTY_FS for mutable state.
profileDir := filepath.Join(fsDir, "profiles")
for _, d := range []string{profileDir} {
if err := os.MkdirAll(d, 0755); err != nil {
return fmt.Errorf("creating %s: %w", d, err)
}
}
// Load-or-create the persistent identity (birb keypair + secrets).
ident, err := loadOrCreateIdentity(filepath.Join(fsDir, "identity.json"), birbUser)
if err != nil {
return fmt.Errorf("identity: %w", err)
}
// Ensure a blocked-feeds file exists (empty by default).
blockedFeedsFile := filepath.Join(fsDir, "blocked_feeds.txt")
if _, statErr := os.Stat(blockedFeedsFile); os.IsNotExist(statErr) {
if err := os.WriteFile(blockedFeedsFile, []byte(""), 0644); err != nil {
return fmt.Errorf("creating blocked feeds file: %w", err)
}
}
// Write the allowlist file from ALLOWED_REQUESTERS (regenerated each start so
// config changes take effect). An empty list yields an empty file, which
// rss-parrot treats as "no allowlist configured" (open to all).
allowedRequestersFile := filepath.Join(fsDir, "allowed_requesters.txt")
if err := os.WriteFile(allowedRequestersFile, []byte(formatAllowlist(allowedRequesters)), 0644); err != nil {
return fmt.Errorf("writing allowed requesters file: %w", err)
}
// rss-parrot's logger always writes to stderr (see rss-parrot-server patch),
// which under systemd is captured by the journal. log_file is ignored; we set
// it to /dev/stderr for clarity.
// Build config.json.
config := map[string]any{
"log_file": "/dev/stderr",
"log_level": logLevel,
"service_port": uint(portNum),
"host": host,
"db_file": dbFile,
"blocked_feeds_file": blockedFeedsFile,
"allowed_requesters_file": allowedRequestersFile,
"profile_dir": profileDir,
"profile_keep_days": 7,
"cache_page_templates": true,
"update_schedule": map[string]int{
"day": 1,
"week": 6,
"weeks4": 24,
"older": 168,
},
"posts_min_count_kept": 20,
"posts_min_days_kept": 50,
"purge_wait_sec": 0,
"fallback_profile_pic": fmt.Sprintf("https://%s/assets/parrot-profile.png", host),
"birb": map[string]any{
"user": birbUser,
"published": ident.BirbPublished,
"manually_approves_follows": false,
"profile_pic": fmt.Sprintf("https://%s/assets/parrot-profile.png", host),
"header_pic": fmt.Sprintf("https://%s/assets/parrot-header.png", host),
"pub_key": ident.BirbPubKey,
"priv_key": ident.BirbPrivKey,
},
}
secrets := map[string]any{
"birb_privkey_passphrase": ident.BirbPrivKeyPass,
"api_keys": []string{ident.APIKey},
"metrics_auth": ident.MetricsAuth,
}
configPath := filepath.Join(fsDir, "config.json")
secretsPath := filepath.Join(fsDir, "secrets.json")
if err := writeJSON(configPath, config, 0644); err != nil {
return fmt.Errorf("writing config.json: %w", err)
}
if err := writeJSON(secretsPath, secrets, 0600); err != nil {
return fmt.Errorf("writing secrets.json: %w", err)
}
// rss-parrot resolves www/ relative to the working directory.
if err := os.Chdir(wwwRoot); err != nil {
return fmt.Errorf("chdir to www root %s: %w", wwwRoot, err)
}
env := append(os.Environ(),
"CONFIG="+configPath,
"SECRETS="+secretsPath,
)
fmt.Fprintf(os.Stderr, "rss-parrot-wrapper: starting rss_parrot on port %s (host=%s, cwd=%s)\n", port, host, wwwRoot)
// exec replaces this process so systemd tracks rss_parrot directly.
return syscall.Exec(rssParrotBin, []string{rssParrotBin}, env)
}
// imagePath resolves an image-absolute path (e.g. /usr/bin/rss_parrot) against
// the image root. An empty root means the image already is the filesystem root
// (system mode), so the path is returned unchanged. Paths that are not
// image-absolute are left alone, so an operator can still point a config value
// at something outside the image.
func imagePath(root, p string) string {
if root == "" || !strings.HasPrefix(p, "/") {
return p
}
return filepath.Join(root, p)
}
func writeJSON(path string, v any, mode os.FileMode) error {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, b, mode)
}
// formatAllowlist turns a comma/newline/space-separated list of monikers into a
// newline-separated file body (one entry per line).
func formatAllowlist(raw string) string {
fields := strings.FieldsFunc(raw, func(r rune) bool {
return r == ',' || r == '\n' || r == '\r' || r == ' ' || r == '\t'
})
if len(fields) == 0 {
return ""
}
return strings.Join(fields, "\n") + "\n"
}
// loadOrCreateIdentity reads the persisted identity or, on first run, generates
// a fresh birb keypair and random secrets and persists them.
func loadOrCreateIdentity(path, birbUser string) (*persistedIdentity, error) {
if data, err := os.ReadFile(path); err == nil {
var ident persistedIdentity
if err := json.Unmarshal(data, &ident); err != nil {
return nil, fmt.Errorf("parsing existing identity.json: %w", err)
}
return &ident, nil
} else if !os.IsNotExist(err) {
return nil, fmt.Errorf("reading identity.json: %w", err)
}
// First run: generate everything.
passphrase, err := randomToken(32)
if err != nil {
return nil, err
}
pubKey, privKey, err := makeKeyPair(passphrase)
if err != nil {
return nil, fmt.Errorf("generating birb keypair: %w", err)
}
metricsAuth, err := randomToken(32)
if err != nil {
return nil, err
}
apiKey, err := randomToken(32)
if err != nil {
return nil, err
}
ident := &persistedIdentity{
BirbPrivKeyPass: passphrase,
MetricsAuth: metricsAuth,
APIKey: apiKey,
BirbPubKey: pubKey,
BirbPrivKey: privKey,
BirbPublished: time.Now().UTC().Format(time.RFC3339),
}
if err := writeJSON(path, ident, 0600); err != nil {
return nil, fmt.Errorf("persisting identity.json: %w", err)
}
fmt.Fprintf(os.Stderr, "rss-parrot-wrapper: generated new birb identity for user %q\n", birbUser)
return ident, nil
}
func randomToken(nBytes int) (string, error) {
b := make([]byte, nBytes)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// makeKeyPair mirrors rss_parrot/logic.keyStore.MakeKeyPair: a 2048-bit RSA key,
// private half PKCS#1 + AES-256 encrypted PEM under the passphrase, public half
// PKCS#1 PEM. rss-parrot's key_store decrypts with x509.DecryptPEMBlock using
// the same passphrase.
func makeKeyPair(passphrase string) (pubKey, privKey string, err error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", "", err
}
keyRaw := x509.MarshalPKCS1PrivateKey(key)
//nolint:staticcheck // rss-parrot uses the deprecated encrypted-PEM API; must match.
encBlock, err := x509.EncryptPEMBlock(
rand.Reader, "RSA PRIVATE KEY", keyRaw,
[]byte(passphrase), x509.PEMCipherAES256)
if err != nil {
return "", "", err
}
privPEM := pem.EncodeToMemory(encBlock)
pubPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(&key.PublicKey),
})
return string(pubPEM), string(privPEM), nil
}
|