-
Notifications
You must be signed in to change notification settings - Fork 6
/
agent.go
153 lines (138 loc) · 4.01 KB
/
agent.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
package main
import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"time"
)
const (
defaultTokenFileLoc = "/var/lib/wiresteward/token"
)
// Agent is the wirestward client instance that manages a set of network devices
// based on configuration generated by remote wiresteward servers.
type Agent struct {
deviceManagers []*DeviceManager
oa *oauthTokenHandler
}
// NewAgent creates an Agent from an AgentConfig. It generates a DeviceManager
// per device specified in the configuration, sets up and starts the associated
// resources.
func NewAgent(cfg *agentConfig) *Agent {
agent := &Agent{}
for _, dev := range cfg.Devices {
urls := []string{}
for _, peer := range dev.Peers {
urls = append(urls, peer.URL)
}
dm := newDeviceManager(dev.Name, dev.MTU, urls, cfg.HTTPClient.Timeout, cfg.HealthCheck)
if err := dm.Run(); err != nil {
logger.Errorf(
"Error starting device `%s`: %v",
dm.Name(),
err,
)
continue
}
agent.deviceManagers = append(agent.deviceManagers, dm)
}
tokenDir := filepath.Dir(defaultTokenFileLoc)
err := os.MkdirAll(tokenDir, 0750)
if err != nil {
logger.Errorf("Unable to create directory=%s", tokenDir)
}
agent.oa = newOAuthTokenHandler(
cfg.OAuth.AuthURL,
cfg.OAuth.TokenURL,
cfg.OAuth.ClientID,
defaultTokenFileLoc,
)
return agent
}
// ListenAndServe sets up and starts an http server, to allow for the OAuth2
// exchange and token renewal.
func (a *Agent) ListenAndServe() {
http.HandleFunc("/oauth2/callback", a.callbackHandler)
http.HandleFunc("/renew", a.renewHandler)
http.HandleFunc("/", a.mainHandler)
logger.Verbosef("Starting agent at http://%s", *flagAgentAddress)
token, err := a.oa.getTokenFromFile()
if err != nil || token.AccessToken == "" || token.Expiry.Before(time.Now()) {
logger.Errorf("cannot get a valid cached token, you need to authenticate")
} else {
a.renewAllLeases(token.AccessToken)
}
if err := http.ListenAndServe(*flagAgentAddress, nil); err != nil {
logger.Errorf("%v", err)
}
}
// Stop calls the Stop method on all DeviceManager instances that this Agent
// controls.
func (a *Agent) Stop() {
for _, dm := range a.deviceManagers {
dm.Stop()
}
}
func (a *Agent) renewAllLeases(token string) {
logger.Verbosef("Running renew leases loop..")
for _, dm := range a.deviceManagers {
dm.RenewTokenAndLease(token)
}
}
func (a *Agent) callbackHandler(w http.ResponseWriter, r *http.Request) {
stateCookie, err := r.Cookie(oauthStateCookieName)
if errors.Is(err, http.ErrNoCookie) {
logger.Errorf("State cookie missing: %s", err)
http.Error(w, "State cookie missing", 500)
return
}
if err != nil {
logger.Errorf("Failed to retrieve state cookie: %s", err)
http.Error(w, "Failed to retrieve state cookie", 500)
return
}
if r.FormValue("state") != stateCookie.Value {
logger.Errorf(
"State token missmatch: expected=%s received=%s", stateCookie.Value, r.FormValue("state"),
)
http.Error(w, "State token missmatch", 500)
return
}
token, err := a.oa.ExchangeToken(r.FormValue("code"))
if err != nil {
fmt.Fprintf(
w,
"error fetching token from web: %v",
err,
)
return
}
a.renewAllLeases(token.AccessToken)
// Redirect to / after renewing leases
rootURL := fmt.Sprintf("http://%s/", r.Host)
http.Redirect(w, r, rootURL, 302)
}
// renewHandler will initiate the auth challenge. Leases renewal will be handled
// in the callback handler.
func (a *Agent) renewHandler(w http.ResponseWriter, r *http.Request) {
url, err := a.oa.prepareTokenWebChalenge(w)
if err != nil {
fmt.Fprintf(w, "error creating web url to get token: %v", err)
return
}
http.Redirect(w, r, url, 302)
}
func (a *Agent) mainHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
token, err := a.oa.getTokenFromFile()
if err != nil || token.AccessToken == "" {
logger.Errorf("cannot get a valid cached token, you need to authenticate")
statusHTTPWriter(w, r, a.deviceManagers, nil)
return
}
statusHTTPWriter(w, r, a.deviceManagers, token)
}