Files
rclone/backend/protondrive/protontest/server.go
T
Lucas WintherandClaude Opus 5.5 ea41704ade protondrive: add session with safe token refresh
Add the session used for authenticated API calls: it sends x-pm-uid,
the bearer token, x-pm-appversion and the Proton Accept header, decodes
failures into api.Error, and on HTTP 401 refreshes the tokens and
retries once. Refresh is single-flight, first adopts tokens another
session saved to the shared store, and on a rejected refresh token
returns a fatal "session expired" error without clearing the stored
credentials or retrying the refresh. The session also tracks the
server's clock from the Date header.

The app version maps development builds to the "alpha" channel, as
Proton's x-pm-appversion grammar has no "dev" channel.

The fake server gains users, sessions, single-use refresh tokens and
401 for invalid access tokens on authenticated routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:33:43 +01:00

235 lines
6.8 KiB
Go

// 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 (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
"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)(/|$)`)
)
// 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 delays
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
AfterHandler bool // run the real handler, then replace its response
}
// fault is an injected Fault with the count of requests it has matched.
type fault struct {
Fault
seen int
}
// fires records a matching request and reports whether it is faulted.
func (f *fault) fires() bool {
f.seen++
n := f.seen - f.Skip
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
}
// New starts a fake server which is closed when the test ends.
func New(t testing.TB) *Server {
s := &Server{
mux: http.NewServeMux(),
requests: make(map[string]int),
users: make(map[string]*User),
sessions: make(map[string]*session),
}
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.srv = httptest.NewServer(http.HandlerFunc(s.serveHTTP))
t.Cleanup(s.srv.Close)
return s
}
// 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.
func (s *Server) ResetRequests() {
s.mu.Lock()
defer s.mu.Unlock()
clear(s.requests)
}
// Inject adds a fault. Faults are checked in the order they were added
// and the first one that fires is applied.
func (s *Server) Inject(f Fault) {
s.mu.Lock()
defer s.mu.Unlock()
s.faults = append(s.faults, &fault{Fault: f})
}
// 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
}
// 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))
s.mu.Unlock()
switch {
case legacyRouteRe.MatchString(r.URL.Path):
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.Fault
}
}
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 {
select {
case <-time.After(f.Delay):
case <-r.Context().Done():
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})
}