summaryrefslogtreecommitdiff
path: root/internal/server.go
blob: 9d279072a81c0864a654da4451c89c2c05ced06e (plain)
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
package internal

import (
	"encoding/json"
	"fmt"
)

// The base type for servers
type ServerBase struct {
	URL         string            `json:"base_url"`
	Endpoints   ServerEndpoints   `json:"endpoints"`
	Profiles    ServerProfileInfo `json:"profiles"`
	ProfilesRaw string            `json:"profiles_raw"`
	Logger      *FileLogger       `json:"-"`
	FSM         *FSM              `json:"-"`
}

// An instute access server
type InstituteAccessServer struct {
	// An instute access server has its own OAuth
	OAuth OAuth `json:"oauth"`

	// Embed the server base
	Base ServerBase `json:"base"`
}

// A secure internet server which has its own OAuth tokens
// It specifies the current location url it is connected to
type SecureInternetHomeServer struct {
	OAuth OAuth `json:"oauth"`

	// The home server has a list of info for each configured server
	BaseMap map[string]*ServerBase `json:"base_map"`

	// We have the home url and the current url
	HomeURL    string `json:"home_url"`
	CurrentURL string `json:"current_url"`
}

type InstituteServers struct {
	Map        map[string]*InstituteAccessServer `json:"map"`
	CurrentURL string                            `json:"current_url"`
}

func (servers *Servers) GetCurrentServer() (Server, error) {
	if servers.IsSecureInternet {
		return &servers.SecureInternetHomeServer, nil
	}
	currentInstitute := servers.InstituteServers.CurrentURL
	institutes := servers.InstituteServers.Map
	if institutes == nil {
		return nil, &ServerGetCurrentNoMapError{}
	}
	institute, exists := institutes[currentInstitute]

	if !exists || institute == nil {
		return nil, &ServerGetCurrentNotFoundError{}
	}
	return institute, nil
}

type Servers struct {
	InstituteServers         InstituteServers         `json:"institute_servers"`
	SecureInternetHomeServer SecureInternetHomeServer `json:"secure_internet_home"`
	IsSecureInternet         bool                     `json:"is_secure_internet"`
}

type Server interface {
	// Gets the current OAuth object
	GetOAuth() *OAuth

	// Gets the server base
	GetBase() (*ServerBase, error)

	// initialize method
	init(url string, fsm *FSM, logger *FileLogger) error
}

// For an institute, we can simply get the OAuth
func (institute *InstituteAccessServer) GetOAuth() *OAuth {
	return &institute.OAuth
}

func (secure *SecureInternetHomeServer) GetOAuth() *OAuth {
	return &secure.OAuth
}

func (institute *InstituteAccessServer) GetBase() (*ServerBase, error) {
	return &institute.Base, nil
}

func (server *SecureInternetHomeServer) GetBase() (*ServerBase, error) {
	if server.BaseMap == nil {
		return nil, &ServerSecureInternetMapNotFoundError{}
	}

	base, exists := server.BaseMap[server.CurrentURL]

	if !exists {
		return nil, &ServerSecureInternetBaseNotFoundError{Current: server.CurrentURL}
	}
	return base, nil
}

func (institute *InstituteAccessServer) init(url string, fsm *FSM, logger *FileLogger) error {
	institute.Base.URL = url
	institute.Base.FSM = fsm
	institute.Base.Logger = logger
	endpoints, endpointsErr := getEndpoints(url)
	if endpointsErr != nil {
		return &ServerInitializeError{URL: url, Err: endpointsErr}
	}
	institute.OAuth.Init(endpoints.API.V3.Authorization, endpoints.API.V3.Token, fsm, logger)
	institute.Base.Endpoints = *endpoints
	return nil
}

func (secure *SecureInternetHomeServer) init(url string, fsm *FSM, logger *FileLogger) error {
	// Initialize the base map if it is non-nil
	if secure.BaseMap == nil {
		secure.BaseMap = make(map[string]*ServerBase)
	}

	// Add it if not present
	base, exists := secure.BaseMap[url]

	if !exists || base == nil {
		// Create the base to be added to the map
		base = &ServerBase{}
		base.URL = url
		endpoints, endpointsErr := getEndpoints(url)
		if endpointsErr != nil {
			return &ServerInitializeError{URL: url, Err: endpointsErr}
		}
		base.Endpoints = *endpoints
	}

	// Pass the fsm and logger
	base.FSM = fsm
	base.Logger = logger

	// Ensure it is in the map
	secure.BaseMap[url] = base

	// Set the home url if it is not set yet
	if secure.HomeURL == "" {
		secure.HomeURL = url
		// Make sure oauth contains our endpoints
		secure.OAuth.Init(base.Endpoints.API.V3.Authorization, base.Endpoints.API.V3.Token, fsm, logger)
	} else { // Else just pass in the fsm and logger
		secure.OAuth.Update(fsm, logger)
	}

	// Set the current url
	secure.CurrentURL = url
	return nil
}

