Skip to content
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,6 @@ You may use, run, modify and distribute the console, including in production, fr
| What | Reviews for one GitHub, GitLab and Bitbucket host each; local executor; repository on/off; `@bot` commands; review history for 30 days; status dashboard; admin sign-in by email | More hosts per platform and per-host bot identities; host, group and pattern rules; team learnings; Docker and Kubernetes executors; token budgets; metrics and long history; audit log viewer; branch-sync skip; SSO domain and group rules |
| Cost | Free in every environment, production included | A license key from Divmora, in every environment (development, CI, staging and production) |

Install a key under **License** in the admin panel, or with `CODEREVIEW_CONSOLE_LICENSE` or `license.file` ([docs/deploy.md](docs/deploy.md#license)). Keys are verified offline. Licenses and trials: licensing@divmora.com.
Install, replace or remove the key under **License** in the admin panel; it applies at once ([docs/deploy.md](docs/deploy.md#license)). Keys are verified offline. Licenses and trials: licensing@divmora.com.

The review engine, [code-review-bot](https://github.com/divmora/code-review-bot), is Apache 2.0 and free in any environment.
90 changes: 71 additions & 19 deletions cmd/console/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,18 @@ func serve(ctx context.Context, args []string) error {
}
lic := loadLicense(ctx, cfg, deps.Store, logger)
if err := requireExecutor(cfg, lic); err != nil {
return err
// Start anyway, so the license can be added in the admin panel;
// reviews are refused until it is (see licensedExecutor).
logger.Error("reviews are paused until a license is added in the admin panel", "error", err)
}
warnSSORules(cfg, lic, logger)
exec, err := newExecutor(cfg)
if err != nil {
return err
}
if cfg.Executor.Type != "local" {
exec = &licensedExecutor{Executor: exec, lic: lic}
}
deps.License = lic
deps.Settings = settings.New(cfg, deps.Store)
deps.Settings.Lic = lic
Expand Down Expand Up @@ -175,6 +180,7 @@ func serve(ctx context.Context, args []string) error {
adm.Settings = deps.Settings
adm.Lic = lic
adm.Hosts = deps.Hosts
adm.ExecutorType = cfg.Executor.Type
deps.Admin = adm
logger.Info("admin enabled", "url", cfg.Admin.BaseURL, "issuer", cfg.Admin.OIDC.Issuer)
}
Expand Down Expand Up @@ -202,7 +208,7 @@ func checkConfig(ctx context.Context, args []string) error {
return err
}
if err := requireExecutor(cfg, loadLicense(ctx, cfg, nil, slog.New(slog.DiscardHandler))); err != nil {
fmt.Printf("note: %v\n (a key pasted in the admin panel is read from the database when the console starts)\n", err)
fmt.Printf("note: %v\n (the console still starts; reviews wait until the license is added in the admin panel)\n", err)
}
fmt.Printf("executor: %s\nworkers: %d\nadmin: %v\nallowlist: %v\ndatabase: %v\n", exec.Name(), cfg.Server.Workers, cfg.Admin.Enabled, cfg.Repos.Allowlist, cfg.Database.URL != "")
if len(hosts.FromConfig(cfg)) > 0 {
Expand Down Expand Up @@ -253,27 +259,59 @@ func checkConfig(ctx context.Context, args []string) error {
return nil
}

// loadLicense reads the license key: $CODEREVIEW_CONSOLE_LICENSE, then
// license.file, then a key pasted in the admin panel (database). Without a
// valid key the console runs the free core.
// loadLicense reads the license key: $CODEREVIEW_CONSOLE_LICENSE (an
// override, e.g. when nobody can sign in), then the key managed in the admin
// panel (database). license.file is deprecated: when the database has no key
// yet, a valid key from the file is copied into it once, and from then on
// the admin panel is where the license changes. Without a database the file
// is read as before. Without a valid key the console runs the free core.
func loadLicense(ctx context.Context, cfg *config.Config, st store.Store, logger *slog.Logger) *license.Manager {
lic := license.Default()
return loadLicenseInto(ctx, license.Default(), cfg, st, logger)
}

// loadLicenseInto is loadLicense with the Manager given (tests trust a test key).
func loadLicenseInto(ctx context.Context, lic *license.Manager, cfg *config.Config, st store.Store, logger *slog.Logger) *license.Manager {
key, source := strings.TrimSpace(os.Getenv("CODEREVIEW_CONSOLE_LICENSE")), "env"
if key == "" && cfg.License.File != "" {
var stored admin.StoredLicense
found := false
if st != nil {
var err error
if found, err = st.GetSetting(ctx, admin.LicenseSetting, &stored); err != nil {
logger.Error("could not read the stored license", "error", err)
}
found = found && stored.Key != ""
}
if key == "" && found {
key, source = stored.Key, "database"
}
if cfg.License.File != "" {
switch {
case st == nil:
logger.Warn("deprecated: license.file; set database.url and manage the license in the admin panel")
case found:
logger.Warn("license.file is ignored: the license is managed in the admin panel (remove license.file)")
default:
logger.Warn("deprecated: license.file; its key is copied into the database once, then the license is managed in the admin panel (remove license.file)")
}
}
if key == "" && !found && cfg.License.File != "" {
b, err := os.ReadFile(cfg.License.File)
if err != nil {
lic.Fail("file", err)
logger.Error("license file unreadable; running the free core", "file", cfg.License.File, "error", err)
return lic
}
key, source = strings.TrimSpace(string(b)), "file"
}
if key == "" && st != nil {
var stored admin.StoredLicense
if found, err := st.GetSetting(ctx, admin.LicenseSetting, &stored); err != nil {
logger.Error("could not read the stored license; running the free core", "error", err)
} else if found {
key, source = stored.Key, "database"
key, source = strings.Join(strings.Fields(string(b)), ""), "file"
if st != nil {
if c, err := lic.Verify(key); err == nil {
detail := map[string]any{"id": c.ID, "customer": c.Customer.Name, "plan": c.Plan, "expires_at": c.ExpiresAt, "from": "license.file"}
if err := st.PutSettingAudited(ctx, admin.LicenseSetting, admin.StoredLicense{Key: key}, detail, "license.file (initial)"); err != nil {
logger.Error("could not copy the license from license.file into the database", "error", err)
} else {
source = "database"
logger.Info("license copied from license.file into the database; manage it in the admin panel from now on")
}
}
}
}
if key == "" {
Expand Down Expand Up @@ -308,15 +346,29 @@ func warnSSORules(cfg *config.Config, lic *license.Manager, logger *slog.Logger)
"allowed_emails", len(o.AllowedEmails))
}

// requireExecutor refuses the docker and kubernetes executors without a
// license that covers them.
// requireExecutor reports whether the docker and kubernetes executors are
// covered by the license.
func requireExecutor(cfg *config.Config, lic *license.Manager) error {
if cfg.Executor.Type == "local" {
return nil
}
if err := lic.Require(license.Executors); err != nil {
return fmt.Errorf("executor.type %s: %w (on a first start, provide the key with CODEREVIEW_CONSOLE_LICENSE or license.file, "+
"or start once with executor.type: local and paste it in the admin panel)", cfg.Executor.Type, err)
return fmt.Errorf("executor.type %s: %w", cfg.Executor.Type, err)
}
return nil
}

// licensedExecutor refuses to run jobs while the license does not cover the
// docker or kubernetes executor. It checks on every job, so a key added in
// the admin panel applies without a restart.
type licensedExecutor struct {
executor.Executor
lic *license.Manager
}

func (e *licensedExecutor) Run(ctx context.Context, t executor.Task) (*executor.Result, error) {
if err := e.lic.Require(license.Executors); err != nil {
return nil, &executor.RunError{Message: "the " + e.Name() + " executor needs a Divmora license with the executors feature: add one under License in the admin panel"}
}
return e.Executor.Run(ctx, t)
}
105 changes: 105 additions & 0 deletions cmd/console/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package main

import (
"context"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/divmora/code-review-console/internal/admin"
"github.com/divmora/code-review-console/internal/config"
"github.com/divmora/code-review-console/internal/ee/license"
"github.com/divmora/code-review-console/internal/ee/license/licensetest"
"github.com/divmora/code-review-console/internal/executor"
"github.com/divmora/code-review-console/internal/store/storetest"
)

var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))

func TestLicenseSources(t *testing.T) {
ctx := context.Background()
k := licensetest.NewKey(t)
fileKey := k.Issue(t, 30*24*time.Hour, license.Hosts)
panelKey := k.Issue(t, 60*24*time.Hour, license.Executors)
envKey := k.Issue(t, 90*24*time.Hour, license.Rules)
path := filepath.Join(t.TempDir(), "license.key")
if err := os.WriteFile(path, []byte(fileKey+"\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg := &config.Config{License: config.License{File: path}}
t.Setenv("CODEREVIEW_CONSOLE_LICENSE", "")

// license.file with an empty database: copied in once, then managed there.
st := storetest.New()
lic := loadLicenseInto(ctx, k.Manager(t), cfg, st, quiet)
if s := lic.Status(); s.Source != "database" || s.Managed || !lic.Has(license.Hosts) {
t.Fatalf("seeded from the file: %+v", s)
}
var stored admin.StoredLicense
if found, _ := st.GetSetting(ctx, admin.LicenseSetting, &stored); !found || stored.Key != fileKey {
t.Fatalf("the file key must be stored: %v %q", found, stored.Key)
}

// A key replaced in the panel wins over the file on the next start.
_ = st.PutSetting(ctx, admin.LicenseSetting, admin.StoredLicense{Key: panelKey}, "a@x")
lic = loadLicenseInto(ctx, k.Manager(t), cfg, st, quiet)
if !lic.Has(license.Executors) || lic.Has(license.Hosts) {
t.Errorf("the panel's key must win over license.file: %+v", lic.Status())
}

// The environment overrides the panel, and the panel can't replace it.
t.Setenv("CODEREVIEW_CONSOLE_LICENSE", envKey)
lic = loadLicenseInto(ctx, k.Manager(t), cfg, st, quiet)
if s := lic.Status(); s.Source != "env" || !s.Managed || !lic.Has(license.Rules) {
t.Errorf("env override: %+v", s)
}
t.Setenv("CODEREVIEW_CONSOLE_LICENSE", "")

// An invalid file key is not copied into the database.
bad := filepath.Join(t.TempDir(), "bad.key")
_ = os.WriteFile(bad, []byte("DIV1.nope"), 0o600)
st2 := storetest.New()
lic = loadLicenseInto(ctx, k.Manager(t), &config.Config{License: config.License{File: bad}}, st2, quiet)
if found, _ := st2.GetSetting(ctx, admin.LicenseSetting, &stored); found || lic.Status().State != license.Invalid {
t.Errorf("invalid file key: stored=%v %+v", found, lic.Status())
}

// Without a database the file is read as before.
lic = loadLicenseInto(ctx, k.Manager(t), cfg, nil, quiet)
if s := lic.Status(); s.Source != "file" || !s.Managed || !lic.Has(license.Hosts) {
t.Errorf("no database: %+v", s)
}
}

type okExec struct{ runs int }

func (e *okExec) Name() string { return "kubernetes" }
func (e *okExec) Run(context.Context, executor.Task) (*executor.Result, error) {
e.runs++
return &executor.Result{}, nil
}

func TestLicensedExecutorAppliesWithoutRestart(t *testing.T) {
k := licensetest.NewKey(t)
lic := k.Manager(t) // no key yet: the free core
inner := &okExec{}
ex := &licensedExecutor{Executor: inner, lic: lic}
_, err := ex.Run(context.Background(), executor.Task{Kind: "review"})
if err == nil || !strings.Contains(err.Error(), "needs a Divmora license") || inner.runs != 0 {
t.Fatalf("unlicensed: %v (runs %d)", err, inner.runs)
}
if err := lic.Install(k.Issue(t, time.Hour, license.Executors), "database"); err != nil {
t.Fatal(err)
}
if _, err := ex.Run(context.Background(), executor.Task{Kind: "review"}); err != nil || inner.runs != 1 {
t.Errorf("after the key is added: %v (runs %d)", err, inner.runs)
}
cfg := &config.Config{Executor: config.Executor{Type: "kubernetes"}}
if err := requireExecutor(cfg, k.Manager(t)); err == nil {
t.Error("requireExecutor still reports the missing feature (for logs and check-config)")
}
}
35 changes: 16 additions & 19 deletions docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,22 @@ by email. Paid features need a Divmora license key (a `DIV1.…` token, or the a
`-----BEGIN DIVMORA LICENSE KEY-----` block) for product `code-review-console`. The README lists
the features.

The key is read from the first of these that is set:

1. `CODEREVIEW_CONSOLE_LICENSE`: the key itself
2. `license.file` in the config: a file holding the key (for example a mounted Secret)
3. the key pasted under **License** in the admin panel (stored in the database, audited without
the key itself)

Keys are verified offline against Divmora's public key; nothing is sent anywhere. A new key
applies at once, except for the executor type, which is checked when the console starts:
`executor.type: docker` or `kubernetes` without the `executors` feature stops startup with a clear
error.

**First start with the docker or kubernetes executor.** Because the check runs before the admin
panel is up, a fresh install can't use the panel to add its first key. Either:

- provide the key by `CODEREVIEW_CONSOLE_LICENSE` or `license.file` for the first start (it can
stay there, or you can paste it in the panel later and remove it), or
- start once with `executor.type: local`, paste the key under **License**, then switch the executor
and restart. The pasted key is stored in the database and read on every later start.
**Manage the key under License in the admin panel**: paste it to install or replace it, or remove it.
It is stored in the database and audited without the key itself, and applies at once, with no
restart. That includes the docker and kubernetes executors: without the `executors` feature the
console still starts, shows "reviews are paused" in the panel and on **Setup**, and refuses review
jobs with a clear error until the key is added.

Two other sources exist:

- `CODEREVIEW_CONSOLE_LICENSE`: an **override**, for example when nobody can sign in. While it is
set, it wins over the panel, and the panel shows the key as managed by the variable.
- `license.file` (**deprecated**): when the database has no key yet, a valid key from the file is
copied into it on start, and from then on the panel manages it. Afterwards the file is ignored,
and the console logs a warning until you remove `license.file`. Without a database, the file is
read as before.

Keys are verified offline against Divmora's public key; nothing is sent anywhere.

When a license expires, paid features keep working for its grace period (14 days unless
the license says otherwise), with a banner in the admin panel. After that the console goes back
Expand Down
5 changes: 3 additions & 2 deletions examples/console.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@ database:
repos:
allowlist: true # review only repositories enabled directly or by a group/pattern rule
require_reviewer: false # true: review an MR/PR only when the bot user is one of its reviewers
# Divmora license key for paid features (or CODEREVIEW_CONSOLE_LICENSE, or paste it in the
# admin panel under License). Without one the console runs the free core.
# The Divmora license key is managed in the admin panel under License (without one the console runs
# the free core). license.file is deprecated: its key is copied into the database once.
# CODEREVIEW_CONSOLE_LICENSE overrides the panel, for example when nobody can sign in.
# license:
# file: /etc/console/license.key

Expand Down
33 changes: 33 additions & 0 deletions internal/admin/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

"github.com/divmora/code-review-bot/pkg/vcs"
"github.com/divmora/code-review-console/internal/config"
"github.com/divmora/code-review-console/internal/ee/license"
"github.com/divmora/code-review-console/internal/ee/license/licensetest"
"github.com/divmora/code-review-console/internal/hosts"
"github.com/divmora/code-review-console/internal/secrets"
Expand Down Expand Up @@ -748,3 +749,35 @@ func TestCommentWarningText(t *testing.T) {
t.Errorf("gitlab with a group hook but no comments: %q", w)
}
}

func TestReviewsPausedWithoutExecutorLicense(t *testing.T) {
e := setup(t, config.OIDC{AllowedEmails: []string{"alice@example.com"}})
e.idp.as(map[string]any{"sub": "u1", "email": "alice@example.com", "email_verified": true})
_ = e.login(t).Body.Close()
e.adm.ExecutorType = "kubernetes"
e.adm.Lic = licensetest.Manager(t, license.Hosts) // no executors feature
if _, body := e.do(t, "GET", "/admin/api/me", "", nil); !bytes.Contains(body, []byte(`"reviews_paused":"reviews are paused: the kubernetes executor needs a license`)) {
t.Errorf("/me must say reviews are paused: %s", body)
}
_, body := e.do(t, "GET", "/admin/api/setup", "", nil)
var st struct {
Steps []struct {
ID string
Done bool
Optional bool
}
Total int
}
_ = json.Unmarshal(body, &st)
if st.Steps[0].ID != "license" || st.Steps[0].Done || st.Steps[0].Optional || st.Total != 7 {
t.Errorf("the license step is required while reviews are paused: %s", body)
}
e.adm.Lic = licensetest.Full(t)
if _, body := e.do(t, "GET", "/admin/api/me", "", nil); !bytes.Contains(body, []byte(`"reviews_paused":""`)) {
t.Errorf("licensed: %s", body)
}
e.adm.ExecutorType, e.adm.Lic = "local", nil
if _, body := e.do(t, "GET", "/admin/api/me", "", nil); !bytes.Contains(body, []byte(`"reviews_paused":""`)) {
t.Errorf("the local executor never needs a license: %s", body)
}
}
3 changes: 3 additions & 0 deletions internal/admin/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ type Admin struct {
// Hosts is the code host registry shared with the server; nil hides
// the Hosts page.
Hosts *hosts.Registry
// ExecutorType is the configured executor (local, docker, kubernetes);
// docker and kubernetes need the executors license feature to run.
ExecutorType string
// Lic is the installed license (nil = the free core). License keys
// pasted in the panel are stored under licenseKey.
Lic *license.Manager
Expand Down
2 changes: 1 addition & 1 deletion internal/admin/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func (a *Admin) apiMe(w http.ResponseWriter, r *http.Request, s *store.Session)
}
writeJSON(w, http.StatusOK, map[string]any{
"email": s.Email, "name": firstNonEmpty(s.Name, s.Email), "expires": s.Expires, "csrf": s.CSRF, "version": version.Version, "license": a.Lic.Status(), "free_retention_days": license.FreeRetentionDays, "profiles": a.profiles, "allowlist": eff.Allowlist, "require_reviewer": eff.RequireReviewer,
"setup": setup,
"setup": setup, "reviews_paused": a.reviewsPaused(),
})
}

Expand Down
2 changes: 1 addition & 1 deletion internal/admin/license.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (a *Admin) apiPutLicense(w http.ResponseWriter, r *http.Request, s *store.S
return
}
if a.Lic.Status().Managed {
writeJSON(w, http.StatusConflict, map[string]string{"error": "the license comes from CODEREVIEW_CONSOLE_LICENSE or license.file; change it there"})
writeJSON(w, http.StatusConflict, map[string]string{"error": "the license comes from CODEREVIEW_CONSOLE_LICENSE, which overrides the panel: remove the variable and restart to manage it here"})
return
}
var req StoredLicense
Expand Down
Loading
Loading