package api import ( "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "html" "log/slog" "net/http" "net/url" "regexp" "strconv" "strings" "time" "github.com/GLINCKER/levelrail/internal/githubapp" "github.com/GLINCKER/levelrail/internal/store" ) // normalizeGitHubInstanceURL validates and normalizes the optional // instance_url query parameter every GitHub App registration entry // point (register/start, register/preview) accepts: "" defaults to // github.com itself, matching every existing connection's own default // (migrations/0061). A non-empty value must be a real https URL with no // path/query/fragment, and is returned with any trailing slash trimmed // so it composes cleanly with the fixed paths BuildManifest and // APIBaseURL append. func normalizeGitHubInstanceURL(raw string) (string, error) { raw = strings.TrimSpace(raw) if raw == "" { return "https://github.com", nil } raw = strings.TrimRight(raw, "/") u, err := url.Parse(raw) if err != nil || u.Scheme != "https" || u.Host == "" || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { return "", fmt.Errorf("instance_url must be a bare https URL like https://ghe.example.com") } return raw, nil } // githubOrgLoginPattern is GitHub's own org login shape (alphanumerics // and hyphens, 1 to 39 characters, no leading hyphen). var githubOrgLoginPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$`) // normalizeGitHubAppOwner validates the optional owner query parameter: // "" means the operator's personal account, anything else must be an org // login, since it is interpolated into a URL path on the GitHub host. func normalizeGitHubAppOwner(raw string) (string, error) { raw = strings.TrimSpace(raw) if raw == "" { return "", nil } if !githubOrgLoginPattern.MatchString(raw) { return "", fmt.Errorf("owner must be a github organization login (letters, digits and hyphens, up to 39 characters)") } return raw, nil } // parseGitHubAppPublic reads the optional public query parameter, // defaulting to false (a private App) when absent or empty. func parseGitHubAppPublic(raw string) (bool, error) { raw = strings.TrimSpace(raw) if raw == "" { return false, nil } v, err := strconv.ParseBool(raw) if err != nil { return false, fmt.Errorf("public must be true or false") } return v, nil } // githubAppRegistrationTarget parses and validates the owner and public // query parameters shared by register/start and register/preview. func githubAppRegistrationTarget(r *http.Request) (owner string, public bool, err error) { q := r.URL.Query() if owner, err = normalizeGitHubAppOwner(q.Get("owner")); err != nil { return "", false, err } if public, err = parseGitHubAppPublic(q.Get("public")); err != nil { return "", false, err } return owner, public, nil } // githubAppManifestActionURL is where the manifest form posts: the // org-scoped create page when owner is set, the personal one otherwise. func githubAppManifestActionURL(instanceURL, owner, state string) string { base := instanceURL + "/settings/apps/new" if owner != "" { base = instanceURL + "/organizations/" + url.PathEscape(owner) + "/settings/apps/new" } return base + "?state=" + url.QueryEscape(state) } // handleStartGitHubAppRegistration handles // GET /api/v1/github-app/register/start: the entry point for GitHub's // manifest flow. Unlike every other handler in this package, this one's // response body is not JSON: GitHub's manifest flow requires an actual // browser form POST to https://github.com/settings/apps/new, submitted // by the browser itself, not a server-to-server call this handler could // make instead (https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest). // So this handler renders a minimal, self-submitting HTML page and the // frontend is expected to navigate the browser here as a real, // full-page GET (window.location.href, not fetch), the same way it must // navigate to GitHub's own confirmation page and back. // // Preconditions checked before anything else: a master key must be // configured (rt.githubAppSecrets != nil, since the very next step // needs somewhere to store the App's credentials), no App may already // be connected (re-registering over an existing connection would orphan // the old App on GitHub's side with nothing here still pointing at it), // and a primary domain must be configured (controlPlaneBaseURL's own // requirement: GitHub needs a real, reachable callback URL). func (rt *Router) handleStartGitHubAppRegistration(w http.ResponseWriter, r *http.Request) { if rt.githubAppSecrets == nil { writeError(w, http.StatusNotImplemented, "the github app connection requires a master key to be configured on this control plane") return } ctx := r.Context() if _, err := rt.githubApp.GetGitHubAppConnection(ctx); err == nil { writeError(w, http.StatusConflict, "a github app is already connected; disconnect it first before registering a new one") return } else if !errors.Is(err, store.ErrGitHubAppConnectionNotFound) { rt.internalError(w, "api: check existing github app connection failed", err) return } baseURL, err := rt.controlPlaneBaseURL(ctx) if err != nil { if errors.Is(err, errNoPrimaryDomain) { writeError(w, http.StatusConflict, "set a primary domain in ingress settings before connecting a github app: github needs a real, reachable callback url") return } rt.internalError(w, "api: get ingress settings for github app registration failed", err) return } instanceURL, err := normalizeGitHubInstanceURL(r.URL.Query().Get("instance_url")) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } if instanceURL != "https://github.com" { if err := rt.githubAppClient.CheckInstanceReachable(ctx, instanceURL); err != nil { writeError(w, http.StatusBadGateway, "could not reach "+instanceURL+": "+err.Error()) return } } owner, public, err := githubAppRegistrationTarget(r) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } state, err := rt.githubAppState.begin(instanceURL) if err != nil { rt.internalError(w, "api: begin github app registration failed", err) return } appName := strings.TrimSpace(r.URL.Query().Get("name")) if appName == "" { appName = githubapp.AppDisplayName(rt.brand.Name, strings.TrimPrefix(baseURL, "https://")) } manifest := githubapp.BuildManifest(appName, baseURL, rt.githubAppManifestConfig) manifest.Public = public manifestJSON, err := json.Marshal(manifest) if err != nil { rt.internalError(w, "api: marshal github app manifest failed", err) return } nonce, err := randomNonce() if err != nil { rt.internalError(w, "api: generate csp nonce for github app manifest form failed", err) return } writeGitHubAppManifestForm(w, instanceURL, owner, state, nonce, manifestJSON) } // githubAppManifestPreviewResource is the wire shape for // GET /api/v1/github-app/register/preview: every field the manifest // form (writeGitHubAppManifestForm) is about to send GitHub, rendered // ahead of the redirect so an operator can see (and rename) the App // before their browser leaves this page. Built from the exact same // githubapp.BuildManifest call handleStartGitHubAppRegistration itself // uses, so preview and the real POST can never drift apart into two // sources of truth. type githubAppManifestPreviewResource struct { InstanceURL string `json:"instance_url"` Owner string `json:"owner"` AppName string `json:"app_name"` HomepageURL string `json:"homepage_url"` CallbackURL string `json:"callback_url"` SetupURL string `json:"setup_url"` WebhookURL string `json:"webhook_url"` WebhookActive bool `json:"webhook_active"` Permissions map[string]string `json:"permissions"` Events []string `json:"events"` Public bool `json:"public"` RequestOAuthOnInstall bool `json:"request_oauth_on_install"` } // handleGetGitHubAppManifestPreview handles // GET /api/v1/github-app/register/preview. Read-only: unlike // handleStartGitHubAppRegistration, this never calls rt.githubAppState.begin, // so opening (and closing without confirming) the preview dialog this // feeds never mints or invalidates a pending CSRF state value. Same // preconditions as the real registration start (master key configured, // no App already connected, primary domain set) since there is nothing // meaningful to preview otherwise, and the frontend dialog that calls // this is only ever shown from the same "Add GitHub App" action that // leads to register/start. func (rt *Router) handleGetGitHubAppManifestPreview(w http.ResponseWriter, r *http.Request) { if rt.githubAppSecrets == nil { writeError(w, http.StatusNotImplemented, "the github app connection requires a master key to be configured on this control plane") return } ctx := r.Context() if _, err := rt.githubApp.GetGitHubAppConnection(ctx); err == nil { writeError(w, http.StatusConflict, "a github app is already connected; disconnect it first before registering a new one") return } else if !errors.Is(err, store.ErrGitHubAppConnectionNotFound) { rt.internalError(w, "api: check existing github app connection failed", err) return } baseURL, err := rt.controlPlaneBaseURL(ctx) if err != nil { if errors.Is(err, errNoPrimaryDomain) { writeError(w, http.StatusConflict, "set a primary domain in ingress settings before connecting a github app: github needs a real, reachable callback url") return } rt.internalError(w, "api: get ingress settings for github app manifest preview failed", err) return } instanceURL, err := normalizeGitHubInstanceURL(r.URL.Query().Get("instance_url")) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } owner, public, err := githubAppRegistrationTarget(r) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } appName := githubapp.AppDisplayName(rt.brand.Name, strings.TrimPrefix(baseURL, "https://")) manifest := githubapp.BuildManifest(appName, baseURL, rt.githubAppManifestConfig) manifest.Public = public writeJSON(w, http.StatusOK, githubAppManifestPreviewResource{ InstanceURL: instanceURL, Owner: owner, AppName: manifest.Name, HomepageURL: manifest.URL, CallbackURL: manifest.RedirectURL, SetupURL: manifest.SetupURL, WebhookURL: manifest.HookAttributes.URL, WebhookActive: manifest.HookAttributes.Active, Permissions: manifest.DefaultPermissions, Events: manifest.DefaultEvents, Public: manifest.Public, RequestOAuthOnInstall: manifest.RequestOAuthOnInstall, }) } // randomNonce generates a CSP script-src nonce, same crypto/rand + // base64 shape as randomToken (auth.go). func randomNonce() (string, error) { buf := make([]byte, 16) if _, err := rand.Read(buf); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(buf), nil } // writeGitHubAppManifestForm renders the auto-submitting form GitHub's // manifest flow expects, posted to /settings/apps/new, or // /organizations//settings/apps/new for an org. // Overrides the global CSP for this response only: script-src 'self' // and form-action 'self' silently block this page's inline auto-submit // and its cross-origin POST (confirmed live: hangs forever, no visible // error). nonce permits only this one script; form-action widens only // to instanceURL's own already-validated origin. func writeGitHubAppManifestForm(w http.ResponseWriter, instanceURL, owner, state, nonce string, manifestJSON []byte) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Security-Policy", fmt.Sprintf( "default-src 'self'; script-src 'nonce-%s'; style-src 'self'; form-action %s; base-uri 'self'; object-src 'none'; frame-ancestors 'none'", nonce, instanceURL)) w.WriteHeader(http.StatusOK) actionURL := githubAppManifestActionURL(instanceURL, owner, state) _, err := fmt.Fprintf(w, ` Connecting GitHub App

Redirecting to GitHub to finish creating the App...

`, html.EscapeString(actionURL), html.EscapeString(string(manifestJSON)), nonce) if err != nil { // The status line and headers are already flushed by this point // (w.WriteHeader above), so there is nothing left to do but log; // the browser just gets a truncated page. Same "log, don't // propagate" shape writeJSON's own encode-failure branch already // establishes for the identical situation. slog.Default().Error("api: write github app manifest form failed", slog.String("error", err.Error())) } } // handleGitHubAppCallback handles GET /api/v1/github-app/callback: the // redirect_url GitHub sends the operator's browser back to once they // confirm App creation on GitHub's own manifest review page, carrying // ?code=...&state=.... This is the one moment the App's real // credentials (client_secret, webhook_secret, the PEM private key) // exist in plaintext outside GitHub; they are encrypted through // rt.githubAppSecrets before anything else touches them, and this // handler's own error paths never log a credential value, the code // parameter, or the raw exchange response body: only // err.Error() (internal/githubapp.Client wraps a truncated, // non-credential-bearing GitHub error body on failure; the success path // never gets logged at all beyond the generic flow completing). // // code and state are validated present before use; state is further // checked against the single pending value handleStartGitHubAppRegistration // generated (pendingState.consume), rejecting a missing, // unknown, expired, or already-used state with a 400, never a panic. func (rt *Router) handleGitHubAppCallback(w http.ResponseWriter, r *http.Request) { rt.invalidateGitRepoCache(r.Context(), gitProviderGitHub) if rt.githubAppSecrets == nil { writeError(w, http.StatusNotImplemented, "the github app connection requires a master key to be configured on this control plane") return } q := r.URL.Query() code := strings.TrimSpace(q.Get("code")) state := strings.TrimSpace(q.Get("state")) if code == "" { writeError(w, http.StatusBadRequest, "missing code parameter") return } if state == "" { writeError(w, http.StatusBadRequest, "missing state parameter") return } instanceURL, ok := rt.githubAppState.consume(state) if !ok { writeError(w, http.StatusBadRequest, "state parameter is invalid, expired, or already used") return } ctx := r.Context() creds, err := rt.githubAppClient.ExchangeManifestCode(ctx, instanceURL, code) if err != nil { rt.logger.Error("api: exchange github app manifest code failed", slog.String("error", err.Error())) writeError(w, http.StatusBadGateway, "failed to exchange the manifest code with github") return } secretsKey := store.GitHubAppSecretsKey() if err := rt.githubAppSecrets.SetValue(ctx, secretsKey, "client_secret", creds.ClientSecret); err != nil { rt.internalError(w, "api: store github app client_secret failed", err) return } if err := rt.githubAppSecrets.SetValue(ctx, secretsKey, "webhook_secret", creds.WebhookSecret); err != nil { rt.internalError(w, "api: store github app webhook_secret failed", err) return } if err := rt.githubAppSecrets.SetValue(ctx, secretsKey, "private_key", creds.PrivateKeyPEM); err != nil { rt.internalError(w, "api: store github app private_key failed", err) return } if err := rt.githubApp.SaveGitHubAppConnection(ctx, store.GitHubAppConnection{ AppID: creds.AppID, ClientID: creds.ClientID, Slug: &creds.Slug, InstanceURL: instanceURL, CreatedAt: time.Now().UTC().Format(time.RFC3339), }); err != nil { rt.internalError(w, "api: save github app connection failed", err) return } // Sends the operator straight into GitHub's own "choose repositories // to install on" page for the App they just created: the natural // next step in this onboarding, so they don't have to go find it // themselves. GitHub redirects back to setup_url (this control // plane's own /api/v1/github-app/installed, handleGitHubAppInstalled // below) once they finish that step. installURL := instanceURL + "/apps/" + url.PathEscape(creds.Slug) + "/installations/new" http.Redirect(w, r, installURL, http.StatusFound) } // handleGitHubAppInstalled handles GET /api/v1/github-app/installed: // the setup_url GitHub's manifest declared // (githubapp.BuildManifest), which GitHub redirects the operator's // browser to after they pick an account/org and repositories to install // the App on, carrying ?installation_id=...&setup_action=.... // // installation_id is validated present and parses as a positive // integer before use, a clean 400 on failure rather than a panic. Once // parsed, this handler does not simply trust it: it signs a fresh // App-level JWT (githubapp.SignAppJWT, using the App's own stored // private key, decrypted in memory only) and calls GitHub's // GET /app/installations/{id} to look the installation up for real, // then checks the returned InstallationInfo.AppID against this // connection's own stored AppID before recording anything. Without that // check, a crafted or stale installation_id belonging to a completely // different GitHub App could get recorded as if it belonged to this // one; GitHub's redirect itself carries no signature over // installation_id that would rule that out on its own. func (rt *Router) handleGitHubAppInstalled(w http.ResponseWriter, r *http.Request) { rt.invalidateGitRepoCache(r.Context(), gitProviderGitHub) if rt.githubAppSecrets == nil { writeError(w, http.StatusNotImplemented, "the github app connection requires a master key to be configured on this control plane") return } raw := strings.TrimSpace(r.URL.Query().Get("installation_id")) if raw == "" { writeError(w, http.StatusBadRequest, "missing installation_id parameter") return } installationID, err := strconv.ParseInt(raw, 10, 64) if err != nil || installationID <= 0 { writeError(w, http.StatusBadRequest, "installation_id must be a positive integer") return } ctx := r.Context() conn, err := rt.githubApp.GetGitHubAppConnection(ctx) if errors.Is(err, store.ErrGitHubAppConnectionNotFound) { writeError(w, http.StatusConflict, "no github app is registered on this control plane yet") return } if err != nil { rt.internalError(w, "api: get github app connection for installation callback failed", err) return } privateKeyPEM, err := rt.githubAppSecrets.Resolve(ctx, store.GitHubAppSecretsKey(), "private_key") if err != nil { rt.internalError(w, "api: resolve github app private key for installation callback failed", err) return } appJWT, err := githubapp.SignAppJWT(conn.AppID, []byte(privateKeyPEM), time.Now()) if err != nil { rt.internalError(w, "api: sign github app jwt for installation callback failed", err) return } info, err := rt.githubAppClient.GetInstallation(ctx, conn.InstanceURL, appJWT, installationID) if err != nil { // A real, reachable failure mode, not just a hypothetical: an // org that requires admin approval to install an App sends this // same redirect for a still-pending request, and the // installation doesn't exist as a real, readable installation // yet. Reported as a clean 502 either way; this can't be // distinguished from any other GitHub API failure here. rt.logger.Error("api: get github app installation failed", slog.String("error", err.Error()), slog.Int64("installation_id", installationID)) writeError(w, http.StatusBadGateway, "failed to look up the installation with github; it may still be pending approval") return } if info.AppID != conn.AppID { rt.logger.Warn("api: github app installation callback reported an installation for a different app", slog.Int64("installation_id", installationID), slog.Int64("reported_app_id", info.AppID), slog.Int64("expected_app_id", conn.AppID)) writeError(w, http.StatusBadRequest, "this installation does not belong to this control plane's github app") return } // Kept for anything still reading the legacy single-installation // columns; UpsertGitHubAppInstallation below is the real multi-org // record and is what repo listing and the installations UI read. if err := rt.githubApp.UpdateGitHubAppInstallation(ctx, installationID, info.AccountLogin); err != nil { rt.internalError(w, "api: record github app installation failed", err) return } // GitHub's own API always sends "User" or "Organization" (lowercased // by githubapp.GetInstallation), but github_app_installations.account_type // has a NOT NULL CHECK constraint that an unexpected empty value would // violate as a 500, not a client-side bug: default rather than trust // an upstream API's response shape to never change. accountType := info.AccountType if accountType != "user" && accountType != "organization" { accountType = "organization" } if err := rt.githubApp.UpsertGitHubAppInstallation(ctx, installationID, info.AccountLogin, accountType); err != nil { rt.internalError(w, "api: upsert github app installation failed", err) return } baseURL, err := rt.controlPlaneBaseURL(ctx) if err != nil { // PrimaryDomain being unset here would be surprising // (registration itself required it to start), but this handler // doesn't assume that's impossible: a plain JSON success body is // a safe fallback over a redirect built from an empty base URL. writeJSON(w, http.StatusOK, map[string]string{"status": "installed"}) return } http.Redirect(w, r, baseURL+"/settings/github-app?github_app=installed", http.StatusFound) }