package thin import ( "context" "encoding/base64" "encoding/json" "errors" "fmt" "net/http" "os" "path/filepath" "reflect" "testing" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire/forgekey" ) func TestRouterRefusalsKeepOperationIdentity(t *testing.T) { ctx := context.Background() f, _ := NewForges(&routeForge{host: forgekey.Hub}) for _, repo := range []string{"github.com/a", "github.com/o/r", "bad"} { _, remote := f.Remote(ctx, repo, Read) _, exists := f.Exists(ctx, repo) create := f.Create(ctx, repo) _, merge := f.Merge(ctx, repo, "main", forge.MergeRequest{}) _, hosted := f.CIHosted(ctx, repo) _, status := f.CIStatus(ctx, repo, "main", forge.CILogsNone) for _, tc := range []struct{ got, want error }{{remote, workspace.ErrGitPassword}, {exists, ErrNoCreate}, {create, ErrNoCreate}, {merge, forge.ErrMergeRefused}, {hosted, forge.ErrCIRead}, {status, forge.ErrCIRead}} { if !errors.Is(tc.got, tc.want) || !errors.Is(tc.got, forgekey.ErrKey) { t.Errorf("%q: %v lost %v or key identity", repo, tc.got, tc.want) } } } _, use := f.Remote(ctx, "o/r", Use(99)) _, duplicate := NewForges(&routeForge{host: forgekey.Hub}, &routeForge{host: forgekey.Hub}) if !errors.Is(use, ErrForgeUse) || !errors.Is(duplicate, ErrForgeDuplicate) || errors.Is(use, forgekey.ErrKey) || errors.Is(duplicate, forgekey.ErrKey) || errors.Is(use, duplicate) || !errors.Is(use, workspace.ErrGitPassword) { t.Fatalf("use and registration need distinct identities: %v / %v", use, duplicate) } } func TestRouterWithProductionFileForge(t *testing.T) { ctx := context.Background() const repo = "amadan.net/carlos/platform" const branch = "equipo/t1-fix" const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" var calls []string ff := accessForge(t, func(w http.ResponseWriter, r *http.Request) { calls = append(calls, r.Method+" "+r.URL.Path) if r.Header.Get("Authorization") != "Bearer SECRET-ACCESS-TOKEN" { t.Error("missing hub credential") } switch r.URL.Path { case "/api/v1/repos": fmt.Fprint(w, `{"repos":[{"ns":"carlos","name":"platform"}]}`) case "/api/v1/repos/carlos/platform/branches/" + branch + "/merge": var req forge.MergeRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ExpectSHA != sha { t.Errorf("merge request: %+v %v", req, err) } fmt.Fprintf(w, `{"merged":true,"sha":%q,"into":"main"}`, sha) case "/api/v1/repos/carlos/platform/ci/hosted": fmt.Fprint(w, `{"on":true}`) case "/api/v1/repos/carlos/platform/ci/status": if r.URL.Query().Get("branch") != branch || r.URL.Query().Get("logs") != forge.CILogsFailed { t.Error("CI query lost") } fmt.Fprintf(w, `{"ns":"carlos","repo":"platform","branch":%q,"sha":%q,"state":"passed"}`, branch, sha) case "/api/v1/agents/access-requests": w.WriteHeader(201) writeAccess(w, "ar_one", "pending") case "/api/v1/agents/access-requests/ar_one": writeAccess(w, "ar_one", "approved") default: t.Error("unexpected route", r.URL) w.WriteHeader(404) } }) if ff.Host() != forgekey.Hub { t.Fatalf("production forge host: %q", ff.Host()) } f, err := NewForges(ff) if err != nil { t.Fatal(err) } for _, use := range []Use{Read, Push} { remote, err := f.Remote(ctx, repo, use) if err != nil || remote.URL != "https://"+repo || remote.GitPassword != "SECRET-GIT-TOKEN" { t.Fatalf("remote %d: %+v %v", use, remote, err) } } res, err := f.Merge(ctx, repo, branch, forge.MergeRequest{ExpectSHA: sha}) if err != nil || !res.Merged || res.SHA != sha { t.Fatalf("merge: %+v %v", res, err) } if hosted, err := f.CIHosted(ctx, repo); err != nil || !hosted { t.Fatal("hosted", hosted, err) } if status, err := f.CIStatus(ctx, repo, branch, forge.CILogsFailed); err != nil || status.SHA != sha || status.State != "passed" { t.Fatal("CI", status, err) } c := accessCommand() if rep, err := f.RequestAccess(ctx, c); err != nil || rep.State != "pending" { t.Fatal("request", rep, err) } if rep, err := f.PollAccess(ctx, "ar_one", c); err != nil || rep.State != "approved" { t.Fatal("poll", rep, err) } // The read lists once; the push and the merge, writes with the // agent-wide credential, each ask the hub afresh (writable). want := []string{"GET /api/v1/repos", "GET /api/v1/repos", "GET /api/v1/repos", "POST /api/v1/repos/carlos/platform/branches/" + branch + "/merge", "GET /api/v1/repos/carlos/platform/ci/hosted", "GET /api/v1/repos/carlos/platform/ci/status", "POST /api/v1/agents/access-requests", "GET /api/v1/agents/access-requests/ar_one"} if !reflect.DeepEqual(calls, want) { t.Fatalf("hub calls: %v", calls) } } type usernameForge struct { Forge remote workspace.Remote } func (f usernameForge) Remote(context.Context, string, Use) (workspace.Remote, error) { return f.remote, nil } func TestHeadsUsesRemoteUsername(t *testing.T) { root := t.TempDir() script := filepath.Join(root, "git") capture := filepath.Join(root, "header") if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s' \"$GIT_CONFIG_VALUE_9\" > '"+capture+"'\n"), 0700); err != nil { t.Fatal(err) } remote := workspace.Remote{URL: "https://github.com/o/r", GitPassword: "fixture-password", GitUsername: "x-access-token"} c := Clones{Root: root, Git: script, Forge: usernameForge{remote: remote}} if _, _, _, err := c.Heads(context.Background(), "github.com/o/r", nil); err != nil && !errors.Is(err, ErrEmptyRepo) { t.Fatal(err) } got, err := os.ReadFile(capture) want := "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("x-access-token:fixture-password")) if err != nil || string(got) != want { t.Fatalf("heads header %q: %v", got, err) } }