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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package main

import (
	"bufio"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"
)

// VarlinkCall represents a Varlink method call (request)
type VarlinkCall struct {
	Method     string         `json:"method"`
	Parameters map[string]any `json:"parameters,omitempty"`
	More       bool           `json:"more,omitempty"`
}

// VarlinkReply represents a Varlink method reply (response)
type VarlinkReply struct {
	Parameters map[string]any `json:"parameters,omitempty"`
	Continues  bool           `json:"continues,omitempty"`
	Error      string         `json:"error,omitempty"`
}

// Action represents a HATEOAS-style action
type Action struct {
	Name        string `json:"name"`
	Href        string `json:"href"`
	Method      string `json:"method"`
	Description string `json:"description"`
}

// CapabilityServer handles Varlink protocol for capability token service
type CapabilityServer struct {
	signer         *TokenSigner
	dialogChannels map[string]chan bool // Maps dialog UUID to result channel
	dialogMutex    sync.Mutex           // Protects dialogChannels map
}

// NewCapabilityServer creates a new capability server
func NewCapabilityServer(signer *TokenSigner) *CapabilityServer {
	return &CapabilityServer{
		signer:         signer,
		dialogChannels: make(map[string]chan bool),
	}
}

func (cs *CapabilityServer) handleConnection(conn net.Conn) {
	defer conn.Close()
	log.Println("Capability token client connected")

	scanner := bufio.NewScanner(conn)
	scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		// Split on null byte
		if i := strings.IndexByte(string(data), 0); i >= 0 {
			return i + 1, data[0:i], nil
		}
		if atEOF && len(data) > 0 {
			return len(data), data, nil
		}
		return 0, nil, nil
	})

	for scanner.Scan() {
		msg := scanner.Bytes()
		log.Printf("Received: %s\n", msg)

		var request VarlinkCall
		if err := json.Unmarshal(msg, &request); err != nil {
			log.Printf("Failed to parse request: %v\n", err)
			continue
		}

		response := cs.handleMethod(request)
		responseBytes, _ := json.Marshal(response)
		responseBytes = append(responseBytes, 0) // Add null terminator
		if _, err := conn.Write(responseBytes); err != nil {
			log.Printf("Failed to write response: %v\n", err)
			return
		}
	}

	if err := scanner.Err(); err != nil {
		log.Printf("Scanner error: %v\n", err)
	}

	log.Println("Capability token client disconnected")
}

func (cs *CapabilityServer) handleMethod(request VarlinkCall) VarlinkReply {
	switch request.Method {
	case "org.varlink.service.GetInfo":
		return VarlinkReply{
			Parameters: map[string]any{
				"vendor":     "Profpatsch",
				"product":    "Capability Token Service",
				"version":    "0.1",
				"url":        "none",
				"interfaces": []string{"de.profpatsch.CapabilityTokens"},
			},
		}

	case "org.varlink.service.GetInterfaceDescription":
		iface, _ := request.Parameters["interface"].(string)
		// Strip method name if provided
		if idx := strings.LastIndex(iface, "."); idx != -1 {
			baseIface := iface[:idx]
			if baseIface == "de.profpatsch.CapabilityTokens" {
				iface = baseIface
			}
		}
		if iface == "de.profpatsch.CapabilityTokens" {
			// Read interface description from file
			desc, err := os.ReadFile("capability-tokens.varlink")
			if err != nil {
				// Fallback to embedded description
				desc = []byte(getInterfaceDescription())
			}
			return VarlinkReply{
				Parameters: map[string]any{
					"description": string(desc),
				},
			}
		}
		return VarlinkReply{Error: "UnknownInterface"}

	case "de.profpatsch.CapabilityTokens.RequestToken":
		return cs.handleRequestToken(request)

	case "de.profpatsch.CapabilityTokens.GetPublicKey":
		return cs.handleGetPublicKey(request)

	case "de.profpatsch.CapabilityTokens.DialogReply":
		return cs.handleDialogReply(request)

	default:
		log.Printf("Unknown method: %s\n", request.Method)
		return VarlinkReply{Error: "UnknownMethod"}
	}
}

