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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,25 @@ func webhookHandler(w http.ResponseWriter, r *http.Request) {
}
```

## App Logo

GitHub can't set an app's logo from a manifest, and has no API for it. Pass
the logo as `Icon` instead: the installer pages show it with a link to
download it and, once the app is created, a link to the app's settings, where
you upload it under **Display information**. GitHub takes a PNG, JPEG, or GIF
of at most 1 MB, and `installer.New` returns an error for anything else.

```go
//go:embed logo.png
var logo []byte

installerHandler, err := runtime.InstallerHandler(installer.Config{
Manifest: manifest,
AppDisplayName: "My GitHub App",
Icon: logo,
})
```

## Configuration

### Environment Variables
Expand Down
70 changes: 68 additions & 2 deletions installer/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"bytes"
"context"
"embed"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
Expand Down Expand Up @@ -37,6 +38,9 @@ const (
disableSetupPath = "/setup/disable"
)

// maxIconSize is the largest logo GitHub takes.
const maxIconSize = 1 << 20

// CredentialsSavedFunc is called after credentials are saved.
type CredentialsSavedFunc func(ctx context.Context, creds *configstore.AppCredentials) error

Expand All @@ -51,6 +55,11 @@ type Config struct {
WebhookURL string
OnCredentialsSaved CredentialsSavedFunc

// Icon is an optional logo for the app: a PNG, JPEG, or GIF of at most
// 1 MB. GitHub can't set a logo from a manifest, so the installer pages
// show it with a link to download it and say where to upload it.
Icon []byte

// OnReloadNeeded is called after credentials are saved to trigger
// a configuration reload. This should be wired to the Runtime's
// ReloadCallback() or a custom reload function.
Expand All @@ -67,7 +76,9 @@ func NewConfigFromEnv() Config {

// Handler handles the GitHub App manifest installation flow.
type Handler struct {
config Config
config Config
iconURL template.URL
iconFile string
}

type indexTemplateData struct {
Expand All @@ -79,6 +90,8 @@ type indexTemplateData struct {
WebhookURL string
NeedsWebhook bool
DefaultAppName string
IconURL template.URL
IconFile string
}

type successTemplateData struct {
Expand All @@ -89,6 +102,9 @@ type successTemplateData struct {
InstallURL string
DisableActionURL string
InstallerDisabled bool
IconURL template.URL
IconFile string
SettingsURL string
}

// New creates a new installer Handler with the given configuration.
Expand All @@ -103,7 +119,30 @@ func New(cfg Config) (*Handler, error) {
if cfg.AppDisplayName == "" {
cfg.AppDisplayName = "GitHub App"
}
return &Handler{config: cfg}, nil
h := &Handler{config: cfg}
if len(cfg.Icon) > 0 {
iconURL, iconFile, err := iconData(cfg.Icon)
if err != nil {
return nil, err
}
h.iconURL, h.iconFile = iconURL, iconFile
}
return h, nil
}

// iconData returns icon as a data URL and a file name for downloading it,
// or an error if GitHub won't take it as a logo.
func iconData(icon []byte) (template.URL, string, error) {
if len(icon) > maxIconSize {
return "", "", fmt.Errorf("icon is %d bytes; github takes at most %d", len(icon), maxIconSize)
}
ext := map[string]string{"image/png": "png", "image/jpeg": "jpg", "image/gif": "gif"}
contentType := http.DetectContentType(icon)
if ext[contentType] == "" {
return "", "", fmt.Errorf("icon is %s; github takes png, jpeg, or gif", contentType)
}
dataURL := "data:" + contentType + ";base64," + base64.StdEncoding.EncodeToString(icon)
return template.URL(dataURL), "logo." + ext[contentType], nil
}

// ServeHTTP implements http.Handler.
Expand Down Expand Up @@ -216,6 +255,8 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
WebhookURL: webhookURL,
NeedsWebhook: h.config.WebhookURL == "",
DefaultAppName: defaultAppName,
IconURL: h.iconURL,
IconFile: h.iconFile,
}

var buf bytes.Buffer
Expand Down Expand Up @@ -385,6 +426,7 @@ func (h *Handler) successDataFromCreds(creds *configstore.AppCredentials) succes
DisableActionURL: disableSetupPath,
}
data.InstallURL = h.installURLFor(creds.AppSlug, creds.HTMLURL)
h.addIcon(&data)
return data
}

Expand All @@ -401,9 +443,33 @@ func (h *Handler) successDataFromStatus(status *configstore.InstallerStatus) suc
DisableActionURL: disableSetupPath,
}
data.InstallURL = h.installURLFor(status.AppSlug, status.HTMLURL)
h.addIcon(&data)
return data
}

// addIcon adds the logo, and the settings page to upload it on, when both
// are known.
func (h *Handler) addIcon(data *successTemplateData) {
settingsURL := h.settingsURLFor(data.AppSlug)
if h.iconURL == "" || settingsURL == "" {
return
}
data.IconURL, data.IconFile, data.SettingsURL = h.iconURL, h.iconFile, settingsURL
}

// settingsURLFor returns the settings page of the app with the given slug,
// where its logo is uploaded.
func (h *Handler) settingsURLFor(slug string) string {
if slug == "" {
return ""
}
if h.config.GitHubOrg != "" {
return fmt.Sprintf("%s/organizations/%s/settings/apps/%s",
h.config.GitHubURL, url.PathEscape(h.config.GitHubOrg), url.PathEscape(slug))
}
return fmt.Sprintf("%s/settings/apps/%s", h.config.GitHubURL, url.PathEscape(slug))
}

func (h *Handler) installURLFor(slug, htmlURL string) string {
if slug != "" {
githubURL := h.config.GitHubURL
Expand Down
130 changes: 130 additions & 0 deletions installer/installer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,136 @@ func TestNew_Validation(t *testing.T) {
})
}

// imageOf returns size bytes that start with header, which is all content
// sniffing reads.
func imageOf(header string, size int) []byte {
b := make([]byte, size)
copy(b, header)
return b
}

func TestNew_Icon(t *testing.T) {
tests := []struct {
name string
icon []byte
wantFile string
wantErr string
}{
{"png", imageOf("\x89PNG\r\n\x1a\n", 64), "logo.png", ""},
{"jpeg", imageOf("\xff\xd8\xff", 64), "logo.jpg", ""},
{"gif", imageOf("GIF89a", 64), "logo.gif", ""},
{"1 MB png", imageOf("\x89PNG\r\n\x1a\n", 1<<20), "logo.png", ""},
{"too big", imageOf("\x89PNG\r\n\x1a\n", 1<<20+1), "", "github takes at most"},
{"not an image", []byte("<svg xmlns='http://www.w3.org/2000/svg'/>"), "", "github takes png, jpeg, or gif"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h, err := New(Config{Store: &mockStore{}, Icon: tt.icon})
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("New() error = %v, want %q", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("New() error = %v", err)
}
if h.iconFile != tt.wantFile {
t.Errorf("iconFile = %q, want %q", h.iconFile, tt.wantFile)
}
})
}
}

func TestHandler_Icon(t *testing.T) {
png := imageOf("\x89PNG\r\n\x1a\n", 64)
registered := func(slug string) *mockStore {
return &mockStore{
statusFunc: func(ctx context.Context) (*configstore.InstallerStatus, error) {
return &configstore.InstallerStatus{Registered: true, AppID: 1, AppSlug: slug}, nil
},
}
}

tests := []struct {
name string
store *mockStore
org string
icon []byte
want []string
notWant []string
}{
{
name: "setup page shows the logo",
store: &mockStore{},
icon: png,
want: []string{`src="data:image/png;base64,`, `download="logo.png"`},
},
{
name: "setup page without an icon",
store: &mockStore{},
notWant: []string{"data:image"},
},
{
name: "org app links its settings",
store: registered("my-app"),
org: "my-org",
icon: png,
want: []string{"Add the Logo", `href="https://github.com/organizations/my-org/settings/apps/my-app"`, `download="logo.png"`},
},
{
name: "personal app links its settings",
store: registered("my-app"),
icon: png,
want: []string{`href="https://github.com/settings/apps/my-app"`},
},
{
name: "settings link escapes the org",
store: registered("my-app"),
org: "../evil",
icon: png,
want: []string{"/organizations/..%2fevil/settings/apps/my-app"},
},
{
name: "no logo step without a slug",
store: registered(""),
icon: png,
notWant: []string{"Add the Logo"},
},
{
name: "no logo step without an icon",
store: registered("my-app"),
notWant: []string{"Add the Logo", "data:image"},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h, err := New(Config{Store: tt.store, GitHubOrg: tt.org, Icon: tt.icon})
if err != nil {
t.Fatalf("New() error = %v", err)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/setup", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
body := strings.ToLower(rec.Body.String())
for _, w := range tt.want {
if !strings.Contains(body, strings.ToLower(w)) {
t.Errorf("page does not contain %q", w)
}
}
for _, w := range tt.notWant {
if strings.Contains(body, strings.ToLower(w)) {
t.Errorf("page contains %q", w)
}
}
})
}
}

