Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,7 @@ automation use.
| `ZENNOTES_VAULT` | Default local vault root |
| `ZENNOTES_SERVER` | Default server selector; precedes `ZENNOTES_VAULT` |
| `ZENNOTES_REMOTE_TOKEN` | Remote API token for scripts; explicit `--token` wins |
| `ZENNOTES_REMOTE_HEADERS` | Extra headers for a server behind an access gateway such as Cloudflare Access, one `Name: value` per line |
| `ZENNOTES_WORKSPACE_SOURCE` | CLI source: `app` or `terminal` |
| `ZENNOTES_CONFIG_DIR` | Override configuration, workspace, and credential locations; also isolates managed instances |
| `XDG_CONFIG_HOME` | Base directory for portable configuration when no explicit override is set |
Expand All @@ -989,6 +990,37 @@ environment, then the applicable saved credentials. `zn connect` stores them
separately from workspace profiles. MCP clients can therefore use a saved
connection without embedding tokens in their own configuration.

### A server behind Cloudflare Access or another gateway

An access gateway in front of the server turns away every request without its
credentials. `zn`, `zn tui` and `zn mcp` send them as extra headers on every
request, the live-update WebSocket included, from `ZENNOTES_REMOTE_HEADERS`:
one `Name: value` per line, blank lines and `#` lines skipped. For a
Cloudflare Access service token:

```sh
export ZENNOTES_REMOTE_HEADERS=$'CF-Access-Client-Id: <client id>.access\nCF-Access-Client-Secret: <client secret>'
zn list --server https://notes.example.com
```

An MCP client's JSON config can only write the line break as `\n`, which
counts as one:

```json
"env": {
"ZENNOTES_REMOTE_HEADERS": "CF-Access-Client-Id: <client id>.access\nCF-Access-Client-Secret: <client secret>"
}
```

Keep the server's own token in `--token`, `ZENNOTES_REMOTE_TOKEN` or
`zn connect`: the gateway checks the headers, then the server checks the
token. Authorization and the headers the connection sets itself (Host,
Content-Type, Upgrade and the like) are refused, and a value that does not
parse stops the command before anything is sent. Headers are never written to
`credentials.toml`. The desktop app takes the same lines in its connect
dialog and keeps them in the system keychain, which zn cannot read, so give
zn the variable too.

## Troubleshooting

