-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathmentix.go
274 lines (241 loc) · 6.68 KB
/
mentix.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
// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package mentix
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/cs3org/reva/pkg/rhttp"
ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1"
"github.com/cs3org/reva/pkg/errtypes"
"github.com/cs3org/reva/pkg/ocm/provider"
"github.com/cs3org/reva/pkg/ocm/provider/authorizer/registry"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
func init() {
registry.Register("mentix", New)
}
// Client is a Mentix API client
type Client struct {
BaseURL string
HTTPClient *http.Client
}
// New returns a new authorizer object.
func New(m map[string]interface{}) (provider.Authorizer, error) {
c := &config{}
if err := mapstructure.Decode(m, c); err != nil {
err = errors.Wrap(err, "error decoding conf")
return nil, err
}
c.init()
client := &Client{
BaseURL: c.URL,
HTTPClient: rhttp.GetHTTPClient(
rhttp.Context(context.Background()),
rhttp.Timeout(time.Duration(c.Timeout*int64(time.Second))),
rhttp.Insecure(c.Insecure),
),
}
return &authorizer{
client: client,
providerIPs: sync.Map{},
conf: c,
}, nil
}
type config struct {
URL string `mapstructure:"url"`
Timeout int64 `mapstructure:"timeout"`
RefreshInterval int64 `mapstructure:"refresh"`
VerifyRequestHostname bool `mapstructure:"verify_request_hostname"`
Insecure bool `mapstructure:"insecure" docs:"false;Whether to skip certificate checks when sending requests."`
}
func (c *config) init() {
if c.URL == "" {
c.URL = "http://localhost:9600/mentix/cs3"
}
}
type authorizer struct {
providers []*ocmprovider.ProviderInfo
providersExpiration int64
client *Client
providerIPs sync.Map
conf *config
}
func normalizeDomain(d string) (string, error) {
var urlString string
if strings.Contains(d, "://") {
urlString = d
} else {
urlString = "https://" + d
}
u, err := url.Parse(urlString)
if err != nil {
return "", err
}
return u.Hostname(), nil
}
func (a *authorizer) fetchProviders() ([]*ocmprovider.ProviderInfo, error) {
if (a.providers != nil) && (time.Now().Unix() < a.providersExpiration) {
return a.providers, nil
}
req, err := http.NewRequest("GET", a.client.BaseURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
res, err := a.client.HTTPClient.Do(req)
if err != nil {
err = errors.Wrap(err,
fmt.Sprintf("mentix: error fetching provider list from: %s", a.client.BaseURL))
return nil, err
}
defer res.Body.Close()
providers := make([]*ocmprovider.ProviderInfo, 0)
if err = json.NewDecoder(res.Body).Decode(&providers); err != nil {
return nil, err
}
a.providers = a.getOCMProviders(providers)
if a.conf.RefreshInterval > 0 {
a.providersExpiration = time.Now().Unix() + a.conf.RefreshInterval
}
return a.providers, nil
}
func (a *authorizer) GetInfoByDomain(ctx context.Context, domain string) (*ocmprovider.ProviderInfo, error) {
normalizedDomain, err := normalizeDomain(domain)
if err != nil {
return nil, err
}
providers, err := a.fetchProviders()
if err != nil {
return nil, err
}
for _, p := range providers {
if strings.Contains(p.Domain, normalizedDomain) {
return p, nil
}
}
return nil, errtypes.NotFound(domain)
}
func (a *authorizer) IsProviderAllowed(ctx context.Context, pi *ocmprovider.ProviderInfo) error {
providers, err := a.fetchProviders()
if err != nil {
return err
}
normalizedDomain, err := normalizeDomain(pi.Domain)
if err != nil {
return err
}
var providerAuthorized bool
if normalizedDomain != "" {
for _, p := range providers {
if p.Domain == normalizedDomain {
providerAuthorized = true
break
}
}
} else {
providerAuthorized = true
}
switch {
case !providerAuthorized:
return errtypes.NotFound(pi.GetDomain())
case !a.conf.VerifyRequestHostname:
return nil
case len(pi.Services) == 0:
return errtypes.NotSupported(
fmt.Sprintf("mentix: provider %s has no supported services", pi.GetDomain()))
}
var ocmHost string
for _, p := range providers {
if p.Domain == normalizedDomain {
ocmHost, err = a.getOCMHost(p)
if err != nil {
return err
}
break
}
}
if ocmHost == "" {
return errtypes.NotSupported(
fmt.Sprintf("mentix: provider %s is missing OCM endpoint", pi.GetDomain()))
}
providerAuthorized = false
var ipList []string
if hostIPs, ok := a.providerIPs.Load(ocmHost); ok {
ipList = hostIPs.([]string)
} else {
addr, err := net.LookupIP(ocmHost)
if err != nil {
return errors.Wrap(err,
fmt.Sprintf("mentix: error looking up IPs for OCM endpoint %s", ocmHost))
}
for _, a := range addr {
ipList = append(ipList, a.String())
}
a.providerIPs.Store(ocmHost, ipList)
}
for _, ip := range ipList {
if ip == pi.Services[0].Host {
providerAuthorized = true
break
}
}
if !providerAuthorized {
return errtypes.BadRequest(
fmt.Sprintf(
"Invalid requesting OCM endpoint IP %s of provider %s",
pi.Services[0].Host, pi.GetDomain()))
}
return nil
}
func (a *authorizer) ListAllProviders(ctx context.Context) ([]*ocmprovider.ProviderInfo, error) {
providers, err := a.fetchProviders()
if err != nil {
return nil, err
}
return providers, nil
}
func (a *authorizer) getOCMProviders(providers []*ocmprovider.ProviderInfo) (po []*ocmprovider.ProviderInfo) {
for _, p := range providers {
_, err := a.getOCMHost(p)
if err == nil {
po = append(po, p)
}
}
return
}
func (a *authorizer) getOCMHost(provider *ocmprovider.ProviderInfo) (string, error) {
for _, s := range provider.Services {
if s.Endpoint.Type.Name == "OCM" {
ocmHost, err := url.Parse(s.Host)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf("mentix: error parsing OCM host URL %s", s.Host))
}
return ocmHost.Host, nil
}
}
return "", errtypes.NotFound("OCM Host")
}