解密后的反向代理服务文件

时间:2019-07-24 12:57:33

标签: http go proxy fileserver

我需要将* os.File放入request.Body中,但是我不知道如何处理文件描述符的关闭(以及消除临时文件)。我无法使用http.ServeFile来提供文件。

我有3个软件: A)用户界面(我无法编辑) B)提供文件的后端 C)一个http反向代理,其作用是对从A到B的请求进行签名,加密从A到B的文件以及解密从B到A的文件。

期望软件A接收解密文件内容的主体。我知道,使用B解密目录中的文件然后打开A会更容易,但是不幸的是,我无法编辑A,而A希望该文件位于请求正文中。

软件的工作流程如下:软件A向C发送请求,C对请求进行签名并将其转发给B,然后C继续解密文件,并在请求中将解密后的内容提供给A身体。

type transportPageServeFile struct {
    http.RoundTripper
    // vault handles encryption and decryption of files
    vault *vault.Container
}

func (t *transportPageServeFile) RoundTrip(req *http.Request) (resp *http.Response, err error) {
    resp, err = t.RoundTripper.RoundTrip(req)
    if err != nil {
        return nil, errors.Wrap(err, "transportPageServeFile")
    }
    // create temporary destination dir for the decrypted file
    dstDir, err := utils.MkTmpDir()
    if err != nil {
        return nil, errors.Wrap(err, "transportPageServeFile")
    }
    defer os.RemoveAll(dstDir) // i'm deleting the directory where the temporary file is stored, deleting it before it even gets transmitted to software A
    fileName := req.Header.Get(api.FileNameHeader)
    decryptedFileDst := fmt.Sprintf("%s/%s", dstDir, fileName)
    // DecryptFileFromReader takes a reader and decrypts the file, saving it in the decided destination
    err = t.vault.DecryptFileFromReader(resp.Body, decryptedFileDst)
    if err != nil {
        return nil, errors.Wrap(err, "transportPageServeFile")
    }
    defer resp.Body.Close()
    // now open the saved decrypted file
    decryptedFile, err := os.Open(decryptedFileDst)
    if err != nil {
        return nil, errors.Wrap(err,"transportPageServeFile")
    }
    defer decryptedFile.Close() // close file before serving the content?
    resp.Body = decryptedFile
    return resp, nil
}
// pageServeFile is the handler of /serveFile
func (rpc *RPC) pageServeFile(c *gin.Context) {
    transport := &transportPageServeFile{RoundTripper:http.DefaultTransport, vault:rpc.vault}
    target, err := url.Parse(rpc.apiEndpoint)
    if err != nil {
        rpc.onError(c, errors.Wrapf(err, "pageServeFile"))
        return
    }
    proxy := httputil.NewSingleHostReverseProxy(target)
    proxy.Transport = transport
    proxy.ServeHTTP(c.Writer, c.Request)
}

如何(使用阅读器)将文件复制到请求正文中?转发响应后,何时/如何关闭文件描述符?

1 个答案:

答案 0 :(得分:0)

响应主体是io.ReadCloser,因此可以合理地假设反向代理调用Close。正如您通过运行以下程序所见,确实如此:

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
    "net/http/httputil"
    "net/url"
    "runtime/debug"
)

type dbg struct{ io.ReadCloser }

func (d dbg) Close() error {
    fmt.Println("Close() called:")
    debug.PrintStack()

    return d.ReadCloser.Close()
}

func main() {
    // srv simulates "software B"
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world"))
    }))

    target, _ := url.Parse(srv.URL)
    p := httputil.NewSingleHostReverseProxy(target)

    // To modify the response, use the aptly named ModifyResponse field; no
    // need to implement a RoundTripper.
    p.ModifyResponse = func(res *http.Response) error {
        res.Body = dbg{res.Body}
        return nil
    }

    req := httptest.NewRequest("GET", "http://example.com/hello", nil)
    rec := httptest.NewRecorder()

    p.ServeHTTP(rec, req)
}

// Output:
// Close() called:
// goroutine 1 [running]:
// runtime/debug.Stack(0x10, 0x0, 0x0)
//         /usr/local/go/src/runtime/debug/stack.go:24 +0x9d
// runtime/debug.PrintStack()
//         /usr/local/go/src/runtime/debug/stack.go:16 +0x22
// main.dbg.Close(0x75b780, 0xc00013e140, 0xc000152000, 0x7f61fc523088)
//         /tmp/tmp.H9O7cizbkv/main.go:17 +0x7f
// net/http/httputil.(*ReverseProxy).ServeHTTP(0xc0000ac0f0, 0x75e460, 0xc000032440, 0xc00010a000)
//         /usr/local/go/src/net/http/httputil/reverseproxy.go:311 +0x8a6
// main.main()
//         /tmp/tmp.H9O7cizbkv/main.go:41 +0x152