Skip to content

Latest commit

 

History

History
434 lines (305 loc) · 27.6 KB

github-app-setup.md

File metadata and controls

434 lines (305 loc) · 27.6 KB

GitHub App Setup

Table of Contents

This guide walks through creating a GitHub App, configuring SchemaBot to receive webhooks, and adding the schemabot.yaml config to your repositories.

If you already ran schemabot init, you can try the PR workflow from your laptop before deploying anything. Start with Before You Start, then follow the steps in order; each one says what changes for a laptop.

Before You Start

  1. Put your schema directory on GitHub. SchemaBot reads schemabot.yaml and the schema files from the PR branch, so the directory init wrote (schema/ by default) must be in a GitHub repository you can install an App on.
  2. Get a webhook URL. GitHub delivers PR comments to SchemaBot's POST /webhook endpoint.
    • On a laptop, use smee.io, which GitHub recommends for webhook development. Open https://smee.io, click Start a new channel, and keep the channel URL for step 1. Then forward the channel to SchemaBot, and leave this running:
      npx smee-client --url https://smee.io/your-channel --target http://localhost:8080/webhook
    • On a deployed server, use its public URL, https://your-domain.com/webhook. See Webhook Ingress.

Create the App from the CLI

schemabot github create-app creates the App described in steps 1 to 4, with the same permissions and events, and installs it. In your browser you click Continue with GitHub, then Create GitHub App, then pick the repositories and click Install. There are no keys to download or copy. The command confirms the install with GitHub and prints where SchemaBot is installed. Press Ctrl-C to skip the install and do it later; the credentials are already saved by then.

schemabot github create-app --org acme-corp --webhook-url https://schemabot.acme.example/webhook
  • --org creates the App under an organization. Without it, the App belongs to your personal account.
  • --name sets the App's name, which must be unique on GitHub. The default is schemabot-<org>, or schemabot-<your username>.
  • --webhook-url is where GitHub sends events. Without it, set the URL later under Webhook in the App's settings. Until then, GitHub records each delivery as failed.
  • --no-browser prints the setup URL instead of opening a browser. The URL is on 127.0.0.1, so open it on the same machine.
  • --schema-dir is where schemabot init wrote your schema files (default schema). See the test repository below.

To try SchemaBot on a repository of its own, tick Also create a private test repository before you click Continue with GitHub. After GitHub creates the App, the command creates a private schemabot-test repository under the same owner, with your schema files under schema/, and the Install screen opens with that repository selected. The option needs the schema files from schemabot init and the GitHub CLI signed in with gh auth login; without them, the page says which is missing. The App gets no extra permissions for this: the repository is created with your own gh sign-in.

The credentials are saved in ~/.schemabot/credentials/github-app-<slug>/, in files only you can read:

File Holds
private-key.pem The App's private key
webhook-secret The secret GitHub signs deliveries with
client-secret The App's OAuth client secret
app.json The App's ID, slug, owner, and URL. No secrets

When this is the only App saved there, schemabot serve uses it on its own as long as the server config sets no app-id, private-key or webhook-secret. Write the server config as 4. Configure SchemaBot shows, leaving out only those three settings, then continue at 5. Start SchemaBot. Settings such as check-name still apply. The command also prints a github: block that points at these files, for a config that names the App itself.

The command never replaces saved credentials: if a directory for the slug already exists, it saves the new App's under github-app-<slug>-2. With more than one App saved, schemabot serve refuses to choose one, so add the printed github: block to the server config. To run a server without GitHub on a machine with saved Apps, set app-id: "0" in its github: section. If you lose a file, generate a new private key or webhook secret in the App's settings. The App and its installs stay.

Steps 1 to 4 below create and configure the same App by hand.

1. Create a GitHub App

Go to Settings > Developer settings > GitHub Apps > New GitHub App (direct link).

Basic Information

Field Value
GitHub App name SchemaBot (or your preferred name)
Homepage URL Your SchemaBot deployment URL, or the repository URL when trying it from a laptop
Description Declarative schema change orchestration via PR comments

Webhook

Field Value
Active Checked
Webhook URL Your smee channel URL on a laptop, or https://your-domain.com/webhook
Webhook secret Generate a random secret (save it for later)

Generate a webhook secret:

openssl rand -hex 32

Permissions

Under Repository permissions, grant:

