• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / mender-server / 1600238645

23 Dec 2024 10:30AM UTC coverage: 76.615% (+3.8%) from 72.818%
1600238645

Pull #274

gitlab-ci

bahaa-ghazal
fix: implement signal handler for `server` commands

Changelog: Title
Ticket: QA-782
Signed-off-by: Bahaa Aldeen Ghazal <bahaa.ghazal@northern.tech>
Pull Request #274: fix: implement signal handler for `server` commands

4254 of 6166 branches covered (68.99%)

Branch coverage included in aggregate %.

63 of 91 new or added lines in 8 files covered. (69.23%)

46 existing lines in 5 files now uncovered.

45257 of 58457 relevant lines covered (77.42%)

21.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.01
/backend/services/useradm/server.go
1
// Copyright 2023 Northern.tech AS
2
//
3
//        Licensed under the Apache License, Version 2.0 (the "License");
4
//        you may not use this file except in compliance with the License.
5
//        You may obtain a copy of the License at
6
//
7
//            http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//        Unless required by applicable law or agreed to in writing, software
10
//        distributed under the License is distributed on an "AS IS" BASIS,
11
//        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//        See the License for the specific language governing permissions and
13
//        limitations under the License.
14
package main
15

16
import (
17
        "net/http"
18
        "os"
19
        "os/signal"
20
        "path"
21
        "path/filepath"
22
        "regexp"
23

24
        "github.com/pkg/errors"
25
        "golang.org/x/sys/unix"
26

27
        "github.com/mendersoftware/mender-server/pkg/config"
28
        "github.com/mendersoftware/mender-server/pkg/log"
29

30
        api_http "github.com/mendersoftware/mender-server/services/useradm/api/http"
31
        "github.com/mendersoftware/mender-server/services/useradm/client/tenant"
32
        "github.com/mendersoftware/mender-server/services/useradm/common"
33
        . "github.com/mendersoftware/mender-server/services/useradm/config"
34
        "github.com/mendersoftware/mender-server/services/useradm/jwt"
35
        "github.com/mendersoftware/mender-server/services/useradm/store/mongo"
36
        useradm "github.com/mendersoftware/mender-server/services/useradm/user"
37
)
38

