: nply/foundationpkgs

commit c2c0c3ac65bf1ff09f7405b9aa2bdfc048d5ea3f
parent 05a1dd6671387abe5e98193ad877a53aa63838d0
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Fri, 30 Oct 2026 01:20:05 +0530

Fix configurable FXA CLI timeouts after interactive prompts
3 files changed, 334 insertions(+), 9 deletions(-)
M
Unix/minimal-fxa-server/APKBUILD
|
8
+++++---
A
Unix/minimal-fxa-server/cli-rpc-timeout.patch
|
302
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
M
docs/firefox-sync.md
|
33
+++++++++++++++++++++++++++------
diff --git a/Unix/minimal-fxa-server/APKBUILD b/Unix/minimal-fxa-server/APKBUILD
@@ -1,6 +1,6 @@
 pkgname=minimal-fxa-server
 pkgver=0_git20260225
-pkgrel=2
+pkgrel=3
 pkgdesc="Minimal Firefox Accounts server and local user management CLI"
 url="https://github.com/ahyattdev/minimal-fxa-server"
 arch="x86_64 aarch64"

@@ -10,10 +10,12 @@ makedepends="go>=1.25.5"
 options="net !strip"
 _commit=8ec5f0d160269f5079431d2b75574337f0552940
 source="$url/archive/$_commit.tar.gz
-	enforce-pkce.patch"
+	enforce-pkce.patch
+	cli-rpc-timeout.patch"
 sha256sums="
 d336c2d13f58b915dca33a3cd20a9d44239d800fa02b38a19b1ee7fd5efbc08a  $_commit.tar.gz
 12162d02df485ec02e668f6b9591458c44c5fd2a7823908f8f620956e0a60348  enforce-pkce.patch
+2d4ea552beb7ba97fb78393e6deac70ac79066aa35ce998c6b7bb283132be052  cli-rpc-timeout.patch
 "
 builddir="$srcdir/$pkgname-$_commit"
 

