| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | ) |
| 21 | |
| 22 | // A runner that can only be a worker asks the instance which protocol it |
| 23 | // speaks before it enrols: an older instance (no protocol route) would take |
| 24 | // the newest runner for the person's primary, so the worker is refused |
| 25 | // with a fixed diagnostic and nothing is sent to the enrolment routes. |
| 26 | func TestWorkerEnrolRefusesAnOlderInstance(t *testing.T) { |
| 27 | for _, tc := range []struct { |
| 28 | name string |
| 29 | protocol string |
| 30 | refused bool |
| 31 | }{ |
| 32 | {"older instance", "", true}, |
| 33 | {"protocol 1", `{"protocol":1}`, true}, |
| 34 | {"protocol 2", `{"protocol":2}`, false}, |
| 35 | } { |
| 36 | t.Run(tc.name, func(t *testing.T) { |
| 37 | var mu sync.Mutex |
| 38 | var paths []string |
| 39 | var begun runnerproto.BeginEnrolmentRequest |
| 40 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 41 | if err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 45 | mu.Lock() |
| 46 | paths = append(paths, r.Method+" "+r.URL.Path) |
| 47 | mu.Unlock() |
| 48 | if r.URL.Path == "/api/enrolments" { |
| 49 | _ = json.NewDecoder(r.Body).Decode(&begun) |
| 50 | } |
| 51 | if r.URL.Path == wire.RunnerProtocolPath && tc.protocol != "" { |
| 52 | _, _ = w.Write([]byte(tc.protocol)) |
| 53 | return |
| 54 | } |
| 55 | http.Error(w, "no", http.StatusNotFound) |
| 56 | })} |
| 57 | go srv.Serve(l) |
| 58 | defer srv.Close() |
| 59 | c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: filepath.Join(t.TempDir(), "state"), WorkerOnly: true} |
| 60 | err = Enrol(context.Background(), c, nil) |
| 61 | code, _ := Diagnostic(err) |
| 62 | mu.Lock() |
| 63 | defer mu.Unlock() |
| 64 | if tc.refused { |
| 65 | if code != "runner.instance_older_than_worker" || len(paths) != 1 { |
| 66 | t.Fatalf("refused %q after %v", code, paths) |
| 67 | } |
| 68 | return |
| 69 | } |
| 70 | if code == "runner.instance_older_than_worker" || len(paths) < 2 { |
| 71 | t.Fatalf("protocol 2 instance refused: %q %v", code, paths) |
| 72 | } |
| 73 | // It says it can only be a worker, so the instance refuses to |
| 74 | // make it anyone's first (primary) runner. |
| 75 | if !begun.WorkerOnly { |
| 76 | t.Fatal("a worker-only machine did not say so") |
| 77 | } |
| 78 | }) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // Enrolment keeps the role the instance gave the runner with its |
| 83 | // credential, before the runner ever connects: worker when the instance |
| 84 | // says so, primary when it says nothing (a primary, or an instance |
| 85 | // without workers). |
| 86 | func TestEnrolKeepsTheRole(t *testing.T) { |
| 87 | for _, tc := range []struct { |
| 88 | answer, want string |
| 89 | mac bool |
| 90 | }{{`,"role":"worker"`, "worker", false}, {"", "primary", false}, {`,"role":"worker"`, "worker", true}, {"", "", true}} { |
| 91 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 92 | if err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 96 | switch r.URL.Path { |
| 97 | case wire.RunnerProtocolPath: |
| 98 | _, _ = w.Write([]byte(`{"protocol":2}`)) |
| 99 | case "/api/enrolments": |
| 100 | _, _ = fmt.Fprintf(w, `{"version":1,"enrolment_id":"e1","instance_id":"inst","device_secret":"s","user_code":"ABCD-EFGH","challenge":"c","verification_uri":"http://%s/runners/enrol","expires_at":%q,"poll_interval_seconds":5}`, r.Host, time.Now().Add(time.Minute).UTC().Format(time.RFC3339)) |
| 101 | case "/api/enrolments/token": |
| 102 | _, _ = fmt.Fprintf(w, `{"version":1,"token":"t","token_type":"Bearer","runner_id":"R2","credential_id":"C2","person":"p@x","expires_at":%q%s}`, time.Now().Add(time.Hour).UTC().Format(time.RFC3339), tc.answer) |
| 103 | default: |
| 104 | http.Error(w, "no", 404) |
| 105 | } |
| 106 | })} |
| 107 | go srv.Serve(l) |
| 108 | state := filepath.Join(t.TempDir(), "state") |
| 109 | c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: tc.mac} |
| 110 | err = Enrol(context.Background(), c, io.Discard) |
| 111 | srv.Close() |
| 112 | if tc.mac && tc.want == "" { |
| 113 | // A Mac the instance made a primary keeps nothing and says why. |
| 114 | code, _ := Diagnostic(err) |
| 115 | if !errors.Is(err, ErrEnrolledAsPrimary) || code != "runner.enrolled_as_primary" { |
| 116 | t.Fatalf("a Mac enrolled as a primary: %v", err) |
| 117 | } |
| 118 | if _, serr := os.Stat(filepath.Join(state, "credentials.json")); !os.IsNotExist(serr) || ReadRole(state) != "" { |
| 119 | t.Fatal("a Mac kept a primary's credential") |
| 120 | } |
| 121 | continue |
| 122 | } |
| 123 | if err != nil { |
| 124 | t.Fatal(err) |
| 125 | } |
| 126 | if role := ReadRole(state); role != tc.want { |
| 127 | t.Fatalf("stored role %q, want %q", role, tc.want) |
| 128 | } |
| 129 | // The credential file stays what older runner binaries read. |
| 130 | raw, _ := os.ReadFile(filepath.Join(state, "credentials.json")) |
| 131 | if tc.want == "primary" && strings.Contains(string(raw), `"role"`) { |
| 132 | t.Fatalf("a primary's credential file names a role: %s", raw) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // The credential is the last thing an enrolment writes: when keeping the |
| 138 | // role fails, no new credential is left beside the installer's earlier |
| 139 | // configuration, which it then puts back (Astra, mac-install-safe). |
| 140 | func TestEnrolCommitsTheCredentialLast(t *testing.T) { |
| 141 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 142 | if err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 146 | switch r.URL.Path { |
| 147 | case wire.RunnerProtocolPath: |
| 148 | _, _ = w.Write([]byte(`{"protocol":2}`)) |
| 149 | case "/api/enrolments": |
| 150 | _, _ = fmt.Fprintf(w, `{"version":1,"enrolment_id":"e1","instance_id":"inst","device_secret":"s","user_code":"ABCD-EFGH","challenge":"c","verification_uri":"http://%s/runners/enrol","expires_at":%q,"poll_interval_seconds":5}`, r.Host, time.Now().Add(time.Minute).UTC().Format(time.RFC3339)) |
| 151 | case "/api/enrolments/token": |
| 152 | _, _ = fmt.Fprintf(w, `{"version":1,"token":"t","token_type":"Bearer","runner_id":"R2","credential_id":"C2","person":"p@x","expires_at":%q,"role":"worker"}`, time.Now().Add(time.Hour).UTC().Format(time.RFC3339)) |
| 153 | default: |
| 154 | http.Error(w, "no", 404) |
| 155 | } |
| 156 | })} |
| 157 | go srv.Serve(l) |
| 158 | defer srv.Close() |
| 159 | state := filepath.Join(t.TempDir(), "state") |
| 160 | // The role cannot be written: a directory with something in it is |
| 161 | // where the role file goes. |
| 162 | if err := os.MkdirAll(filepath.Join(state, RoleFile, "x"), 0700); err != nil { |
| 163 | t.Fatal(err) |
| 164 | } |
| 165 | if err := os.Chmod(state, 0700); err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: true} |
| 169 | if err := Enrol(context.Background(), c, io.Discard); err == nil { |
| 170 | t.Fatal("enrolled without its role") |
| 171 | } |
| 172 | if _, err := os.Lstat(filepath.Join(state, "credentials.json")); !os.IsNotExist(err) { |
| 173 | t.Fatalf("a credential was kept without its role: %v", err) |
| 174 | } |
| 175 | } |
| 176 | |