func (cs *CapabilityServer) handleRequestToken(request VarlinkCall) VarlinkReply {
	// Extract parameters
	tokenID, ok := request.Parameters["token_id"].(string)
	if !ok {
		return VarlinkReply{Error: "InvalidParameter: token_id required"}
	}

	scopeRaw, ok := request.Parameters["scope"].(map[string]any)
	if !ok {
		return VarlinkReply{Error: "InvalidParameter: scope required"}
	}

	sessionID, ok := request.Parameters["session"].(string)
	if !ok {
		return VarlinkReply{Error: "InvalidParameter: session required"}
	}

	reason, _ := request.Parameters["reason"].(string)
	tokenDescription, _ := request.Parameters["token_description"].(string)
	fieldDescriptions, _ := request.Parameters["field_descriptions"].(map[string]any)

	// NOTE: We don't validate token types here - capability service is a dumb signer!
	// Resource services (like maildir-varlink) are responsible for validating
	// tokens they receive match expected types/scopes.

	// Path normalization is handled by signer.IssueToken() for security

	// Prompt user for approval
	approved, err := cs.UserApproval(tokenID, scopeRaw, sessionID, reason, tokenDescription, fieldDescriptions)
	if err != nil {
		return VarlinkReply{Error: fmt.Sprintf("PromptFailed: %v", err)}
	}

	if !approved {
		NotifyTokenDenied(tokenID)
		return VarlinkReply{Error: "TokenDenied: user denied the request"}
	}

	// Issue token (default 2-hour TTL)
	token, err := cs.signer.IssueToken(tokenID, scopeRaw, sessionID, 2*time.Hour)
	if err != nil {
		return VarlinkReply{Error: fmt.Sprintf("SigningFailed: %v", err)}
	}

	NotifyTokenIssued(tokenID, scopeRaw)

	// Build HATEOAS actions
	actions := []Action{
		{
			Name:        "get_public_key",
			Href:        "unix://" + getSocketPath(),
			Method:      "de.profpatsch.CapabilityTokens.GetPublicKey",
			Description: "Get public key for verifying tokens",
		},
	}

	return VarlinkReply{
		Parameters: map[string]any{
			"token":             token,
			"available_actions": actions,
		},
	}
}

func (cs *CapabilityServer) handleGetPublicKey(request VarlinkCall) VarlinkReply {
	publicKeyB64 := cs.signer.GetPublicKey()

	actions := []Action{
		{
			Name:        "request_token",
			Href:        "unix://" + getSocketPath(),
			Method:      "de.profpatsch.CapabilityTokens.RequestToken",
			Description: "Request a new capability token",
		},
	}

	return VarlinkReply{
		Parameters: map[string]any{
			"public_key_base64": publicKeyB64,
			"available_actions": actions,
		},
	}
}

func getSocketPath() string {
	return filepath.Join("/run/user", strconv.Itoa(os.Getuid()), "de.Profpatsch.CapabilityTokens")
}

// generateDialogID creates a random base64-encoded dialog identifier
func generateDialogID() (string, error) {
	bytes := make([]byte, 16) // 16 bytes = 128 bits
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(bytes), nil
}

// handleDialogReply handles the callback from dialog subprocess
func (cs *CapabilityServer) handleDialogReply(request VarlinkCall) VarlinkReply {
	dialogID, ok := request.Parameters["dialog_uuid"].(string)
	if !ok {
		return VarlinkReply{Error: "InvalidParameter: dialog_uuid required"}
	}

	approved, ok := request.Parameters["approved"].(bool)
	if !ok {
		return VarlinkReply{Error: "InvalidParameter: approved required"}
	}

	log.Printf("Dialog reply: dialog_id=%s approved=%v\n", dialogID, approved)

	// Find the channel for this dialog
	cs.dialogMutex.Lock()
	ch, exists := cs.dialogChannels[dialogID]
	cs.dialogMutex.Unlock()

	if !exists {
		return VarlinkReply{Error: fmt.Sprintf("UnknownDialog: dialog_uuid %s not found", dialogID)}
	}

	// Send result to waiting goroutine
	ch <- approved

	return VarlinkReply{Parameters: map[string]any{}}
}

