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

mendersoftware / useradm / 1807193300

08 May 2025 10:54AM UTC coverage: 59.747% (-27.3%) from 87.019%
1807193300

Pull #439

gitlab-ci

alfrunes
Merge `alfrunes:1.22.x` into `mendersoftware:1.22.x`
Pull Request #439: :building_construction: Upgrade dependencies

2363 of 3955 relevant lines covered (59.75%)

12.76 hits per line

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

16.43
/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
        "path"
20
        "path/filepath"
21
        "regexp"
22

23
        "github.com/ant0ine/go-json-rest/rest"
24
        "github.com/mendersoftware/go-lib-micro/config"
25
        "github.com/mendersoftware/go-lib-micro/log"
26
        "github.com/pkg/errors"
27

28
        api_http "github.com/mendersoftware/useradm/api/http"
29
        "github.com/mendersoftware/useradm/authz"
30
        "github.com/mendersoftware/useradm/client/tenant"
31
        "github.com/mendersoftware/useradm/common"
32
        . "github.com/mendersoftware/useradm/config"
33
        "github.com/mendersoftware/useradm/jwt"
34
        "github.com/mendersoftware/useradm/store/mongo"
35
        useradm "github.com/mendersoftware/useradm/user"
36
)
37

38
func SetupAPI(stacktype string, authz authz.Authorizer, jwth map[int]jwt.Handler,
39
        jwthFallback jwt.Handler) (*rest.Api, error) {
2✔
40
        api := rest.NewApi()
2✔
41
        if err := SetupMiddleware(api, stacktype, authz, jwth, jwthFallback); err != nil {
3✔
42
                return nil, errors.Wrap(err, "failed to setup middleware")
1✔
43
        }
1✔
44

45
        //this will override the framework's error resp to the desired one:
46
        // {"error": "msg"}
47
        // instead of:
48
        // {"Error": "msg"}
49
        rest.ErrorFieldName = "error"
1✔
50

1✔
51
        return api, nil
1✔
52
}
53

