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
|
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
// CapabilityClient connects to the capability token service to request signed tokens
type CapabilityClient struct {
conn net.Conn
socketPath string
mu sync.Mutex // Protect concurrent access to connection
}
// NewCapabilityClient connects to the capability token service
func NewCapabilityClient() (*CapabilityClient, error) {
socketPath := filepath.Join("/run/user", strconv.Itoa(os.Getuid()), "de.Profpatsch.CapabilityTokens")
conn, err := net.Dial("unix", socketPath)
if err != nil {
return nil, fmt.Errorf("failed to connect to capability service at %s: %w", socketPath, err)
}
log.Printf("Connected to capability token service at %s\n", socketPath)
return &CapabilityClient{
conn: conn,
socketPath: socketPath,
}, nil
}
// isTransportError checks if an error is a transport/connection error
// (as opposed to an application error from the capability service).
// Transport errors should trigger reconnection.
func isTransportError(err error) bool {
if err == nil {
return false
}
// Check for common transport errors
if errors.Is(err, io.EOF) ||
errors.Is(err, io.ErrClosedPipe) ||
errors.Is(err, io.ErrUnexpectedEOF) {
return true
}
// Check for network errors
var netErr *net.OpError
if errors.As(err, &netErr) {
return true
}
// Check error message for common patterns
errMsg := err.Error()
if strings.Contains(errMsg, "broken pipe") ||
strings.Contains(errMsg, "connection reset") ||
strings.Contains(errMsg, "connection refused") {
return true
}
return false
}
// reconnect closes the current connection and establishes a new one.
// This method assumes the mutex is already held by the caller.
func (cc *CapabilityClient) reconnect() error {
log.Printf("Attempting to reconnect to capability service at %s...\n", cc.socketPath)
// Close old connection if it exists
if cc.conn != nil {
cc.conn.Close()
}
// Establish new connection
conn, err := net.Dial("unix", cc.socketPath)
if err != nil {
return fmt.Errorf("failed to reconnect to capability service at %s: %w", cc.socketPath, err)
}
cc.conn = conn
log.Printf("Successfully reconnected to capability service at %s\n", cc.socketPath)
return nil
}
// doRequest performs the actual request/response exchange with the capability service.
// This method assumes the mutex is already held by the caller.
func (cc *CapabilityClient) doRequest(call VarlinkCall) (map[string]any, error) {
// Send request
callBytes, err := json.Marshal(call)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
callBytes = append(callBytes, 0) // Add null terminator
if _, err := cc.conn.Write(callBytes); err != nil {
return nil, fmt.Errorf("failed to write request: %w", err)
}
// Read response
scanner := bufio.NewScanner(cc.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 nil, fmt.Errorf("failed to read response: %w", err)
}
return nil, fmt.Errorf("no response from capability service")
}
responseBytes := scanner.Bytes()
var response VarlinkReply
if err := json.Unmarshal(responseBytes, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
// Check for errors (these are application errors, not transport errors)
if response.Error != "" {
return nil, fmt.Errorf("capability service error: %s", response.Error)
}
// Extract token from response
token, ok := response.Parameters["token"].(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid response: missing or invalid token field")
}
return token, nil
}
// RequestToken requests a signed capability token from the capability service.
// This proxies the request to de.profpatsch.CapabilityTokens.RequestToken.
// If a transport error occurs, it attempts to reconnect once and retry the request.
func (cc *CapabilityClient) RequestToken(
sessionUUID string,
tokenID string,
scope map[string]any,
reason string,
tokenDescription string,
fieldDescriptions map[string]any,
) (map[string]any, error) {
cc.mu.Lock()
defer cc.mu.Unlock()
// Build Varlink call
call := VarlinkCall{
Method: "de.profpatsch.CapabilityTokens.RequestToken",
Parameters: map[string]any{
"token_id": tokenID,
"scope": scope,
"session": sessionUUID,
},
}
if reason != "" {
call.Parameters["reason"] = reason
}
if tokenDescription != "" {
call.Parameters["token_description"] = tokenDescription
}
if fieldDescriptions != nil {
call.Parameters["field_descriptions"] = fieldDescriptions
}
// Make the request
token, err := cc.doRequest(call)
// If successful, return immediately
if err == nil {
return token, nil
}
// If it's a transport error, attempt reconnection and retry
if isTransportError(err) {
log.Printf("Transport error during token request: %v\n", err)
if reconnectErr := cc.reconnect(); reconnectErr != nil {
return nil, fmt.Errorf("reconnection failed: %w (original error: %v)", reconnectErr, err)
}
// Retry the request after successful reconnection
log.Printf("Retrying token request after reconnection\n")
token, err = cc.doRequest(call)
if err != nil {
return nil, fmt.Errorf("token request failed after reconnection: %w", err)
}
return token, nil
}
// Not a transport error - return the error as-is
return nil, err
}
// Close closes the connection to the capability service
func (cc *CapabilityClient) Close() error {
if cc.conn != nil {
return cc.conn.Close()
}
return nil
}
|