Permission Access Used For
Administration Read Optional. Needed only with skip_unrequired_branches on: read classic branch protection, so SchemaBot skips PRs into non-default branches that do not require its check. Without it, SchemaBot plans and checks PRs into every branch
Checks Read & Write Create SchemaBot check runs and read GitHub check runs for the require_passing_checks gate
Commit statuses Read Read legacy commit statuses for the require_passing_checks gate
Contents Read Read schemabot.yaml, schema files, CODEOWNERS, and commit refs
Issues Read & Write Post PR comments and add reactions
Merge queues Read Receive merge_group events so SchemaBot can publish its checks on merge-queue commits (only needed if a repo uses a merge queue)
Metadata Read Required (granted automatically)
Pull requests Read & Write Fetch PR info, changed files, and reviews

Under Organization permissions, grant:

Permission Access Used For
Members Read Verify GitHub team membership for review policies, CODEOWNERS review gates, and PR command authorization

Subscribe to Events

Event Purpose
Check run Receive check_run.rerequested so a human clicking Re-run on a SchemaBot check re-plans the PR head
Check suite Receive check_suite.rerequested when someone clicks Re-run all checks, which re-plans every open PR at that commit. Also receive check_suite.requested as a redundant auto-plan convergence signal: when the organic pull_request delivery for a push is lost upstream, SchemaBot recovers the missing auto-plan from the check suite instead of waiting for the next reconciler scan
Issue comment Receive schemabot plan, schemabot help, etc. from PR comments
Merge group Publish a passing SchemaBot check on a merge-queue commit so a required SchemaBot check does not block the merge queue (only needed if a repo uses a merge queue)
Pull request Auto-plan each affected database on PR open/synchronize/reopen and clean up locks and stored check state on close
Push Publish a passing SchemaBot check on default-branch commits so branch rulesets can select the App as a pinned required-check source (rulesets only index Apps whose check suites ran against the target branch)

Subscribe to Merge group, not Merge queue entry — the two are distinct events, and SchemaBot handles only merge_group. The Merge group event requires the Merge queues: Read repository permission above. Because that is a new permission, adding it to an existing App marks the App as requesting new permissions, which an org or repository admin must approve on each installation before it takes effect.

The Push event needs no new permission — Contents: Read above already unlocks it — so subscribing an existing App takes effect immediately on every installation, with no admin re-approval. Expect webhook delivery volume to rise once subscribed: GitHub sends a push event for every branch and tag push on installed repositories, and SchemaBot discards everything but default-branch pushes.

The Check suite event likewise needs no new permission — Checks: Read & Write above already unlocks it — so subscribing takes effect immediately. It also raises delivery volume (GitHub sends check_suite.requested for every push to every branch), and SchemaBot acknowledges and drops every suite that has no open PR at its head. Without this subscription, Re-run all checks does nothing on SchemaBot checks, and the recovery feature receives no deliveries and is silently inert: lost auto-plans then wait for the reconciler's next scan instead of converging within the recovery grace.

Where Can This GitHub App Be Installed?

Choose Only on this account for private use, or Any account if you plan to share the app.

Create the App

Click Create GitHub App. Note the App ID shown on the next page.

2. Generate a Private Key

On the app settings page, scroll to Private keys and click Generate a private key.

A .pem file will be downloaded. Store it securely — this is your app's authentication credential.

3. Install the App

Go to your app's settings page, click Install App in the sidebar, and install it on your organization or account.

You can restrict it to specific repositories or grant access to all repositories.

4. Configure SchemaBot

If schemabot github create-app created the App and it is the only App saved in ~/.schemabot/credentials, leave out app-id, private-key and webhook-secret below: schemabot serve finds the App there. The server still needs the rest of its config, such as storage, the databases, and check-name if you set one.

If you ran schemabot init, it already wrote a full server config, with storage and your database, at ~/.schemabot/runtimes/<name>/runtime.yaml (ls ~/.schemabot/runtimes/ shows the name). Copy it, and fill in its empty github: block:

cp ~/.schemabot/runtimes/<name>/runtime.yaml ~/schemabot-server.yaml
github:
  app-id: "123456"                                # From step 1
  private-key: "file:/path/to/private-key.pem"    # From step 2
  webhook-secret: "env:GITHUB_WEBHOOK_SECRET"      # From step 1

