vvauth 2.5.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/vault.go CHANGED
@@ -1,209 +1,17 @@
1
1
  package vvauth
2
2
 
3
3
  import (
4
- "bytes"
5
- "encoding/base64"
6
4
  "encoding/json"
7
- "errors"
8
5
  "fmt"
9
- "io"
10
- "net/http"
11
6
  "strings"
12
7
 
13
- sshagentcrypt "github.com/131/ssh-agent-crypt"
14
- "golang.org/x/crypto/ssh/agent"
8
+ vauthlogin "github.com/131/vauth-login"
15
9
  )
16
10
 
17
- // HTTPError reports an unexpected Vault status code.
18
- type HTTPError struct {
19
- Status int
20
- Body string
21
- }
22
-
23
- func (e *HTTPError) Error() string {
24
- return fmt.Sprintf("Unexpected status %d: %s", e.Status, e.Body)
25
- }
26
-
27
- // auth is the Vault auth block of a login or renewal response.
28
- type auth struct {
29
- ClientToken string `json:"client_token"`
30
- LeaseDuration int64 `json:"lease_duration"`
31
- Renewable bool `json:"renewable"`
32
- }
33
-
34
- // lookup is the relevant part of auth/token/lookup-self.
35
- type lookup struct {
36
- TTL float64 `json:"ttl"`
37
- Renewable bool `json:"renewable"`
38
- CreationTTL int64 `json:"creation_ttl"`
39
- EntityID string `json:"entity_id"`
40
- }
41
-
42
- func (v *Vauth) vaultURL(path string) string {
43
- return strings.TrimRight(v.VaultAddr, "/") + "/v1/" + strings.TrimLeft(path, "/")
44
- }
45
-
46
- // request performs a Vault API call. A JSON payload is sent when non-nil.
47
- // With expect > 0, another status is returned as *HTTPError.
48
- func (v *Vauth) request(method, path, token string, payload any, expect int) (int, []byte, error) {
49
- var body io.Reader
50
- if payload != nil {
51
- encoded, err := json.Marshal(payload)
52
- if err != nil {
53
- return 0, nil, err
54
- }
55
- body = bytes.NewReader(encoded)
56
- }
57
- req, err := http.NewRequest(method, v.vaultURL(path), body)
58
- if err != nil {
59
- return 0, nil, err
60
- }
61
- if payload != nil {
62
- req.Header.Set("Content-Type", "application/json")
63
- }
64
- if token != "" {
65
- req.Header.Set("X-Vault-Token", token)
66
- }
67
- res, err := v.httpClient().Do(req)
68
- if err != nil {
69
- return 0, nil, err
70
- }
71
- defer res.Body.Close()
72
- response, err := io.ReadAll(res.Body)
73
- if err != nil {
74
- return res.StatusCode, nil, err
75
- }
76
- if expect > 0 && res.StatusCode != expect {
77
- return res.StatusCode, response, &HTTPError{res.StatusCode, string(response)}
78
- }
79
- return res.StatusCode, response, nil
80
- }
81
-
82
- func (v *Vauth) httpClient() *http.Client {
83
- if v.HTTPClient != nil {
84
- return v.HTTPClient
85
- }
86
- return http.DefaultClient
87
- }
88
-
89
- func parseAuth(response []byte, invalid string) (*auth, error) {
90
- var parsed struct {
91
- Auth *auth `json:"auth"`
92
- }
93
- if err := json.Unmarshal(response, &parsed); err != nil || parsed.Auth == nil || parsed.Auth.ClientToken == "" || parsed.Auth.LeaseDuration < 0 {
94
- return nil, errors.New(invalid)
95
- }
96
- return parsed.Auth, nil
97
- }
98
-
99
- func (v *Vauth) loginVault(path string, payload any) (*auth, error) {
100
- status, response, err := v.request("POST", "auth/"+path+"/login", "", payload, 0)
101
- if err != nil {
102
- return nil, err
103
- }
104
- if status != 200 {
105
- return nil, fmt.Errorf("Could not login to vault : %s", response)
106
- }
107
- return parseAuth(response, "Invalid Vault login response")
108
- }
109
-
110
- func (v *Vauth) loginVaultSSH(config *SSHAuth) (*auth, error) {
111
- path := config.Path
112
- if path == "" {
113
- path = "ssh"
114
- }
115
- v.debug("Trying to auth as '%s'", config.Role)
116
- conn, err := sshagentcrypt.DialAgent(v.Agent)
117
- if err != nil {
118
- return nil, fmt.Errorf("Could not reach ssh-agent at %s: %w", v.Agent, err)
119
- }
120
- defer conn.Close()
121
- client := agent.NewClient(conn)
122
- keys, err := client.List()
123
- if err != nil {
124
- return nil, fmt.Errorf("Unable to list ssh-agent keys: %w", err)
125
- }
126
- for _, key := range keys {
127
- _, response, err := v.request("GET", "auth/"+path+"/nonce", "", nil, 200)
128
- if err != nil {
129
- return nil, err
130
- }
131
- var challenge struct {
132
- Data struct {
133
- Nonce string `json:"nonce"`
134
- } `json:"data"`
135
- }
136
- if err := json.Unmarshal(response, &challenge); err != nil {
137
- return nil, fmt.Errorf("Invalid nonce response: %w", err)
138
- }
139
- nonce := []byte(challenge.Data.Nonce)
140
- signature, err := client.Sign(key, nonce)
141
- if err != nil {
142
- v.debug("ssh : agent refused to sign with public key %s", key.Comment)
143
- continue
144
- }
145
- payload := map[string]string{
146
- "public_key": key.Type() + " " + base64.StdEncoding.EncodeToString(key.Marshal()),
147
- "role": config.Role,
148
- "nonce": base64.StdEncoding.EncodeToString(nonce),
149
- "signature": base64.StdEncoding.EncodeToString(signature.Blob),
150
- }
151
- auth, err := v.loginVault(path, payload)
152
- if err != nil {
153
- v.debug("ssh : invalid challenge for public key %s", key.Comment)
154
- continue
155
- }
156
- return auth, nil
157
- }
158
- return nil, errors.New("Could not login to vault")
159
- }
160
-
161
- func (v *Vauth) lookupToken(token string) (*lookup, int64, error) {
162
- _, response, err := v.request("GET", "auth/token/lookup-self", token, nil, 200)
163
- if err != nil {
164
- return nil, 0, err
165
- }
166
- var parsed struct {
167
- Data *lookup `json:"data"`
168
- }
169
- if err := json.Unmarshal(response, &parsed); err != nil || parsed.Data == nil || parsed.Data.TTL < 0 {
170
- return nil, 0, errors.New("Invalid Vault token TTL")
171
- }
172
- lease := parsed.Data.CreationTTL
173
- if cached := v.readTokenCache(); cached != nil && cached.Token == token {
174
- lease = cached.LeaseDuration
175
- }
176
- return parsed.Data, lease, nil
177
- }
178
-
179
- func (v *Vauth) renewToken(token string) (*auth, error) {
180
- _, response, err := v.request("POST", "auth/token/renew-self", token, map[string]any{}, 200)
181
- if err != nil {
182
- return nil, err
183
- }
184
- return parseAuth(response, "Invalid Vault token renewal response")
185
- }
186
-
187
- func (v *Vauth) lookupIdentity(token, id string) (map[string]any, error) {
188
- _, response, err := v.request("GET", "identity/entity/id/"+id, token, nil, 200)
189
- if err != nil {
190
- return nil, err
191
- }
192
- var parsed struct {
193
- Data struct {
194
- Metadata map[string]any `json:"metadata"`
195
- } `json:"data"`
196
- }
197
- if err := json.Unmarshal(response, &parsed); err != nil {
198
- return nil, fmt.Errorf("Invalid identity response: %w", err)
199
- }
200
- return parsed.Data.Metadata, nil
201
- }
202
-
203
11
  // vaultRead returns the data of a kv2 secret.
204
12
  func (v *Vauth) vaultRead(mount, secretPath string, optional bool) (map[string]any, error) {
205
13
  secretPath = strings.Trim(secretPath, "/")
206
- status, response, err := v.request("GET", mount+"/data/"+secretPath, v.VaultToken, nil, 0)
14
+ status, response, err := v.Request("GET", mount+"/data/"+secretPath, v.VAULT_TOKEN(), nil, 0)
207
15
  if err != nil {
208
16
  return nil, err
209
17
  }
@@ -211,7 +19,7 @@ func (v *Vauth) vaultRead(mount, secretPath string, optional bool) (map[string]a
211
19
  return map[string]any{}, nil
212
20
  }
213
21
  if status != 200 {
214
- return nil, fmt.Errorf("Could not read vault secret '%s/%s' : %s", mount, secretPath, response)
22
+ return nil, &vauthlogin.HTTPError{Status: status, Body: string(response)}
215
23
  }
216
24
  var parsed struct {
217
25
  Data struct {
@@ -227,12 +35,12 @@ func (v *Vauth) vaultRead(mount, secretPath string, optional bool) (map[string]a
227
35
  // vaultWrite replaces the data of a kv2 secret.
228
36
  func (v *Vauth) vaultWrite(mount, secretPath string, data map[string]any) error {
229
37
  secretPath = strings.Trim(secretPath, "/")
230
- status, response, err := v.request("POST", mount+"/data/"+secretPath, v.VaultToken, map[string]any{"data": data}, 0)
38
+ status, response, err := v.Request("POST", mount+"/data/"+secretPath, v.VAULT_TOKEN(), map[string]any{"data": data}, 0)
231
39
  if err != nil {
232
40
  return err
233
41
  }
234
42
  if status != 200 {
235
- return fmt.Errorf("Could not write vault secret '%s/%s' : %s", mount, secretPath, response)
43
+ return &vauthlogin.HTTPError{Status: status, Body: string(response)}
236
44
  }
237
45
  return nil
238
46
  }