summaryrefslogtreecommitdiffstats
path: root/gustodia.go
blob: 8a5b0dea7b027ffb7869b352a0488963a52a3548 (plain)
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
/* Authors:
 *     Christian Heimes <cheimes@redhat.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright (C) 2015 Red Hat, Inc.
 * All rights reserved.
 *
 * Custodia entrypoint for Docker
 */
package main

import (
    "bufio"
    "fmt"
    "encoding/json"
    "errors"
    "log"
    "net"
    "net/http"
    "os"
    "path"
    "strings"
    "syscall"
)

const PREFIX string = "CUSTODIA_"
const SECRET_PREFIX string = PREFIX + "SECRET_"
const BASE_PATH string = "http+unix://localhost/secrets/"

/* Unix Domain Socket transport
 *
 */

type UDSTransport struct {
    SocketPath string
}

func (uds *UDSTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    if req.URL == nil {
        if req.Body != nil {
            req.Body.Close()
        }
        return nil, errors.New("uds: nil Request.URL")
    }
    if req.Header == nil {
        if req.Body != nil {
            req.Body.Close()
        }
        return nil, errors.New("uds: nil Request.Header")
    }
    if req.URL.Scheme != "http+unix" {
        if req.Body != nil {
            req.Body.Close()
        }
        return nil, errors.New("uds: unsupported protocol scheme " + req.URL.Scheme)
    }
    if req.URL.Host != "localhost" {
        if req.Body != nil {
            req.Body.Close()
        }
        return nil, errors.New("uds: Host must be 'localhost'")
    }
    conn, err := net.Dial("unix", uds.SocketPath)
    if err != nil {
        return nil, err
    }
    // XXX: leaks conn
    req.Write(conn)
    return http.ReadResponse(bufio.NewReader(conn), req)
}

func UnixClient(path string) *http.Client {
    transport := new(http.Transport)
    uds := &UDSTransport{SocketPath: path}
    transport.RegisterProtocol("http+unix", uds)
    client := &http.Client{Transport: transport}
    return client
}

/* Custodia client
 */
type CustodiaMessage struct {
    Type string  `json:"type"`
    Value string `json:"value"`
}

type CustodiaSecret struct {
    Name string
    Value string
    Secret string
    Fetched bool
}

type CustodiaClient struct {
    SocketPath string
    BasePath string
    Prefix string
    SecretPrefix string
    RemoteUser string
    Secrets []*CustodiaSecret
}

func NewCustodiaClient(socketpath, remoteuser string) *CustodiaClient {
    return &CustodiaClient{
        SocketPath: socketpath,
        BasePath: BASE_PATH,
        Prefix: PREFIX,
        SecretPrefix: SECRET_PREFIX,
        RemoteUser: remoteuser,
        Secrets: []*CustodiaSecret{},
    }
}

func (cc *CustodiaClient) FindEnvs() {
    for _, env := range os.Environ() {
        if strings.HasPrefix(env, cc.SecretPrefix) {
            pair := strings.SplitN(env, "=", 2)
            sec := &CustodiaSecret{
                Name: pair[0][len(cc.SecretPrefix):],
                Value: pair[1],
                Secret: "",
                Fetched: false,
            }
            cc.Secrets = append(cc.Secrets, sec)
        }
    }
}

func (cc *CustodiaClient) QueryCustodia() {
    if len(cc.Secrets) == 0 {
        return
    }
    client := UnixClient(cc.SocketPath)

    for _, sec := range cc.Secrets {
        path := cc.BasePath + sec.Value
        req, err := http.NewRequest(
            "GET", path, nil)
        if err != nil {
            panic(err)
        }
        if cc.RemoteUser != "" {
            req.Header.Add("REMOTE_USER", cc.RemoteUser)
        }
        resp, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        defer resp.Body.Close()

        if resp.StatusCode != http.StatusOK {
            log.Fatalf("%v: %v\n", path, resp.Status)
        }

        var m CustodiaMessage
        body := json.NewDecoder(resp.Body)
        err = body.Decode(&m)
        if err != nil {
            log.Fatalf("%v json error: %v", path, err)
        }

        if len(m.Value) > 0 {
            sec.Secret = m.Value
            sec.Fetched = true
        }
    }
}

func (cc CustodiaClient) MakeEnv() []string {
    environ := []string{}
    for _, env := range os.Environ() {
        if ! strings.HasPrefix(env, cc.Prefix) {
            environ = append(environ, env)
        }
    }
    for _, sec := range cc.Secrets {
        if sec.Fetched {
            env := fmt.Sprintf("%s=%s", sec.Name, sec.Secret)
            environ = append(environ, env)
        }
    }
    return environ
}

func (cc CustodiaClient) Debug() {
    fmt.Printf("%v secret(s):\n", len(cc.Secrets))
    for _, sec := range cc.Secrets {
        fmt.Printf("  %+v\n", *sec)
    }
    fmt.Println("Environ:")
    environ := cc.MakeEnv()
    for _, env := range environ {
        fmt.Printf("  %v\n", env)
    }
    fmt.Println()
}

func main() {
    debug := os.Getenv("CUSTODIA_DEBUG") != ""

    if len(os.Args) < 2 {
        log.Fatalf("%s entrypoint [args]", os.Args[0])
    }

    socketpath := os.Getenv("CUSTODIA_SOCKET")
    if socketpath == "" {
        // default socket is in the same directory as program
        socketpath = path.Join(path.Dir(os.Args[0]), "server_socket")
    }
    remoteuser := os.Getenv("CUSTODIA_REMOTE_USER")

    client := NewCustodiaClient(socketpath, remoteuser)
    if debug {
        fmt.Printf("%+v\n", client)
    }
    client.FindEnvs()
    client.QueryCustodia()
    environ := client.MakeEnv()
    if debug {
        client.Debug()
    }

    args := os.Args[1:]
    syscall.Exec(args[0], args, environ)
}