func getInterfaceDescription() string {
	return `# Capability Token Service
# Stateless signing service that prompts users and signs authorization tokens.
# Tokens are validated by resource services (e.g., maildir-varlink).

interface de.profpatsch.CapabilityTokens

# HATEOAS Action type for discoverable APIs
type Action (
  name: string,
  href: string,
  method: string,
  description: string
)

# Request a capability token (prompts user for approval)
method RequestToken(
  token_id: string,
  scope: object,
  session: string,
  reason: ?string,
  token_description: ?string,
  field_descriptions: ?object
) -> (
  token: object,
  available_actions: []Action
)

# Get the public key for token verification
method GetPublicKey() -> (
  public_key_base64: string,
  available_actions: []Action
)

error TokenDenied (reason: string)
error SigningFailed (message: string)
`
}

// TokenRequest holds the data for a token approval dialog
type TokenRequest struct {
	TokenID           string         `json:"token_id"`
	Scope             map[string]any `json:"scope"`
	SessionID         string         `json:"session_id"`
	Reason            string         `json:"reason,omitempty"`
	TokenDescription  string         `json:"token_description,omitempty"`
	FieldDescriptions map[string]any `json:"field_descriptions,omitempty"`
}

// runDialog displays the approval dialog using gum and calls back via Varlink
// Returns exit code 0 on success, 1 on error
func runDialog(jsonData string) int {
	// Get dialog ID from environment
	dialogID := os.Getenv("DIALOG_ID")
	if dialogID == "" {
		fmt.Fprintln(os.Stderr, "Error: DIALOG_ID environment variable not set")
		return 1
	}

	// Parse JSON
	var req TokenRequest
	if err := json.Unmarshal([]byte(jsonData), &req); err != nil {
		fmt.Fprintf(os.Stderr, "Error parsing JSON: %v\n", err)
		return 1
	}

	// Check if gum is available
	if _, err := exec.LookPath("gum"); err != nil {
		fmt.Println("Error: gum not found")
		fmt.Println("Install with: nix profile install nixpkgs#gum")
		fmt.Print("Press Enter to close...")
		fmt.Scanln()
		return 1
	}

	// Header
	cmd := exec.Command("gum", "style", "--border", "double", "--border-foreground", "212", "--padding", "1 2", "--width", "60", "Authorization Request")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()
	fmt.Println()

	// Reason
	if req.Reason != "" {
		cmd = exec.Command("gum", "style", "--foreground", "33", fmt.Sprintf("Reason: %s", req.Reason))
		cmd.Stdout = os.Stdout
		cmd.Run()
		fmt.Println()
	}

	// Token type + description
	cmd = exec.Command("gum", "style", "--bold", fmt.Sprintf("Token Type: %s", req.TokenID))
	cmd.Stdout = os.Stdout
	cmd.Run()

	if req.TokenDescription != "" {
		cmd = exec.Command("gum", "style", "--foreground", "240", req.TokenDescription)
		cmd.Stdout = os.Stdout
		cmd.Run()
	}
	fmt.Println()

	// Session
	cmd = exec.Command("gum", "style", fmt.Sprintf("Session: %s", req.SessionID))
	cmd.Stdout = os.Stdout
	cmd.Run()
	fmt.Println()

	// Scope fields with descriptions
	cmd = exec.Command("gum", "style", "--bold", "Requested Access:")
	cmd.Stdout = os.Stdout
	cmd.Run()

	for key, value := range req.Scope {
		cmd = exec.Command("gum", "style", fmt.Sprintf("  • %s: %v", key, value))
		cmd.Stdout = os.Stdout
		cmd.Run()

		if req.FieldDescriptions != nil {
			if desc, ok := req.FieldDescriptions[key].(string); ok && desc != "" {
				cmd = exec.Command("gum", "style", "--foreground", "240", fmt.Sprintf("    └─ %s", desc))
				cmd.Stdout = os.Stdout
				cmd.Run()
			}
		}
	}
	fmt.Println()

	// Mandatory delay to prevent accidental approvals
	cmd = exec.Command("gum", "style", "--foreground", "240", "Please review carefully...")
	cmd.Stdout = os.Stdout
	cmd.Run()

	time.Sleep(1 * time.Second)
	fmt.Println()

	// Confirmation prompt
	cmd = exec.Command("gum", "confirm", "Allow this access?", "--affirmative", "Allow", "--negative", "Deny")
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	approved := false
	if err := cmd.Run(); err == nil {
		// Exit code 0 means approved
		approved = true
	}
	// Exit code 1 (or other error) means denied

	// Call back to Varlink service with result
	if err := sendDialogReply(dialogID, approved); err != nil {
		fmt.Fprintf(os.Stderr, "Error sending dialog reply: %v\n", err)
		return 1
	}

	return 0
}