39
func RunServer(c config.Reader) error {
2✔
40

2✔
41
        l := log.New(log.Ctx{})
2✔
42

2✔
43
        authorizer := &SimpleAuthz{}
2✔
44

2✔
45
        // let's now go through all the existing keys and load them
2✔
46
        jwtHandlers, err := addPrivateKeys(
2✔
47
                l,
2✔
48
                filepath.Dir(c.GetString(SettingServerPrivKeyPath)),
2✔
49
                c.GetString(SettingServerPrivKeyFileNamePattern),
2✔
50
        )
2✔
51
        if err != nil {
2✔
52
                return err
×
53
        }
×
54

55
        // the handler for keyId equal 0 is the one associated with the
56
        // SettingServerPrivKeyPathDefault key. it is the one serving all the previously
57
        // issued tokens (before the kid introduction in the JWTs)
58
        defaultHandler, err := jwt.NewJWTHandler(
2✔
59
                SettingServerPrivKeyPathDefault,
2✔
60
                c.GetString(SettingServerPrivKeyFileNamePattern),
2✔
61
        )
2✔
62
        if err == nil && defaultHandler != nil {
2✔
63
                // the key with id 0 is by default the default one. this allows
×
64
                // to support tokens without "kid" in the header
×
65
                // it is possible, that you rotated the default key, in which case you have to
×
66
                // set USERADM_SERVER_PRIV_KEY_PATH=/etc/useradm/rsa/private.id.2048.pem
×
67
                // where private.id.2048.pem is the new key, with new id. the new one will by default
×
68
                // be used to issue new tokens, while any other token which has id that we have
×
69
                // will be authorized against its matching key (by id from "kid" in JWT header)
×
70
                // or which does not have "kid" will be authorized against the key with id 0.
×
71
                // in other words: the key with id 0 (if not present as private.id.0.pem)
×
72
                // is the default one, and all the JWT with no "kid" in headers are being
×
73
                // checked against it.
×
74
                jwtHandlers[common.KeyIdZero] = defaultHandler
×
75
        }
×
76

77
        // if the default path is different from the currently set key path
78
        // we still have not loaded this key. this happens when the key rotation took place,
79
        // someone exported USERADM_SERVER_PRIV_KEY_PATH=path-to-a-new-key and this key
80
        // now will serve all. if we do not have this, the Login will fall back to the keyId
81
        // from the filename and either use the KeyIdZero key or fail to find the key to issue a
82
        // token if the one set in USERADM_SERVER_PRIV_KEY_PATH does have id in the filename
83
        // (but does not exist because we have not loaded it)
84
        // this also means that careless setting of USERADM_SERVER_PRIV_KEY_PATH to a key that does
85
        // not match the SettingServerPrivKeyFileNamePattern will result in
86
        // KeyIdZero handler overwrite and lack of back support for tokens signed by it.
87
        if c.GetString(SettingServerPrivKeyPath) != SettingServerPrivKeyPathDefault {
4✔
88
                defaultHandler, err = jwt.NewJWTHandler(
2✔
89
                        c.GetString(SettingServerPrivKeyPath),
2✔
90
                        c.GetString(SettingServerPrivKeyFileNamePattern),
2✔
91
                )
2✔
92
                if err == nil && defaultHandler != nil {
4✔
93
                        keyId := common.KeyIdFromPath(
2✔
94
                                c.GetString(SettingServerPrivKeyPath),
2✔
95
                                c.GetString(SettingServerPrivKeyFileNamePattern),
2✔
96
                        )
2✔
97
                        if keyId == common.KeyIdZero {
4✔
98
                                l.Warnf(
2✔
99
                                        "currently set private key %s either does not match %s pattern"+
2✔
100
                                                " or has explicitly set id=0. we are overridding the default"+
2✔
101
                                                " private key handler with id=0",
2✔
102
                                        c.GetString(SettingServerPrivKeyPath),
2✔
103
                                        c.GetString(SettingServerPrivKeyFileNamePattern),
2✔
104
                                )
2✔
105
                        }
2✔
106
                        jwtHandlers[keyId] = defaultHandler
2✔
107
                }
108
        }
109

110
        var jwtFallbackHandler jwt.Handler
2✔
111
        fallback := c.GetString(SettingServerFallbackPrivKeyPath)
2✔
112
        if err == nil && fallback != "" {
2✔
113
                jwtFallbackHandler, err = jwt.NewJWTHandler(
×
114
                        fallback,
×
115
                        c.GetString(SettingServerPrivKeyFileNamePattern),
×
116
                )
×
117
        }
×
118
        if err != nil {
2✔
119
                return err
×
120
        }
×
121

122
        db, err := mongo.GetDataStoreMongo(dataStoreMongoConfigFromAppConfig(c))
2✔
123
        if err != nil {
2✔
124
                return errors.Wrap(err, "database connection failed")
×
125
        }
×
126

127
        ua := useradm.NewUserAdm(jwtHandlers, db,
2✔
128
                useradm.Config{
2✔
129
                        Issuer:                         c.GetString(SettingJWTIssuer),
2✔
130
                        ExpirationTimeSeconds:          int64(c.GetInt(SettingJWTExpirationTimeout)),
2✔
131
                        LimitSessionsPerUser:           c.GetInt(SettingLimitSessionsPerUser),
2✔
132
                        LimitTokensPerUser:             c.GetInt(SettingLimitTokensPerUser),
2✔
133
                        TokenLastUsedUpdateFreqMinutes: c.GetInt(SettingTokenLastUsedUpdateFreqMinutes),
2✔
134
                        PrivateKeyPath:                 c.GetString(SettingServerPrivKeyPath),
2✔
135
                        PrivateKeyFileNamePattern:      c.GetString(SettingServerPrivKeyFileNamePattern),
2✔
136
                })
2✔
137

2✔
138
        if tadmAddr := c.GetString(SettingTenantAdmAddr); tadmAddr != "" {
2✔
139
                l.Infof("settting up tenant verification")
×
140

×
141
                tc := tenant.NewClient(tenant.Config{
×
142
                        TenantAdmAddr: tadmAddr,
×
143
                })
×
144

×
145
                ua = ua.WithTenantVerification(tc)
×
146
        }
×
147

148
        useradmapi := api_http.NewUserAdmApiHandlers(ua, db, jwtHandlers,
2✔
149
                api_http.Config{
2✔
150
                        TokenMaxExpSeconds: c.GetInt(SettingTokenMaxExpirationSeconds),
2✔
151
                        JWTFallback:        jwtFallbackHandler,
2✔
152
                })
2✔
153

2✔
154
        handler, err := useradmapi.Build(authorizer)
2✔
155
        if err != nil {
2✔
156
                return errors.Wrap(err, "useradm API handlers setup failed")
×
157
        }
×
158

159
        addr := c.GetString(SettingListen)
2✔
160
        l.Printf("listening on %s", addr)
2✔
161

2✔
162
        srv := &http.Server{
2✔
163
                Addr:    addr,
2✔
164
                Handler: handler,
2✔
165
        }
2✔
166

2✔
167
        errChan := make(chan error, 1)
2✔
168
        go func() {
4✔
169
                if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
2✔
NEW
170
                        errChan <- err
×
NEW
171
                }
×
172
        }()
173
        quit := make(chan os.Signal, 1)
2✔
174
        signal.Notify(quit, unix.SIGINT, unix.SIGTERM)
2✔
175
        select {
2✔
176
        case sig := <-quit:
2✔
177
                l.Infof("received signal %s: terminating", sig)
2✔
NEW
178
        case err := <-errChan:
×
NEW
179
                l.Errorf("server terminated unexpectedly: %s", err.Error())
×
NEW
180
                return err
×
181
        }
182
        l.Info("server shutdown")
2✔
183

2✔
184
        return nil
2✔
185
}
186

187
func addPrivateKeys(
188
        l *log.Logger,
189
        privateKeysDirectory string,
190
        privateKeyPattern string,
191
) (handlers map[int]jwt.Handler, err error) {
3✔
192
        files, err := os.ReadDir(privateKeysDirectory)
3✔
193
        if err != nil {
3✔
194
                return
×
195
        }
×
196

197
        r, err := regexp.Compile(privateKeyPattern)
3✔
198
        if err != nil {
3✔
199
                return
×
200
        }
×
201

202
        handlers = make(map[int]jwt.Handler, len(files))
3✔
203
        for _, fileEntry := range files {
6✔
204
                if r.MatchString(fileEntry.Name()) {
4✔
205
                        keyPath := path.Join(privateKeysDirectory, fileEntry.Name())
1✔
206
                        handler, err := jwt.NewJWTHandler(keyPath, privateKeyPattern)
1✔
207
                        if err != nil {
1✔
208
                                continue
×
209
                        }
210
                        keyId := common.KeyIdFromPath(keyPath, privateKeyPattern)
1✔
211
                        l.Infof("loaded private key id=%d from %s", keyId, keyPath)
1✔
212
                        handlers[keyId] = handler
1✔
213
                }
214
        }
215
        return handlers, nil
3✔
216
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc