backplane-lic

module
v0.0.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT

README

backplane-lic

A Backplane tool service that reproduces the Keygen CE 1.7 licensing API 1:1 — same URLs, JSON:API documents, headers, error codes and behavior — so existing Keygen clients (keygen-go, vendor backends) cannot tell the difference. Single account (Keygen "singleplayer"), licensing scope only: no releases, artifacts, environments, event/request logs, SSO or billing. Managed from the Backplane console (internal gRPC + UI plugin, later phase).

Layout

cmd/lic/                 the binary: Config, composition via internal/service
internal/domain/         pure rules: entities, crypto helpers (account keys)
internal/app/            scenarios: licenses, machines (components, processes,
                         usage journal, heartbeat cull), users, policies, …
pkg/licensing/           Go client library; installation/, request/, usage/,
                         lictest/ (the server in a test's process)
internal/infra/postgres/ schema.sql, sqld queries, generated db, repositories
internal/infra/httpapi/  ogen handler: JSON:API rendering, error mapping
internal/infra/portal/   embedded customer SPA and HTTP mount
portal/                  standalone React + Vite customer portal
internal/oas/            ogen output (generated — never edit)
internal/service/        composition root + Config
openapi/src/             OpenAPI 3.1 fragments (source of truth)
openapi/openapi.yaml     bundled spec (generated by `make spec`, committed)
deployments/             compose dev deps, Dockerfile, dev.yaml

Developing

make configure   # pinned tools into ./bin (sqld, golangci-lint, easyp, …)
make up          # postgres :5440, valkey :6390 (compose project `lic`)
make db-init     # regenerate the single init migration from schema.sql
make db          # generate typed queries + validate migrations
make spec        # bundle openapi/src → openapi/openapi.yaml
make gen-api     # … and generate the ogen server into internal/oas
make lint        # golangci-lint
make test        # unit tests (DB tests skip without LIC_TEST_DATABASE_URL)
make test-live   # unit tests against the compose PostgreSQL/Valkey
make portal      # install and build the customer SPA into the embed directory
make build       # build the portal first, then ./bin/lic

make down stops the dev dependencies. The keygen profile reproduces the Keygen CE reference server for the conformance suite on :3900 (do not run it while the kgce compose project holds the port): make keygen-up / make keygen-down; requests need Host: api.keygen.test and X-Forwarded-Proto: https, admin admin@example.com / adminadmin123.

Running

make build
BACKPLANE_CONFIG_FILE=deployments/dev.yaml \
BACKPLANE_PUBLIC_PORT=8090 BACKPLANE_INTERNAL_PORT=9440 \
BACKPLANE_INTERNAL_SECRET=dev-internal-secret-change-me \
  ./bin/lic

Then GET /v1/ping (200), GET /v1/health (204) and — once the middleware pipeline lands — the JSON:API under /v1/accounts/{account}/… with Keygen-compatible authentication and signatures.

Configuration

File (BACKPLANE_CONFIG_FILE) < env LIC_* (the SDK block reads BACKPLANE_*) < Consul KV for live fields. See deployments/dev.yaml:

Field Env Description
store.dsn LIC_STORE_DSN PostgreSQL connection string
cache.addr LIC_CACHE_ADDR Valkey address (cache-aside, optional)
cache.sentinel.master_set, cache.sentinel.addrs, cache.sentinel.password LIC_CACHE_SENTINEL_MASTER_SET, LIC_CACHE_SENTINEL_ADDRS, LIC_CACHE_SENTINEL_PASSWORD Valkey under Sentinel instead of cache.addr: the client follows the primary across failovers
account.id LIC_ACCOUNT_ID the single account's UUID, created at startup if missing
account.slug LIC_ACCOUNT_SLUG the account's slug (also its API address)
account.name LIC_ACCOUNT_NAME display name
account.ed25519_seed LIC_ACCOUNT_ED25519_SEED secret: hex 32-byte ed25519 seed the account signs with instead of a generated one
http.portal.enabled LIC_HTTP_PORTAL_ENABLED serve the customer portal; defaults to false
http.portal.basePath LIC_HTTP_PORTAL_BASE_PATH mount path; defaults to /portal, cannot be / or under /v1
brand.name LIC_BRAND_NAME vendor name in the portal and messages; defaults to Licenses
brand.tagline LIC_BRAND_TAGLINE headline on the portal sign-in page
brand.logoUrl LIC_BRAND_LOGO_URL https logo shown in the portal header and messages
brand.faviconUrl LIC_BRAND_FAVICON_URL https favicon of the portal
brand.accentColor LIC_BRAND_ACCENT_COLOR #RRGGBB accent for buttons, links and focus rings
brand.supportEmail LIC_BRAND_SUPPORT_EMAIL support address in the portal footer and messages
brand.supportUrl LIC_BRAND_SUPPORT_URL https support page
brand.termsUrl LIC_BRAND_TERMS_URL https terms of service, linked from the portal footer
brand.privacyUrl LIC_BRAND_PRIVACY_URL https privacy policy, linked from the portal footer

The account row is created at startup with generated keys (secret key, RSA-2048, ed25519, ECDSA P-256) that anchor token digests and response signatures. With account.ed25519_seed the ed25519 key is the vendor's own, so license and machine files verify against a public key already embedded in the vendor's binaries; the other keys stay generated. The seed is used only when the row is created: an existing account whose ed25519 key is another one stops startup (ErrEd25519Mismatch) — the key is never rotated silently.

With cache.addr set, token lookups are cached in Valkey under the account's token generation. Regenerating or revoking a token, and the bulk revocation of password changes, start a new generation, so a changed token is never served from the cache; entries otherwise expire after 30 seconds. Bearers are always read live. Account rows hold the private signing keys and are never cached. Valkey also shares the password-attempt windows between replicas.

Declared catalog

catalog.products declares products, their policies and named product tokens, so an installation comes up with them and no manual API calls. It is read at startup only (a restart applies a change): token values are secrets and never come from Consul. In env the section is one JSON value, LIC_CATALOG_PRODUCTS='[...]'; a file can carry it as YAML. Either way it holds the token values, so it comes from a secret (a file or a variable a secret store fills); values are not expanded from other variables. The console and logs show the values as ***.

catalog:
  products:
    - id: 7d4c0a52-1f3e-4b6a-9c2d-5e8f1a2b3c4d   # fixed: clients name the product by it
      name: Komeet
      code: komeet                                # optional, as the API
      # distribution_strategy, url, platforms, metadata: optional, as the API
      policies:
        - id: 0f6b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d
          # Keygen's policy attributes, named as the API names them.
          attributes: {name: pilot, duration: 2592000, maxMachines: 1,
                       machineUniquenessStrategy: UNIQUE_PER_POLICY,
                       expirationStrategy: REVOKE_ACCESS}
      tokens:
        - name: relay                             # unique per product
          value: prod-…v3                         # secret: prod-<64 lowercase hex>v3
          permissions: [machine.read]             # empty or "*": the product's whole set

At every start, one replica at a time (a PostgreSQL advisory lock), lic:

  • creates a declared product or policy that is missing, with the declared id, and updates one that differs; attributes a policy does not list keep their value (Keygen's defaults on creation);
  • refuses to start when a declared policy changes what is fixed at creation (its product, scheme, encrypted, usePool): ErrImmutable;
  • creates a named token with the declared value, or rotates the token of that name (the oldest on the product) to a changed value or permission set, keeping its id; the old value stops authenticating at once;
  • reports products, policies and product tokens the catalog does not declare (one log line with counts; the console's account page), and never deletes them.

A malformed catalog (an id that is not a UUID, a repeated id or token name, a token value of another form, a permission outside the product role's set, a policy attribute the API would refuse) stops startup naming the field.

A product token's permissions narrow the product role's set, as Keygen EE does: relay above reads machines and nothing else. Tokens created through the API keep *.

In the console, declared objects carry the mark From the configuration: editing, deleting and regenerating them is off (the next start would undo it), their operations (a pool key, a check) stay. A declared token shows its permissions.

Machines, components and processes

Machines (devices), their components and their processes follow Keygen. Every route lives under /v1/accounts/{account}; {id} of a machine is its UUID or its fingerprint. A PUT on an update route is the same as PATCH.

Resource Routes
Machines GET/POST /machines, GET/PATCH/DELETE /machines/{id} (create is an activation, delete a deactivation)
Machine relationships GET /machines/{id}/product, /license, /owner, /user (the license's owner), /group; PATCH /machines/{id}/owner, /group
Heartbeat POST /machines/{id}/actions/ping, ping-heartbeat, reset, reset-heartbeat
Check-out and proof GET/POST /machines/{id}/actions/check-out, POST /machines/{id}/actions/generate-offline-proof
Usage journal POST /machines/{id}/actions/report-usage, GET /machines/{id}/usage
Components GET/POST /components, GET/PATCH/DELETE /components/{id}, GET /components/{id}/machine, /license, /product, GET /machines/{id}/components, GET /machines/{id}/components/{componentId}
Processes GET/POST /processes (spawn), GET/PATCH/DELETE /processes/{id} (kill), POST /processes/{id}/actions/ping, GET /processes/{id}/machine, /license, /product, GET /machines/{id}/processes, GET /machines/{id}/processes/{processId}

A machine's metadata keys starting with vendor (vendorPaymentDeadline, vendorMode, …; stored underscored as vendor_…) are the vendor's: the signed machine file carries them for the product to trust. Only the admin family and the machine's product write them; an activation by anyone else that sets one is a 403 METADATA_KEY_RESERVED (an update's metadata is the vendor's alone already, as in Keygen). A backplane extension.

A component is a named hardware fingerprint of a machine; its fingerprint is unique within the policy's component uniqueness scope (default UNIQUE_PER_MACHINE). A machine's fingerprint is unique within the policy's machine uniqueness scope (default UNIQUE_PER_LICENSE). A process is a running instance on a machine, identified by a pid unique per machine; the policy's process leasing (PER_MACHINE by default, PER_LICENSE, PER_USER) counts them against the machine's own maxProcesses override or else the license's.

Check-out: machine files and offline proofs

Check-out by the licensee (license key or license token) of a suspended license is a 403 LICENSE_SUSPENDED, of a banned one (its owner banned) a 403 LICENSE_BANNED; an expired license still gets its file (the license inside is expired) unless its policy's expirationStrategy is REVOKE_ACCESS, then a 403 LICENSE_EXPIRED. The vendor side always gets the file. Recorded against Keygen CE (machines_checkout_states).

GET …/actions/check-out answers the signed certificate itself (-----BEGIN MACHINE FILE-----, as an attachment named {machine}.lic); POST …/actions/check-out answers it inside a machine-file document. The parameters are encrypt, algorithm, ttl and include: query parameters on GET, meta merged with the query on POST. The algorithm is <encoding>+<signature>; encoding is base64 or, with encrypt, aes-256-gcm keyed by the license key and the machine fingerprint. The ttl defaults to one month and is at least one hour (3600 seconds; less is a 400 CHECKOUT_TTL_INVALID with source parameter ttl, no upper bound); an explicit null asks for a perpetual file. include embeds license, license.entitlements, license.product, license.policy, license.owner (alias license.user), license.users, components, environment, group and owner.

On the client, MachineFile.Verify checks the signature, and Decode (base64) or Decrypt(licenseKey, fingerprint) reads the dataset. A file that decodes but fails the time policy, being past its expiry or issued in the future beyond the clock skew, answers its dataset together with ErrMachineFileExpired or ErrClockOutOfSync (license files: ErrLicenseFileExpired). A lapsed lease stays readable (issued, expiry, metadata); a format, key or fingerprint failure answers no dataset. Decoding never checks the signature: only a file that passed Verify is authentic.

POST …/actions/generate-offline-proof answers the machine with meta.proof: proof/<dataset>.<signature>, the dataset JSON (account, product, policy, license, machine, timestamp) and its RSA-SHA256 signature by the account key, both URL-safe base64. Admins, developers, sales and support agents and the product bearer can send their own dataset in meta.dataset.

Heartbeats and the cull

A machine's heartbeat duration is the policy's heartbeatDuration, else 600 seconds. With the FROM_CREATION heartbeat basis the clock starts at activation, otherwise at the first ping. A machine is NOT_STARTED before its first ping (while still inside the duration), ALIVE until the next ping is due, then DEAD; RESURRECTED is the status right after a ping revived a dead one. Processes follow the same rules with their own pings.

A dead machine is revived by a ping while its policy's resurrection strategy allows it: ALWAYS_REVIVE, or within the window after death of 1_MINUTE_REVIVE, 2_MINUTE_REVIVE, 5_MINUTE_REVIVE, 10_MINUTE_REVIVE or 15_MINUTE_REVIVE. NO_REVIVE (the default) never revives; a ping outside the window answers 422 MACHINE_HEARTBEAT_DEAD.

The heartbeat-cull job runs every 2 minutes, under an advisory lock so one replica works per tick, and visits up to 500 dead machines and 500 dead processes per pass. For each it sends the death event once (machine.heartbeat.dead, process.heartbeat.dead), then applies the policy's cull strategy: DEACTIVATE_DEAD (the default when unset) deletes the record once its resurrection window has passed and updates the license's machine counters; KEEP_DEAD keeps it. ALWAYS_REVIVE records are never culled.

POST /v1/accounts/{account}/search follows Keygen: licenses, users, products, policies, groups and entitlements by their searchable attributes, AND or OR combined, answered as the type's list document. Machines are accepted as a search type, but their search is not implemented and answers an empty list. Where Keygen fails with a server error (an unknown op, a non-string term for a text attribute, meta of the wrong kind, the EE request-log search), lic answers a 400 in Keygen's error style instead.

Customer portal

A license's page lists its installations (machines): each shows its fingerprint, its status and the usage the vendor accepted (its vendorUsageAck). The customer downloads an installation's lease (its machine file, check-out) and uploads its usage report file (report-usage) there — the path of an installation without a connection of its own — and activates a new installation by its fingerprint and installation public key (the activation request). A protected license offers no activation.

Enable the portal on the same HTTP listener as the public API:

http:
  portal:
    enabled: true
    basePath: /portal
brand:
  name: Acme Software
  tagline: All your Acme licenses in one place.
  logoUrl: https://acme.example/logo.svg
  accentColor: "#3366ff"
  supportEmail: support@acme.example
  termsUrl: https://acme.example/terms
  privacyUrl: https://acme.example/privacy

Nothing in the portal or the shipped messages names a particular vendor: brand is the installation's identity. Startup fails on a non-https URL, a color other than #RRGGBB or a malformed support address. Logo and favicon hosts are added to the portal's Content-Security-Policy img-src; everything else stays 'self'. Messages receive the same identity as brand_name, brand_logo_url, brand_accent_color, support_email, support_url and portal_url.

Customers with role user sign in at /portal; operators use the separate Backplane console. The portal has no admin controls and calls only /v1/accounts/{configured-account-id}/..., using the customer's own token. It supports English and Russian, light/dark themes, password recovery, password changes, TOTP setup, customer licenses, and personal API tokens. The shared ui-kit provides standalone controls without the Backplane shell.

Session tokens stay in sessionStorage, not localStorage, so closing the tab ends the browser's stored session. Logout first revokes the token through the public API. Deploy over HTTPS; the portal itself doesn't implement a second authentication backend.

Password reset links must point to /portal/reset#account=<account-id>&user=<user-id>&token=<reset-token> (replace /portal if you configure a different base path). Parameters belong in the URL fragment so HTTP requests and access logs never contain the reset token. The page clears the fragment immediately after loading. Query-string reset credentials are not accepted. The reset form uses the public POST /users/{user-id}/actions/reset-password action with the reset token and new password. The lic.Deliver automation (below) produces these links from automation.portalBase; serving the SPA adds no email endpoint.

License downloads use the public check-out action and save its certificate as a .lic file. Keygen allows a user to check out only their own unprotected licenses; the portal displays permission and API errors rather than bypassing those restrictions. Legacy-encrypted keys that the public API omits cannot be recovered by the portal; it shows an unavailable value and no copy action.

Default customer permissions also omit product.read and policy.read. Product and plan names therefore aren't available through the direct resource or license-relationship read endpoints; include=product,policy on a license read doesn't provide them either. The portal keeps the license list and detail usable, uses the license's own name as the heading, and omits inaccessible product and plan fields. Keys, status, expiry, usage and entitlements remain visible. If the public API permits those relationship reads, the portal displays the names normally.

make build installs frontend dependencies with the immutable Yarn lockfile, builds the SPA, copies it into internal/infra/portal/dist, then compiles Go. The release Dockerfile performs the same build in a Node stage before the Go stage. Like backplane-templates, the repository includes a minimal embed placeholder so plain go build ./... works without Node; this placeholder isn't a usable portal. Run make portal before a manual Go release build. Don't commit generated bundles over the placeholder. If GitHub Packages requires authentication in your build environment, pass your user Yarn configuration (~/.yarnrc.yml with the scope tokens) as a BuildKit secret instead of copying credentials into the image:

docker build --secret id=yarnrc,src="$HOME/.yarnrc.yml" -f deployments/Dockerfile .

The server serves deep links with the SPA index and injects the configured base path, title, and public account id; it never injects credentials. Index responses use Cache-Control: no-store; hashed Vite assets use public, max-age=31536000, immutable. Missing assets return 404, not HTML. The portal sets a same-origin content security policy and no-referrer so reset-link tokens don't leak through the Referer header.

To run frontend checks:

cd portal
env -u HTTPS_PROXY -u HTTP_PROXY -u https_proxy -u http_proxy yarn typecheck
env -u HTTPS_PROXY -u HTTP_PROXY -u https_proxy -u http_proxy yarn test
env -u HTTPS_PROXY -u HTTP_PROXY -u https_proxy -u http_proxy yarn build

Installation automation

Lic declares the optional lic.Deliver hook. Without a binding, password reset retains Keygen's webhook-only behavior. With the shipped binding, lic calls templates.Render, then courier.SendMail; lic contains no SMTP credentials or message branding. POST /passwords still returns the same 204, and meta.deliver: false suppresses mail without suppressing the webhook.

Mount deployments/wiring into the Backplane platform container and set BACKPLANE_WIRING_DIR to its mount path, for example /etc/backplane/wiring. Mount deployments/templates into backplane-templates and set TEMPLATES_FILES_DIR=/etc/lic-templates to that mount path. Both services reconcile their files automatically; no console import or startup job is needed. Keep unrelated wiring and templates in those directories too, since removing a file removes its managed definition.

Configure lic's public portal link and message language:

automation:
  portalBase: https://licenses.example.com/portal
  locale: en

The environment overrides are LIC_AUTOMATION_PORTAL_BASE and LIC_AUTOMATION_LOCALE. portalBase must identify the public portal, not the API; the reset link appends /reset#account=<uuid>&user=<uuid>&token=<claim>. The fragment stays in the browser, out of server/proxy logs and Referer headers. The portal reads it client-side and submits token as passwordResetToken with newPassword to the existing user reset-password action. Templates include English and Russian; the templates service handles language fallback.

Transactions and retries

The business mutation, Keygen webhook records and automation outbox records commit together. The pg-outbox relay performs hook calls and event publication after commit. A failed delivery retries the same stored message and token, not the password-reset request. The message ID becomes hook.Key, so a lost reply retries the same Backplane execution; binding steps also retain their activity idempotency keys. Delivery remains at-least-once: the configured courier channel must honor its activity key to avoid duplicate external mail. An unbound hook, including a binding removed between Bound and Call, succeeds without mail. Other hook errors remain retryable.

The relay uses the webhook retry budget (16 attempts), then retains a dead record for 30 days for operator investigation. Completed outbox payloads are cleared. Reset URLs contain credentials; restrict database access and don't log delivery payloads. Backplane password-reset events contain user identity only, never the reset token.

Lic declares these stable Backplane event names: lic.UserCreated, lic.PasswordResetRequested, lic.LicenseCreated, lic.LicenseExpiringSoon, lic.LicenseExpired, lic.LicenseRenewed, lic.LicenseSuspended, lic.LicenseReinstated (a suspended license active again), lic.LicenseRevoked, lic.LicenseValidationFailed and lic.UsageIncremented. License events are keyed by the license id and carry account_id, license_id, product_id, policy_id, user_id, expiry, uses, suspended, validation_code and occurred_at, never the key or the metadata. Event IDs survive relay retries; consumers must deduplicate by ID. Installations need NATS JetStream for events and Backplane's hook execution transport for mail. A missing transport leaves committed work pending; it never turns a committed password reset into an HTTP delivery error.

Activities

Other services can call these typed activities from wiring:

Activity Input Result
lic.CreateLicense policy_id, optional owner_id, name, key, expiry, metadata license snapshot and key
lic.GetLicense license (UUID or key) license snapshot and key
lic.SuspendLicense / lic.RenewLicense license updated snapshot and key
lic.ValidateKey key, optional product, policy, fingerprints, entitlements valid, code, detail, nullable license
lic.IncrementUsage license, increment updated snapshot and key

These are installation-internal admin operations, not an alternative public authentication API. Restrict who can author wiring and invoke internal activities. The handlers use the same application scenarios as HTTP, so policy checks, key generation and Keygen webhooks still apply.

Mutating activities, including validation touches, commit a durable result receipt with the business write. They take their key from activity.InfoOf(ctx).Key; concurrent attempts serialize under a PostgreSQL transaction lock. Repeating the same key returns the committed result, while reusing it with different input fails permanently. Receipts have no automatic expiry: deleting one permits an old retry to repeat its mutation. They may contain a license key, including the one-time plaintext of a legacy-encrypted key, so treat this table as credential storage. Domain validation errors fail without retry; storage and transport failures remain retryable.

Testing against the real server: pkg/licensing/lictest

lictest.Start(t, dsn) runs this server inside a test's process on a loopback port, over a PostgreSQL the caller provides (migrated on start), in an account of its own, so tests of a consumer share one database and run in parallel. It answers a *lictest.Server with URL (the client's APIURL), AccountID, Slug, AdminToken and PublicKey (the account's Ed25519 verify key, hex), and builds a fixture through the API as the admin:

srv := lictest.Start(t, dsn)
product := srv.Product(t, "app")
policy := srv.Policy(t, product, lictest.Attributes{"maxMachines": 1}) // over name + scheme ED25519_SIGN
license := srv.License(t, policy, lictest.Attributes{"metadata": map[string]any{"plan": "pro"}})
vendor := srv.Client(t, licensing.Config{Token: srv.ProductToken(t, product)})
user := srv.Client(t, licensing.Config{LicenseKey: license.Key})
status, body := srv.Do(t, http.MethodGet, "/machines", nil) // any admin call under the account

Attributes are the API's JSON:API attributes (camelCase); the server validates them. The repository's own end-to-end tests (test/e2e) run on it.

Client library: installation, request signing, usage journal

Three packages under pkg/licensing (installation, request, usage) extend the Go client library for machine-bound installations with Ed25519 keys and RFC 9421 HTTP Message Signatures.

pkg/licensing/installation — installation key management
  • installation.NewKey() generates an Ed25519 key pair.
  • The machine fingerprint is lowercase hex SHA-256 of the raw public key.
  • installation.Activate(ctx, license, key, opts...) activates with the fingerprint and metadata (publicKey).
  • installation.PublicKeyOf(machine) reads the publicKey from metadata and verifies it hashes to the fingerprint.
  • installation.ActivationRequest is the air-gapped activation payload (JSON, camelCase field names).
  • *licensing.Machine.UpdateMetadata(ctx, patch) merges vendor-side values into the machine's metadata (so they ride inside its signed machine file): it reads the machine, applies the patch (a JSON null removes a key, every other key is kept), sends the whole map with PATCH …/machines/{id} (the server replaces metadata whole) and refreshes the machine. Concurrent writers are last-write-wins; keys are camelCase on the wire. The keys activation owns, fingerprint and publicKey, are refused with licensing.ErrReservedMetadata.
pkg/licensing/request — RFC 9421 request signing and verification
  • Client side: request.NewTransport(base, key) wraps an http.RoundTripper and signs every request with Ed25519 (alg="ed25519", keyid = fingerprint).
  • Server side: request.NewAuthenticator(licensingClient, opts) verifies signatures, checks the nonce (in-memory replay guard), validates the machine's licence, and caches the result with single-flight.
  • request.Authenticator.Middleware is an http.Handler that also covers ConnectRPC handlers (they implement http.Handler).
Wire contract: request signing

Covered components: @method, @target-uri, plus content-digest (sha-256) for requests with a body. Signature parameters: created (UNIX timestamp), nonce (random), keyid (fingerprint), alg (ed25519). The signing base and header format follow RFC 9421.

Implemented directly from the RFC; no external library is used (github.com/yaronf/httpsign requires Go 1.27+; the project is on Go 1.26).

pkg/licensing/usage — signed usage hash chain
  • usage.NewJournal(domain, fingerprint, epoch, acked) maintains an in-memory hash chain. Append(event) returns (seq, hash).
  • usage.NewReport(domain, fingerprint) builds a report; Sign(priv) and Verify(pub, acked) handle Ed25519 signatures.
  • Typed sentinels: ErrInvalidSignature, ErrGap, ErrFork, ErrChainBroken, ErrFormat.
  • usage.Journal persists nothing — the product owns storage.
Wire contract: report JSON
{
  "format": 1,
  "domain": "komeet-usage/v1",
  "fingerprint": "<hex>",
  "epoch": <uint64>,
  "seqFrom": <uint64>,
  "seqTo": <uint64>,
  "prevHash": "<hex sha256>",
  "events": "<base64 of length-prefixed canonical encoding>",
  "head": "<hex sha256>",
  "counters": {"ops": 5},
  "build": "1.0.0",
  "signature": "<base64 ed25519>"
}

Canonical event encoding: each event is [4-byte big-endian length][event bytes], concatenated.

Signing payload: "backplane-usage-sig/v1" || domain || fingerprint || epoch(be64) || seqFrom(be64) || seqTo(be64) || prevHash || head.

Server endpoints
POST /v1/accounts/{account}/machines/{id}/actions/report-usage
  Body:  {"meta": {"report": <Report>}}
  Reply: {"data": <machine>, "meta": {"ack": {"epoch": ..., "seq": ..., "hash": "..."}}}

GET /v1/accounts/{account}/machines/{id}/usage?after=<seq>&limit=<n>
  Reply: {"meta": {"epoch": ..., "events": [...], "head": {...}, "acks": [...]}}

The journal is a backplane extension to the machine resource. Reporting needs the heartbeat-ping permission on the machine (the same callers that may ping it); the report is signed by the Ed25519 key in the machine's publicKey metadata and must continue the accepted head. Re-sending an accepted report answers its ack again. Reading the journal is for the vendor side only: the admin family and the machine's product. after is a sequence number; limit defaults to 100 and is capped at 1000. The journal is deleted together with its machine.

An accepted report also sets the machine's vendorUsageAck metadata to its ack, so the next machine file carries it to an installation that reports offline. One report carries at most 10,000 events (usage.MaxReportEvents); Journal.Report cuts a longer tail, the rest goes in the next report after the ack.

Refusals:

Code Status Meaning
USAGE_REPORT_TOO_LARGE 422 more than 10,000 events in one report
USAGE_KEY_MISSING 422 the machine has no publicKey metadata
USAGE_KEY_INVALID 422 the publicKey is not an Ed25519 key
USAGE_FINGERPRINT_MISMATCH 422 the report's fingerprint is not the machine's
USAGE_SIGNATURE_INVALID 422 the signature does not verify
USAGE_CHAIN_BROKEN 422 the head does not match the reported events
USAGE_FORMAT_INVALID 422 the report is malformed
USAGE_FORK 409 the report forks the accepted chain
USAGE_GAP 409 the report skips events after the accepted head

Client methods: *licensing.Machine.ReportUsage(ctx, report) and *licensing.Machine.Usage(ctx, afterSeq, limit). The wire contract is documented in pkg/licensing/usage/doc.go.

API additions to the licensing client
  • *licensing.Client.Machine(ctx, idOrFingerprint) — looks up a machine by UUID or fingerprint with token authentication. The identifier is validated to contain only hex digits and hyphens, then escaped with url.PathEscape.
  • *licensing.Client.ValidateMachine(ctx, fingerprint) — looks up the machine, fetches its licence, and validates it with the fingerprint scope.

Metrics

Name Type Labels
lic.license.validations counter code: Keygen's validation code (VALID, EXPIRED, SUSPENDED, …) or the refusal's code
lic.machine.activations counter outcome: ok, the refusal code (MACHINE_LIMIT_EXCEEDED, METADATA_KEY_RESERVED, …), error
lic.checkouts counter kind (license, machine), outcome (ok, LICENSE_SUSPENDED, LICENSE_BANNED, LICENSE_EXPIRED, …, error)
lic.usage.reports counter outcome: ok, USAGE_SIGNATURE_INVALID, USAGE_CHAIN_BROKEN, USAGE_REPORT_TOO_LARGE, …, error
lic.webhook.deliveries counter outcome: delivered, failing (retried), failed (final)

The SDK's metrics come on top (backplane reference/metrics), the HTTP API's request metrics among them.

Directories

Path Synopsis
cmd
lic command
lic is the Backplane licensing service: a 1:1 clone of the Keygen CE licensing API (URLs, JSON:API documents, headers, error codes, behavior) so Keygen clients cannot tell the difference.
lic is the Backplane licensing service: a 1:1 clone of the Keygen CE licensing API (URLs, JSON:API documents, headers, error codes, behavior) so Keygen clients cannot tell the difference.
internal
app/access
Group and group-owner resource authorization (GroupPolicy, Groups::GroupOwnerPolicy).
Group and group-owner resource authorization (GroupPolicy, Groups::GroupOwnerPolicy).
app/accounts
Package accounts is the account scenario: the single account's bootstrap and (later) its settings.
Package accounts is the account scenario: the single account's bootstrap and (later) its settings.
app/apperr
Package apperr is the typed application error: everything a handler needs to render a Keygen error document (status, title, detail, code, source pointer/parameter/header, docs link).
Package apperr is the typed application error: everything a handler needs to render a Keygen error document (status, title, detail, code, source pointer/parameter/header, docs link).
app/authn
Package authn is the authentication scenario: every Authorization scheme and the ?token=/?auth= query form, resolved to a principal.
Package authn is the authentication scenario: every Authorization scheme and the ?token=/?auth= query form, resolved to a principal.
app/automation
Package automation records installation automation in the same transaction as Keygen webhooks.
Package automation records installation automation in the same transaction as Keygen webhooks.
app/catalog
Package catalog is the declared catalog: products, their policies and named product tokens of fixed value, taken from the configuration and reconciled at startup.
Package catalog is the declared catalog: products, their policies and named product tokens of fixed value, taken from the configuration and reconciled at startup.
app/entitlements
Package entitlements is the entitlement scenario: the account-level CRUD of the features policies and licenses attach.
Package entitlements is the entitlement scenario: the account-level CRUD of the features policies and licenses attach.
app/events
Package events is where scenarios report what happened: a Keygen webhook event ("license.created", "machine.heartbeat.ping", …) with the resource document it carries.
Package events is where scenarios report what happened: a Keygen webhook event ("license.created", "machine.heartbeat.ping", …) with the resource document it carries.
app/groups
Package groups is the group scenario: CRUD, the member relationship indexes and the owners join resource.
Package groups is the group scenario: CRUD, the member relationship indexes and the owners join resource.
app/jobs
Package jobs is the periodic-jobs runner: every tick takes a PG advisory xact lock so exactly one replica runs it, then runs the jobs that are due — the heartbeat cull and the prunes Keygen runs on cron (sidekiq-cron).
Package jobs is the periodic-jobs runner: every tick takes a PG advisory xact lock so exactly one replica runs it, then runs the jobs that are due — the heartbeat cull and the prunes Keygen runs on cron (sidekiq-cron).
app/keys
Package keys is the key scenario: the members of pooled policies' key pools (create requires a pooled policy; the pool itself lives under /policies/{id}/pool).
Package keys is the key scenario: the members of pooled policies' key pools (create requires a pooled policy; the pool itself lives under /policies/{id}/pool).
app/licenses
License actions: revoke, renew, suspend, reinstate, check-in and the usage counters.
License actions: revoke, renew, suspend, reinstate, check-in and the usage counters.
app/machines
Package machines is the machine scenario: index, show, activation, update, deactivation, the heartbeat actions, machine-file check-outs and the relationship routes (product, license, owner, user, group).
Package machines is the machine scenario: index, show, activation, update, deactivation, the heartbeat actions, machine-file check-outs and the relationship routes (product, license, owner, user, group).
app/paging
Package paging parses the three pagination modes (limit, offset, keyset) and the order parameter exactly like the reference, and builds the collection links (with pagination meta nested in links).
Package paging parses the three pagination modes (limit, offset, keyset) and the order parameter exactly like the reference, and builds the collection links (with pagination meta nested in links).
app/passwords
Package passwords is the password-reset request scenario (POST /passwords): always a 204, indistinguishable for unknown emails.
Package passwords is the password-reset request scenario (POST /passwords): always a 204, indistinguishable for unknown emails.
app/policies
Package policies is the policy scenario: CRUD over the full attribute surface, the product/license relationship routes, the key pool and entitlement attach/detach.
Package policies is the policy scenario: CRUD over the full attribute surface, the product/license relationship routes, the key pool and entitlement attach/detach.
app/products
Package products is the product scenario: CRUD, the product's relationship routes (policies, licenses, machines, tokens, users) and product-token generation.
Package products is the product scenario: CRUD, the product's relationship routes (policies, licenses, machines, tokens, users) and product-token generation.
app/search
Package search is POST /search: it validates a typed query, authorizes the bearer, and resolves the matching ids of one resource type.
Package search is POST /search: it validates a typed query, authorizes the bearer, and resolves the matching ids of one resource type.
app/secondfactors
Package secondfactors is the TOTP second-factor scenario: create (secret revealed), enable/disable (OTP-verified), delete, and the index/show reads.
Package secondfactors is the TOTP second-factor scenario: create (secret revealed), enable/disable (OTP-verified), delete, and the index/show reads.
app/telemetry
Package telemetry is lic's business counters: validations by their code, activations, check-outs and usage reports by outcome.
Package telemetry is lic's business counters: validations by their code, activations, check-outs and usage reports by outcome.
app/tokens
Package tokens is the token scenario: generation (the POST /tokens endpoint).
Package tokens is the token scenario: generation (the POST /tokens endpoint).
app/users
Package users is the user scenario: the bootstrap admin seed, the status computation, CRUD, the password/ban actions and the relationship reads (me/profile included).
Package users is the user scenario: the bootstrap admin seed, the status computation, CRUD, the password/ban actions and the relationship reads (me/profile included).
app/webhooks
Package webhooks is the webhook scenario: endpoint CRUD (the URL, subscription and signature rules), the webhook-events routes (index, show, destroy, retry) and the event publisher that writes the outbox rows inside the caller's transaction.
Package webhooks is the webhook scenario: endpoint CRUD (the URL, subscription and signature rules), the webhook-events routes (index, show, destroy, retry) and the event publisher that writes the outbox rows inside the caller's transaction.
domain
Package domain holds the pure rules of the licensing model: entities, enums, sentinels, key schemes and the expiry/status/heartbeat math.
Package domain holds the pure rules of the licensing model: entities, enums, sentinels, key schemes and the expiry/status/heartbeat math.
domain/crypto
Package crypto holds the key generation and signing helpers: account keys, license-key schemes, license/machine files, response signatures and token secrets/digests.
Package crypto holds the key generation and signing helpers: account keys, license-key schemes, license/machine files, response signatures and token secrets/digests.
domain/jsonapi
Package jsonapi holds the wire-format transforms every handler shares: the metadata key casing (camelCase on the wire, snake_case stored) and the timestamp rendering.
Package jsonapi holds the wire-format transforms every handler shares: the metadata key casing (camelCase on the wire, snake_case stored) and the timestamp rendering.
infra/automation
Package automation declares the service-owned Backplane contracts and dispatches committed outbox records to the SDK.
Package automation declares the service-owned Backplane contracts and dispatches committed outbox records to the SDK.
infra/cache
Package cache holds the cache-aside decorators of storage ports.
Package cache holds the cache-aside decorators of storage ports.
infra/commit
Package commit runs actions after the surrounding transaction commits: effects outside the database (a cache invalidation) must not be observed before the change they describe.
Package commit runs actions after the surrounding transaction commits: effects outside the database (a cache invalidation) must not be observed before the change they describe.
infra/console
Package console bridges the internal operator API to the real HTTP API.
Package console bridges the internal operator API to the real HTTP API.
infra/httpapi
Package httpapi is the HTTP face of the service: the ogen handler (thin: extract params, call one scenario, translate the outcome), JSON:API rendering, the error mapping and the full middleware pipeline (request id, path normalisation, content negotiation, authentication, response signing).
Package httpapi is the HTTP face of the service: the ogen handler (thin: extract params, call one scenario, translate the outcome), JSON:API rendering, the error mapping and the full middleware pipeline (request id, path normalisation, content negotiation, authentication, response signing).
infra/portal
Package portal serves the standalone customer portal, outside the public JSON:API middleware.
Package portal serves the standalone customer portal, outside the public JSON:API middleware.
infra/postgres
The full licenses repository: rows with their policy and owner context, the filtered index, the relationship rows and the actions' writes (internal/app/licenses).
The full licenses repository: rows with their policy and owner context, the filtered index, the relationship rows and the actions' writes (internal/app/licenses).
infra/render
License, machine, license-user/license-entitlement and license-file documents (the reference's LicenseSerializer, MachineSerializer, LicenseUserSerializer, LicenseEntitlementSerializer and LicenseFileSerializer).
License, machine, license-user/license-entitlement and license-file documents (the reference's LicenseSerializer, MachineSerializer, LicenseUserSerializer, LicenseEntitlementSerializer and LicenseFileSerializer).
infra/webhook
Package webhook implements pg-outbox delivery: signed HTTP POSTs with Keygen's outcome classification, URL checks and auto-disable rules.
Package webhook implements pg-outbox delivery: signed HTTP POSTs with Keygen's outcome classification, URL checks and auto-disable rules.
oas
Code generated by ogen, DO NOT EDIT.
Code generated by ogen, DO NOT EDIT.
service
Package service is the composition root: it wires the configuration, the dependencies (PostgreSQL, Valkey) and the scenarios into the tree the Backplane SDK runs.
Package service is the composition root: it wires the configuration, the dependencies (PostgreSQL, Valkey) and the scenarios into the tree the Backplane SDK runs.
testkit
Package testkit holds the helpers tests share: creating the bootstrap admin user and her token directly in the database.
Package testkit holds the helpers tests share: creating the bootstrap admin user and her token directly in the database.
ui
Package ui carries the console module built by make web.
Package ui carries the console module built by make web.
pkg
licensing
Package licensing is an idiomatic Go client for the Keygen licensing API (https://keygen.sh), working both against Keygen CE/EE and any 1:1 compatible implementation.
Package licensing is an idiomatic Go client for the Keygen licensing API (https://keygen.sh), working both against Keygen CE/EE and any 1:1 compatible implementation.
licensing/installation
Package installation manages license-bound installation keys and
Package installation manages license-bound installation keys and
licensing/internal/jsonapi
Package jsonapi is the licensing client's private JSON:API transport: the document envelope, request encoding, and response decoding into the client's typed structs.
Package jsonapi is the licensing client's private JSON:API transport: the document envelope, request encoding, and response decoding into the client's typed structs.
licensing/lictest
Package lictest runs a real backplane-lic server inside a test's process, for integration tests of what uses the licensing API: the server's own HTTP handler on a loopback port, over a PostgreSQL the caller provides (migrated on start), in an account of its own, so tests share one database and run in parallel.
Package lictest runs a real backplane-lic server inside a test's process, for integration tests of what uses the licensing API: the server's own HTTP handler on a loopback port, over a PostgreSQL the caller provides (migrated on start), in an account of its own, so tests share one database and run in parallel.
licensing/request
Package request signs and verifies HTTP requests with RFC 9421 HTTP Message Signatures (Ed25519).
Package request signs and verifies HTTP requests with RFC 9421 HTTP Message Signatures (Ed25519).
licensing/usage
Package usage implements a signed hash chain for usage journals.
Package usage implements a signed hash chain for usage journals.
proto
test
conformance
Package conformance provides a differential test harness that replays HTTP scenarios against a Keygen CE-compatible server, records normalised golden transcripts from the live Keygen CE reference, and diffs live runs against them.
Package conformance provides a differential test harness that replays HTTP scenarios against a Keygen CE-compatible server, records normalised golden transcripts from the live Keygen CE reference, and diffs live runs against them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL