Skip to content

Commit f4b7ec2

Browse files
Fix silly "runner remove" logic error (#184)
* make trace work for github auth and pat token request * fix don't retry session creation after removal, since error message changed
1 parent fb09403 commit f4b7ec2

5 files changed

Lines changed: 38 additions & 34 deletions

File tree

.github/workflows/build.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,12 @@ jobs:
262262
# Show debug logs of loglevel test
263263
./actions-runner/Runner.Client --server http://localhost:5000 -W ./.github/testworkflows/loglevel.yml --log-output-dir ./logs -s ACTIONS_STEP_DEBUG=true
264264
265+
- name: Test if removal works
266+
timeout-minutes: 1
267+
run: |
268+
export JIT_TOKEN="$(./runner/github-act-runner configure --unattended --url http://localhost:5000/runner/test --token WhichToken --print-jitconfig)"
269+
./runner/github-act-runner remove --jitconfig "$JIT_TOKEN" --token WhichToken
270+
./runner/github-act-runner run --jitconfig "$JIT_TOKEN" && exit 1 || [[ "$?" = "1" ]]
265271
- name: Archive Test Results
266272
if: ${{always()}}
267273
run: tar czf ../logs.tar.gz .

actionsrunner/runner.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,8 @@ func (run *RunRunner) Run(runnerenv RunnerEnvironment, listenerctx context.Conte
248248
deleteSession()
249249
session2, err := vssConnection.CreateSession(joblisteningctx)
250250
if err != nil {
251-
if strings.Contains(err.Error(), "invalid_client") || strings.Contains(err.Error(), "TaskAgentNotFoundException") {
252-
runnerenv.Printf("Fatal: It seems this runner was removed from GitHub, Failed to recreate Session for %v ( %v ): %v\n", instance.Agent.Name, instance.RegistrationURL, err.Error())
251+
if strings.Contains(err.Error(), "invalid_client") || strings.Contains(err.Error(), "invalid_grant") || strings.Contains(err.Error(), "TaskAgentNotFoundException") || /* runner.server only */ strings.Contains(err.Error(), "Not Found") {
252+
runnerenv.Printf("Fatal: It looks like this runner has been removed from GitHub, Failed to recreate Session for %v ( %v ): %v\n", instance.Agent.Name, instance.RegistrationURL, err.Error())
253253
return 1
254254
}
255255
runnerenv.Printf("Failed to recreate Session for %v ( %v ), waiting 30 sec before retry: %v\n", instance.Agent.Name, instance.RegistrationURL, err.Error())

main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ func main() {
306306
remove.ReadFromEnvironment()
307307
var settings *runnerconfiguration.RunnerSettings
308308
var err error
309-
if local {
309+
if !local {
310310
if jitConfig != "" {
311311
if settings, err = runnerCompat.ParseJitRunnerConfig(jitConfig); err != nil {
312312
fmt.Printf("jitconfig is corrupted: %v, please reconfigure the runner\n", err.Error())
@@ -349,7 +349,7 @@ func main() {
349349
cmdRemove.Flags().StringVar(&remove.Name, "name", "", "name of the runner to remove")
350350
cmdRemove.Flags().BoolVar(&remove.Trace, "trace", false, "trace http communication with the github action service")
351351
cmdRemove.Flags().BoolVar(&remove.Force, "force", false, "force remove the instance even if the service responds with an error")
352-
cmdRemove.Flags().StringVarP(&jitConfig, "jitconfig", "", os.Getenv("ACTIONS_RUNNER_INPUT_JITCONFIG"), "read the runner configuration from the jitconfig")
352+
cmdRemove.Flags().StringVarP(&jitConfig, "jitconfig", "", os.Getenv("ACTIONS_RUNNER_INPUT_JITCONFIG"), "read the runner configuration from the jitconfig, this doesn't replace token/pat")
353353
cmdRemove.Flags().BoolVar(&local, "local", local, "only delete the configuration")
354354

355355
var cmdWorker = &cobra.Command{

protocol/connection.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ type VssConnection struct {
2525
TenantURL string
2626
connectionData *ConnectionData
2727
Token string
28+
AuthHeader string
2829
PoolID int64
2930
TaskAgent *TaskAgent
3031
Key *rsa.PrivateKey
@@ -230,6 +231,8 @@ func (vssConnection *VssConnection) requestWithContextNoAuth(ctx context.Context
230231
}
231232
if len(vssConnection.Token) > 0 {
232233
header["Authorization"] = []string{"bearer " + vssConnection.Token}
234+
} else if len(vssConnection.AuthHeader) > 0 {
235+
header["Authorization"] = []string{vssConnection.AuthHeader}
233236
}
234237
if vssConnection.Trace {
235238
fmt.Printf("Http %v Request started %v\nHeaders:\n%v\nBody: `%v`\n", method, requesturl, getHeadersAsString(request.Header), getBodyAsString(buf))
@@ -264,7 +267,7 @@ func (vssConnection *VssConnection) requestWithContextNoAuth(ctx context.Context
264267
if failed {
265268
return response.StatusCode, fmt.Errorf("http failure: %v", traceMessage)
266269
}
267-
if response.StatusCode != 200 && responseBody != nil {
270+
if response.StatusCode == 204 && responseBody != nil {
268271
return response.StatusCode, io.EOF
269272
}
270273
return response.StatusCode, setResponseBody(responseReader, responseBody)

runnerconfiguration/common.go

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ package runnerconfiguration
22

33
import (
44
"bytes"
5+
"context"
56
"crypto/rsa"
67
"crypto/tls"
78
"crypto/x509"
89
"encoding/base64"
910
"encoding/json"
1011
"fmt"
11-
"io/ioutil"
1212
"net/http"
1313
"net/url"
1414
"os"
@@ -96,9 +96,15 @@ type RunnerSettings struct {
9696
}
9797

9898
func gitHubAuth(config *ConfigureRemoveRunner, c *http.Client, runnerEvent string, apiEndpoint string, survey Survey) (*protocol.GitHubAuthResult, error) {
99+
if config.URL == "" {
100+
config.URL = survey.GetInput("Which GitHub Url is assosiated with this runner (Normally this isn't missing):", "")
101+
}
99102
registerUrl, err := url.Parse(config.URL)
100103
if err != nil {
101-
return nil, fmt.Errorf("invalid Url: %v\n", config.URL)
104+
return nil, fmt.Errorf("invalid Url: %v", config.URL)
105+
}
106+
if registerUrl.Hostname() == "" {
107+
return nil, fmt.Errorf("invalid Url missing Hostname: %v", config.URL)
102108
}
103109
apiscope := "/"
104110
if strings.ToLower(registerUrl.Host) == "github.com" {
@@ -122,22 +128,15 @@ func gitHubAuth(config *ConfigureRemoveRunner, c *http.Client, runnerEvent strin
122128
} else {
123129
return nil, fmt.Errorf("unsupported registration url")
124130
}
125-
req, _ := http.NewRequest("POST", url.String(), nil)
126-
req.SetBasicAuth("github", config.Pat)
127-
req.Header.Add("Accept", "application/vnd.github.v3+json")
128-
resp, err := c.Do(req)
129-
if err != nil {
130-
return nil, fmt.Errorf("failed to retrieve %v token via pat: %v\n", apiEndpoint, err.Error())
131-
}
132-
defer resp.Body.Close()
133-
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
134-
body, _ := ioutil.ReadAll(resp.Body)
135-
return nil, fmt.Errorf("failed to retrieve %v via pat [%v]: %v\n", apiEndpoint, fmt.Sprint(resp.StatusCode), string(body))
131+
client := &protocol.VssConnection{
132+
AuthHeader: fmt.Sprintf("Basic %v", base64.StdEncoding.EncodeToString([]byte("GitHub:"+config.Pat))),
133+
Trace: config.Trace,
134+
Client: c,
136135
}
137136
tokenresp := &protocol.GitHubRunnerRegisterToken{}
138-
dec := json.NewDecoder(resp.Body)
139-
if err := dec.Decode(tokenresp); err != nil {
140-
return nil, fmt.Errorf("failed to decode registration token via pat: " + err.Error())
137+
err = client.RequestWithContext2(context.Background(), "POST", url.String(), "", nil, tokenresp)
138+
if err != nil {
139+
return nil, fmt.Errorf("failed to retrieve %v token via pat: %v", apiEndpoint, err.Error())
141140
}
142141
config.Token = tokenresp.Token
143142
} else if !config.Unattended {
@@ -159,21 +158,16 @@ func gitHubAuth(config *ConfigureRemoveRunner, c *http.Client, runnerEvent strin
159158
}
160159
finalregisterUrl := registerUrl.String()
161160

162-
r, _ := http.NewRequest("POST", finalregisterUrl, buf)
163-
r.Header["Authorization"] = []string{"RemoteAuth " + config.Token}
164-
resp, err := c.Do(r)
165-
if err != nil {
166-
return nil, fmt.Errorf("failed to register Runner: %v\n", err)
161+
client := &protocol.VssConnection{
162+
AuthHeader: "RemoteAuth " + config.Token,
163+
Trace: config.Trace,
164+
Client: c,
167165
}
168-
defer resp.Body.Close()
169-
if resp.StatusCode != 200 {
170-
return nil, fmt.Errorf("failed to register Runner with status code: %v\n", resp.StatusCode)
171-
}
172-
173166
res := &protocol.GitHubAuthResult{}
174-
dec := json.NewDecoder(resp.Body)
175-
if err := dec.Decode(res); err != nil {
176-
return nil, fmt.Errorf("error decoding struct from JSON: %v\n", err)
167+
err = client.RequestWithContext2(context.Background(), "POST", finalregisterUrl, "", buf, res)
168+
169+
if err != nil {
170+
return nil, fmt.Errorf("failed to authenticate as Runner Admin: %v", err)
177171
}
178172
return res, nil
179173
}
@@ -189,6 +183,7 @@ func (config *RemoveRunner) Authenticate(c *http.Client, survey Survey) (*protoc
189183
func (config *ConfigureRunner) Authenicate(c *http.Client, survey Survey) (*protocol.GitHubAuthResult, error) {
190184
return config.Authenticate(c, survey)
191185
}
186+
192187
// Deprecated: Use the Authenticate method.
193188
func (config *RemoveRunner) Authenicate(c *http.Client, survey Survey) (*protocol.GitHubAuthResult, error) {
194189
return config.Authenticate(c, survey)

0 commit comments

Comments
 (0)