54
func RunServer(c config.Reader) error {
×
55

×
56
        l := log.New(log.Ctx{})
×
57

×
58
        authorizer := &SimpleAuthz{}
×
59

×
60
        // let's now go through all the existing keys and load them
×
61
        jwtHandlers, err := addPrivateKeys(
×
62
                l,
×
63
                filepath.Dir(c.GetString(SettingServerPrivKeyPath)),
×
64
                c.GetString(SettingServerPrivKeyFileNamePattern),
×
65
        )
×
66
        if err != nil {
×
67
                return err
×
68
        }
×
69

70
        // the handler for keyId equal 0 is the one associated with the
71
        // SettingServerPrivKeyPathDefault key. it is the one serving all the previously
72
        // issued tokens (before the kid introduction in the JWTs)
73
        defaultHandler, err := jwt.NewJWTHandler(
×
74
                SettingServerPrivKeyPathDefault,
×
75
                c.GetString(SettingServerPrivKeyFileNamePattern),
×
76
        )
×
77
        if err == nil && defaultHandler != nil {
×
78
                // the key with id 0 is by default the default one. this allows
×
79
                // to support tokens without "kid" in the header
×
80
                // it is possible, that you rotated the default key, in which case you have to
×
81
                // set USERADM_SERVER_PRIV_KEY_PATH=/etc/useradm/rsa/private.id.2048.pem
×
82
                // where private.id.2048.pem is the new key, with new id. the new one will by default
×
83
                // be used to issue new tokens, while any other token which has id that we have
×
84
                // will be authorized against its matching key (by id from "kid" in JWT header)
×
85
                // or which does not have "kid" will be authorized against the key with id 0.
×
86
                // in other words: the key with id 0 (if not present as private.id.0.pem)
×
87
                // is the default one, and all the JWT with no "kid" in headers are being
×
88
                // checked against it.
×
89
                jwtHandlers[common.KeyIdZero] = defaultHandler
×
90
        }
×
91

92
        // if the default path is different from the currently set key path
93
        // we still have not loaded this key. this happens when the key rotation took place,
94
        // someone exported USERADM_SERVER_PRIV_KEY_PATH=path-to-a-new-key and this key
95
        // now will serve all. if we do not have this, the Login will fall back to the keyId
96
        // from the filename and either use the KeyIdZero key or fail to find the key to issue a
97
        // token if the one set in USERADM_SERVER_PRIV_KEY_PATH does have id in the filename
98
        // (but does not exist because we have not loaded it)
99
        // this also means that careless setting of USERADM_SERVER_PRIV_KEY_PATH to a key that does
100
        // not match the SettingServerPrivKeyFileNamePattern will result in
101
        // KeyIdZero handler overwrite and lack of back support for tokens signed by it.
102
        if c.GetString(SettingServerPrivKeyPath) != SettingServerPrivKeyPathDefault {
×
103
                defaultHandler, err = jwt.NewJWTHandler(
×
104
                        c.GetString(SettingServerPrivKeyPath),
×
105
                        c.GetString(SettingServerPrivKeyFileNamePattern),
×
106
                )
×
107
                if err == nil && defaultHandler != nil {
×
108
                        keyId := common.KeyIdFromPath(
×
109
                                c.GetString(SettingServerPrivKeyPath),
×
110
                                c.GetString(SettingServerPrivKeyFileNamePattern),
×
111
                        )
×
112
                        if keyId == common.KeyIdZero {
×
113
                                l.Warnf(
×
114
                                        "currently set private key %s either does not match %s pattern"+
×
115
                                                " or has explicitly set id=0. we are overridding the default"+
×
116
                                                " private key handler with id=0",
×
117
                                        c.GetString(SettingServerPrivKeyPath),
×
118
                                        c.GetString(SettingServerPrivKeyFileNamePattern),
×
119
                                )
×
120
                        }
×
121
                        jwtHandlers[keyId] = defaultHandler
×
122
                }
123
        }
124

125
        var jwtFallbackHandler jwt.Handler
×
126
        fallback := c.GetString(SettingServerFallbackPrivKeyPath)
×
127
        if err == nil && fallback != "" {
×
128
                jwtFallbackHandler, err = jwt.NewJWTHandler(
×
129
                        fallback,
×
130
                        c.GetString(SettingServerPrivKeyFileNamePattern),
×
131
                )
×
132
        }
×
133
        if err != nil {
×
134
                return err
×
135
        }
×
136

137
        db, err := mongo.GetDataStoreMongo(dataStoreMongoConfigFromAppConfig(c))
×
138
        if err != nil {
×
139
                return errors.Wrap(err, "database connection failed")
×
140
        }
×
141

142
        ua := useradm.NewUserAdm(jwtHandlers, db,
×
143
                useradm.Config{
×
144
                        Issuer:                         c.GetString(SettingJWTIssuer),
×
145
                        ExpirationTimeSeconds:          int64(c.GetInt(SettingJWTExpirationTimeout)),
×
146
                        LimitSessionsPerUser:           c.GetInt(SettingLimitSessionsPerUser),
×
147
                        LimitTokensPerUser:             c.GetInt(SettingLimitTokensPerUser),
×
148
                        TokenLastUsedUpdateFreqMinutes: c.GetInt(SettingTokenLastUsedUpdateFreqMinutes),
×
149
                        PrivateKeyPath:                 c.GetString(SettingServerPrivKeyPath),
×
150
                        PrivateKeyFileNamePattern:      c.GetString(SettingServerPrivKeyFileNamePattern),
×
151
                })
×
152

×
153
        if tadmAddr := c.GetString(SettingTenantAdmAddr); tadmAddr != "" {
×
154
                l.Infof("settting up tenant verification")
×
155

×
156
                tc := tenant.NewClient(tenant.Config{
×
157
                        TenantAdmAddr: tadmAddr,
×
158
                })
×
159

×
160
                ua = ua.WithTenantVerification(tc)
×
161
        }
×
162

163
        useradmapi := api_http.NewUserAdmApiHandlers(ua, db, jwtHandlers,
×
164
                api_http.Config{
×
165
                        TokenMaxExpSeconds: c.GetInt(SettingTokenMaxExpirationSeconds),
×
166
                })
×
167

×
168
        api, err := SetupAPI(
×
169
                c.GetString(SettingMiddleware),
×
170
                authorizer,
×
171
                jwtHandlers,
×
172
                jwtFallbackHandler,
×
173
        )
×
174
        if err != nil {
×
175
                return errors.Wrap(err, "API setup failed")
×
176
        }
×
177

178
        apph, err := useradmapi.GetApp()
×
179
        if err != nil {
×
180
                return errors.Wrap(err, "useradm API handlers setup failed")
×
181
        }
×
182
        api.SetApp(apph)
×
183

×
184
        addr := c.GetString(SettingListen)
×
185
        l.Printf("listening on %s", addr)
×
186

×
187
        return http.ListenAndServe(addr, api.MakeHandler())
×
188
}
189

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

200
        r, err := regexp.Compile(privateKeyPattern)
1✔
201
        if err != nil {
1✔
202
                return
×
203
        }
×
204

205
        handlers = make(map[int]jwt.Handler, len(files))
1✔
206
        for _, fileEntry := range files {
14✔
207
                if r.MatchString(fileEntry.Name()) {
23✔
208
                        keyPath := path.Join(privateKeysDirectory, fileEntry.Name())
10✔
209
                        handler, err := jwt.NewJWTHandler(keyPath, privateKeyPattern)
10✔
210
                        if err != nil {
10✔
211
                                continue
×
212
                        }
213
                        keyId := common.KeyIdFromPath(keyPath, privateKeyPattern)
10✔
214
                        l.Infof("loaded private key id=%d from %s", keyId, keyPath)
10✔
215
                        handlers[keyId] = handler
10✔
216
                }
217
        }
218
        return handlers, nil
1✔
219
}
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