Leave the rest as init wrote it. That config names one environment: the one you gave init, which is development unless you chose another. The PR commands below use it where the examples say -e staging.

That config also leaves API authentication off, and schemabot serve listens on every network interface, so anyone who can reach port 8080 can read and change your database. The webhook secret protects only /webhook. Run it only where other machines cannot reach that port, such as behind a firewall that blocks incoming connections, or set up authentication first (see Run locally).

Otherwise, add the github: section to your SchemaBot server config (config.yaml):

storage:
  dsn: "env:SCHEMABOT_DSN"

github:
  app-id: "123456"                                 # From step 1
  private-key: "file:/path/to/private-key.pem"     # PEM file
  webhook-secret: "env:GITHUB_WEBHOOK_SECRET"      # From step 1
  check-name: "SchemaBot X"                      # Optional Check Run base name

databases:
  mydb:
    type: mysql
    environments:
      staging:
        dsn: "env:STAGING_DSN"
      production:
        dsn: "env:PRODUCTION_DSN"

The private-key and webhook-secret fields support secret references — the same format used for DSNs:

Format Example
Direct value "my-secret"
Environment variable "env:GITHUB_WEBHOOK_SECRET"
File "file:/run/secrets/github-key.pem"
AWS Secrets Manager "secretsmanager:my-app/github#private-key"

For AWS deployments, see deploy/aws/ which stores credentials in Secrets Manager.

5. Start SchemaBot

Point SCHEMABOT_CONFIG_FILE at the config from step 4: the copy of init's config, or your own config.yaml:

SCHEMABOT_CONFIG_FILE=~/schemabot-server.yaml schemabot serve   # or SCHEMABOT_CONFIG_FILE=/path/to/config.yaml

You should see:

{"level":"INFO","msg":"GitHub webhook endpoint registered"}
{"level":"INFO","msg":"starting server","port":"8080"}

If the log says GitHub App not configured — webhook endpoint disabled instead, the github: block is still empty. On a laptop, keep this running alongside the smee client from Before You Start.

6. Add schemabot.yaml Config to Your Repository

If you ran schemabot init, it already wrote this directory, and Before You Start put it on GitHub. Skip to step 7.

You don't have to write the schema directory by hand. Once the database is registered in the server config (step 4), schemabot onboard -d mydb -e staging -s ./schema pulls the live schema and generates the whole directory — schemabot.yaml, a subdirectory per namespace (the schema name on MySQL, the keyspace on Vitess), and one .sql file per table — then verifies the result plans clean against the source environment. Use --dry-run to preview the files first. Onboard always generates the namespace-subdirectory layout shown under Schema File Layout below; the flat MySQL layout there is a hand-maintained alternative.

Create (or let schemabot onboard create) a schemabot.yaml file in the directory containing your schema SQL files:

my-repo/
  schema/
    schemabot.yaml      <-- config file
    users.sql
    orders.sql
    products.sql
database: mydb
type: mysql
Field Required Description
database Yes Must match a database name in your SchemaBot server config
type Yes "mysql", "vitess", "strata" (experimental; requires server opt-in — see Strata), or "postgres"
ignore_namespaces No Namespace subdirectories to exclude from plans, applies, and checks (see Ignoring Namespaces)
ignore_tables No Live table names to withhold from the planner, so an undeclared table is neither created nor dropped. An entry wrapped in slashes, such as /^relay_[0-9]+_feed$/, is a regular expression matched against the whole name (see Ignoring Tables)
drop_tables No MySQL only. Exact names of live tables no schema file declares that the plan should drop, such as an online schema change's leftover _ table, which the planner otherwise skips. Each drop is an unsafe change, and the plan lists any entry that names no table (see Dropping Tables)

Environment availability and promotion order are configured on the SchemaBot server.

Schema File Layout

MySQL (schema-name subdirectory — what schemabot onboard generates):

schema/
  schemabot.yaml
  mydb/
    users.sql
    orders.sql

MySQL (flat structure, hand-maintained):

schema/
  schemabot.yaml
  users.sql
  orders.sql

Vitess (keyspace subdirectories):

schema/
  schemabot.yaml
  commerce/
    users.sql
    orders.sql
    vschema.json
  lookup/
    lookup_table.sql
    vschema.json

Each .sql file should contain a single CREATE TABLE statement using the canonical format that matches SHOW CREATE TABLE output:

CREATE TABLE `users` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

7. Test It

