-
Notifications
You must be signed in to change notification settings - Fork 47
/
credservice.go
84 lines (80 loc) · 2.2 KB
/
credservice.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
package main
import (
"context"
"net/http"
"sync"
"time"
)
const DEFAULT_LIST_LIMIT = 3
func CredService(interval, timeout time.Duration,
extVer string,
country string,
proxytype string,
logger *CondLogger,
backoffInitial time.Duration,
backoffDeadline time.Duration,
) (auth AuthProvider, tunnels *ZGetTunnelsResponse, err error) {
var mux sync.Mutex
var auth_header, user_uuid string
auth = func() (res string) {
(&mux).Lock()
res = auth_header
(&mux).Unlock()
return
}
tx_res, tx_err := EnsureTransaction(context.Background(), timeout, func(ctx context.Context, client *http.Client) bool {
tunnels, user_uuid, err = Tunnels(ctx, logger, client, extVer, country, proxytype,
DEFAULT_LIST_LIMIT, timeout, backoffInitial, backoffDeadline)
if err != nil {
logger.Error("Configuration bootstrap error: %v. Retrying with the fallback mechanism...", err)
return false
}
return true
})
if tx_err != nil {
logger.Critical("Transaction recovery mechanism failure: %v", tx_err)
err = tx_err
return
}
if !tx_res {
logger.Critical("All attempts failed.")
return
}
auth_header = basic_auth_header(TemplateLogin(user_uuid), tunnels.AgentKey)
go func() {
var (
err error
tuns *ZGetTunnelsResponse
user_uuid string
)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
<-ticker.C
logger.Info("Rotating credentials...")
tx_res, tx_err := EnsureTransaction(context.Background(), timeout, func(ctx context.Context, client *http.Client) bool {
tuns, user_uuid, err = Tunnels(ctx, logger, client, extVer, country, proxytype,
DEFAULT_LIST_LIMIT, timeout, backoffInitial, backoffDeadline)
if err != nil {
logger.Error("Credential rotation error: %v. Retrying with the fallback mechanism...", err)
return false
}
return true
})
if tx_err != nil {
logger.Critical("Transaction recovery mechanism failure: %v", tx_err)
err = tx_err
continue
}
if !tx_res {
logger.Critical("All rotation attempts failed.")
continue
}
(&mux).Lock()
auth_header = basic_auth_header(TemplateLogin(user_uuid), tuns.AgentKey)
(&mux).Unlock()
logger.Info("Credentials rotated successfully.")
}
}()
return
}