: nply/foundationpkgs

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
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/main_test.go b/cmd/fxa-user/main_test.go
new file mode 100644
index 0000000..23ae485
--- /dev/null
+++ b/cmd/fxa-user/main_test.go
@@ -0,0 +1,175 @@
+package main
+
+import (
+	"bufio"
+	"bytes"
+	"context"
+	"fmt"
+	"io"
+	"net"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/ahyattdev/minimal-fxa-server/usermgmt"
+	"google.golang.org/grpc"
+)
+
+// Run the real CLI entry point in a child so os.Exit cannot terminate the suite.
+func TestCLIProcess(t *testing.T) {
+	if os.Getenv("FXA_CLI_TEST_PROCESS") != "1" {
+		return
+	}
+	for i, arg := range os.Args {
+		if arg == "--" {
+			os.Args = append([]string{"fxa-user"}, os.Args[i+1:]...)
+			main()
+			os.Exit(0)
+		}
+	}
+	os.Exit(2)
+}
+
+func cliCommand(t *testing.T, timeout, socket string, args ...string) *exec.Cmd {
+	t.Helper()
+	binary, err := os.Executable()
+	if err != nil {
+		t.Fatal(err)
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+	t.Cleanup(cancel)
+	cmd := exec.CommandContext(ctx, binary, append([]string{"-test.run=^TestCLIProcess$", "--"}, args...)...)
+	for _, entry := range os.Environ() {
+		if !strings.HasPrefix(entry, "FXA_TIMEOUT=") && !strings.HasPrefix(entry, "FXA_SOCKET=") && !strings.HasPrefix(entry, "FXA_CLI_TEST_PROCESS=") {
+			cmd.Env = append(cmd.Env, entry)
+		}
+	}
+	cmd.Env = append(cmd.Env, "FXA_CLI_TEST_PROCESS=1", "FXA_TIMEOUT="+timeout, "FXA_SOCKET="+socket)
+	return cmd
+}
+
+type timeoutServer struct {
+	usermgmt.UnimplementedUserManagementServer
+	timeout time.Duration
+	block   bool
+}
+
+func (s timeoutServer) DeleteUser(ctx context.Context, _ *usermgmt.DeleteUserRequest) (*usermgmt.DeleteUserResponse, error) {
+	deadline, ok := ctx.Deadline()
+	remaining := time.Until(deadline)
+	if !ok || remaining <= s.timeout/2 || remaining > s.timeout {
+		return nil, fmt.Errorf("RPC did not receive a fresh deadline: %v", remaining)
+	}
+	return &usermgmt.DeleteUserResponse{Success: true}, nil
+}
+
+func (s timeoutServer) ListUsers(ctx context.Context, _ *usermgmt.ListUsersRequest) (*usermgmt.ListUsersResponse, error) {
+	if s.block {
+		<-ctx.Done()
+		return nil, ctx.Err()
+	}
+	deadline, ok := ctx.Deadline()
+	remaining := time.Until(deadline)
+	if !ok || remaining <= s.timeout/2 || remaining > s.timeout {
+		return nil, fmt.Errorf("unexpected RPC deadline: %v", remaining)
+	}
+	return &usermgmt.ListUsersResponse{}, nil
+}
+
+func startTimeoutServer(t *testing.T, server timeoutServer) string {
+	t.Helper()
+	// Keep Unix socket paths below the macOS limit, even with a long TMPDIR.
+	dir, err := os.MkdirTemp("/tmp", "fxa-cli-")
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { os.RemoveAll(dir) })
+	socket := filepath.Join(dir, "rpc.sock")
+	listener, err := net.Listen("unix", socket)
+	if err != nil {
+		t.Fatal(err)
+	}
+	grpcServer := grpc.NewServer()
+	usermgmt.RegisterUserManagementServer(grpcServer, server)
+	t.Cleanup(grpcServer.Stop)
+	go grpcServer.Serve(listener)
+	return socket
+}
+
+func TestDeleteDeadlineStartsAfterConfirmation(t *testing.T) {
+	const timeout = 500 * time.Millisecond
+	socket := startTimeoutServer(t, timeoutServer{timeout: timeout})
+	cmd := cliCommand(t, timeout.String(), socket, "delete", "fixture@example.invalid")
+	stdin, err := cmd.StdinPipe()
+	if err != nil {
+		t.Fatal(err)
+	}
+	stdout, err := cmd.StdoutPipe()
+	if err != nil {
+		t.Fatal(err)
+	}
+	var stderr bytes.Buffer
+	cmd.Stderr = &stderr
+	if err := cmd.Start(); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
+	reader := bufio.NewReader(stdout)
+	prompt, err := reader.ReadString(':')
+	if err != nil || !strings.Contains(prompt, "[y/N]") {
+		t.Fatalf("missing confirmation prompt: %q, %v", prompt, err)
+	}
+	// Longer than the entire RPC budget: a deadline created before input fails.
+	time.Sleep(3 * timeout)
+	if _, err := io.WriteString(stdin, "y\n"); err != nil {
+		t.Fatal(err)
+	}
+	stdin.Close()
+	output, err := io.ReadAll(reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := cmd.Wait(); err != nil || !bytes.Contains(output, []byte("User deleted:")) {
+		t.Fatalf("delete after delayed input: %v, stdout=%s, stderr=%s", err, output, &stderr)
+	}
+}
+
+func TestCLITimeout(t *testing.T) {
+	buildTimeout, err := time.ParseDuration(defaultRPCTimeout)
+	if err != nil || buildTimeout <= 0 {
+		t.Fatalf("invalid build-time default: %q", defaultRPCTimeout)
+	}
+	for _, invalid := range []string{"0s", "-1s", "invalid"} {
+		t.Run(invalid, func(t *testing.T) {
+			output, err := cliCommand(t, invalid, "", "list").CombinedOutput()
+			if err == nil || !bytes.Contains(output, []byte("Invalid RPC timeout")) {
+				t.Fatalf("invalid timeout accepted: %v, %s", err, output)
+			}
+		})
+	}
+	for _, tc := range []struct {
+		name    string
+		value   string
+		timeout time.Duration
+		block   bool
+	}{
+		{"default", "", buildTimeout, false},
+		{"runtime override", "2s", 2 * time.Second, false},
+		{"deadline enforced", "100ms", 100 * time.Millisecond, true},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			socket := startTimeoutServer(t, timeoutServer{timeout: tc.timeout, block: tc.block})
+			output, err := cliCommand(t, tc.value, socket, "list").CombinedOutput()
+			if tc.block {
+				if err == nil || !bytes.Contains(output, []byte("DeadlineExceeded")) {
+					t.Fatalf("RPC deadline not enforced: %v, %s", err, output)
+				}
+			} else if err != nil || !bytes.Contains(output, []byte("No users found")) {
+				t.Fatalf("list failed: %v, %s", err, output)
+			}
+		})
+	}
+}