-
Notifications
You must be signed in to change notification settings - Fork 9
/
app.go
265 lines (234 loc) · 6.31 KB
/
app.go
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
package fedbox
import (
"context"
"net/http"
"os"
"path/filepath"
"syscall"
"git.sr.ht/~mariusor/lw"
w "git.sr.ht/~mariusor/wrapper"
vocab "github.com/go-ap/activitypub"
"github.com/go-ap/auth"
"github.com/go-ap/cache"
"github.com/go-ap/client"
"github.com/go-ap/errors"
ap "github.com/go-ap/fedbox/activitypub"
"github.com/go-ap/fedbox/internal/config"
st "github.com/go-ap/fedbox/storage"
"github.com/go-ap/processing"
"github.com/go-chi/chi/v5"
"github.com/openshift/osin"
)
func init() {
// set local path typer to validate collections
processing.Typer = pathTyper{}
}
type LogFn func(string, ...any)
type canStore = cache.CanStore
type FedBOX struct {
R chi.Router
auth *auth.Server
conf config.Options
self vocab.Service
client client.C
storage st.FullStorage
version string
caches canStore
keyGenerator func(act *vocab.Actor) error
stopFn func()
logger lw.Logger
}
var (
emptyFieldsLogFn = func(lw.Ctx, string, ...any) {}
emptyLogFn = func(string, ...any) {}
emptyStopFn = func() {}
InfoLogFn = func(l lw.Logger) func(lw.Ctx, string, ...any) {
if l == nil {
return emptyFieldsLogFn
}
return func(f lw.Ctx, s string, p ...any) { l.WithContext(f).Infof(s, p...) }
}
ErrLogFn = func(l lw.Logger) func(lw.Ctx, string, ...any) {
if l == nil {
return emptyFieldsLogFn
}
return func(f lw.Ctx, s string, p ...any) { l.WithContext(f).Errorf(s, p...) }
}
)
var InternalIRI = vocab.IRI("https://fedbox/")
// New instantiates a new FedBOX instance
func New(l lw.Logger, ver string, conf config.Options, db st.FullStorage) (*FedBOX, error) {
if db == nil {
return nil, errors.Newf("invalid storage")
}
if conf.BaseURL == "" {
return nil, errors.Newf("invalid empty BaseURL config")
}
app := FedBOX{
version: ver,
conf: conf,
R: chi.NewRouter(),
storage: db,
stopFn: emptyStopFn,
logger: l,
caches: cache.New(conf.RequestCache),
}
if metaSaver, ok := db.(st.MetadataTyper); ok {
keysType := "ED25519"
if conf.MastodonCompatible {
keysType = "RSA"
}
l.Infof("Setting actor key generator %T[%s]", metaSaver, keysType)
app.keyGenerator = AddKeyToPerson(metaSaver, keysType)
}
errors.IncludeBacktrace = conf.LogLevel == lw.TraceLevel
selfIRI := ap.DefaultServiceIRI(conf.BaseURL)
app.self, _ = ap.LoadActor(db, selfIRI)
if app.self.ID != selfIRI {
app.infFn("trying to bootstrap the instance's self service")
if saver, ok := db.(st.CanBootstrap); ok {
app.self = ap.Self(selfIRI)
if err := saver.CreateService(app.self); err != nil {
app.errFn("unable to save the instance's self service: %s", err)
return nil, err
}
}
keysType := KeyTypeED25519
if conf.MastodonCompatible {
keysType = KeyTypeRSA
}
if saver, ok := db.(st.MetadataTyper); ok {
if err := AddKeyToPerson(saver, keysType)(&app.self); err != nil {
app.errFn("unable to save the instance's self service public key: %s", err)
}
}
}
app.client = *client.New(
client.WithLogger(l.WithContext(lw.Ctx{"log": "client"})),
client.SkipTLSValidation(!conf.Env.IsProd()),
)
as, err := auth.New(
auth.WithURL(conf.BaseURL),
auth.WithStorage(app.storage),
auth.WithClient(&app.client),
auth.WithLogger(l.WithContext(lw.Ctx{"log": "osin"})),
)
if err != nil {
l.Warnf(err.Error())
return nil, err
}
app.auth = as
app.R.Group(app.Routes())
return &app, err
}
func (f *FedBOX) Config() config.Options {
return f.conf
}
func (f *FedBOX) Storage() st.FullStorage {
return f.storage
}
// Stop
func (f *FedBOX) Stop() {
if st, ok := f.storage.(osin.Storage); ok {
st.Close()
}
f.stopFn()
}
func (f *FedBOX) reload() (err error) {
f.conf, err = config.LoadFromEnv(f.conf.Env, f.conf.TimeOut)
f.caches.Delete()
return err
}
func (f *FedBOX) actorFromRequest(r *http.Request) vocab.Actor {
act, err := f.auth.LoadActorFromAuthHeader(r)
if err != nil {
f.logger.Errorf("unable to load an authorized Actor from request: %+s", err)
}
return act
}
// Run is the wrapper for starting the web-server and handling signals
func (f *FedBOX) Run(c context.Context) error {
// Create a deadline to wait for.
ctx, cancelFn := context.WithTimeout(c, f.conf.TimeOut)
defer cancelFn()
sockType := ""
setters := []w.SetFn{w.Handler(f.R)}
if f.conf.Secure {
if len(f.conf.CertPath)+len(f.conf.KeyPath) > 0 {
setters = append(setters, w.WithTLSCert(f.conf.CertPath, f.conf.KeyPath))
} else {
f.conf.Secure = false
}
}
if f.conf.Listen == "systemd" {
sockType = "Systemd"
setters = append(setters, w.OnSystemd())
} else if filepath.IsAbs(f.conf.Listen) {
dir := filepath.Dir(f.conf.Listen)
if _, err := os.Stat(dir); err == nil {
sockType = "socket"
setters = append(setters, w.OnSocket(f.conf.Listen))
defer func() {
if err := os.RemoveAll(f.conf.Listen); err != nil {
f.logger.Errorf("Failed cleaning up: %s", err)
}
}()
}
} else {
sockType = "TCP"
setters = append(setters, w.OnTCP(f.conf.Listen))
}
logCtx := lw.Ctx{
"URL": f.conf.BaseURL,
"version": f.version,
"listenOn": f.conf.Listen,
"TLS": f.conf.Secure,
}
if sockType != "" {
logCtx["listenOn"] = f.conf.Listen + "[" + sockType + "]"
}
// Get start/stop functions for the http server
srvRun, srvStop := w.HttpServer(setters...)
logger := f.logger.WithContext(logCtx)
logger.Infof("Started")
f.stopFn = func() {
if err := srvStop(ctx); err != nil {
logger.Errorf(err.Error())
}
}
defer f.stopFn()
exit := w.RegisterSignalHandlers(w.SignalHandlers{
syscall.SIGHUP: func(_ chan<- int) {
logger.Infof("SIGHUP received, reloading configuration")
if err := f.reload(); err != nil {
logger.Errorf("Failed: %+s", err.Error())
}
},
syscall.SIGINT: func(exit chan<- int) {
logger.Infof("SIGINT received, stopping")
exit <- 0
},
syscall.SIGTERM: func(exit chan<- int) {
logger.Infof("SIGITERM received, force stopping")
exit <- 0
},
syscall.SIGQUIT: func(exit chan<- int) {
logger.Infof("SIGQUIT received, force stopping with core-dump")
exit <- 0
},
}).Exec(ctx, srvRun)
if exit == 0 {
logger.Infof("Shutting down")
}
return nil
}
func (f *FedBOX) infFn(s string, p ...any) {
if f.logger != nil {
f.logger.Infof(s, p...)
}
}
func (f *FedBOX) errFn(s string, p ...any) {
if f.logger != nil {
f.logger.Errorf(s, p...)
}
}