package web import ( "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "strings" "testing" "time" "gitea.mynodes.xyz/ilker/llmgw/internal/config" "gitea.mynodes.xyz/ilker/llmgw/internal/store" ) func TestTheProfileKeepsAPersonsSSHKeysForSlurm(t *testing.T) { ctx := t.Context() st, err := store.OpenSQLite(ctx, filepath.Join(t.TempDir(), "s.db")) if err != nil { t.Fatal(err) } defer st.Close() ayse := store.User{ID: "usr-a", Email: "ayse@llmt.test", Name: "Ayşe", State: store.UserActive, CreatedAt: time.Now()} if err := st.CreateUser(ctx, ayse); err != nil { t.Fatal(err) } set := config.SlurmSettings{Enabled: true, Controller: "llmt-1", Users: config.UsersLlmgw, Shared: config.SharedStorage{Path: "/shared", Server: "llmt-1"}} p := NewAccountPages(fakeAccounts{user: ayse}, st, nil, "v0", slog.New(slog.DiscardHandler)) p.SetSlurm(st, func() config.SlurmSettings { return set }) mux := http.NewServeMux() p.Register(mux) do := func(form url.Values) (int, string) { req := httptest.NewRequest(http.MethodGet, "/profile", nil) if form != nil { form.Set("csrf", "tok") req = httptest.NewRequest(http.MethodPost, "/profile/ssh-keys", strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } req.AddCookie(&http.Cookie{Name: SessionCookie, Value: "good"}) req.AddCookie(&http.Cookie{Name: csrfCookie, Value: "tok"}) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) return rec.Code, rec.Body.String() } _, page := do(nil) for _, want := range []string{`action="/profile/ssh-keys"`, "ssh ayse@llmt-1", "UID 200000", "/shared/home/ayse"} { if !strings.Contains(page, want) { t.Errorf("the page lacks %q", want) } } key := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILq3vMdLAKlaDdxwrSgCtP/j/qrF4nzxNBNGuJmK5vxh ayse@laptop" _, saved := do(url.Values{"keys": {key + "\n"}}) u, _ := st.SlurmUserByID(ctx, ayse.ID) if len(u.SSHKeys) != 1 || u.SSHKeys[0] != key || !strings.Contains(saved, "within a minute") { t.Fatalf("kept %v", u.SSHKeys) } _, bad := do(url.Values{"keys": {"not a key"}}) if !strings.Contains(bad, "Not kept") || !strings.Contains(bad, "not a key") { t.Error("a bad key was not refused, or the box lost what was typed") } if u, _ := st.SlurmUserByID(ctx, ayse.ID); len(u.SSHKeys) != 1 { t.Error("a refused form changed the keys") } // Off: neither the part nor the form. set.Users = "" if _, page := do(nil); strings.Contains(page, "ssh-keys") { t.Error("offered with slurm.users off") } if code, _ := do(url.Values{"keys": {key}}); code != http.StatusNotFound { t.Errorf("posted with slurm.users off: %d", code) } }