### Copy a TUI version report
Expand Down
1 change: 1 addition & 0 deletions internal/cli/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ var globalFlags = []helpRow{
var environmentRows = []helpRow{
{"ZENNOTES_VAULT", "Default vault root when --vault is not given", ""},
{"ZENNOTES_REMOTE_TOKEN", "Server token for CI and scripts; `zn connect` stores one for you otherwise", ""},
{"ZENNOTES_REMOTE_HEADERS", "Extra headers for a server behind an access gateway such as Cloudflare Access, one \"Name: value\" per line", ""},
{"ZENNOTES_SERVER", "Default server when neither --vault nor --server is given (otherwise zn follows the vault the app has open)", ""},
{"ZENNOTES_CONFIG_DIR", "Override the ZenNotes config directory", ""},
{"ZENNOTES_WORKSPACE_SOURCE", "Default workspace source: app or terminal. `zn tui` uses terminal unless its flag overrides it", ""},
Expand Down
10 changes: 1 addition & 9 deletions internal/remote/assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"mime/multipart"
"net/http"
"path/filepath"
"strings"
)

func (c *Client) ImportAsset(ctx context.Context, note, name string, body io.Reader) (vault.ImportedAsset, error) {
Expand Down Expand Up @@ -38,18 +37,11 @@ func (c *Client) ImportAsset(ctx context.Context, note, name string, body io.Rea
return vault.ImportedAsset{}, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
if c.AuthToken != "" {
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
}
resp, err := c.http.Do(req)
resp, err := c.send(req, "/api/assets/upload")
if err != nil {
return vault.ImportedAsset{}, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
return vault.ImportedAsset{}, &RequestError{Status: resp.StatusCode, Message: requestErrorMessage(c.BaseURL, "/api/assets/upload", resp.StatusCode, http.StatusText(resp.StatusCode), strings.TrimSpace(string(raw)))}
}
var out vault.ImportedAsset
err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out)
return out, err
Expand Down
91 changes: 64 additions & 27 deletions internal/remote/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,16 @@ func ConnectionErrorMessage(baseURL string, err error) string {
return fmt.Sprintf("Could not connect to the ZenNotes server at %s. Make sure the server is running and the URL is correct.%s%s", baseURL, detail, hint)
}

func requestErrorMessage(baseURL, path string, status int, statusText, text string) string {
func requestErrorMessage(baseURL, path string, status int, statusText, contentType, text string) string {
if status == 401 {
return fmt.Sprintf("The ZenNotes server rejected the connection. Check the auth token for %s and try again.", baseURL)
}
// The ZenNotes server answers in plain text. An HTML 403 came from
// something in front of it, most often an access gateway turning away a
// request without its headers; its page would only be noise here.
if status == http.StatusForbidden && strings.Contains(strings.ToLower(contentType), "text/html") {
return GatewayRefusedMessage(baseURL)
}
msg := fmt.Sprintf("Remote server request failed (%d %s) for %s", status, statusText, path)
if text != "" {
msg += ": " + text
Expand All @@ -80,16 +86,64 @@ func requestErrorMessage(baseURL, path string, status int, statusText, text stri
type Client struct {
BaseURL string
AuthToken string
http *http.Client
// Headers go with every request and the change feed's handshake, for an
// access gateway in front of the server (see headers.go).
Headers []Header
headersErr error
http *http.Client
}

// NewClient binds a client to a server and an optional token.
// NewClient binds a client to a server and an optional token. It sends the
// extra headers from ZENNOTES_REMOTE_HEADERS; a value that does not parse
// fails every request with the reason, before anything is sent.
func NewClient(baseURL, authToken string) *Client {
headers, err := EnvHeaders()
return &Client{
BaseURL: NormalizeBaseURL(baseURL),
AuthToken: authToken,
http: &http.Client{Timeout: 60 * time.Second},
BaseURL: NormalizeBaseURL(baseURL),
AuthToken: authToken,
Headers: headers,
headersErr: err,
http: &http.Client{Timeout: 60 * time.Second},
}
}

// requestHeaders is what every request to the server carries: the token,
// then the extra headers, which never replace one already set.
func (c *Client) requestHeaders(h http.Header) error {
if c.headersErr != nil {
return c.headersErr
}
if c.AuthToken != "" && h.Get("Authorization") == "" {
h.Set("Authorization", "Bearer "+c.AuthToken)
}
ApplyHeaders(h, c.Headers)
return nil
}

// send performs a prepared request and turns every failure into the error a
// caller shows: the network, a gateway's sign-in redirect, a non-2xx answer.
// A returned response is 2xx and the caller closes it.
func (c *Client) send(req *http.Request, path string) (*http.Response, error) {
if err := c.requestHeaders(req.Header); err != nil {
return nil, err
}
resp, err := c.http.Do(req)
if err != nil {
return nil, errors.New(ConnectionErrorMessage(c.BaseURL, err))
}
if msg := gatewayRedirectMessage(c.BaseURL, resp.Request.URL); msg != "" {
resp.Body.Close()
return nil, &RequestError{Status: http.StatusForbidden, Message: msg}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
defer resp.Body.Close()
text, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
return nil, &RequestError{
Status: resp.StatusCode,
Message: requestErrorMessage(c.BaseURL, path, resp.StatusCode, http.StatusText(resp.StatusCode), resp.Header.Get("Content-Type"), strings.TrimSpace(string(text))),
}
}
return resp, nil
}

// NewClientWithTransport is a client whose requests go through transport instead
Expand Down Expand Up @@ -118,24 +172,14 @@ func (c *Client) do(ctx context.Context, method, path string, body any, out any)
if err != nil {
return err
}
if c.AuthToken != "" {
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
resp, err := c.send(req, path)
if err != nil {
return errors.New(ConnectionErrorMessage(c.BaseURL, err))
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
text, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
return &RequestError{
Status: resp.StatusCode,
Message: requestErrorMessage(c.BaseURL, path, resp.StatusCode, http.StatusText(resp.StatusCode), strings.TrimSpace(string(text))),
}
}
if out == nil || resp.StatusCode == http.StatusNoContent {
return nil
}
Expand All @@ -155,18 +199,11 @@ func (c *Client) GetRaw(ctx context.Context, path string) ([]byte, error) {
if err != nil {
return nil, err
}
if c.AuthToken != "" {
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
}
resp, err := c.http.Do(req)
resp, err := c.send(req, path)
if err != nil {
return nil, errors.New(ConnectionErrorMessage(c.BaseURL, err))
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
text, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
return nil, &RequestError{Status: resp.StatusCode, Message: requestErrorMessage(c.BaseURL, path, resp.StatusCode, http.StatusText(resp.StatusCode), strings.TrimSpace(string(text)))}
}
return io.ReadAll(io.LimitReader(resp.Body, 64<<20))
}

Expand Down
Loading
Loading