func Login(server Server) error {
	return server.GetOAuth().Login("org.eduvpn.app.linux")
}

func EnsureTokens(server Server) error {
	base, baseErr := server.GetBase()

	if baseErr != nil {
		return &ServerEnsureTokensError{Err: baseErr}
	}
	if server.GetOAuth().NeedsRelogin() {
		base.Logger.Log(LOG_INFO, "OAuth: Tokens are invalid, relogging in")
		loginErr := Login(server)

		if loginErr != nil {
			return &ServerEnsureTokensError{Err: loginErr}
		}
	}
	return nil
}

func NeedsRelogin(server Server) bool {
	return server.GetOAuth().NeedsRelogin()
}

func CancelOAuth(server Server) {
	server.GetOAuth().Cancel()
}

func (servers *Servers) EnsureServer(url string, isSecureInternet bool, fsm *FSM, logger *FileLogger) (Server, error) {
	// Intialize the secure internet server
	// This calls the init method which takes care of the rest
	if isSecureInternet {
		initErr := servers.SecureInternetHomeServer.init(url, fsm, logger)

		if initErr != nil {
			return nil, &ServerEnsureServerError{Err: initErr}
		}

		servers.IsSecureInternet = true
		return &servers.SecureInternetHomeServer, nil
	}

	instituteServers := &servers.InstituteServers

	if instituteServers.Map == nil {
		instituteServers.Map = make(map[string]*InstituteAccessServer)
	}

	institute, exists := instituteServers.Map[url]

	// initialize the server if it doesn't exist yet
	if !exists {
		institute = &InstituteAccessServer{}
	}

	// Set the current server
	instituteServers.CurrentURL = url
	instituteInitErr := institute.init(url, fsm, logger)
	if instituteInitErr != nil {
		return nil, &ServerEnsureServerError{Err: instituteInitErr}
	}
	instituteServers.Map[url] = institute
	servers.IsSecureInternet = false
	return institute, nil
}

type ServerProfile struct {
	ID             string   `json:"profile_id"`
	DisplayName    string   `json:"display_name"`
	VPNProtoList   []string `json:"vpn_proto_list"`
	DefaultGateway bool     `json:"default_gateway"`
}

type ServerProfileInfo struct {
	Current string `json:"current_profile"`
	Info    struct {
		ProfileList []ServerProfile `json:"profile_list"`
	} `json:"info"`
}

type ServerEndpointList struct {
	API           string `json:"api_endpoint"`
	Authorization string `json:"authorization_endpoint"`
	Token         string `json:"token_endpoint"`
}

// Struct that defines the json format for /.well-known/vpn-user-portal"
type ServerEndpoints struct {
	API struct {
		V2 ServerEndpointList `json:"http://eduvpn.org/api#2"`
		V3 ServerEndpointList `json:"http://eduvpn.org/api#3"`
	} `json:"api"`
	V string `json:"v"`
}

// Make this a var which we can overwrite in the tests
var WellKnownPath string = ".well-known/vpn-user-portal"

func getEndpoints(baseURL string) (*ServerEndpoints, error) {
	url := fmt.Sprintf("%s/%s", baseURL, WellKnownPath)
	_, body, bodyErr := HTTPGet(url)

	if bodyErr != nil {
		return nil, &ServerGetEndpointsError{Err: bodyErr}
	}

	endpoints := &ServerEndpoints{}
	jsonErr := json.Unmarshal(body, endpoints)

	if jsonErr != nil {
		return nil, &ServerGetEndpointsError{Err: jsonErr}
	}

	return endpoints, nil
}

func (profile *ServerProfile) supportsWireguard() bool {
	for _, proto := range profile.VPNProtoList {
		if proto == "wireguard" {
			return true
		}
	}
	return false
}

func getCurrentProfile(server Server) (*ServerProfile, error) {
	base, baseErr := server.GetBase()

	if baseErr != nil {
		return nil, &ServerGetCurrentProfileError{Err: baseErr}
	}
	profileID := base.Profiles.Current
	for _, profile := range base.Profiles.Info.ProfileList {
		if profile.ID == profileID {
			return &profile, nil
		}
	}
	return nil, &ServerGetCurrentProfileNotFoundError{ProfileID: profileID}
}

func getConfigWithProfile(server Server) (string, error) {
	base, baseErr := server.GetBase()

	if baseErr != nil {
		return "", &ServerGetConfigWithProfileError{Err: baseErr}
	}
	if !base.FSM.HasTransition(HAS_CONFIG) {
		return "", &FSMWrongStateTransitionError{Got: base.FSM.Current, Want: HAS_CONFIG}
	}
	profile, profileErr := getCurrentProfile(server)

	if profileErr != nil {
		return "", &ServerGetConfigWithProfileError{Err: profileErr}
	}

	if profile.supportsWireguard() {
		return WireguardGetConfig(server)
	}
	return OpenVPNGetConfig(server)
}

