/
main.go
203 lines (184 loc) · 6.46 KB
/
main.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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
env "github.com/caarlos0/env/v6"
jitsi "github.com/jitsi/jitsi-slack"
stats "github.com/jitsi/prometheus-stats"
"github.com/justinas/alice"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
)
type appCfg struct {
// Slack App/OAuth client configuration
SlackSigningSecret string `env:"SLACK_SIGNING_SECRET,required"`
SlackClientID string `env:"SLACK_CLIENT_ID,required"`
SlackClientSecret string `env:"SLACK_CLIENT_SECRET,required"`
SlackAppID string `env:"SLACK_APP_ID,required"`
SlackAppSharableURL string `env:"SLACK_APP_SHARABLE_URL,required"`
// jitsi configuration
JitsiTokenSigningKey string `env:"JITSI_TOKEN_SIGNING_KEY,required"`
JitsiTokenKid string `env:"JITSI_TOKEN_KID,required"`
JitsiTokenIssuer string `env:"JITSI_TOKEN_ISS,required"`
JitsiTokenAudience string `env:"JITSI_TOKEN_AUD,required"`
JitsiConferenceHost string `env:"JITSI_CONFERENCE_HOST,required"`
// dynamodb configuration
TokenTable string `env:"TOKEN_TABLE,required"`
ServerCfgTable string `env:"SERVER_CFG_TABLE,required"`
DynamoRegion string `env:"DYNAMO_REGION,required"`
// application configuration
HTTPPort string `env:"HTTP_PORT" envDefault:"8080"`
StatsPort string `env:"STATS_PORT" envDefault:"0"`
}
var (
log = zerolog.New(os.Stdout).With().
Timestamp().
Logger()
)
func main() {
// Extract app configuration from env variables.
app := appCfg{}
err := env.Parse(&app)
if err != nil {
log.Fatal().Err(err).Msg("service is misconfigured")
}
// set up acces to dynamodb stores
cfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(app.DynamoRegion))
if err != nil {
log.Fatal().Err(err).Msg("cannot start service w/o aws session")
}
svc := dynamodb.NewFromConfig(cfg)
tokenStore := jitsi.TokenStore{
TableName: app.TokenTable,
DB: svc,
}
authTenantSupportTest := func(srv string) bool {
if srv == app.JitsiConferenceHost {
return true
}
return false
}
srvCfgStore := jitsi.ServerCfgStore{
TableName: app.ServerCfgTable,
DB: svc,
DefaultServer: app.JitsiConferenceHost,
TenantScopedURLs: authTenantSupportTest,
AuthenticatedURLSupport: authTenantSupportTest,
}
// Setup handlers for slash commands.
slashCmd := jitsi.SlashCommandHandlers{
MeetingGenerator: &jitsi.MeetingGenerator{
ServerConfigReader: &srvCfgStore,
MeetingTokenGenerator: jitsi.TokenGenerator{
Lifetime: time.Hour * 24,
PrivateKey: app.JitsiTokenSigningKey,
Issuer: app.JitsiTokenIssuer,
Audience: app.JitsiTokenAudience,
Kid: app.JitsiTokenKid,
},
},
SlackSigningSecret: app.SlackSigningSecret,
SharableURL: app.SlackAppSharableURL,
TokenReader: &tokenStore,
TokenWriter: &tokenStore,
ServerConfigWriter: &srvCfgStore,
}
evHandle := jitsi.EventHandler{
SlackSigningSecret: app.SlackSigningSecret,
TokenWriter: &tokenStore,
}
oauthHandler := jitsi.SlackOAuthHandlers{
ClientID: app.SlackClientID,
ClientSecret: app.SlackClientSecret,
AppID: app.SlackAppID,
TokenWriter: &tokenStore,
}
// Create an http mux and a server for that mux.
handler := http.NewServeMux()
addr := fmt.Sprintf(":%s", app.HTTPPort)
srv := &http.Server{
// It's important to set http server timeouts for the publicly available service api.
// 5 seconds between when connection is accepted to when the body is fully reaad.
ReadTimeout: 5 * time.Second,
// 10 seconds from end of request headers read to end of response write.
WriteTimeout: 10 * time.Second,
// 120 seconds for an idle KeeP-Alive connection.
IdleTimeout: 120 * time.Second,
Addr: addr,
Handler: handler,
}
// Create a middleware chain setup to log http access and inject
// a logger into the request context.
chain := alice.New(
hlog.NewHandler(log),
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
hlog.FromRequest(r).Info().
Str("method", r.Method).
Str("url", r.URL.String()).
Int("status", status).
Int("size", size).
Dur("duration", duration).
Msg("")
}),
hlog.RemoteAddrHandler("ip"),
hlog.UserAgentHandler("user_agent"),
hlog.RefererHandler("referer"),
hlog.RequestIDHandler("req_id", "Request-Id"),
)
// Wrap handlers with middleware chain.
slashJitsi := stats.WrapHTTPHandler("slashJitsi", chain.ThenFunc(slashCmd.Jitsi))
slackOAuth := stats.WrapHTTPHandler("slackOAuth", chain.ThenFunc(oauthHandler.Auth))
slackEvent := stats.WrapHTTPHandler("slackEvent", chain.ThenFunc(evHandle.Handle))
// wrap metrics collection and publish endpoint
statsPort, err := strconv.ParseInt(app.StatsPort, 10, 16)
if err != nil || statsPort > 65535 || statsPort < 0 {
log.Fatal().Err(err).Msg("bad port for stats server")
}
if statsPort > 0 {
slashJitsi = stats.WrapHTTPHandler("slashJitsi", slashJitsi)
slackOAuth = stats.WrapHTTPHandler("slackOAuth", slackOAuth)
slackEvent = stats.WrapHTTPHandler("slackEvent", slackEvent)
http.Handle("/metrics", promhttp.Handler())
}
// Add routes and wrapped handlers to mux.
handler.Handle("/slash/jitsi", slashJitsi) // slash command handler
handler.Handle("/slack/auth", slackOAuth) // handles "Add to Slack"
handler.Handle("/slack/event", slackEvent) // handles workspace removal of app
handler.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "health check passed")
})
// Register stats handler on default http handler.
http.Handle("/metrics", promhttp.Handler())
// Start the server and set it up for graceful shutdown.
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
go func() {
log.Info().Msgf("listening on :%s", app.HTTPPort)
err = srv.ListenAndServe()
log.Fatal().Err(err).Msg("shutting server down")
}()
// Start stats server
if statsPort > 0 {
go func() {
log.Info().Msgf("stats listening on :%s", app.StatsPort)
log.Fatal().Err(http.ListenAndServe(":"+app.StatsPort, nil)).Msg("shutting stat server down")
}()
}
<-stop
log.Info().Msg("shutting server down")
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = srv.Shutdown(ctx)
if err != nil {
log.Fatal().Err(err).Msg("unable to shutdown cleanly")
}
}