// Package protontest is a fake Proton Drive API server for tests. // // It must not import the protondrive backend, whose tests use it. package protontest import ( "bytes" "encoding/json" "fmt" "io" "net" "net/http" "net/http/httptest" "regexp" "slices" "strconv" "strings" "sync" "testing" "time" "github.com/ProtonMail/gopenpgp/v3/crypto" "github.com/rclone/rclone/backend/protondrive/api" ) var ( // appVersionRe is Proton's published x-pm-appversion grammar // (SDK README, "Usage Guidelines") with the name fixed to rclone. appVersionRe = regexp.MustCompile(`^external-drive-rclone@[0-9]+\.[0-9]+\.[0-9]+(-(stable|beta|alpha))?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`) // legacyRouteRe matches the removed share-scoped routes and // everything beneath them. legacyRouteRe = regexp.MustCompile(`^/drive/shares/[^/]+/(links|folders|files|events)(/|$)`) ) // legacyRequests counts the requests for legacy routes, per "METHOD // path", made to every server in the process, so a test binary can // check none was made after all its tests have run. var legacyRequests = struct { mu sync.Mutex counts map[string]int }{counts: make(map[string]int)} // LegacyRequests returns a copy of the count, per "METHOD path", of // the requests for removed share-scoped routes made to every server in // the process since it started. ResetRequests doesn't change it. func LegacyRequests() map[string]int { legacyRequests.mu.Lock() defer legacyRequests.mu.Unlock() out := make(map[string]int, len(legacyRequests.counts)) for k, v := range legacyRequests.counts { out[k] = v } return out } // Fault describes a scripted failure for requests to one route. type Fault struct { Method string // HTTP method to match; empty matches any Pattern string // route pattern as registered, e.g. "/tests/ping" Skip int // matching requests let through before faulting Times int // matching requests faulted after Skip; 0 means forever Status int // HTTP status to return; 0 with Drop false only holds the request Code int // Proton code in the error body RetryAfter int // Retry-After header in seconds, if non-zero Drop bool // close the connection instead of responding Delay time.Duration // wait before handling the request Gather bool // hold each faulted request until all Times have arrived AfterHandler bool // run the real handler, then replace its response // Hold, if set, makes each faulted request run the real handler on // arrival and get its response only once Hold is closed, so the // response is as of arrival. Held, if set, is sent to once the // response is ready and held. Hold <-chan struct{} Held chan<- struct{} } // fault is an injected Fault with the count of requests it has matched. type fault struct { Fault seen int gathered chan struct{} // closed when the last of Times has arrived, if Gather } // fires records a matching request and reports whether it is faulted. func (f *fault) fires() bool { f.seen++ n := f.seen - f.Skip if f.Gather && n == f.Times { close(f.gathered) } return n > 0 && (f.Times == 0 || n <= f.Times) } // Server is a fake Proton API server. type Server struct { srv *httptest.Server mux *http.ServeMux mu sync.Mutex requests map[string]int // count per "METHOD pattern" faults []*fault clockSkew time.Duration users map[string]*User // by username sessions map[string]*session // by UID srp map[string]*srpLogin // by SRPSession forks map[string]*fork // by Selector childrenPageSize int eventsPageSize int downloads map[string]*download // block URLs by ID unlockedKeys map[string]*crypto.Key // by keyCacheID uploads map[string]*uploadURL // block upload URLs by ID storageUploads int // block uploads in progress storagePeak int // most block uploads in progress at once secrets []issuedSecret // every secret issued, in order keysAs map[string]*User // whose keys GET /core/v4/keys/all serves for an email, overriding the owner's readLag int // reads of a node after a change which don't see it; see SetReadLag readLagView LagView // what lagging reads of a changed node see lagging map[string]*lagView // nodes whose reads lag, by ID // driveRequirements is sent as x-pm-drive-requirements headers if // not empty; see SetDriveRequirements. driveRequirements []string } // New starts a fake server which is closed when the test ends. func New(t testing.TB) *Server { s := newServer() s.srv = httptest.NewServer(http.HandlerFunc(s.serveHTTP)) t.Cleanup(s.Close) return s } // NewStandalone starts a fake server listening on addr, such as // "127.0.0.1:0", for use outside tests. Call Close to stop it. func NewStandalone(addr string) (*Server, error) { l, err := net.Listen("tcp", addr) if err != nil { return nil, fmt.Errorf("protontest: listen: %w", err) } s := newServer() s.srv = httptest.NewUnstartedServer(http.HandlerFunc(s.serveHTTP)) _ = s.srv.Listener.Close() s.srv.Listener = l s.srv.Start() return s, nil } // newServer returns a server with its routes registered, not yet // listening. func newServer() *Server { s := &Server{ mux: http.NewServeMux(), requests: make(map[string]int), users: make(map[string]*User), sessions: make(map[string]*session), srp: make(map[string]*srpLogin), forks: make(map[string]*fork), childrenPageSize: defaultChildrenPageSize, eventsPageSize: defaultEventsPageSize, downloads: make(map[string]*download), unlockedKeys: make(map[string]*crypto.Key), uploads: make(map[string]*uploadURL), lagging: make(map[string]*lagView), } s.handle("GET", "/tests/ping", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]int{"Code": api.CodeOK}) }) s.registerAuth() s.registerAccount() s.registerDrive() return s } // Close stops the server and blocks until all its requests are done. func (s *Server) Close() { s.srv.Close() } // URL returns the base URL of the server. func (s *Server) URL() string { return s.srv.URL } // Client returns an HTTP client configured for the server. func (s *Server) Client() *http.Client { return s.srv.Client() } // Requests returns a copy of the request count per "METHOD pattern", // e.g. "GET /drive/v2/volumes/{volumeID}/folders/{linkID}/children". // // Requests for unregistered or legacy routes are counted under their // path. func (s *Server) Requests() map[string]int { s.mu.Lock() defer s.mu.Unlock() out := make(map[string]int, len(s.requests)) for k, v := range s.requests { out[k] = v } return out } // ResetRequests zeroes the request counts and the peak of // StorageUploadPeak. func (s *Server) ResetRequests() { s.mu.Lock() defer s.mu.Unlock() clear(s.requests) s.storagePeak = s.storageUploads } // ServeKeysAs makes GET /core/v4/keys/all serve owner's primary // address keys for email, as a hostile server could, whoever owns // email. func (s *Server) ServeKeysAs(email string, owner *User) { s.mu.Lock() defer s.mu.Unlock() if s.keysAs == nil { s.keysAs = make(map[string]*User) } s.keysAs[email] = owner } // SecretKind is a kind of secret the server issues. type SecretKind int // Kinds of secret the server issues. const ( SessionToken SecretKind = iota + 1 // an access or refresh token ForkSelector // the selector polling a session fork StorageToken // a block upload or download token ) // issuedSecret is a secret the server handed to a client. type issuedSecret struct { kind SecretKind value string } // newSecretLocked returns a new random secret of kind and records it // for IssuedSecrets. s.mu must be held. func (s *Server) newSecretLocked(kind SecretKind) string { secret := randomID() s.secrets = append(s.secrets, issuedSecret{kind: kind, value: secret}) return secret } // IssuedSecrets returns every secret of the kinds given, or of any kind // if none is, which the server has handed to a client, in order. func (s *Server) IssuedSecrets(kinds ...SecretKind) []string { s.mu.Lock() defer s.mu.Unlock() var out []string for _, secret := range s.secrets { if len(kinds) == 0 || slices.Contains(kinds, secret.kind) { out = append(out, secret.value) } } return out } // Inject adds a fault. Faults are checked in the order they were added // and the first one that fires is applied. A Gather fault needs Times. func (s *Server) Inject(f Fault) { if f.Gather && f.Times <= 0 { panic("protontest: a Gather fault needs Times") } s.mu.Lock() defer s.mu.Unlock() s.faults = append(s.faults, &fault{Fault: f, gathered: make(chan struct{})}) } // SetClockSkew shifts the Date header of every response by d. func (s *Server) SetClockSkew(d time.Duration) { s.mu.Lock() defer s.mu.Unlock() s.clockSkew = d } // SetDriveRequirements makes every response carry an // x-pm-drive-requirements header with each of values, as Proton // announces upcoming requirements; none if values is empty. func (s *Server) SetDriveRequirements(values ...string) { s.mu.Lock() defer s.mu.Unlock() s.driveRequirements = values } // handle registers h for method and an http.ServeMux path pattern. func (s *Server) handle(method, pattern string, h http.HandlerFunc) { s.mux.HandleFunc(method+" "+pattern, h) } // serveHTTP checks, counts and dispatches every request. func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) { _, pattern := s.mux.Handler(r) // Registered patterns are "METHOD /path"; keep the path part. _, pattern, _ = strings.Cut(pattern, " ") key := r.Method + " " + pattern if pattern == "" { key = r.Method + " " + r.URL.Path } s.mu.Lock() s.requests[key]++ w.Header().Set("Date", time.Now().Add(s.clockSkew).UTC().Format(http.TimeFormat)) for _, v := range s.driveRequirements { w.Header().Add("x-pm-drive-requirements", v) } if pattern == storageUploadPattern { s.storageUploads++ s.storagePeak = max(s.storagePeak, s.storageUploads) defer func() { s.mu.Lock() s.storageUploads-- s.mu.Unlock() }() } s.mu.Unlock() switch { case legacyRouteRe.MatchString(r.URL.Path): legacyRequests.mu.Lock() legacyRequests.counts[r.Method+" "+r.URL.Path]++ legacyRequests.mu.Unlock() writeError(w, http.StatusGone, 0, "protontest: legacy route "+r.URL.Path+" was removed") return case r.Header.Get("x-pm-drive-sdk-version") != "": writeError(w, http.StatusBadRequest, api.CodeInvalidSection, "protontest: x-pm-drive-sdk-version must not be sent") return case !appVersionRe.MatchString(r.Header.Get("x-pm-appversion")): writeError(w, http.StatusBadRequest, api.CodeInvalidSection, fmt.Sprintf("protontest: invalid x-pm-appversion %q", r.Header.Get("x-pm-appversion"))) return case pattern == "": writeError(w, http.StatusNotFound, 0, "protontest: no route for "+r.Method+" "+r.URL.Path) return } if f := s.activeFault(r.Method, pattern); f != nil { s.serveFault(w, r, f) return } s.mux.ServeHTTP(w, r) } // activeFault records the request against every matching fault and // returns the first one that fires, or nil. func (s *Server) activeFault(method, pattern string) *fault { s.mu.Lock() defer s.mu.Unlock() var active *fault for _, f := range s.faults { if f.Pattern != pattern || (f.Method != "" && f.Method != method) { continue } if f.fires() && active == nil { active = f } } return active } // serveFault applies f to a request for a registered route. func (s *Server) serveFault(w http.ResponseWriter, r *http.Request, f *fault) { if f.Delay > 0 || f.Gather { // The server notices a client giving up, and cancels the request // context, only once the request body has been read. if body, err := io.ReadAll(r.Body); err == nil { r.Body = io.NopCloser(bytes.NewReader(body)) } } if f.Gather { select { case <-f.gathered: case <-r.Context().Done(): return } } if f.Delay > 0 { select { case <-time.After(f.Delay): case <-r.Context().Done(): return } } if f.Hold != nil { rec := httptest.NewRecorder() s.mux.ServeHTTP(rec, r) if f.Held != nil { f.Held <- struct{}{} } select { case <-f.Hold: case <-r.Context().Done(): return } for k, v := range rec.Header() { w.Header()[k] = v } w.WriteHeader(rec.Code) _, _ = w.Write(rec.Body.Bytes()) return } if f.Status == 0 && !f.Drop { s.mux.ServeHTTP(w, r) return } if f.AfterHandler { s.mux.ServeHTTP(httptest.NewRecorder(), r) } if f.Drop { conn, _, err := http.NewResponseController(w).Hijack() if err != nil { panic(fmt.Sprintf("protontest: drop connection: %v", err)) } _ = conn.Close() return } if f.RetryAfter > 0 { w.Header().Set("Retry-After", strconv.Itoa(f.RetryAfter)) } writeError(w, f.Status, f.Code, "protontest: injected fault") } // writeJSON writes v as a JSON response with the given HTTP status. func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } // writeError writes an api.Error response. func writeError(w http.ResponseWriter, status, code int, msg string) { writeJSON(w, status, &api.Error{Code: code, Message: msg}) }