-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweb.go
More file actions
executable file
·232 lines (194 loc) · 5.49 KB
/
web.go
File metadata and controls
executable file
·232 lines (194 loc) · 5.49 KB
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
package web
import (
"context"
"errors"
"fmt"
"net/http"
nurl "net/url"
"os"
"strings"
"time"
"github.com/DevLabFoundry/aws-cli-auth/internal/credentialexchange"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/utils"
)
var (
ErrTimedOut = errors.New("timed out waiting for input or user closed aws-cli-auth browser instance")
)
// WebConfig
type WebConfig struct {
// CustomChromeExecutable can point to a chromium like browser executable
// e.g. chrome, chromium, brave, edge, (any other chromium based browser)
CustomChromeExecutable string
datadir string
// timeout value in seconds
timeout int32
headless bool
leakless bool
noSandbox bool
}
func NewWebConf(datadir string) *WebConfig {
return &WebConfig{
datadir: datadir,
headless: false,
timeout: 120,
}
}
func (wc *WebConfig) WithTimeout(timeoutSeconds int32) *WebConfig {
wc.timeout = timeoutSeconds
return wc
}
func (wc *WebConfig) WithHeadless() *WebConfig {
wc.headless = true
return wc
}
func (wc *WebConfig) WithNoSandbox() *WebConfig {
wc.noSandbox = true
return wc
}
type Web struct {
conf *WebConfig
launcher *launcher.Launcher
browser *rod.Browser
ctx context.Context
}
// New returns an initialised instance of Web struct
func New(ctx context.Context, conf *WebConfig) *Web {
l := BuildLauncher(ctx, conf)
url := l.MustLaunch()
browser := rod.New().
ControlURL(url).
MustConnect().NoDefaultDevice()
web := &Web{
conf: conf,
launcher: l,
browser: browser,
ctx: ctx,
}
return web
}
func BuildLauncher(ctx context.Context, conf *WebConfig) *launcher.Launcher {
l := launcher.New()
if conf.CustomChromeExecutable != "" {
l.Bin(conf.CustomChromeExecutable)
}
// try default locations if custom location is not specified and default location exists
if defaultExecPath, found := launcher.LookPath(); conf.CustomChromeExecutable == "" && defaultExecPath != "" && found {
l.Bin(defaultExecPath)
}
// common set up
l.Devtools(false).
UserDataDir(conf.datadir).
Headless(conf.headless).
NoSandbox(conf.noSandbox).
Leakless(conf.leakless)
return l
}
func (web *Web) WithConfig(conf *WebConfig) *Web {
web.conf = conf
return web
}
// GetSamlLogin performs a saml login for a given
func (web *Web) GetSamlLogin(conf credentialexchange.CredentialConfig) (string, error) {
// close browser even on error
// should cover most cases even with leakless: false
defer web.MustClose()
web.browser.MustPage(conf.ProviderUrl)
router := web.browser.HijackRequests()
defer router.MustStop()
capturedSaml := make(chan string)
router.MustAdd(fmt.Sprintf("%s*", conf.AcsUrl), func(ctx *rod.Hijack) {
if ctx.Request.Method() == "POST" || ctx.Request.Method() == "GET" {
cp := ctx.Request.Body()
capturedSaml <- cp
}
})
go router.Run()
go func() {
<-web.ctx.Done()
web.MustClose()
}()
// forever loop wait for either a successfully
// extracted SAMLResponse
//
// Timesout after a specified timeout - default 120s
for {
select {
case saml := <-capturedSaml:
saml = strings.Split(saml, "SAMLResponse=")[1]
saml = strings.Split(saml, "&")[0]
return nurl.QueryUnescape(saml)
case <-time.After(time.Duration(web.conf.timeout) * time.Second):
return "", fmt.Errorf("%w", ErrTimedOut)
// listen for closing of browser
// gracefully clean up
case browserEvent := <-web.browser.Event():
if browserEvent != nil && browserEvent.Method == "Inspector.detached" {
return "", fmt.Errorf("%w", ErrTimedOut)
}
}
}
}
// GetSSOCredentials
func (web *Web) GetSSOCredentials(conf credentialexchange.CredentialConfig) (string, error) {
go func() {
<-web.ctx.Done()
web.MustClose()
}()
// close browser even on error
// should cover most cases even with leakless: false
defer web.MustClose()
web.browser.MustPage(conf.ProviderUrl)
router := web.browser.HijackRequests()
defer router.MustStop()
capturedCreds, loadedUserInfo := make(chan string), make(chan bool)
router.MustAdd(conf.SsoUserEndpoint, func(ctx *rod.Hijack) {
ctx.MustLoadResponse()
if ctx.Request.Method() == "GET" {
ctx.Response.SetHeader(
"Content-Type", "text/html; charset=utf-8",
"Content-Location", conf.SsoCredFedEndpoint,
"Location", conf.SsoCredFedEndpoint)
ctx.Response.Payload().ResponseCode = http.StatusMovedPermanently
loadedUserInfo <- true
}
})
router.MustAdd(conf.SsoCredFedEndpoint, func(ctx *rod.Hijack) {
_ = ctx.LoadResponse(http.DefaultClient, true)
if ctx.Request.Method() == "GET" {
cp := ctx.Response.Body()
capturedCreds <- cp
}
})
go router.Run()
// forever loop wait for either a successfully
// extracted Creds
//
// Timesout after a specified timeout - default 120s
for {
select {
case <-loadedUserInfo:
// empty case to ensure user endpoint sets correct clientside cookies
case creds := <-capturedCreds:
return creds, nil
case <-time.After(time.Duration(web.conf.timeout) * time.Second):
return "", fmt.Errorf("%w", ErrTimedOut)
// listen for closing of browser
// gracefully clean up
case browserEvent := <-web.browser.Event():
if browserEvent != nil && browserEvent.Method == "Inspector.detached" {
return "", fmt.Errorf("%w", ErrTimedOut)
}
}
}
}
func (web *Web) MustClose() {
// swallows errors here - until a structured logger
_ = web.browser.Close()
utils.Sleep(0.5)
// remove process just in case
// os.Process is cross platform safe way to remove a process
osprocess := os.Process{Pid: web.launcher.PID()}
_ = osprocess.Kill()
}