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
56 changes: 13 additions & 43 deletions cmd/dashboard/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ package dashboard

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
Expand All @@ -28,7 +24,9 @@ Rendering takes several seconds.

Dune withholds the image when a chart on the dashboard shows enterprise datasets
that are not available to AI tools, or a query that has never completed; the
command then fails and lists those visualizations.
command then fails and lists those visualizations. It also fails when the image
is too large to return, or when the dashboard is private and its owner team
allows no share links.

For a private dashboard, rendering needs a share link: Dune reuses the
dashboard's active share link or creates one, as the Share button on dune.com
Expand All @@ -50,7 +48,7 @@ Examples:
type dashboardImage struct {
DashboardID int `json:"dashboardId"`
DashboardURL string `json:"dashboardUrl"`
DashboardImageURL string `json:"dashboardImageUrl"`
ImageOmittedReason string `json:"imageOmittedReason"`
WithheldVisualizationIDs []int `json:"withheldVisualizationIds"`
}

Expand Down Expand Up @@ -78,30 +76,27 @@ func runImage(cmd *cobra.Command, args []string) error {
"that are not available to AI tools, or a query that has never completed", strings.Join(ids, ", "))
}

var jpeg []byte
switch {
case len(images) > 0:
jpeg = images[0]
case res.DashboardImageURL != "":
// The tool leaves out images larger than it returns inline.
if jpeg, err = download(cmd, res.DashboardImageURL); err != nil {
return err
if len(images) == 0 {
switch res.ImageOmittedReason {
case "too_large":
return fmt.Errorf("the image of dashboard %d is too large to return; open it on dune.com: %s",
dashboardID, res.DashboardURL)
case "sharing_disabled":
return fmt.Errorf("dashboard %d is private and its owner team allows no share links, "+
"so it cannot be rendered", dashboardID)
}
default:
return fmt.Errorf("getDashboardImage returned no image for dashboard %d", dashboardID)
}
if err := os.WriteFile(path, jpeg, 0o644); err != nil {
if err := os.WriteFile(path, images[0], 0o644); err != nil {
return err
}

w := cmd.OutOrStdout()
if output.FormatFromCmd(cmd) == output.FormatJSON {
// The image URL of a private dashboard carries its share key, so it is left out.
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return err
}
delete(out, "dashboardImageUrl")
delete(out, "imageIncluded")
out["file"] = path
return output.PrintJSON(w, out)
Expand All @@ -110,28 +105,3 @@ func runImage(cmd *cobra.Command, args []string) error {
fmt.Fprintf(w, "Dashboard: %s\n", res.DashboardURL)
return nil
}

func download(cmd *cobra.Command, imageURL string) ([]byte, error) {
req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, imageURL, nil)
if err != nil {
return nil, errors.New("getDashboardImage returned an invalid image URL")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
// Drop the URL from the error: it may carry the dashboard's share key.
var urlErr *url.Error
if errors.As(err, &urlErr) {
err = urlErr.Err
}
return nil, fmt.Errorf("downloading the dashboard image: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("downloading the dashboard image failed: %s", resp.Status)
}
// A 200 with an HTML error or login page must not be saved as the image.
if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "image/") {
return nil, fmt.Errorf("downloading the dashboard image failed: got %q instead of an image", ct)
}
return io.ReadAll(resp.Body)
}
58 changes: 13 additions & 45 deletions cmd/dashboard/widget_image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package dashboard_test

import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -67,11 +65,10 @@ func TestUpdateWidgetRejectsBadInput(t *testing.T) {
}
}

func TestImageSavesInlineJPEGAndHidesShareURL(t *testing.T) {
func TestImageSavesInlineJPEG(t *testing.T) {
path := filepath.Join(t.TempDir(), "d.jpg")
fake := &dunemcptest.Fake{
Results: map[string]string{"getDashboardImage": `{"dashboardId":5,"dashboardUrl":"https://dune.com/alice/d",
"dashboardImageUrl":"https://api.dune.com/screenshot?url=https://dune.com/alice/d/SHAREKEY",
"imageIncluded":true,"withheldVisualizationIds":[]}`},
Images: map[string][][]byte{"getDashboardImage": {{0xff, 0xd8, 0x01}}},
}
Expand All @@ -82,54 +79,25 @@ func TestImageSavesInlineJPEGAndHidesShareURL(t *testing.T) {
got, err := os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, []byte{0xff, 0xd8, 0x01}, got)
assert.NotContains(t, out, "SHAREKEY")
var printed map[string]any
require.NoError(t, json.Unmarshal([]byte(out), &printed))
assert.Equal(t, path, printed["file"])
}

func TestImageDownloadsWhenTooLargeToInline(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/jpeg")
_, _ = w.Write([]byte("big-jpeg"))
}))
t.Cleanup(srv.Close)
path := filepath.Join(t.TempDir(), "d.jpg")
fake := &dunemcptest.Fake{Results: map[string]string{"getDashboardImage": `{"dashboardId":5,
"dashboardUrl":"https://dune.com/alice/d","dashboardImageUrl":"` + srv.URL + `/KEY",
"imageIncluded":false,"withheldVisualizationIds":[]}`}}
out, err := runDash(fake, "image", "5", "--file", path)
require.NoError(t, err)
got, _ := os.ReadFile(path)
assert.Equal(t, "big-jpeg", string(got))
assert.NotContains(t, out, "KEY")
}

func imageFake(url string) *dunemcptest.Fake {
return &dunemcptest.Fake{Results: map[string]string{"getDashboardImage": `{"dashboardId":5,
"dashboardUrl":"https://dune.com/alice/d","dashboardImageUrl":"` + url + `",
"imageIncluded":false,"withheldVisualizationIds":[]}`}}
}

func TestImageDownloadFailuresKeepTheShareKeyOut(t *testing.T) {
closed := httptest.NewServer(http.NotFoundHandler())
closed.Close()
html := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte("<html>login</html>"))
}))
t.Cleanup(html.Close)
forbidden := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
t.Cleanup(forbidden.Close)

for name, base := range map[string]string{"connection refused": closed.URL, "html page": html.URL, "403": forbidden.URL} {
t.Run(name, func(t *testing.T) {
func TestImageOmittedReasonIsReported(t *testing.T) {
for reason, want := range map[string]string{
"too_large": "too large to return; open it on dune.com: https://dune.com/alice/d",
"sharing_disabled": "allows no share links",
"": "returned no image for dashboard 5",
} {
t.Run(reason, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "d.jpg")
_, err := runDash(imageFake(base+"/SHAREKEY"), "image", "5", "--file", path)
fake := &dunemcptest.Fake{Results: map[string]string{"getDashboardImage": `{"dashboardId":5,
"dashboardUrl":"https://dune.com/alice/d","imageIncluded":false,
"imageOmittedReason":"` + reason + `","withheldVisualizationIds":[]}`}}
_, err := runDash(fake, "image", "5", "--file", path)
require.Error(t, err)
assert.NotContains(t, err.Error(), "SHAREKEY")
assert.Contains(t, err.Error(), want)
assert.NoFileExists(t, path)
})
}
Expand Down
Loading