func TestHandler_ServeHTTP_Routing(t *testing.T) {
store := &mockStore{
statusFunc: func(ctx context.Context) (*configstore.InstallerStatus, error) {
Expand Down
30 changes: 30 additions & 0 deletions installer/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,29 @@
font-size: 14px;
color: #6e5b00;
}
.logo {
display: flex;
gap: 12px;
align-items: center;
background: #f6f8fa;
border: 1px solid #d0d7de;
border-radius: 6px;
padding: 12px;
margin-bottom: 16px;
font-size: 14px;
}
.logo img {
width: 64px;
height: 64px;
border-radius: 8px;
flex: none;
}
.logo p {
margin: 0;
}
.logo a {
color: #0969da;
}
</style>
</head>
<body>
Expand All @@ -104,6 +127,13 @@ <h1>{{.AppDisplayName}} Installer</h1>
</div>
{{end}}

{{if .IconURL}}
<div class="logo">
<img src="{{.IconURL}}" alt="{{.AppDisplayName}} logo" width="64" height="64">
<p>GitHub can't set an app's logo from the manifest. Once the app is created, the next page says where to upload this one. <a href="{{.IconURL}}" download="{{.IconFile}}">Download the logo</a></p>
</div>
{{end}}

<form id="manifest-form" action="{{.FormActionURL}}" method="post">
<div class="form-group">
<label for="app_name">App Name</label>
Expand Down
25 changes: 25 additions & 0 deletions installer/templates/success.html
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,21 @@
color: #24292f;
font-size: 14px;
}
.logo {
display: flex;
gap: 12px;
align-items: center;
font-size: 14px;
}
.logo img {
width: 64px;
height: 64px;
border-radius: 8px;
flex: none;
}
.logo p {
margin: 0;
}
</style>
</head>
<body>
Expand All @@ -145,6 +160,16 @@ <h3>Next Step: Install the App</h3>
</div>
{{end}}

{{if .IconURL}}
<div class="next-step">
<h3>Add the Logo</h3>
<div class="logo">
<img src="{{.IconURL}}" alt="{{.AppDisplayName}} logo" width="64" height="64">
<p>GitHub can't set an app's logo from the manifest, so add it by hand: <a href="{{.IconURL}}" download="{{.IconFile}}">download the logo</a>, open the <a href="{{.SettingsURL}}" target="_blank" rel="noopener">app's settings</a>, and under <strong>Display information</strong>, click <strong>Upload a logo</strong>.</p>
</div>
</div>
{{end}}

{{if .DisableActionURL}}
<div class="disable-panel">
<h3>Disable Web Installer</h3>
Expand Down