Skip to content
Myr

Add API Keys for fzf --listen (#3374)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Boaz Yaniv · committed by GitHub · parent 3c09c77 · Browse files · 5 files+83 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+83 added−9 removed

  • tests:+21 added−0 removed
  • other:+62 added−9 removed

5 files+83 added−9 removed

modified:man/man1/fzf.1+12 added-1 removed
770 unmodified lines
771Start HTTP server on the given port. It allows external processes to send772actions to perform via POST method. If the port number is omitted or given as7730, fzf will choose the port automatically and export it as \fBFZF_PORT\fR774environment variable to the child processes started via \fBexecute\fR and775\fBexecute-silent\fR actions.775\fBexecute-silent\fR actions. If \fBFZF_API_KEY\fR environment variable is776set, the server would require sending an API key with the same value in the777\fBx-api-key\fR HTTP header.778779e.g.780 \fB# Start HTTP server on port 6266781 fzf --listen 6266782783 # Send action to the server784 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'785786 # Start HTTP server on port 6266 and send an authenticated action787 export FZF_API_KEY="$(head -c 32 /dev/urandom | base64)"788 curl -XPOST localhost:6266 -H "x-api-key: $FZF_API_KEY" -d 'change-query(yo)'789790 # Choose port automatically and export it as $FZF_PORT to the child process791 fzf --listen --bind 'start:execute-silent:echo $FZF_PORT > /tmp/fzf-port'792 \fR793.TP
11 unmodified lines
805this case make sure that the command is POSIX-compliant.806.TP807.B FZF_DEFAULT_OPTS808Default options. e.g. \fBexport FZF_DEFAULT_OPTS="--extended --cycle"\fR809.TP810.B FZF_API_KEY811Can be used to require an API key when using \fB--listen\fR option. If not set,812no authentication will be required by the server. You can set this value if813you need to protect against DNS rebinding and privilege escalation attacks.814815.SH EXIT STATUS816.BR 0 " Normal exit"817.br
494 unmodified lines
modified:src/options.go+1 added
123 unmodified lines
124 Environment variables125 FZF_DEFAULT_COMMAND Default command to use when input is tty126 FZF_DEFAULT_OPTS Default options127 (e.g. '--layout=reverse --inline-info')128 FZF_API_KEY X-API-Key header for HTTP server (--listen)129130`131132const defaultInfoSep = " < "
1985 unmodified lines
modified:src/server.go+35 added-8 removed
1 unmodified line
23import (4 "bufio"5 "bytes"6 "crypto/subtle"7 "errors"8 "fmt"9 "net"10 "os"11 "strconv"12 "strings"13 "time"14)
1 unmodified line
16const (17 crlf = "\r\n"18 httpOk = "HTTP/1.1 200 OK" + crlf19 httpBadRequest = "HTTP/1.1 400 Bad Request" + crlf20 httpUnauthorized = "HTTP/1.1 401 Unauthorized" + crlf21 httpReadTimeout = 10 * time.Second22 maxContentLength = 1024 * 102423)2425type httpServer struct {26 apiKey []byte27 channel chan []*action28}2930func startHttpServer(port int, channel chan []*action) (error, int) {31 if port < 0 {32 return nil, port33 }
14 unmodified lines
48 return err, port49 }50 }5152 server := httpServer{53 apiKey: []byte(os.Getenv("FZF_API_KEY")),54 channel: channel,55 }5657 go func() {58 for {59 conn, err := listener.Accept()60 if err != nil {
2 unmodified lines
63 } else {64 continue65 }66 }54 conn.Write([]byte(handleHttpRequest(conn, channel)))67 conn.Write([]byte(server.handleHttpRequest(conn)))68 conn.Close()69 }70 listener.Close()71 }()
6 unmodified lines
78//79// * No --listen: 2.8MB80// * --listen with net/http: 5.7MB81// * --listen w/o net/http: 3.3MB69func handleHttpRequest(conn net.Conn, channel chan []*action) string {82func (server *httpServer) handleHttpRequest(conn net.Conn) string {83 contentLength := 084 apiKey := ""85 body := ""86 unauthorized := func(message string) string {87 message += "\n"88 return httpUnauthorized + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)89 }90 bad := func(message string) string {91 message += "\n"92 return httpBadRequest + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)93 }
28 unmodified lines
122 section++123 continue124 }125 pair := strings.SplitN(text, ":", 2)126 if len(pair) == 2 {127 switch strings.ToLower(pair[0]) {108 if len(pair) == 2 && strings.ToLower(pair[0]) == "content-length" {109 length, err := strconv.Atoi(strings.TrimSpace(pair[1]))110 if err != nil || length <= 0 || length > maxContentLength {111 return bad("invalid content length")128 case "content-length":129 length, err := strconv.Atoi(strings.TrimSpace(pair[1]))130 if err != nil || length <= 0 || length > maxContentLength {131 return bad("invalid content length")132 }133 contentLength = length134 case "x-api-key":135 apiKey = strings.TrimSpace(pair[1])136 }113 contentLength = length137 }138 case 2:139 body += text140 }141 }142143 if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 {144 return unauthorized("invalid api key")145 }146147 if len(body) < contentLength {148 return bad("incomplete request")149 }150 body = body[:contentLength]
8 unmodified lines
159 if len(actions) == 0 {160 return bad("no action specified")161 }162136 channel <- actions163 server.channel <- actions164 return httpOk165}
modified:test/test_go.rb+21 added
14 unmodified lines
15 FZF_TMUX FZF_TMUX_OPTS16 FZF_CTRL_T_COMMAND FZF_CTRL_T_OPTS17 FZF_ALT_C_COMMAND18 FZF_ALT_C_OPTS FZF_CTRL_R_OPTS19 FZF_API_KEY20 fish_history21].freeze22DEFAULT_TIMEOUT = 1023
2726 unmodified lines
2750 setup2751 end2752 end27532754 def test_listen_with_api_key2755 post_uri = URI('http://localhost:6266')2756 tmux.send_keys 'seq 10 | FZF_API_KEY=123abc fzf --listen 6266', :Enter2757 tmux.until { |lines| assert_equal 10, lines.item_count }2758 # Incorrect API Key2759 [nil, { 'x-api-key' => '' }, { 'x-api-key' => '124abc' }].each do |headers|2760 res = Net::HTTP.post(post_uri, 'change-query(yo)+reload(seq 100)+change-prompt:hundred> ', headers)2761 assert_equal '401', res.code2762 assert_equal 'Unauthorized', res.message2763 assert_equal "invalid api key\n", res.body2764 end2765 # Valid API Key2766 [{ 'x-api-key' => '123abc' }, { 'X-API-Key' => '123abc' }].each do |headers|2767 res = Net::HTTP.post(post_uri, 'change-query(yo)+reload(seq 100)+change-prompt:hundred> ', headers)2768 assert_equal '200', res.code2769 tmux.until { |lines| assert_equal 100, lines.item_count }2770 tmux.until { |lines| assert_equal 'hundred> yo', lines[-1] }2771 end2772 end27732774 def test_toggle_alternative_preview_window2775 tmux.send_keys "seq 10 | #{FZF} --bind space:toggle-preview --preview-window '<100000(hidden,up,border-none)' --preview 'echo /{}/{}/'", :Enter2776 tmux.until { |lines| assert_equal 10, lines.item_count }2777 tmux.until { |lines| refute_includes lines, '/1/1/' }
684 unmodified lines
modified:CHANGELOG.md+14 added
1CHANGELOG2=========340.42.15------6- `--listen` server can be secured by setting `$FZF_API_KEY` environment7 variable.8 ```sh9 export FZF_API_KEY="$(head -c 32 /dev/urandom | base64)"1011 # Server12 fzf --listen 62661314 # Client15 curl localhost:6266 -H "x-api-key: $FZF_API_KEY" -d 'change-query(yo)'16 ```17180.42.019------20- Added new info style: `--info=right`21- Added new info style: `--info=inline-right`
1661 unmodified lines