summaryrefslogtreecommitdiff
path: root/internal/server/api.go
blob: 80ecf2e61800e508e27bbeacea3455979193466e (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
package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"

	httpw "github.com/jwijenbergh/eduvpn-common/internal/http"
	"github.com/jwijenbergh/eduvpn-common/internal/types"
)

func APIGetEndpoints(baseURL string) (*ServerEndpoints, error) {
	errorMessage := "failed getting server endpoints"
	url := fmt.Sprintf("%s/%s", baseURL, WellKnownPath)
	_, body, bodyErr := httpw.HTTPGet(url)

	if bodyErr != nil {
		return nil, &types.WrappedErrorMessage{Message: errorMessage, Err: bodyErr}
	}

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

	if jsonErr != nil {
		return nil, &types.WrappedErrorMessage{Message: errorMessage, Err: jsonErr}
	}

	return endpoints, nil
}

func apiAuthorized(
	server Server,
	method string,
	endpoint string,
	opts *httpw.HTTPOptionalParams,
) (http.Header, []byte, error) {
	errorMessage := "failed API authorized"
	// Ensure optional is not nil as we will fill it with headers
	if opts == nil {
		opts = &httpw.HTTPOptionalParams{}
	}
	base, baseErr := server.GetBase()

	if baseErr != nil {
		return nil, nil, &types.WrappedErrorMessage{Message: errorMessage, Err: baseErr}
	}

	url := base.Endpoints.API.V3.API + endpoint

	// Make sure the tokens are valid, this will return an error if re-login is needed
	oauthErr := EnsureTokens(server)
	if oauthErr != nil {
		return nil, nil, &types.WrappedErrorMessage{Message: errorMessage, Err: oauthErr}
	}

	headerKey := "Authorization"
	headerValue := fmt.Sprintf("Bearer %s", GetHeaderToken(server))
	if opts.Headers != nil {
		opts.Headers.Add(headerKey, headerValue)
	} else {
		opts.Headers = http.Header{headerKey: {headerValue}}
	}
	return httpw.HTTPMethodWithOpts(method, url, opts)
}

func apiAuthorizedRetry(
	server Server,
	method string,
	endpoint string,
	opts *httpw.HTTPOptionalParams,
) (http.Header, []byte, error) {
	errorMessage := "failed authorized API retry"
	header, body, bodyErr := apiAuthorized(server, method, endpoint, opts)

	if bodyErr != nil {
		var error *httpw.HTTPStatusError

		// Only retry authorized if we get a HTTP 401
		if errors.As(bodyErr, &error) && error.Status == 401 {
			// Mark the token as expired and retry so we trigger the refresh flow
			MarkTokenExpired(server)
			retryHeader, retryBody, retryErr := apiAuthorized(server, method, endpoint, opts)
			if retryErr != nil {
				return nil, nil, &types.WrappedErrorMessage{Message: errorMessage, Err: retryErr}
			}
			return retryHeader, retryBody, nil
		}
		return nil, nil, &types.WrappedErrorMessage{Message: errorMessage, Err: bodyErr}
	}
	return header, body, nil
}

func APIInfo(server Server) error {
	errorMessage := "failed API /info"
	_, body, bodyErr := apiAuthorizedRetry(server, http.MethodGet, "/info", nil)
	if bodyErr != nil {
		return &types.WrappedErrorMessage{Message: errorMessage, Err: bodyErr}
	}
	structure := ServerProfileInfo{}
	jsonErr := json.Unmarshal(body, &structure)

	if jsonErr != nil {
		return &types.WrappedErrorMessage{Message: errorMessage, Err: jsonErr}
	}

	base, baseErr := server.GetBase()

	if baseErr != nil {
		return &types.WrappedErrorMessage{Message: errorMessage, Err: baseErr}
	}

	// Store the profiles and make sure that the current profile is not overwritten
	previousProfile := base.Profiles.Current
	base.Profiles = structure
	base.Profiles.Current = previousProfile
	base.ProfilesRaw = string(body)
	return nil
}

func APIConnectWireguard(
	server Server,
	profile_id string,
	pubkey string,
	supportsOpenVPN bool,
) (string, string, time.Time, error) {
	errorMessage := "failed obtaining a WireGuard configuration"
	headers := http.Header{
		"content-type": {"application/x-www-form-urlencoded"},
		"accept":       {"application/x-wireguard-profile"},
	}

	if supportsOpenVPN {
		headers.Add("accept", "application/x-openvpn-profile")
	}

	urlForm := url.Values{
		"profile_id": {profile_id},
		"public_key": {pubkey},
	}
	header, connectBody, connectErr := apiAuthorizedRetry(
		server,
		http.MethodPost,
		"/connect",
		&httpw.HTTPOptionalParams{Headers: headers, Body: urlForm},
	)
	if connectErr != nil {
		return "", "", time.Time{}, &types.WrappedErrorMessage{
			Message: errorMessage,
			Err:     connectErr,
		}
	}

	expires := header.Get("expires")

	pTime, pTimeErr := http.ParseTime(expires)
	if pTimeErr != nil {
		return "", "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: pTimeErr}
	}

	contentType := header.Get("content-type")

	content := "openvpn"
	if contentType == "application/x-wireguard-profile" {
		content = "wireguard"
	}
	return string(connectBody), content, pTime, nil
}

func APIConnectOpenVPN(server Server, profile_id string) (string, time.Time, error) {
	errorMessage := "failed obtaining an OpenVPN configuration"
	headers := http.Header{
		"content-type": {"application/x-www-form-urlencoded"},
		"accept":       {"application/x-openvpn-profile"},
	}

	urlForm := url.Values{
		"profile_id": {profile_id},
	}

	header, connectBody, connectErr := apiAuthorizedRetry(
		server,
		http.MethodPost,
		"/connect",
		&httpw.HTTPOptionalParams{Headers: headers, Body: urlForm},
	)
	if connectErr != nil {
		return "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: connectErr}
	}

	expires := header.Get("expires")
	pTime, pTimeErr := http.ParseTime(expires)
	if pTimeErr != nil {
		return "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: pTimeErr}
	}
	return string(connectBody), pTime, nil
}

// This needs no further return value as it's best effort
// FIXME: doAuth should not be needed here
func APIDisconnect(server Server) {
	apiAuthorized(server, http.MethodPost, "/disconnect", nil)
}