// sendDialogReply sends the dialog result back to the capability service via Varlink
func sendDialogReply(dialogID string, approved bool) error {
	socketPath := getSocketPath()

	conn, err := net.Dial("unix", socketPath)
	if err != nil {
		return fmt.Errorf("failed to connect to capability service: %w", err)
	}
	defer conn.Close()

	// Build Varlink call
	call := VarlinkCall{
		Method: "de.profpatsch.CapabilityTokens.DialogReply",
		Parameters: map[string]any{
			"dialog_uuid": dialogID,
			"approved":    approved,
		},
	}

	callBytes, err := json.Marshal(call)
	if err != nil {
		return fmt.Errorf("failed to marshal request: %w", err)
	}
	callBytes = append(callBytes, 0) // Add null terminator

	if _, err := conn.Write(callBytes); err != nil {
		return fmt.Errorf("failed to write request: %w", err)
	}

	// Read response
	scanner := bufio.NewScanner(conn)
	scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		// Split on null byte
		if i := strings.IndexByte(string(data), 0); i >= 0 {
			return i + 1, data[0:i], nil
		}
		if atEOF && len(data) > 0 {
			return len(data), data, nil
		}
		return 0, nil, nil
	})

	if !scanner.Scan() {
		if err := scanner.Err(); err != nil {
			return fmt.Errorf("failed to read response: %w", err)
		}
		return fmt.Errorf("no response from capability service")
	}

	responseBytes := scanner.Bytes()

	var response VarlinkReply
	if err := json.Unmarshal(responseBytes, &response); err != nil {
		return fmt.Errorf("failed to unmarshal response: %w", err)
	}

	if response.Error != "" {
		return fmt.Errorf("capability service error: %s", response.Error)
	}

	return nil
}

func main() {
	// Parse command-line arguments
	flag.Parse()
	args := flag.Args()

	// Check for dialog subcommand
	if len(args) >= 2 && args[0] == "dialog" && args[1] == "--json" {
		if len(args) < 3 {
			fmt.Fprintln(os.Stderr, "Usage: capability-token-service dialog --json '{...}'")
			os.Exit(1)
		}
		jsonData := args[2]
		exitCode := runDialog(jsonData)
		os.Exit(exitCode)
	}

	// Default: run as server
	runServer()
}

func runServer() {
	// Load or generate ED25519 keys
	keyPair, err := LoadOrGenerateKeys()
	if err != nil {
		log.Fatalf("Failed to load keys: %v\n", err)
	}

	log.Printf("Loaded ED25519 public key: %s\n", keyPair.PublicKeyBase64())

	// Create token signer
	signer := NewTokenSigner(keyPair)

	// Create server
	server := NewCapabilityServer(signer)

	socketPath := getSocketPath()

	// Remove existing socket
	os.Remove(socketPath)

	// Listen on Unix socket
	listener, err := net.Listen("unix", socketPath)
	if err != nil {
		log.Fatalf("Failed to listen on socket: %v\n", err)
	}
	defer listener.Close()

	log.Printf("Capability Token service listening on %s\n", socketPath)

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("Accept error: %v\n", err)
			continue
		}
		go server.handleConnection(conn)
	}
}