package runner import ( "context" "errors" "path/filepath" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) // enrolledState writes what an enrolled runner keeps: its credential, // live until expires, and the enrolment it came from, for origin and // instance ("" origin writes no enrolment record). func enrolledState(t *testing.T, state, origin, instance string, expires time.Time) { t.Helper() if err := runnerproto.JournalCredentials(filepath.Join(state, "credentials.json"), runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Version: 1, RunnerID: "r1", Token: "t", ExpiresAt: expires}}); err != nil { t.Fatal(err) } if origin == "" { return } if err := runnerproto.JournalCredentials(filepath.Join(state, "enrolment.json"), pendingEnrolment{Origin: origin, Label: "Mac", Code: runnerproto.DeviceCode{InstanceID: instance}}); err != nil { t.Fatal(err) } } // An installer asks, before it stops anything or rewrites the runner's // configuration, whether the state is enrolled with another Equipo: the // enrolment Enrol refuses (Tito Studio, 2026-11-28: a staging runner's // state, then a production install). It changes nothing and needs no lock. func TestEnrolledElsewhere(t *testing.T) { const prod, staging = "https://equipo.example", "https://equipo-staging.example" live, expired := time.Now().Add(time.Hour), time.Now().Add(-time.Hour) for _, c := range []struct { name string origin, instance string expires time.Time none bool want bool wantOrigin string }{ {name: "nothing enrolled", none: true}, {name: "this instance", origin: prod, instance: "team1", expires: live}, {name: "another origin", origin: staging, instance: "team1", expires: live, want: true, wantOrigin: staging}, {name: "another instance", origin: prod, instance: "team2", expires: live, want: true, wantOrigin: prod}, {name: "expired elsewhere", origin: staging, instance: "team1", expires: expired}, {name: "no enrolment record", origin: "", expires: live, want: true}, } { t.Run(c.name, func(t *testing.T) { state := filepath.Join(t.TempDir(), "state") if !c.none { enrolledState(t, state, c.origin, c.instance, c.expires) } other, elsewhere, err := EnrolledElsewhere(state, prod, "team1") if err != nil || elsewhere != c.want || other != c.wantOrigin { t.Fatalf("got %q %v %v", other, elsewhere, err) } // Enrol refuses exactly these, before asking anyone (the // others would ask: cancelled, they never reach the network). ctx, cancel := context.WithCancel(context.Background()) cancel() err = Enrol(ctx, Config{Origin: prod, InstanceID: "team1", StateDir: state}, nil) if c.want != errors.Is(err, provider.ErrIdentity) { t.Fatalf("enrol %v", err) } }) } }