package runner import ( "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/wire" ) // A runner that can only be a worker asks the instance which protocol it // speaks before it enrols: an older instance (no protocol route) would take // the newest runner for the person's primary, so the worker is refused // with a fixed diagnostic and nothing is sent to the enrolment routes. func TestWorkerEnrolRefusesAnOlderInstance(t *testing.T) { for _, tc := range []struct { name string protocol string refused bool }{ {"older instance", "", true}, {"protocol 1", `{"protocol":1}`, true}, {"protocol 2", `{"protocol":2}`, false}, } { t.Run(tc.name, func(t *testing.T) { var mu sync.Mutex var paths []string var begun runnerproto.BeginEnrolmentRequest l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() paths = append(paths, r.Method+" "+r.URL.Path) mu.Unlock() if r.URL.Path == "/api/enrolments" { _ = json.NewDecoder(r.Body).Decode(&begun) } if r.URL.Path == wire.RunnerProtocolPath && tc.protocol != "" { _, _ = w.Write([]byte(tc.protocol)) return } http.Error(w, "no", http.StatusNotFound) })} go srv.Serve(l) defer srv.Close() c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: filepath.Join(t.TempDir(), "state"), WorkerOnly: true} err = Enrol(context.Background(), c, nil) code, _ := Diagnostic(err) mu.Lock() defer mu.Unlock() if tc.refused { if code != "runner.instance_older_than_worker" || len(paths) != 1 { t.Fatalf("refused %q after %v", code, paths) } return } if code == "runner.instance_older_than_worker" || len(paths) < 2 { t.Fatalf("protocol 2 instance refused: %q %v", code, paths) } // It says it can only be a worker, so the instance refuses to // make it anyone's first (primary) runner. if !begun.WorkerOnly { t.Fatal("a worker-only machine did not say so") } }) } } // Enrolment keeps the role the instance gave the runner with its // credential, before the runner ever connects: worker when the instance // says so, primary when it says nothing (a primary, or an instance // without workers). func TestEnrolKeepsTheRole(t *testing.T) { for _, tc := range []struct { answer, want string mac bool }{{`,"role":"worker"`, "worker", false}, {"", "primary", false}, {`,"role":"worker"`, "worker", true}, {"", "", true}} { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case wire.RunnerProtocolPath: _, _ = w.Write([]byte(`{"protocol":2}`)) case "/api/enrolments": _, _ = 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)) case "/api/enrolments/token": _, _ = 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) default: http.Error(w, "no", 404) } })} go srv.Serve(l) state := filepath.Join(t.TempDir(), "state") c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: tc.mac} err = Enrol(context.Background(), c, io.Discard) srv.Close() if tc.mac && tc.want == "" { // A Mac the instance made a primary keeps nothing and says why. code, _ := Diagnostic(err) if !errors.Is(err, ErrEnrolledAsPrimary) || code != "runner.enrolled_as_primary" { t.Fatalf("a Mac enrolled as a primary: %v", err) } if _, serr := os.Stat(filepath.Join(state, "credentials.json")); !os.IsNotExist(serr) || ReadRole(state) != "" { t.Fatal("a Mac kept a primary's credential") } continue } if err != nil { t.Fatal(err) } if role := ReadRole(state); role != tc.want { t.Fatalf("stored role %q, want %q", role, tc.want) } // The credential file stays what older runner binaries read. raw, _ := os.ReadFile(filepath.Join(state, "credentials.json")) if tc.want == "primary" && strings.Contains(string(raw), `"role"`) { t.Fatalf("a primary's credential file names a role: %s", raw) } } } // The credential is the last thing an enrolment writes: when keeping the // role fails, no new credential is left beside the installer's earlier // configuration, which it then puts back (Astra, mac-install-safe). func TestEnrolCommitsTheCredentialLast(t *testing.T) { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case wire.RunnerProtocolPath: _, _ = w.Write([]byte(`{"protocol":2}`)) case "/api/enrolments": _, _ = 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)) case "/api/enrolments/token": _, _ = 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)) default: http.Error(w, "no", 404) } })} go srv.Serve(l) defer srv.Close() state := filepath.Join(t.TempDir(), "state") // The role cannot be written: a directory with something in it is // where the role file goes. if err := os.MkdirAll(filepath.Join(state, RoleFile, "x"), 0700); err != nil { t.Fatal(err) } if err := os.Chmod(state, 0700); err != nil { t.Fatal(err) } c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: true} if err := Enrol(context.Background(), c, io.Discard); err == nil { t.Fatal("enrolled without its role") } if _, err := os.Lstat(filepath.Join(state, "credentials.json")); !os.IsNotExist(err) { t.Fatalf("a credential was kept without its role: %v", err) } }