protondrive: add hermetic contract test harness

Add protonfake, a command which serves the fake Proton server on a
given address and prints the endpoint and a saved session of a user
with a Drive volume as key=value lines, for an fstest test server
script. protontest gains NewStandalone and Close for it.

Add setupFakeRemote, which configures TestProtonDriveFake: with a
fresh session on the fake through environment variables, and
TestIntegrationFake, which runs the backend contract suite against it.
It is skipped until the backend has an endpoint option.

client_salted_key_pass is written base64 encoded, the meaning the key
has in existing configs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas WintherandClaude Opus 5.5 committed 2026-11-11 17:01:53 +01:00
1 parent e23de0b586
commit 414de88c99
6 files changed
+246 -4

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
package protondrive_test
import (
"encoding/base64"
"net/http"
"os"
"testing"
"github.com/rclone/rclone/backend/protondrive"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeEnvPrefix starts the environment variables configuring the
// TestProtonDriveFake: remote.
const fakeEnvPrefix = "RCLONE_CONFIG_TESTPROTONDRIVEFAKE_"
// setupFakeRemote starts a fake Proton server with one user and
// configures the TestProtonDriveFake: remote, through environment
// variables, with a saved session of that user.
func setupFakeRemote(t *testing.T) (remoteName string, srv *protontest.Server, user *protontest.User) {
srv = protontest.New(t)
user = srv.AddUser("user", "pass")
sess := srv.NewSession(user)
t.Setenv(fakeEnvPrefix+"TYPE", "protondrive")
t.Setenv(fakeEnvPrefix+"ENDPOINT", srv.URL())
t.Setenv(fakeEnvPrefix+"CLIENT_UID", sess.UID)
t.Setenv(fakeEnvPrefix+"CLIENT_ACCESS_TOKEN", sess.AccessToken)
t.Setenv(fakeEnvPrefix+"CLIENT_REFRESH_TOKEN", sess.RefreshToken)
// The config holds the salted key password base64 encoded.
t.Setenv(fakeEnvPrefix+"CLIENT_SALTED_KEY_PASS", base64.StdEncoding.EncodeToString([]byte(user.KeyPassword())))
t.Setenv(fakeEnvPrefix+"DRAFT_CLIENT_UID", random.String(32))
return "TestProtonDriveFake:", srv, user
}
// TestSetupFakeRemote checks the configured session is accepted by the
// fake server.
func TestSetupFakeRemote(t *testing.T) {
remoteName, srv, user := setupFakeRemote(t)
assert.Equal(t, "TestProtonDriveFake:", remoteName)
assert.Equal(t, "protondrive", os.Getenv(fakeEnvPrefix+"TYPE"))
assert.Equal(t, srv.URL(), os.Getenv(fakeEnvPrefix+"ENDPOINT"))
assert.NotEmpty(t, os.Getenv(fakeEnvPrefix+"DRAFT_CLIENT_UID"))
keyPass, err := base64.StdEncoding.DecodeString(os.Getenv(fakeEnvPrefix + "CLIENT_SALTED_KEY_PASS"))
require.NoError(t, err)
assert.Equal(t, user.KeyPassword(), string(keyPass))
require.NotEmpty(t, os.Getenv(fakeEnvPrefix+"CLIENT_REFRESH_TOKEN"))
req, err := http.NewRequest("GET", os.Getenv(fakeEnvPrefix+"ENDPOINT")+"/core/v4/users", nil)
require.NoError(t, err)
req.Header.Set("x-pm-appversion", "external-drive-rclone@1.0.0-stable")
req.Header.Set("x-pm-uid", os.Getenv(fakeEnvPrefix+"CLIENT_UID"))
req.Header.Set("Authorization", "Bearer "+os.Getenv(fakeEnvPrefix+"CLIENT_ACCESS_TOKEN"))
resp, err := srv.Client().Do(req)
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
// TestIntegrationFake runs integration tests against the fake server.
func TestIntegrationFake(t *testing.T) {
if *fstest.RemoteName != "" {
t.Skip("skipping as -remote is set")
}
// TODO: remove once the backend has an endpoint option.
t.Skip("the backend cannot be pointed at the fake server yet")
remoteName, _, _ := setupFakeRemote(t)
fstests.Run(t, &fstests.Opt{
RemoteName: remoteName,
NilObject: (*protondrive.Object)(nil),
QuickTestOK: true,
})
}
@@ -0,0 +1,57 @@
// Command protonfake serves a fake Proton Drive API for integration
// tests.
//
// It prints the rclone config of a signed in user with a Drive volume
// as key=value lines on stdout, then serves until interrupted.
//
// go run ./backend/protondrive/protontest/cmd/protonfake -addr 127.0.0.1:0
package main
import (
"encoding/base64"
"flag"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"github.com/rclone/rclone/backend/protondrive/protontest"
)
func main() {
addr := flag.String("addr", "127.0.0.1:0", "address to listen on")
flag.Parse()
stop := make(chan struct{})
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
go func() {
<-sig
close(stop)
}()
if err := run(*addr, os.Stdout, stop); err != nil {
fmt.Fprintln(os.Stderr, "protonfake:", err)
os.Exit(1)
}
}
// run serves a fake server on addr until stop is closed, after writing
// its endpoint and a fresh session's config to out.
func run(addr string, out io.Writer, stop <-chan struct{}) error {
srv, err := protontest.NewStandalone(addr)
if err != nil {
return err
}
defer srv.Close()
user := srv.AddUser("protonfake", "protonfake")
sess := srv.NewSession(user)
// The config holds the salted key password base64 encoded.
keyPass := base64.StdEncoding.EncodeToString([]byte(user.KeyPassword()))
_, err = fmt.Fprintf(out, "endpoint=%s\nclient_uid=%s\nclient_access_token=%s\nclient_refresh_token=%s\nclient_salted_key_pass=%s\ntype=protondrive\n",
srv.URL(), sess.UID, sess.AccessToken, sess.RefreshToken, keyPass)
if err != nil {
return fmt.Errorf("write config: %w", err)
}
<-stop
return nil
}
@@ -0,0 +1,65 @@
package main
import (
"bufio"
"encoding/base64"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRun(t *testing.T) {
pr, pw := io.Pipe()
stop := make(chan struct{})
done := make(chan error, 1)
go func() {
err := run("127.0.0.1:0", pw, stop)
_ = pw.Close()
done <- err
}()
wantKeys := []string{"endpoint", "client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass", "type"}
values := make(map[string]string)
lines := bufio.NewScanner(pr)
for _, key := range wantKeys {
require.True(t, lines.Scan(), "missing line for %s", key)
k, v, ok := strings.Cut(lines.Text(), "=")
require.True(t, ok, "line %q is not key=value", lines.Text())
require.Equal(t, key, k)
require.NotEmpty(t, v, key)
values[k] = v
}
assert.Equal(t, "protondrive", values["type"])
assert.False(t, strings.HasSuffix(values["endpoint"], ":0"), "endpoint %q must carry the bound port", values["endpoint"])
keyPass, err := base64.StdEncoding.DecodeString(values["client_salted_key_pass"])
require.NoError(t, err)
assert.Len(t, keyPass, 31, "a key password is the last 31 characters of a bcrypt hash")
req, err := http.NewRequest("GET", values["endpoint"]+"/core/v4/users", nil)
require.NoError(t, err)
req.Header.Set("x-pm-appversion", "external-drive-rclone@1.0.0-stable")
req.Header.Set("x-pm-uid", values["client_uid"])
req.Header.Set("Authorization", "Bearer "+values["client_access_token"])
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
close(stop)
extra := lines.Scan()
assert.False(t, extra, "unexpected output %q", lines.Text())
require.NoError(t, <-done)
_, err = http.Get(values["endpoint"] + "/tests/ping")
assert.Error(t, err, "server still answering after stop")
}
func TestRunBadAddress(t *testing.T) {
var out strings.Builder
err := run("not an address", &out, make(chan struct{}))
assert.Error(t, err)
assert.Empty(t, out.String())
}
+30 -2
View File
@@ -8,6 +8,7 @@ import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"regexp"
@@ -87,6 +88,30 @@ type Server struct {
// 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),
@@ -106,11 +131,14 @@ func New(t testing.TB) *Server {
s.registerAuth()
s.registerAccount()
s.registerDrive()
s.srv = httptest.NewServer(http.HandlerFunc(s.serveHTTP))
t.Cleanup(s.srv.Close)
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
@@ -269,3 +269,18 @@ func TestErrorJSON(t *testing.T) {
assert.JSONEq(t, `{"Code":2500,"Error":"exists","Details":{"ConflictLinkID":"x"}}`, string(b))
assert.True(t, strings.Contains(e.Error(), "exists") && strings.Contains(e.Error(), "2500") && strings.Contains(e.Error(), "422"), e.Error())
}
func TestNewStandalone(t *testing.T) {
s, err := NewStandalone("127.0.0.1:0")
require.NoError(t, err)
assert.False(t, strings.HasSuffix(s.URL(), ":0"), "URL %q must carry the bound port", s.URL())
resp, _ := ping(t, s)
assert.Equal(t, http.StatusOK, resp.StatusCode)
s.Close()
_, err = s.Client().Get(s.URL() + "/tests/ping")
assert.Error(t, err, "server still answering after Close")
_, err = NewStandalone("not an address")
assert.Error(t, err)
}
+2 -2
View File
@@ -1007,11 +1007,11 @@ Reference: `client/js/src/internal/upload/` (`manager.ts`,
Guarded by `t.Skip` until Task 14 (the old backend has no `endpoint`
option).
- [ ] **Step 1:** Write `fake_test.go` and `protonfake`; run
- [x] **Step 1:** Write `fake_test.go` and `protonfake`; run
`go run ./backend/protondrive/protontest/cmd/protonfake -addr 127.0.0.1:0`
and confirm the six lines print; `go test ./backend/protondrive/ -run TestIntegrationFake -v`
shows SKIP.
- [ ] **Step 2: Commit** `protondrive: add hermetic contract test harness`.
- [x] **Step 2: Commit** `protondrive: add hermetic contract test harness`.
### Task 14: Swap - rewrite `protondrive.go` on the new client