-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
224 lines (189 loc) · 5.46 KB
/
server.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
package server
import (
"context"
"encoding/hex"
"net"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"github.com/nrc-no/notcore/internal/db"
"github.com/nrc-no/notcore/internal/locales"
"github.com/nrc-no/notcore/internal/logging"
"github.com/nrc-no/notcore/internal/server/middleware"
"go.uber.org/zap"
)
type AzuriteOptions struct {
accountName string
accountKey string
containerName string
}
func (o Options) New(ctx context.Context) (*Server, error) {
l := logging.NewLogger(ctx)
if err := o.validate(); err != nil {
l.Error("invalid options", zap.Error(err))
return nil, err
}
sqlDb, err := sqlx.ConnectContext(ctx, o.DatabaseDriver, o.DatabaseDSN)
if err != nil {
l.Error("failed to connect to db", zap.Error(err))
return nil, err
}
// TODO: make this configurable at some point
sqlDb.SetMaxIdleConns(5)
sqlDb.SetMaxOpenConns(10)
sqlDb.SetConnMaxLifetime(time.Minute * 20)
if err := db.Migrate(context.Background(), sqlDb); err != nil {
l.Error("failed to migrate database", zap.Error(err))
return nil, err
}
if err := locales.LoadTranslations(); err != nil {
l.Error("failed to load translations", zap.Error(err))
return nil, err
}
// create the healthz db repository
healthzRepo := db.NewHealthzRepo(sqlDb)
// create the individual db repository
individualRepo := db.NewIndividualRepo(sqlDb)
// create the country db repository
countryRepo := db.NewCountryRepo(sqlDb)
s := &Server{address: o.Address}
// parse html templates
tpl, err := parseTemplates(o.LoginURL, o.TokenRefreshURL, o.TokenRefreshInterval)
if err != nil {
l.Error("failed to parse templates", zap.Error(err))
return nil, err
}
// create the oidc provider
oidcProvider, err := oidc.NewProvider(ctx, o.OIDCIssuerURL)
if err != nil {
l.Error("failed to get oidc provider", zap.Error(err))
return nil, err
}
// create the id token verifier
oidcVerifier := oidcProvider.Verifier(&oidc.Config{
ClientID: o.OAuthClientID,
SupportedSigningAlgs: []string{oidc.RS256},
})
idTokenVerifier := middleware.NewIDTokenVerifier(oidcVerifier)
hashKey1, err := hex.DecodeString(o.HashKey1)
if err != nil {
l.Error("failed to decode hash key 1", zap.Error(err))
return nil, err
}
blockKey1, err := hex.DecodeString(o.BlockKey1)
if err != nil {
l.Error("failed to decode block key 1", zap.Error(err))
return nil, err
}
hashKey2, err := hex.DecodeString(o.HashKey2)
if err != nil {
l.Error("failed to decode hash key 2", zap.Error(err))
return nil, err
}
blockKey2, err := hex.DecodeString(o.BlockKey2)
if err != nil {
l.Error("failed to decode block key 2", zap.Error(err))
return nil, err
}
azuriteOptions := AzuriteOptions{
accountName: o.AzuriteAccountName,
accountKey: o.AzuriteAccountKey,
containerName: o.DownloadsContainerName,
}
azureBlobClient, err := getAzureBlobStorageClient(ctx, o.AzureBlobStorageURL, azuriteOptions, o.UserAssignedIdentityClientId)
if err != nil {
l.Error("failed to get azure blob storage client", zap.Error(err))
return nil, err
}
sessionStore := sessions.NewCookieStore(
hashKey1,
blockKey1,
hashKey2,
blockKey2,
)
sessionStore.MaxAge(60 * 60) // 1 hour
sessionStore.Options.HttpOnly = true
sessionStore.Options.Secure = true
sessionStore.Options.SameSite = http.SameSiteStrictMode
// build the router
s.router = buildRouter(
healthzRepo,
individualRepo,
countryRepo,
o.JwtGroups,
o.IdTokenAuthHeaderName,
o.IdTokenAuthHeaderFormat,
o.AccessTokenHeaderName,
o.AccessTokenHeaderFormat,
o.LoginURL,
o.EnableBetaFeatures,
oidcProvider,
idTokenVerifier,
sessionStore,
tpl,
azureBlobClient,
o.DownloadsContainerName,
)
return s, nil
}
type Server struct {
address string
listener net.Listener
router *mux.Router
}
func (s *Server) Start(ctx context.Context) error {
l := logging.NewLogger(ctx)
l.Info("starting server")
var err error
s.listener, err = net.Listen("tcp", s.address)
if err != nil {
return err
}
l.Info("listening on " + s.listener.Addr().String())
go func() {
<-ctx.Done()
l.Info("stopping server")
s.listener.Close()
}()
err = http.Serve(s.listener, s.router)
l.Info("server stopped")
if err != nil {
return err
}
return nil
}
func getAzureBlobStorageClient(ctx context.Context, storageUrl string, azuriteOptions AzuriteOptions, userAssignedIdentityClientId string) (*azblob.Client, error) {
isLocalEnvironment := strings.Contains(storageUrl, "localhost") || strings.Contains(storageUrl, "127.0.0.1")
if isLocalEnvironment {
credential, err := azblob.NewSharedKeyCredential(azuriteOptions.accountName, azuriteOptions.accountKey)
if err != nil {
return nil, err
}
client, err := azblob.NewClientWithSharedKeyCredential(storageUrl, credential, nil)
if err != nil {
return nil, err
}
client.CreateContainer(ctx, azuriteOptions.containerName, nil)
return client, nil
} else {
clientID := azidentity.ClientID(userAssignedIdentityClientId)
opts := azidentity.ManagedIdentityCredentialOptions{ID: clientID}
credential, err := azidentity.NewManagedIdentityCredential(&opts)
if err != nil {
return nil, err
}
client, err := azblob.NewClient(storageUrl, credential, nil)
if err != nil {
return nil, err
}
return client, nil
}
}