Open a PR that modifies a schema file, then comment:

schemabot plan -e staging

With the config schemabot init wrote, name the environment you gave init instead, such as schemabot plan -e development.

SchemaBot will:

  1. React with 👀 to acknowledge the command
  2. Fetch the schemabot.yaml config and schema files from the PR branch
  3. Diff the desired schema against the live database
  4. Post a comment with the DDL plan
  5. Create a GitHub Check Run showing the result

Other commands:

schemabot help                  # Show command reference
schemabot plan                  # Plan for all configured environments
schemabot plan -d mydb          # Plan for a specific database (multi-db repos)

First apply for a schema directory that is already merged

SchemaBot plans a database when the PR changes a file under its schema directory. A PR that changes nothing there gets a passing No schema files changed check, even when the database itself is still empty. That is the usual shape of a new database: the declarative schema files merge first, and the database is configured on the SchemaBot server afterwards, so no PR diff is left to trigger the plan.

Reconcile the drift with a nonce edit. Add or toggle a # nonce comment line in the database's schemabot.yaml and open the PR. The change is inert, but it sits in the schema directory, so SchemaBot plans the whole directory against the live schema and the plan shows every table to create, including the ones whose files the PR did not touch. Apply from the plan comment as usual:

schemabot apply -e staging

The same edit reconciles drift on any database, not only a new one. See Reconciling drift with a nonce edit.

Environment Variables Reference

Variable Required Default Description
SCHEMABOT_CONFIG_FILE One of these two — Path to server config YAML
SCHEMABOT_CONFIG One of these two — The server config YAML itself, for hosts that cannot mount a file
STORAGE_DSN No — Fallback storage DSN if storage.dsn is not set in config
GITHUB_APP_ID No — Fallback if github.app-id is not set in config
PORT No 8080 HTTP server port
GRPC_PORT No — gRPC server port; the gRPC listener starts only when this is set
LOG_LEVEL No info debug, info, warn, error

GitHub credentials (private-key, webhook-secret) are configured in the YAML config file using secret references, not environment variables. This keeps all configuration in one place and supports any secret backend.

Webhook Ingress

GitHub needs to reach SchemaBot's POST /webhook endpoint over the public internet. If your deployment already has a public URL (e.g., AWS App Runner, a VM with a public IP), set the GitHub App's Webhook URL directly:

https://your-schemabot-host/webhook

See deploy/aws/ for a complete example using App Runner.

If SchemaBot runs on Kubernetes, pods aren't publicly accessible by default. You'll need an ingress path — for example, an API Gateway or reverse proxy in front of an internal load balancer, or an ingress controller like nginx or Traefik with a route to /webhook.

For local development and PR testing, smee.io proxies GitHub webhooks to your machine, so you can test the full PR workflow without deploying anything. Before You Start sets it up. To test against an App that already serves a deployment, temporarily set its Webhook URL to the smee channel URL, and switch it back to your production endpoint when done.

IP Allowlisting

GitHub publishes its webhook source IPs at https://api.github.com/meta (the hooks field). Restricting your webhook endpoint to these CIDRs is recommended as defense-in-depth. SchemaBot validates every webhook signature via HMAC-SHA256 (see below), so IP allowlisting provides an additional layer of protection.

Webhook Signature Validation

SchemaBot validates the X-Hub-Signature-256 header on every webhook request using HMAC-SHA256 and the configured webhook-secret. Requests with invalid or missing signatures are rejected with HTTP 401.

The secret is required: schemabot serve refuses to start without one, and a webhook handler built without one refuses every delivery. See Authentication for the opt-in a test or local harness can use instead.

Rotating the webhook secret

GitHub signs each delivery with one secret, and changing it on GitHub takes effect immediately. To rotate without refusing deliveries, keep the old secret in the config as previous-webhook-secret while the change rolls out. SchemaBot accepts a delivery signed with either secret.

  1. Deploy the new secret as webhook-secret and the old one as previous-webhook-secret. SchemaBot reads secrets once at startup, so when the config points at a secretsmanager: or file: reference, changing the value behind it also needs a restart.
  2. Wait until every pod runs the new config, then change the webhook secret in the GitHub App settings to the new secret. A pod still on the old config refuses deliveries signed with the new secret, and a rolling deploy reaches pods at different times.
  3. Wait until deliveries have arrived since step 2 and none of them logged webhook delivery verified with the secret being rotated out, then remove previous-webhook-secret and deploy again. A quiet log on its own can also mean no deliveries arrived.