func askForProfileID(server Server) error {
	base, baseErr := server.GetBase()

	if baseErr != nil {
		return &ServerAskForProfileIDError{Err: baseErr}
	}
	if !base.FSM.HasTransition(ASK_PROFILE) {
		return &FSMWrongStateTransitionError{Got: base.FSM.Current, Want: ASK_PROFILE}
	}
	base.FSM.GoTransitionWithData(ASK_PROFILE, base.ProfilesRaw, false)
	return nil
}

func GetConfig(server Server) (string, error) {
	base, baseErr := server.GetBase()

	if baseErr != nil {
		return "", &ServerGetConfigError{Err: baseErr}
	}
	if !base.FSM.InState(REQUEST_CONFIG) {
		return "", &FSMWrongStateError{Got: base.FSM.Current, Want: REQUEST_CONFIG}
	}
	infoErr := APIInfo(server)

	if infoErr != nil {
		return "", &ServerGetConfigError{Err: infoErr}
	}

	// Set the current profile if there is only one profile
	if len(base.Profiles.Info.ProfileList) == 1 {
		base.Profiles.Current = base.Profiles.Info.ProfileList[0].ID
		return getConfigWithProfile(server)
	}

	profileErr := askForProfileID(server)

	if profileErr != nil {
		return "", &ServerGetConfigError{Err: profileErr}
	}

	return getConfigWithProfile(server)
}

type ServerGetCurrentProfileNotFoundError struct {
	ProfileID string
}

func (e *ServerGetCurrentProfileNotFoundError) Error() string {
	return fmt.Sprintf("failed to get current profile, profile with ID: %s not found", e.ProfileID)
}

type ServerGetConfigWithProfileError struct {
	Err error
}

func (e *ServerGetConfigWithProfileError) Error() string {
	return fmt.Sprintf("failed to get config including profile with error %v", e.Err)
}

type ServerGetEndpointsError struct {
	Err error
}

func (e *ServerGetEndpointsError) Error() string {
	return fmt.Sprintf("failed to get server endpoint with error %v", e.Err)
}

type ServerGetSecureInternetHomeError struct{}

func (e *ServerGetSecureInternetHomeError) Error() string {
	return "failed to get secure internet home server, not found"
}

type ServerCopySecureInternetOAuthError struct {
	Err error
}

func (e *ServerCopySecureInternetOAuthError) Error() string {
	return fmt.Sprintf("failed to copy oauth tokens from home server with error %v", e.Err)
}

type ServerEnsureServerEmptyURLError struct{}

func (e *ServerEnsureServerEmptyURLError) Error() string {
	return "failed ensuring server, empty url provided"
}

type ServerEnsureServerError struct {
	Err error
}

func (e *ServerEnsureServerError) Error() string {
	return fmt.Sprintf("failed ensuring server with error %v", e.Err)
}

type ServerGetCurrentNoMapError struct{}

func (e *ServerGetCurrentNoMapError) Error() string {
	return "failed getting current server, no servers available"
}

type ServerGetCurrentNotFoundError struct{}

func (e *ServerGetCurrentNotFoundError) Error() string {
	return "failed getting current server, not found"
}

type ServerGetConfigError struct {
	Err error
}

func (e *ServerGetConfigError) Error() string {
	return fmt.Sprintf("failed getting server config with error %v", e.Err)
}

type ServerInitializeError struct {
	URL string
	Err error
}

func (e *ServerInitializeError) Error() string {
	return fmt.Sprintf("failed initializing server with url %s and error %v", e.URL, e.Err)
}

type ServerInstituteBaseNotFoundError struct {
	Err error
}

func (e *ServerInstituteBaseNotFoundError) Error() string {
	return "institute base not found"
}

type ServerSecureInternetMapNotFoundError struct{}

func (e *ServerSecureInternetMapNotFoundError) Error() string {
	return "secure internet map not found"
}

type ServerSecureInternetBaseNotFoundError struct {
	Current string
}

func (e *ServerSecureInternetBaseNotFoundError) Error() string {
	return fmt.Sprintf("secure internet base not found with current: %s", e.Current)
}

type ServerGetCurrentProfileError struct {
	Err error
}

func (e *ServerGetCurrentProfileError) Error() string {
	return fmt.Sprintf("failed getting current profile with error: %v", e.Err)
}

type ServerAskForProfileIDError struct {
	Err error
}

func (e *ServerAskForProfileIDError) Error() string {
	return fmt.Sprintf("ask for profile ID error: %v", e.Err)
}

type ServerEnsureTokensError struct {
	Err error
}

func (e *ServerEnsureTokensError) Error() string {
	return fmt.Sprintf("failed ensuring tokens with error: %v", e.Err)
}