Files
t5de-importer/internal/importer/importer_test.go
T
dhkatzandClaude Opus 5.5 7dfbeb5ba3
CI / build (pull_request) Successful in 21s
CI / image (pull_request) Skipped
Pull request / title (pull_request) Successful in 1s
feat: sign in to IMVU for Access Pass products
The importer signs in with the first of the console's accounts that IMVU takes, reports refusals and whether the
account has Access Pass, and keeps the session so restarts don't sign in again. With it, it lists whole shops
signed in for the hub ("list" jobs) and looks up products the hub can't see before importing them, so Access Pass
products import too. IMVU's sign-in works only with a desktop browser's User-Agent, which signed-in requests send.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 07:39:02 -08:00

455 lines
15 KiB
Go

package importer
import (
"archive/zip"
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.t5de.dev/t5de/t5de-importer/internal/accounts"
"git.t5de.dev/t5de/t5de-importer/internal/hub"
"git.t5de.dev/t5de/t5de-importer/internal/imvu"
"git.t5de.dev/t5de/t5de-importer/internal/imvutest"
"git.t5de.dev/t5de/t5de-importer/internal/keys"
)
// fakeHub is the hub's importer API, as t5de-hub's docs/products.md has it, and a catalog's upload.
type fakeHub struct {
t *testing.T
mu sync.Mutex
cfg hub.Config
queue []hub.Job
claims int
hello map[string]string
reports map[string]hub.Outcome
done map[string]map[string][]byte // job → the uploaded product's files
account map[string]hub.AccountReport
reportsOf map[string][]hub.AccountReport // every report, by account
listings map[string][]hub.Seen // "list" jobs' products
infos map[string]*hub.Seen // what the importer saw of jobs' products
catalog *httptest.Server
}
func newFakeHub(t *testing.T) (*fakeHub, *httptest.Server) {
h := &fakeHub{t: t, reports: map[string]hub.Outcome{}, done: map[string]map[string][]byte{}, account: map[string]hub.AccountReport{},
reportsOf: map[string][]hub.AccountReport{}, listings: map[string][]hub.Seen{}, infos: map[string]*hub.Seen{}}
h.catalog = httptest.NewServer(http.HandlerFunc(h.upload))
t.Cleanup(h.catalog.Close)
s := httptest.NewServer(http.HandlerFunc(h.serve))
t.Cleanup(s.Close)
return h, s
}
func (h *fakeHub) serve(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
if r.Header.Get("Authorization") != "Importer cat1:secret" {
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "forbidden", "message": "Not an importer."})
return
}
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
path := strings.TrimPrefix(r.URL.Path, "/api/v1/importer")
switch {
case path == "/hello":
h.hello = map[string]string{"version": body["version"].(string), "publicKey": body["publicKey"].(string)}
json.NewEncoder(w).Encode(h.cfg)
case path == "/config":
json.NewEncoder(w).Encode(h.cfg)
case path == "/jobs/claim":
h.claims++
n := min(int(body["limit"].(float64)), len(h.queue))
if h.cfg.Paused {
n = 0
}
jobs := h.queue[:n]
h.queue = h.queue[n:]
json.NewEncoder(w).Encode(map[string]any{"jobs": jobs})
case strings.HasSuffix(path, "/token"):
job := strings.TrimSuffix(strings.TrimPrefix(path, "/jobs/"), "/token")
json.NewEncoder(w).Encode(map[string]string{
"token": fmt.Sprintf("import:%s:%v", job, body["imvuRevision"]),
"url": h.catalog.URL + "/api/v1/uploads",
})
case strings.HasSuffix(path, "/listing"):
var l struct{ Products []hub.Seen }
b, _ := json.Marshal(body)
json.Unmarshal(b, &l)
job := strings.TrimSuffix(strings.TrimPrefix(path, "/jobs/"), "/listing")
h.listings[job] = l.Products
json.NewEncoder(w).Encode(map[string]int{"listed": len(l.Products), "queued": len(l.Products)})
case strings.HasSuffix(path, "/info"):
job := strings.TrimSuffix(strings.TrimPrefix(path, "/jobs/"), "/info")
answer := map[string]any{"rating": nil, "covered": false}
if body["found"] == true {
var p hub.Seen
b, _ := json.Marshal(body)
json.Unmarshal(b, &p)
h.infos[job] = &p
answer = map[string]any{"rating": p.Rating, "covered": p.CreatorID == 903}
} else {
h.infos[job] = nil
}
json.NewEncoder(w).Encode(answer)
case strings.HasPrefix(path, "/jobs/"):
var o hub.Outcome
b, _ := json.Marshal(body)
json.Unmarshal(b, &o)
h.reports[strings.TrimPrefix(path, "/jobs/")] = o
w.Write([]byte(`{}`))
case strings.HasPrefix(path, "/accounts/"):
var a hub.AccountReport
b, _ := json.Marshal(body)
json.Unmarshal(b, &a)
h.account[strings.TrimPrefix(path, "/accounts/")] = a
h.reportsOf[strings.TrimPrefix(path, "/accounts/")] = append(h.reportsOf[strings.TrimPrefix(path, "/accounts/")], a)
if a.Received { // the hub drops its sealed copy
for i := range h.cfg.Accounts {
if h.cfg.Accounts[i].ID == strings.TrimPrefix(path, "/accounts/") {
h.cfg.Accounts[i].Sealed = nil
}
}
}
w.Write([]byte(`{}`))
default:
http.NotFound(w, r)
}
}
// upload is the catalog's upload: the importer's .chkn, registered at once (which marks its job done).
func (h *fakeHub) upload(w http.ResponseWriter, r *http.Request) {
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer import:")
f, _, err := r.FormFile("file")
if !ok || err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
data, _ := io.ReadAll(f)
z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
files := map[string][]byte{}
for _, zf := range z.File {
rc, _ := zf.Open()
files[zf.Name], _ = io.ReadAll(rc)
}
job, rev, _ := strings.Cut(tok, ":")
files["(revision)"] = []byte(rev)
h.mu.Lock()
h.done[job] = files
h.mu.Unlock()
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"product": "p-" + job, "revision": 1})
}
func (h *fakeHub) settled(n int) bool {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.reports)+len(h.done)+len(h.listings) >= n
}
func sealFor(t *testing.T, k *keys.Key, imvuID int64, password string) *string {
t.Helper()
der, _ := base64.StdEncoding.DecodeString(k.PublicKey)
pub, _ := x509.ParsePKIXPublicKey(der)
plain, _ := json.Marshal(map[string]any{"imvuId": imvuID, "password": password})
ct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub.(*rsa.PublicKey), plain, nil)
if err != nil {
t.Fatal(err)
}
s := base64.StdEncoding.EncodeToString(ct)
return &s
}
func newImporter(t *testing.T, h *httptest.Server, cdn *imvutest.CDN) *Importer {
return newImporterIn(t, h, cdn, t.TempDir())
}
func newImporterIn(t *testing.T, h *httptest.Server, cdn *imvutest.CDN, dir string) *Importer {
k, _, err := keys.Load(dir)
if err != nil {
t.Fatal(err)
}
store, err := accounts.Open(dir)
if err != nil {
t.Fatal(err)
}
sessions := filepath.Join(dir, "sessions")
if err := os.MkdirAll(sessions, 0o700); err != nil {
t.Fatal(err)
}
var logs bytes.Buffer
t.Cleanup(func() {
if t.Failed() {
t.Log(logs.String())
}
})
return &Importer{
Hub: hub.New(h.URL, "cat1", "secret", "test", nil),
CDN: &imvu.CDN{URL: cdn.URL, UserAgent: "test", Limiter: imvu.NewLimiter(10)},
Key: k,
Accounts: store,
Version: "1.2.3",
UserAgent: "test",
Tmp: t.TempDir(),
Sessions: sessions,
Logger: log.New(&logs, "", 0),
ConfigEvery: 50 * time.Millisecond,
ClaimEvery: 10 * time.Millisecond,
RetryEvery: 10 * time.Millisecond,
}
}
func runUntil(t *testing.T, im *Importer, until func() bool) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
stopped := make(chan error)
go func() { stopped <- im.Run(ctx) }()
deadline := time.Now().Add(20 * time.Second)
for !until() {
if time.Now().After(deadline) {
cancel()
<-stopped
t.Fatal("timed out")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
if err := <-stopped; err != nil {
t.Fatal(err)
}
}
func TestImports(t *testing.T) {
cdn := imvutest.New(t)
index := imvutest.Index(5000)
cdn.Add(9001, 1, imvutest.File{Name: "index.xml", Data: index})
cdn.Add(9001, 2,
imvutest.File{Name: "index.xml", Data: index},
imvutest.File{Name: "dress.png", Data: []byte("16x16"), URL: "aaa.png", Original: []byte("the full-size texture")},
imvutest.File{Name: "Skin%20%5B03%5D.xrf", URL: "bbb.xrf", Original: []byte("a material kept on the CDN only")},
)
for rev := 1; rev <= 3; rev++ {
cdn.Add(9002, rev, imvutest.File{Name: "index.xml", Data: index})
}
cdn.Add(9005, 1, imvutest.File{Name: "index.xml", Data: index})
h, srv := newFakeHub(t)
h.cfg.Settings = hub.Settings{Rate: 10, Concurrency: 2}
h.queue = []hub.Job{
{ID: "a", Kind: "import", IMVUProduct: 9001, Rating: "general"},
{ID: "b", Kind: "recheck", IMVUProduct: 9002, LastRevision: 3, Rating: "general"},
{ID: "c", Kind: "import", IMVUProduct: 9003}, // the hub doesn't know its rating
{ID: "d", Kind: "import", IMVUProduct: 9004, Rating: "general"},
{ID: "e", Kind: "import", IMVUProduct: 9005, Rating: "adult"},
}
im := newImporter(t, srv, cdn)
runUntil(t, im, func() bool { return h.settled(5) })
if h.hello["version"] != "1.2.3" || h.hello["publicKey"] != im.Key.PublicKey {
t.Errorf("hello %v", h.hello)
}
// The newest revision, converted: originals in, _contents.json out, ProductRating added.
a := h.done["a"]
if a == nil {
t.Fatalf("job a wasn't uploaded; reports %v", h.reports)
}
if string(a["(revision)"]) != "2" || string(a["dress.png"]) != "the full-size texture" ||
string(a["Skin%20%5B03%5D.xrf"]) != "a material kept on the CDN only" || a["_contents.json"] != nil {
t.Errorf("job a uploaded %q", a)
}
if !bytes.Contains(a["index.xml"], []byte("<ProductRating>GA</ProductRating>")) || !bytes.Contains(a["index.xml"], []byte("product://5000/index.xml")) {
t.Errorf("job a's index.xml: %s", a["index.xml"])
}
if e := h.done["e"]; e == nil || !bytes.Contains(e["index.xml"], []byte("<ProductRating>AP</ProductRating>")) {
t.Errorf("job e (adult): %q", e)
}
if o := h.reports["b"]; o.Status != "unchanged" || o.IMVURevision != 3 {
t.Errorf("job b: %+v", o)
}
if o := h.reports["c"]; o.Status != "failed" || !strings.Contains(o.Reason, "no IMVU account is signed in") {
t.Errorf("job c: %+v", o)
}
if o := h.reports["d"]; o.Status != "failed" || !strings.Contains(o.Reason, "no revision") {
t.Errorf("job d: %+v", o)
}
if len(h.reports) != 3 || len(h.done) != 2 {
t.Errorf("reports %v, uploads %d", h.reports, len(h.done))
}
}
func TestAccountsAndPause(t *testing.T) {
cdn := imvutest.New(t)
h, srv := newFakeHub(t)
dir := t.TempDir()
im := newImporterIn(t, srv, cdn, dir)
if err := im.Accounts.Put(accounts.Account{ID: "gone", IMVUID: 1, Sealed: "x"}); err != nil {
t.Fatal(err)
}
okSealed := sealFor(t, im.Key, 100, "pw")
h.cfg = hub.Config{
Paused: true,
Settings: hub.Settings{Rate: 1, Concurrency: 1},
Accounts: []hub.Account{
{ID: "ok", IMVUID: 100, Username: "Importer1", Sealed: okSealed},
{ID: "moved", IMVUID: 200, Username: "Importer2", Sealed: sealFor(t, im.Key, 999, "pw")},
{ID: "waiting", IMVUID: 300, Username: "Importer3"},
},
}
h.queue = []hub.Job{{ID: "x", Kind: "import", IMVUProduct: 1, Rating: "general"}}
runUntil(t, im, func() bool {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.account) == 2
})
if !h.account["ok"].Received || h.account["moved"].State != "needs_password" {
t.Errorf("account reports %+v", h.account)
}
if a, ok := im.Accounts.Get("ok"); !ok || a.IMVUID != 100 || a.Sealed != *okSealed {
t.Errorf("kept %+v, %v", a, ok)
}
if _, ok := im.Accounts.Get("gone"); ok {
t.Error("an account the hub no longer lists is still kept")
}
if _, ok := im.Accounts.Get("moved"); ok {
t.Error("a password for another account was kept")
}
// Reopened from disk: the same.
again, err := accounts.Open(dir)
if err != nil {
t.Fatal(err)
}
if _, ok := again.Get("ok"); !ok {
t.Error("not saved")
}
if len(h.queue) != 1 || len(h.reports) != 0 {
t.Errorf("paused, yet jobs were taken: queue %v", h.queue)
}
}
func TestHelloRefused(t *testing.T) {
cdn := imvutest.New(t)
_, srv := newFakeHub(t)
im := newImporter(t, srv, cdn)
im.Hub = hub.New(srv.URL, "cat1", "wrong", "test", nil)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := im.Run(ctx); err == nil {
t.Error("ran with a refused key")
}
}
func TestSignedIn(t *testing.T) {
api := imvutest.NewAPI(t)
api.Users = []imvutest.User{
{ID: 777, Username: "ImporterAP", Password: "right", AccessPass: true},
{ID: 778, Username: "NoLuck", Password: "right"},
{ID: 903, Username: "apkeeperAv"},
}
api.Products = []imvutest.Product{
{ID: 9501, Name: "Coat", CreatorID: 903},
{ID: 9502, Name: "Robe", CreatorID: 903, AccessPass: true},
}
cdn := imvutest.New(t)
cdn.Add(9502, 1, imvutest.File{Name: "index.xml", Data: imvutest.Index(5000)})
h, srv := newFakeHub(t)
dir := t.TempDir()
im := newImporterIn(t, srv, cdn, dir)
im.APIURL = api.URL
h.cfg = hub.Config{
Settings: hub.Settings{Rate: 10, Concurrency: 1},
Accounts: []hub.Account{
{ID: "wrong", IMVUID: 778, Username: "NoLuck", Sealed: sealFor(t, im.Key, 778, "not the password")},
{ID: "ap", IMVUID: 777, Username: "ImporterAP", Sealed: sealFor(t, im.Key, 777, "right")},
},
}
h.queue = []hub.Job{
{ID: "list", Kind: "list", IMVUCreator: 903},
{ID: "robe", Kind: "import", IMVUProduct: 9502}, // hidden from the hub: no rating
{ID: "gone", Kind: "import", IMVUProduct: 9599},
}
runUntil(t, im, func() bool { return h.settled(3) })
// The first account is refused; the second signs in, with Access Pass (which IMVU shows it alone).
if r := h.account["wrong"]; r.State != "sign_in_failed" || !strings.Contains(r.Message, "Invalid username or password") {
t.Errorf("refused account: %+v", r)
}
if r := h.account["ap"]; r.State != "ok" || r.AccessPass == nil || !*r.AccessPass {
t.Errorf("signed-in account: %+v", r)
}
// The shop as the account lists it: the Access Pass product too.
if got := h.listings["list"]; len(got) != 2 || got[1] != (hub.Seen{ID: 9502, Name: "Robe", Rating: "adult", CreatorID: 903, CreatorName: "creator903", Purchasable: true}) {
t.Errorf("listing %+v", got)
}
// The hidden product: looked up, reported, imported as adult.
if p := h.infos["robe"]; p == nil || p.Rating != "adult" || p.CreatorID != 903 {
t.Errorf("robe info %+v", p)
}
if robe := h.done["robe"]; robe == nil || !bytes.Contains(robe["index.xml"], []byte("<ProductRating>AP</ProductRating>")) {
t.Errorf("robe: %q (reports %v)", robe, h.reports)
}
if p, ok := h.infos["gone"]; !ok || p != nil {
t.Errorf("gone info %+v, %v", p, ok)
}
if o := h.reports["gone"]; o.Status != "failed" || !strings.Contains(o.Reason, "deleted?") {
t.Errorf("gone: %+v", o)
}
// A restart resumes the saved session: no new sign-in.
signIns := api.SignIns
h.mu.Lock()
h.queue = []hub.Job{{ID: "list2", Kind: "list", IMVUCreator: 903}}
h.mu.Unlock()
again := newImporterIn(t, srv, cdn, dir)
again.Key = im.Key
again.APIURL = api.URL
runUntil(t, again, func() bool { return h.settled(4) })
if api.SignIns != signIns {
t.Errorf("signed in again: %d sign-ins, was %d", api.SignIns, signIns)
}
// The refused account isn't tried again within the hour (same password), even after a restart.
refusals := 0
for _, r := range h.reportsOf["wrong"] {
if r.State == "sign_in_failed" {
refusals++
}
}
if refusals != 1 {
t.Errorf("the refused account was refused %d times", refusals)
}
// IMVU ends the session: the importer signs in again.
api.EndSessions()
h.mu.Lock()
h.queue = []hub.Job{{ID: "list3", Kind: "list", IMVUCreator: 903}, {ID: "list4", Kind: "list", IMVUCreator: 903}}
h.mu.Unlock()
runUntil(t, again, func() bool {
h.mu.Lock()
defer h.mu.Unlock()
return (h.listings["list3"] != nil || h.reports["list3"].Status != "") && (h.listings["list4"] != nil || h.reports["list4"].Status != "")
})
if api.SignIns != signIns+1 || len(h.listings["list3"]) != 2 || len(h.listings["list4"]) != 2 {
t.Errorf("after the session ended: %d sign-ins (want %d); listings %d and %d, reports %v", api.SignIns, signIns+1, len(h.listings["list3"]), len(h.listings["list4"]), h.reports)
}
}