github:
  webhook-secret: "env:GITHUB_WEBHOOK_SECRET"                    # the new secret
  previous-webhook-secret: "env:GITHUB_PREVIOUS_WEBHOOK_SECRET"  # the old secret, removed after step 3

previous-repo-webhook-secret does the same for repo-webhook-secret. In multi-App mode, each entry under apps: accepts its own previous-webhook-secret; repository webhooks are not served in multi-App mode, so previous-repo-webhook-secret there fails startup. Startup also fails when a previous secret is set without the matching current secret, or when either resolves to an empty value, such as an unset environment variable.

Repository-level Webhooks (optional)

A single deployment can also accept deliveries from a repository-level webhook (a webhook configured directly on a repo, rather than on the GitHub App). This lets several SchemaBot deployments that share one GitHub App all receive the same repo's events. Set a separate secret for these deliveries:

github:
  webhook-secret: "env:GITHUB_WEBHOOK_SECRET"           # App-installed deliveries
  repo-webhook-secret: "env:GITHUB_REPO_WEBHOOK_SECRET" # repository-level deliveries

When repo-webhook-secret is set, deliveries whose X-GitHub-Hook-Installation-Target-Type header is repository are HMAC-verified against this secret. Such deliveries carry no installation id in their payload, so SchemaBot resolves the App's installation for the repo via the App JWT and caches it. Leave repo-webhook-secret unset to disable this path; App-installed deliveries are unaffected either way.

Follow the pre-merge workflow to take your first schema change through review, apply, and merge.

Troubleshooting

Webhook not receiving events: Check that the webhook URL is reachable from GitHub. Use the Recent Deliveries tab on your GitHub App's settings page to see delivery attempts and response codes.

401 Unauthorized on webhook: The webhook secret in your GitHub App settings doesn't match GITHUB_WEBHOOK_SECRET. Regenerate and update both.

"No schemabot.yaml config found" comment: SchemaBot couldn't find a schemabot.yaml file in the PR's changed file directories. Make sure the file exists and is committed to the PR branch.

"Database Not Found" comment: A command's -d flag named a database that no schemabot.yaml in the repository declares. Check the database field of the intended schemabot.yaml; the comparison is case-insensitive. On a repository too large for GitHub to return its full tree, SchemaBot searches only the directories listed under the database's allowed_dirs in the server config, and the comment lists the directories it searched.

"Database Not Available to This Repository" comment: A command's -d flag named a database whose allowed_repos in the server config does not include this repository. No schemabot.yaml in the repository can manage that database, so none was searched. Add the repository to the database's allowed_repos if it should manage the database.

"Database Not Configured" comment: A command's -d flag named a database that has no key under databases: in your SchemaBot server config. The repository's schemabot.yaml may be correct; the database still has to be configured on the server before SchemaBot can plan or apply changes for it. On a repository shared by several SchemaBot deployments, only a deployment named with -t, or one that is not the aggregate leader, answers this way; the leader keeps searching the repository so a database no deployment serves is still reported.

"Database Not Registered" comment: On a repository shared by several SchemaBot deployments, the PR's schemabot.yaml declares a database the aggregate leader has no key for under databases:, and its schema directory is under none of the paths the leader expects another deployment to report on. The comment speaks only for the deployment named in its header: a leader serving other environments keeps its own registry and may register the database. When several leaders split a repository's environments, only one answers: the leader serving the command's -e environment, or, for a command without -e, the leader serving the first environment in environment_order. The others log the decision and stay silent. When the PR carries several such configs, the one reply lists them all under "Databases Not Registered". If a database is new to SchemaBot, register it on that deployment with an allowed_dirs entry naming its schema directory; if it is already registered, move the schemabot.yaml and its schema files under the directory registered for it.

"Repository Too Large to Search" comment: GitHub truncated the repository tree, and the server config gave SchemaBot no exhaustive set of directories to search instead. Give the database an allowed_dirs entry naming its schema directory so discovery can probe that directory alone.

"not configured on this SchemaBot instance" comment: The database field in schemabot.yaml doesn't match any key under databases: in your SchemaBot server config. The consumer value is folded to lowercase before matching, so only the letters need to agree with the (lowercase) server key.