This repository has been archived by the owner on Aug 3, 2023. It is now read-only.
forked from SUSE/stratos
/
main.go
279 lines (232 loc) · 8.43 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package yamlgenerated
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/epinio/ui-backend/src/jetstream/repository/interfaces"
"github.com/labstack/echo/v4"
"gopkg.in/yaml.v2"
log "github.com/sirupsen/logrus"
)
// GeneratedPlugin represents a generated plugin
type GeneratedPlugin struct {
initMethod func() error
middlewarePlugin func() (interfaces.MiddlewarePlugin, error)
endpointPlugin func() (interfaces.EndpointPlugin, error)
routePlugin func() (interfaces.RoutePlugin, error)
}
var authTypeToConnectTypeMap = map[string]string{
interfaces.AuthTypeHttpBasic: interfaces.AuthConnectTypeCreds,
interfaces.AuthTypeBearer: interfaces.AuthConnectTypeBearer,
interfaces.AuthTypeToken: interfaces.AuthConnectTypeToken,
}
const defaultTokenUsername = "**token**"
type pluginConfig struct {
// Name is the endpoint type
Name string `yaml:"name"`
// SubType of the endpoint
SubType string `yaml:"sub_type"`
// AuthType - for now, only one auth type is supported
AuthType string `yaml:"auth_type"`
// UserInfoAPI is the Rest URL to fetch User if
UserInfoAPI string `yaml:"user_info"`
// UserInfoPath is the path in the response to the above REST API to get the username from the retrurned JSON
UserInfoPath string `yaml:"user_info_path"`
}
// Init the plugin
func (gp GeneratedPlugin) Init() error { return gp.initMethod() }
func (gp GeneratedPlugin) GetMiddlewarePlugin() (interfaces.MiddlewarePlugin, error) {
return gp.middlewarePlugin()
}
func (gp GeneratedPlugin) GetEndpointPlugin() (interfaces.EndpointPlugin, error) {
return gp.endpointPlugin()
}
func (gp GeneratedPlugin) GetRoutePlugin() (interfaces.RoutePlugin, error) {
return gp.routePlugin()
}
// GeneratedEndpointPlugin represents a generated endpoint plugin
type GeneratedEndpointPlugin struct {
portalProxy interfaces.PortalProxy
endpointType string
subTypes map[string]pluginConfig
}
func (gep GeneratedEndpointPlugin) GetType() string {
return gep.endpointType
}
func (gep GeneratedEndpointPlugin) Register(ec echo.Context) error {
return gep.portalProxy.RegisterEndpoint(ec, gep.Info)
}
func (gep GeneratedEndpointPlugin) Validate(userGUID string, cnsiRecord interfaces.CNSIRecord, tokenRecord interfaces.TokenRecord) error {
return nil
}
func (gep GeneratedEndpointPlugin) Connect(ec echo.Context, cnsiRecord interfaces.CNSIRecord, userId string) (*interfaces.TokenRecord, bool, error) {
params := new(interfaces.LoginToCNSIParams)
err := interfaces.BindOnce(params, ec)
if err != nil {
return nil, false, err
}
subType, ok := gep.subTypes[cnsiRecord.SubType]
if !ok {
return nil, false, fmt.Errorf("Unknown subtype %q for endpoint type %q", cnsiRecord.SubType, gep.GetType())
}
authType := subType.AuthType
expectedConnectType, ok := authTypeToConnectTypeMap[authType]
if !ok {
return nil, false, fmt.Errorf("Unknown authentication type %q for endpoint type %q", authType, gep.GetType())
}
if expectedConnectType != params.ConnectType {
return nil, false, fmt.Errorf("Only %q connect type is supported for %q.%q endpoints", expectedConnectType, gep.GetType(), cnsiRecord.SubType)
}
var tr *interfaces.TokenRecord
switch params.ConnectType {
case interfaces.AuthConnectTypeCreds:
if len(params.Username) == 0 || len(params.Password) == 0 {
return nil, false, errors.New("Need username and password")
}
authString := fmt.Sprintf("%s:%s", params.Username, params.Password)
base64EncodedAuthString := base64.StdEncoding.EncodeToString([]byte(authString))
tr = &interfaces.TokenRecord{
AuthType: interfaces.AuthTypeHttpBasic,
AuthToken: base64EncodedAuthString,
RefreshToken: params.Username,
}
case interfaces.AuthConnectTypeBearer:
authString := ec.FormValue("token")
base64EncodedAuthString := base64.StdEncoding.EncodeToString([]byte(authString))
tr = &interfaces.TokenRecord{
AuthType: interfaces.AuthTypeBearer,
AuthToken: base64EncodedAuthString,
}
tr.RefreshToken = gep.fetchUsername(subType, &cnsiRecord, tr)
case interfaces.AuthConnectTypeToken:
authString := ec.FormValue("token")
base64EncodedAuthString := base64.StdEncoding.EncodeToString([]byte(authString))
tr = &interfaces.TokenRecord{
AuthType: interfaces.AuthTypeToken,
AuthToken: base64EncodedAuthString,
}
tr.RefreshToken = gep.fetchUsername(subType, &cnsiRecord, tr)
}
return tr, false, nil
}
// We support a basic mechanism for fetching the username of the user if configured
func (gep GeneratedEndpointPlugin) fetchUsername(config pluginConfig, cnsiRecord *interfaces.CNSIRecord, tr *interfaces.TokenRecord) string {
if len(config.UserInfoAPI) == 0 || len(config.UserInfoPath) == 0 {
// Not configured
return defaultTokenUsername
}
// Make a request to the user info endpoint
resp, err := gep.portalProxy.DoProxySingleRequestWithToken(cnsiRecord.GUID, tr, "GET", config.UserInfoAPI, nil, nil)
if err != nil {
return defaultTokenUsername
}
if resp.StatusCode != http.StatusOK {
return defaultTokenUsername
}
// Find the username from the returned document
var data map[string]interface{}
if err = json.Unmarshal(resp.Response, &data); err == nil {
name := getJSONValue(data, config.UserInfoPath)
if len(name) > 0 {
return name
}
}
return defaultTokenUsername
}
func getJSONValue(data map[string]interface{}, valuePath string) string {
parts := strings.Split(valuePath, ".")
value := data[parts[0]]
if value != nil {
if len(parts) == 1 {
// This was the last part
if sName, ok := value.(string); ok {
return sName
}
return ""
}
// Not the last path, so get the next level item
if sNextLevel, ok := value.(map[string]interface{}); ok {
return getJSONValue(sNextLevel, strings.Join(parts[1:], "."))
}
}
// Failed to find the value
return ""
}
// Info gets the info for the endpoint
func (gep GeneratedEndpointPlugin) Info(apiEndpoint string, skipSSLValidation bool) (interfaces.CNSIRecord, interface{}, error) {
var dummy interface{}
var newCNSI interfaces.CNSIRecord
newCNSI.CNSIType = gep.GetType()
_, err := url.Parse(apiEndpoint)
if err != nil {
return newCNSI, nil, err
}
newCNSI.TokenEndpoint = apiEndpoint
newCNSI.AuthorizationEndpoint = apiEndpoint
return newCNSI, dummy, nil
}
// UpdateMetadata allows the pluigin to update the metadata for endpoints - not used in the generic case
func (gep GeneratedEndpointPlugin) UpdateMetadata(info *interfaces.Info, userGUID string, echoContext echo.Context) {
// no-op
}
// MakePluginsFromConfig will generate plugins for the yaml-configured endpoints
func MakePluginsFromConfig() {
log.Debug("MakePluginsFromConfig")
var config []pluginConfig
yamlFile, err := ioutil.ReadFile("plugins.yaml")
if err != nil {
log.Errorf("Can't generate plugins from YAML: %v ", err)
return
}
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
log.Errorf("Failed to unmarshal YAML: %v ", err)
return
}
plugins := make(map[string]GeneratedEndpointPlugin)
for _, plugin := range config {
if len(plugin.Name) == 0 {
log.Errorf("Plugin must have a name")
return
}
log.Debugf("Processing plugin for endpoint %s and sub-type %s", plugin.Name, plugin.SubType)
// Create a plugin if needed then add this sub type to the plugin
ep, ok := plugins[plugin.Name]
if !ok {
ep = createPluginForEndpointType(plugin.Name)
plugins[plugin.Name] = ep
}
// Add this subtype to the plugin - subtype can be empty
if _, ok := ep.subTypes[plugin.SubType]; ok {
log.Warnf("Sub-type %s already declared for endpoint type %s - ignoring", plugin.Name, plugin.SubType)
} else {
ep.subTypes[plugin.SubType] = plugin
}
}
}
func createPluginForEndpointType(endpointType string) GeneratedEndpointPlugin {
log.Debugf("Generating plugin %s", endpointType)
gep := GeneratedEndpointPlugin{}
gep.endpointType = endpointType
gep.subTypes = make(map[string]pluginConfig)
gp := GeneratedPlugin{}
gp.initMethod = func() error { return nil }
gp.endpointPlugin = func() (interfaces.EndpointPlugin, error) { return gep, nil }
gp.middlewarePlugin = func() (interfaces.MiddlewarePlugin, error) { return nil, errors.New("Not implemented") }
gp.routePlugin = func() (interfaces.RoutePlugin, error) { return nil, errors.New("Not implemented") }
interfaces.AddPlugin(
endpointType,
[]string{},
func(portalProxy interfaces.PortalProxy) (interfaces.StratosPlugin, error) {
log.Debugf("%s -- initializing", endpointType)
gep.portalProxy = portalProxy
return gp, nil
},
)
return gep
}