-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
258 lines (227 loc) · 6.21 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
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
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"embed"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/labstack/echo/v4/middleware"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jwt"
libDiscovery "github.com/nuts-foundation/go-nuts-client/nuts/discovery"
"github.com/nuts-foundation/go-nuts-client/nuts/vcr"
"github.com/nuts-foundation/go-nuts-client/nuts/vdr"
"github.com/nuts-foundation/nuts-admin/discovery"
"github.com/nuts-foundation/nuts-admin/identity"
"github.com/nuts-foundation/nuts-admin/issuer"
"github.com/rs/zerolog"
"io/fs"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/labstack/echo/v4"
"github.com/lestrrat-go/jwx/jwa"
"github.com/nuts-foundation/nuts-admin/api"
)
const assetPath = "web/dist"
//go:embed web/dist/*
var embeddedFiles embed.FS
var logger zerolog.Logger
func getFileSystem(useFS bool) http.FileSystem {
if useFS {
logger.Info().Msg("using live mode")
return http.FS(os.DirFS(assetPath))
}
logger.Debug().Msg("using embed mode")
fsys, err := fs.Sub(embeddedFiles, assetPath)
if err != nil {
panic(err)
}
return http.FS(fsys)
}
func main() {
logger = zerolog.New(log.Writer()).With().Timestamp().Logger()
config := loadConfig()
config.Print()
e := echo.New()
e.HideBanner = true
e.HTTPErrorHandler = httpErrorHandler
e.HideBanner = true
e.HidePort = true
if config.AccessLogs {
e.Use(accessLoggerMiddleware(func(c echo.Context) bool {
return c.Request().URL.Path == "/status"
}, logger))
}
nodeAddress, err := url.Parse(config.Node.Address)
if err != nil {
log.Fatalf("unable to parse node address: %s", err)
}
// API security
// TODO
//tokenGenerator := func() (string, error) {
// return "", nil
//}
//if config.apiKey != nil {
// tokenGenerator = createTokenGenerator(config)
//}
vdrClient, _ := vdr.NewClient(config.Node.Address)
vcrClient, _ := vcr.NewClient(config.Node.Address)
discoveryClient, _ := libDiscovery.NewClient(config.Node.Address)
// Initialize wrapper
discoveryService := discovery.Service{
Client: discoveryClient,
}
identityService := identity.Service{
VDRClient: vdrClient,
VCRClient: vcrClient,
DiscoveryService: discoveryService,
}
apiWrapper := api.Wrapper{
Identity: identityService,
Discovery: discoveryService,
IssuerService: issuer.Service{
IdentityService: identityService,
VCRClient: vcrClient,
},
}
api.RegisterHandlers(e, apiWrapper)
api.ConfigureProxy(logger, e, nodeAddress)
// Setup asset serving:
// Check if we use live mode from the file system or using embedded files
useFS := len(os.Args) > 1 && os.Args[1] == "live"
assetHandler := http.FileServer(getFileSystem(useFS))
e.GET("/status", func(context echo.Context) error {
return context.String(http.StatusOK, "OK")
})
e.GET("/*", echo.WrapHandler(assetHandler))
// Start server
e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", config.HTTPPort)))
}
// httpErrorHandler includes the err.Err() string in a { "error": "msg" } json hash
func httpErrorHandler(err error, c echo.Context) {
var (
code = http.StatusInternalServerError
msg interface{}
)
type Map map[string]interface{}
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
msg = he.Message
if he.Internal != nil {
err = fmt.Errorf("%v, %v", err, he.Internal)
}
} else {
msg = err.Error()
}
if _, ok := msg.(string); ok {
msg = Map{"error": msg}
}
// Send response
if !c.Response().Committed {
if c.Request().Method == http.MethodHead {
err = c.NoContent(code)
} else {
err = c.JSON(code, msg)
}
if err != nil {
c.Logger().Error(err)
}
}
}
func requestsStatusEndpoint(context echo.Context) bool {
return context.Request().RequestURI == "/status"
}
// createTokenGenerator generates valid API tokens for the Nuts node and signs them with the private key
func createTokenGenerator(config Config) func() (string, error) {
return func() (string, error) {
key, err := jwkKey(config.apiKey)
if err != nil {
return "", err
}
issuedAt := time.Now()
notBefore := issuedAt
expires := notBefore.Add(time.Second * time.Duration(5))
token, err := jwt.NewBuilder().
Issuer(config.Node.Auth.User).
Audience([]string{config.Node.Auth.Audience}).
IssuedAt(issuedAt).
NotBefore(notBefore).
Expiration(expires).
JwtID(uuid.New().String()).
Build()
bytes, err := jwt.Sign(token, jwa.SignatureAlgorithm(key.Algorithm()), key)
if err != nil {
return "", err
}
return string(bytes), nil
}
}
func jwkKey(signer crypto.Signer) (key jwk.Key, err error) {
// ssh key format
key, err = jwk.New(signer)
if err != nil {
return nil, err
}
switch k := signer.(type) {
case *rsa.PrivateKey:
key.Set(jwk.AlgorithmKey, jwa.PS512)
case *ecdsa.PrivateKey:
var alg jwa.SignatureAlgorithm
alg, err = ecAlg(k)
key.Set(jwk.AlgorithmKey, alg)
default:
err = fmt.Errorf("unsupported signing private key: %T", k)
return
}
err = jwk.AssignKeyID(key)
return
}
func ecAlg(key *ecdsa.PrivateKey) (alg jwa.SignatureAlgorithm, err error) {
alg, err = ecAlgUsingPublicKey(key.PublicKey)
return
}
func ecAlgUsingPublicKey(key ecdsa.PublicKey) (alg jwa.SignatureAlgorithm, err error) {
switch key.Params().BitSize {
case 256:
alg = jwa.ES256
case 384:
alg = jwa.ES384
case 521:
alg = jwa.ES512
default:
err = errors.New("unsupported key")
}
return
}
// accessLoggerMiddleware returns middleware that logs metadata of HTTP requests.
// Should be added as the outer middleware to catch all errors and potential status rewrites
func accessLoggerMiddleware(skipper middleware.Skipper, logger zerolog.Logger) echo.MiddlewareFunc {
return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
Skipper: skipper,
LogURI: true,
LogStatus: true,
LogMethod: true,
LogRemoteIP: true,
LogError: true,
LogValuesFunc: func(c echo.Context, values middleware.RequestLoggerValues) error {
event := logger.Info().Fields(map[string]interface{}{
"remote_ip": values.RemoteIP,
"method": values.Method,
"uri": values.URI,
"status": values.Status,
})
if logger.GetLevel() >= zerolog.DebugLevel {
event.Fields(map[string]interface{}{
"headers": values.Headers,
})
}
event.Msg("HTTP request")
return nil
},
})
}