@@ -28,7 +30,7 @@ build() {
 	export GOOS=linux CGO_ENABLED=0
 	cd "$builddir"
 	# Explicit exe overrides abuild's default PIE flag: no glibc/musl loader needed.
-	# Serial builds fit the small CI host; only the listed PKCE patch is applied.
+	# Serial builds fit the small CI host; only the listed patches are applied.
 	go build -p 1 -buildmode=exe -mod=readonly -trimpath -ldflags="-s -w" -o minimal-fxa-server .
 	go build -p 1 -buildmode=exe -mod=readonly -trimpath -ldflags="-s -w" -o fxa-user ./cmd/fxa-user
 	# Pure-Go Linux binaries can be checked on Debian despite the Alpine ABI target.
diff --git a/Unix/minimal-fxa-server/cli-rpc-timeout.patch b/Unix/minimal-fxa-server/cli-rpc-timeout.patch
@@ -0,0 +1,302 @@
+diff --git a/README.md b/README.md
+index 8f9cc46..431117f 100644
+--- a/README.md
++++ b/README.md
+@@ -64,6 +64,17 @@ fxa-user passwd user@example.com
+ fxa-user list
+ ```
+ 
++The CLI's RPC timeout starts after interactive input, not while typing passwords
++or confirming deletion. Override it at runtime with a positive Go duration:
++
++```sh
++FXA_TIMEOUT=30s fxa-user create user@example.com
++```
++
++The default is `10s`; packagers can change it with
++`go build -ldflags="-X main.defaultRPCTimeout=30s" ./cmd/fxa-user`.
++`FXA_TIMEOUT` takes precedence over that build-time default.
++
+ The CLI connects via Unix socket for security. In Docker/Kubernetes:
+ ```bash
+ kubectl exec -it <pod> -- fxa-user create admin@example.com
+diff --git a/cmd/fxa-user/main.go b/cmd/fxa-user/main.go
+index e6cc367..2aff785 100644
+--- a/cmd/fxa-user/main.go
++++ b/cmd/fxa-user/main.go
+@@ -13,12 +13,25 @@ import (
+ 	"google.golang.org/grpc/credentials/insecure"
+ )
+ 
++// Override at build time with -ldflags="-X main.defaultRPCTimeout=30s".
++var defaultRPCTimeout = "10s"
++
+ func main() {
+ 	if len(os.Args) < 2 {
+ 		printUsage()
+ 		os.Exit(1)
+ 	}
+ 
++	timeoutValue := os.Getenv("FXA_TIMEOUT")
++	if timeoutValue == "" {
++		timeoutValue = defaultRPCTimeout
++	}
++	rpcTimeout, err := time.ParseDuration(timeoutValue)
++	if err != nil || rpcTimeout <= 0 {
++		fmt.Fprintln(os.Stderr, "Invalid RPC timeout: use a positive duration such as 10s or 1m")
++		os.Exit(1)
++	}
++
+ 	socketPath := os.Getenv("FXA_SOCKET")
+ 	if socketPath == "" {
+ 		socketPath = usermgmt.DefaultSocketPath
+@@ -35,8 +48,7 @@ func main() {
+ 	defer conn.Close()
+ 
+ 	client := usermgmt.NewUserManagementClient(conn)
+-	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+-	defer cancel()
++	ctx := context.Background()
+ 
+ 	switch os.Args[1] {
+ 	case "create":
+@@ -44,24 +56,24 @@ func main() {
+ 			fmt.Fprintf(os.Stderr, "Usage: fxa-user create <email>\n")
+ 			os.Exit(1)
+ 		}
+-		createUser(ctx, client, os.Args[2])
++		createUser(ctx, client, os.Args[2], rpcTimeout)
+ 
+ 	case "delete":
+ 		if len(os.Args) < 3 {
+ 			fmt.Fprintf(os.Stderr, "Usage: fxa-user delete <email>\n")
+ 			os.Exit(1)
+ 		}
+-		deleteUser(ctx, client, os.Args[2])
++		deleteUser(ctx, client, os.Args[2], rpcTimeout)
+ 
+ 	case "passwd":
+ 		if len(os.Args) < 3 {
+ 			fmt.Fprintf(os.Stderr, "Usage: fxa-user passwd <email>\n")
+ 			os.Exit(1)
+ 		}
+-		changePassword(ctx, client, os.Args[2])
++		changePassword(ctx, client, os.Args[2], rpcTimeout)
+ 
+ 	case "list":
+-		listUsers(ctx, client)
++		listUsers(ctx, client, rpcTimeout)
+ 
+ 	case "help", "-h", "--help":
+ 		printUsage()
+@@ -74,7 +86,7 @@ func main() {
+ }
+ 
+ func printUsage() {
+-	fmt.Println(`fxa-user - Firefox Account user management CLI
++	fmt.Printf(`fxa-user - Firefox Account user management CLI
+ 
+ Usage:
+   fxa-user <command> [arguments]
+@@ -86,10 +98,12 @@ Commands:
+   list             List all users
+ 
+ Environment:
+-  FXA_SOCKET       Path to the gRPC Unix socket (default: /var/run/fxa/usermgmt.sock)`)
++  FXA_SOCKET       Path to the gRPC Unix socket (default: /var/run/fxa/usermgmt.sock)
++  FXA_TIMEOUT      RPC timeout after interactive input (default: %s)
++`, defaultRPCTimeout)
+ }
+ 
+-func createUser(ctx context.Context, client usermgmt.UserManagementClient, email string) {
++func createUser(ctx context.Context, client usermgmt.UserManagementClient, email string, timeout time.Duration) {
+ 	password, err := promptPassword("Password: ")
+ 	if err != nil {
+ 		fmt.Fprintf(os.Stderr, "Failed to read password: %v\n", err)
+@@ -112,6 +126,9 @@ func createUser(ctx context.Context, client usermgmt.UserManagementClient, email
+ 		os.Exit(1)
+ 	}
+ 
++	// Start the RPC deadline after interactive input, not while the user types.
++	ctx, cancel := context.WithTimeout(ctx, timeout)
++	defer cancel()
+ 	resp, err := client.CreateUser(ctx, &usermgmt.CreateUserRequest{
+ 		Email:    email,
+ 		Password: password,
+@@ -124,7 +141,7 @@ func createUser(ctx context.Context, client usermgmt.UserManagementClient, email
+ 	fmt.Printf("User created: %s (ID: %s)\n", resp.Email, resp.UserId)
+ }
+ 
+-func deleteUser(ctx context.Context, client usermgmt.UserManagementClient, email string) {
++func deleteUser(ctx context.Context, client usermgmt.UserManagementClient, email string, timeout time.Duration) {
+ 	fmt.Printf("Are you sure you want to delete user %s? [y/N]: ", email)
+ 	var confirm string
+ 	fmt.Scanln(&confirm)
+@@ -134,6 +151,8 @@ func deleteUser(ctx context.Context, client usermgmt.UserManagementClient, email
+ 		return
+ 	}
+ 
++	ctx, cancel := context.WithTimeout(ctx, timeout)
++	defer cancel()
+ 	_, err := client.DeleteUser(ctx, &usermgmt.DeleteUserRequest{
+ 		Email: email,
+ 	})
+@@ -145,7 +164,7 @@ func deleteUser(ctx context.Context, client usermgmt.UserManagementClient, email
+ 	fmt.Printf("User deleted: %s\n", email)
+ }
+ 
+-func changePassword(ctx context.Context, client usermgmt.UserManagementClient, email string) {
++func changePassword(ctx context.Context, client usermgmt.UserManagementClient, email string, timeout time.Duration) {
+ 	password, err := promptPassword("New password: ")
+ 	if err != nil {
+ 		fmt.Fprintf(os.Stderr, "Failed to read password: %v\n", err)
+@@ -168,6 +187,8 @@ func changePassword(ctx context.Context, client usermgmt.UserManagementClient, e
+ 		os.Exit(1)
+ 	}
+ 
++	ctx, cancel := context.WithTimeout(ctx, timeout)
++	defer cancel()
+ 	_, err = client.ChangePassword(ctx, &usermgmt.ChangePasswordRequest{
+ 		Email:       email,
+ 		NewPassword: password,
+@@ -180,7 +201,9 @@ func changePassword(ctx context.Context, client usermgmt.UserManagementClient, e
+ 	fmt.Printf("Password changed for: %s\n", email)
+ }
+ 
+-func listUsers(ctx context.Context, client usermgmt.UserManagementClient) {
++func listUsers(ctx context.Context, client usermgmt.UserManagementClient, timeout time.Duration) {
++	ctx, cancel := context.WithTimeout(ctx, timeout)
++	defer cancel()
+ 	resp, err := client.ListUsers(ctx, &usermgmt.ListUsersRequest{})
+ 	if err != nil {
+ 		fmt.Fprintf(os.Stderr, "Failed to list users: %v\n", err)
+diff --git a/cmd/fxa-user/tests/prompt_timeout.py b/cmd/fxa-user/tests/prompt_timeout.py
+new file mode 100644
+index 0000000..eb4b6e5
+--- /dev/null
++++ b/cmd/fxa-user/tests/prompt_timeout.py
+@@ -0,0 +1,124 @@
++#!/usr/bin/env python3
++"""Regression: interactive time must not consume the CLI's 10-second RPC deadline.
++
++Run from the repository root: python3 cmd/fxa-user/tests/prompt_timeout.py
++Uses a disposable local gRPC stub and PTYs, not real accounts. Requires Go.
++"""
++import os
++import pathlib
++import pty
++import select
++import subprocess
++import tempfile
++import time
++
++STUB = r'''package main
++import (
++ "context"
++ "net"
++ "os"
++ "time"
++ "fmt"
++ "github.com/ahyattdev/minimal-fxa-server/usermgmt"
++ "google.golang.org/grpc"
++)
++type server struct { usermgmt.UnimplementedUserManagementServer }
++func checkDeadline(ctx context.Context) error {
++ expected,err:=time.ParseDuration(os.Getenv("EXPECTED_TIMEOUT"));if err!=nil{return err}
++ deadline,ok:=ctx.Deadline();remaining:=time.Until(deadline)
++ if !ok || remaining > expected || remaining < expected*3/4 {return fmt.Errorf("unexpected RPC deadline")};return nil
++}
++func (server) CreateUser(ctx context.Context,_ *usermgmt.CreateUserRequest)(*usermgmt.CreateUserResponse,error){return &usermgmt.CreateUserResponse{Email:"fixture@example.invalid",UserId:"fixture"},checkDeadline(ctx)}
++func (server) ChangePassword(ctx context.Context,_ *usermgmt.ChangePasswordRequest)(*usermgmt.ChangePasswordResponse,error){return &usermgmt.ChangePasswordResponse{Success:true},checkDeadline(ctx)}
++func (server) DeleteUser(ctx context.Context,_ *usermgmt.DeleteUserRequest)(*usermgmt.DeleteUserResponse,error){return &usermgmt.DeleteUserResponse{Success:true},checkDeadline(ctx)}
++func (server) ListUsers(ctx context.Context,_ *usermgmt.ListUsersRequest)(*usermgmt.ListUsersResponse,error){return &usermgmt.ListUsersResponse{},checkDeadline(ctx)}
++func main(){l,e:=net.Listen("unix",os.Args[1]);if e!=nil{panic(e)};s:=grpc.NewServer();usermgmt.RegisterUserManagementServer(s,server{});if e=s.Serve(l);e!=nil{panic(e)}}
++'''
++
++
++def check_command(binary, socket, command):
++    master, slave = pty.openpty()
++    env = dict(os.environ, FXA_SOCKET=str(socket), FXA_TIMEOUT="2s")
++    process = subprocess.Popen(
++        [str(binary), command, "fixture@example.invalid"],
++        stdin=slave, stdout=slave, stderr=slave, env=env,
++    )
++    os.close(slave)
++    output, sent = b"", 0
++    try:
++        deadline = time.monotonic() + 35
++        while time.monotonic() < deadline:
++            ready, _, _ = select.select([master], [], [], 0.2)
++            if ready:
++                try:
++                    chunk = os.read(master, 4096)
++                except OSError:
++                    break
++                if not chunk:
++                    break
++                output += chunk
++                prompts = output.count(b"assword:") if command != "delete" else output.count(b"[y/N]:")
++                while sent < prompts:
++                    if sent == 0:
++                        time.sleep(11)
++                    value = b"synthetic-password-only\n" if command != "delete" else b"y\n"
++                    os.write(master, value)
++                    sent += 1
++            if process.poll() is not None:
++                break
++        result = process.wait(timeout=5)
++        assert b"DeadlineExceeded" not in output, command + ": deadline expired during user input"
++        expected = {"create": b"User created:", "passwd": b"Password changed for:", "delete": b"User deleted:"}[command]
++        assert result == 0 and expected in output, command + ": command failed"
++        print("PASS:", command, "accepts an 11-second pause at its prompt")
++    finally:
++        if process.poll() is None:
++            process.kill()
++            process.wait()
++        os.close(master)
++
++
++root = pathlib.Path(__file__).resolve().parents[3]
++go = os.environ.get("GO", "go")
++with tempfile.TemporaryDirectory(prefix="fxa-cli-timeout-", dir="/tmp") as directory:
++    work = pathlib.Path(directory)
++    (work / "server.go").write_text(STUB)
++    subprocess.run([go, "build", "-o", str(work / "stub"), str(work / "server.go")], cwd=root, check=True)
++    subprocess.run([go, "build", "-ldflags=-X main.defaultRPCTimeout=1s", "-o", str(work / "fxa-user"), "./cmd/fxa-user"], cwd=root, check=True)
++    env = dict(os.environ)
++    env.pop("FXA_TIMEOUT", None)
++    help_text = subprocess.check_output([str(work / "fxa-user"), "--help"], env=env)
++    assert b"(default: 1s)" in help_text, "build-time override missing from help"
++    for invalid in ["0s", "-1s", "invalid"]:
++        result = subprocess.run([str(work / "fxa-user"), "list"], env=dict(env, FXA_TIMEOUT=invalid), capture_output=True)
++        assert result.returncode != 0 and b"Invalid RPC timeout" in result.stderr
++    print("PASS: build-time default and invalid timeout validation")
++    socket = work / "rpc.sock"
++    server = subprocess.Popen([str(work / "stub"), str(socket)], env=dict(env, EXPECTED_TIMEOUT="1s"))
++    try:
++        for _ in range(100):
++            if socket.exists():
++                break
++            assert server.poll() is None, "stub server exited"
++            time.sleep(0.05)
++        assert socket.exists(), "stub server did not start"
++        subprocess.run([str(work / "fxa-user"), "list"], env=dict(env, FXA_SOCKET=str(socket)), check=True, capture_output=True)
++        print("PASS: RPC uses the build-time default when FXA_TIMEOUT is unset")
++    finally:
++        server.terminate()
++        server.wait(timeout=5)
++    socket.unlink(missing_ok=True)
++    server = subprocess.Popen([str(work / "stub"), str(socket)], env=dict(env, EXPECTED_TIMEOUT="2s"))
++    try:
++        for _ in range(100):
++            if socket.exists():
++                break
++            assert server.poll() is None, "stub server exited"
++            time.sleep(0.05)
++        assert socket.exists(), "stub server did not start"
++        for command in ["create", "passwd", "delete"]:
++            check_command(work / "fxa-user", socket, command)
++        print("PASS: FXA_TIMEOUT overrides the build-time default")
++    finally:
++        server.terminate()
++        server.wait(timeout=5)
diff --git a/docs/firefox-sync.md b/docs/firefox-sync.md
@@ -3,9 +3,16 @@
 ## Deployment
 
 `Unix/minimal-fxa-server/APKBUILD` packages upstream commit
-`8ec5f0d160269f5079431d2b75574337f0552940` as `0_git20260225-r2`, with
-`enforce-pkce.patch`: 27 production lines enforce S256 PKCE and client-ID
-binding in both authorization-code exchange endpoints, plus regression tests.
+`8ec5f0d160269f5079431d2b75574337f0552940` as `0_git20260225-r3`, with:
+
+- `enforce-pkce.patch`: 27 production lines enforce S256 PKCE and client-ID
+  binding in both authorization-code exchange endpoints, plus regression tests.
+- `cli-rpc-timeout.patch`: starts CLI RPC deadlines after interactive input,
+  supports a positive-duration `FXA_TIMEOUT` runtime override and a
+  `-ldflags="-X main.defaultRPCTimeout=30s"` build-time default override.
+  Without an override the RPC timeout remains 10 seconds, but time spent typing
+  passwords or confirming deletion no longer consumes it.
+
 Missing PKCE and `plain` exchanges are intentionally rejected. Existing sessions
 and refresh-token exchanges are unchanged. Firefox Desktop 158.0.1's bundled
 source sends the required fields; a real browser login remains unverified.

@@ -84,8 +91,16 @@ No permanent user or default password was created. Run interactively:
 ssh -t cdg-1 'fxa-user create your-email@example.com'
 ```
 
-The CLI prompts for a password and confirmation. The email is a local account
-identifier; it does not register a Mozilla account. Manage accounts with
+The CLI prompts for a password and confirmation. Take as long as needed at the
+prompts; the RPC timeout starts afterward. To allow a longer server response:
+
+```sh
+ssh -t cdg-1 'FXA_TIMEOUT=30s fxa-user create your-email@example.com'
+```
+
+`FXA_TIMEOUT` must be a positive Go duration (`30s`, `1m`, etc.). This setting
+belongs to the CLI process, not the Accounts service environment file.
+The email is a local account identifier; it does not register a Mozilla account. Manage accounts with
 `fxa-user list`, `fxa-user passwd EMAIL`, and `fxa-user delete EMAIL` (interactive
 confirmation required for deletion).
 

@@ -136,12 +151,18 @@ network independence remains unverified.
 keys derived from non-secret user ID/timestamp inputs, no-op credential
 revocation, or outstanding Go/runtime dependency findings. Do not interpret
 successful health checks as security approval for sensitive Sync data.
-The original deployment accepted the key-derivation risk; r2 only fixes PKCE.
+The original deployment accepted the key-derivation risk; r2 fixes PKCE and r3
+adds the CLI timeout correction. Neither release fixes the other security issues.
 
 The patch's unit tests run during package checks. Its PostgreSQL endpoint tests
 require `FXA_TEST_DATABASE_URI` pointing at a disposable database (never the live
 Accounts database); each case rolls back its transaction. Run against the patched
 source with `FXA_TEST_DATABASE_URI='...' go test -race ./oauth`.
+The separate CLI regression test uses synthetic responses from a disposable
+Unix-socket gRPC stub, not live accounts:
+`python3 cmd/fxa-user/tests/prompt_timeout.py`. It checks linker/runtime timeout
+overrides and 11-second pauses at create/password/delete prompts; this Python
+integration test is a manual release check, not part of the Go-only package checks.
 
 Back up all three databases (`minimal_fxa`, `syncstorage_rs`, `tokenserver_rs`)
 and both secret configuration files before upgrades. Preserve signing/master