mirror of
https://github.com/coder/coder.git
synced 2026-11-01 04:47:17 +08:00
**TLDR:** When someone using free Coder taps a "Start trial for free" button, we now write down which page they tapped it on, and whether they went on to actually start the trial. That tells us which locked features make people want Premium. ## Brief summary - Records two things: the button being clicked, and a trial actually being started. - Each click gets a random ID that travels with the person to the trial form, so we can tell who finished from who walked away. - Records a short label for the page (like `appearance` or `audit_log`), never the web address, so no customer names are collected. #28226 added the trial form and has since merged, so this now targets `main`. ## Description Today the "Start trial for free" button just moves you to the Premium page and nothing is recorded, so there is no way to know which feature convinced someone. This adds two events: | Event | Happens when | |---|---| | `cta_click` | Someone clicks "Start trial for free" | | `trial_signup` | A trial licence is actually issued | The click generates a random ID. It rides along to the trial form and gets saved on the signup, so a click and a signup can be matched up later. Clicks with no matching signup are the people who gave up. Trials started without a paywall (for example straight from the sidebar) are labelled `direct`, so "no label" never gets confused with "broken". A few small choices worth knowing: - The ID is kept in browser session storage, not in the web address, so the URL stays clean. It expires after 30 minutes. - The trial signup event is recorded by the server, not the browser, so nobody can fake a signup. - The browser cannot say which kind of event it is sending. It can only report a click; the server labels it. - Only people allowed to start a trial are counted. The server rejects the rest, which matters because a few paywalls show their button to everyone. - Nothing is recorded at all when telemetry is turned off. There is deliberately no "paywall was shown" event. Every admin page visit would report one, which is a lot of noise for little insight. Every paywall in the [Premium Copy Updates](https://www.notion.so/coderhq/Premium-Copy-Updates-3c1d579be59280a59557cabd54fd8a1f) table has a label. The rows that do not are badges and alerts with no button to click. ## Proof Ran a local Coder with no licence and clicked the paywall button on the Appearance page. What the browser sent, and the reply: ```json POST /api/v2/deployment/premium-funnel-events -> 204 No Content {"id":"92d96afa-f975-4789-b8a7-b1fd19d4df85","source":"appearance","variant":"premium"} ``` What the browser saved for the trial form, same ID: ```json {"id":"92d96afa-f975-4789-b8a7-b1fd19d4df85","source":"appearance","createdAt":1787268520857} ``` The click then landed on the Premium page with the trial form. Screenshots of the network panel, the saved value, and the Premium page are attached below. The form itself was not submitted, since that would contact the real licence server. ## Testing - Backend tests: a click is recorded with the server's own label, an unknown page label is refused, and a normal member is refused. - Storybook tests: button clicked and ID saved on all three paywall styles, plus the case where the viewer only sees guidance text and has nothing to click. - Unit tests for the saved ID: expiry, bad data, unknown page label, and the `direct` fallback. - `make gen` is clean, and lint, types, and formatting pass. Two stories fail on `main` today and fail the same way here: `ExternalAuthSettingsPageView > Page` and `PremiumPageView > No License`. Neither file is touched by this branch; both were verified failing on `main` with this branch checked out elsewhere. ## Follow-up coder/coder-telemetry-server#45 saves these events for reporting. It merges after this one. <details> <summary>Plan and decisions</summary> **Goal:** find out which Premium paywall drives trial signups, and tell abandons apart from completions. **Options considered and dropped:** 1. Put `?from=appearance` in the URL. Rejected: messy for users. 2. Use router state. Rejected: lost if the page is refreshed. 3. Let the browser report the signup. Rejected: it could be faked or lost during the redirect. 4. Work out the page from the URL. Rejected: URLs contain organization and template names. 5. Report every paywall impression. Rejected: one event per admin page visit is noise, and the click is the signal. 6. Separate event types and tables. Rejected: makes the matching query harder for no gain. **Event shape:** ```go type PremiumFunnelEvent struct { ID uuid.UUID // event ID; for a click this is also the matching ID EventType string // cta_click | trial_signup, set by the server Source string // appearance, audit_log, ..., direct Variant string // which paywall design was shown AttributionID uuid.UUID // the click this signup came from UserID uuid.UUID CreatedAt time.Time } ``` **Where the code lives:** nothing under `components/` imports from `modules/`, so the paywall components stay presentational and only gain an `onCTAClick` prop. New wrappers in `modules/paywall/` own the reporting, one per paywall style, each taking a fixed `source`. **Self-review:** the `frontend-review` skill caught that reading permissions inside the wrapper forced an auth context into presentational page views, which broke their stories. Every call site already passes `canViewPremium={permissions.viewAllLicenses}` and the button only renders when that is true, so the wrapper no longer reads permissions and the server stays the gate. It also flagged one unattributed paywall on the Security page, now wired up as `browser_only`. </details> > Generated with [Coder Agents](https://coder.com/agents) on behalf of @david-fraley
523 lines
16 KiB
Go
523 lines
16 KiB
Go
package coderd
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/ed25519"
|
|
"database/sql"
|
|
_ "embed"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd"
|
|
"github.com/coder/coder/v2/coderd/audit"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbtime"
|
|
"github.com/coder/coder/v2/coderd/httpapi"
|
|
"github.com/coder/coder/v2/coderd/httpmw"
|
|
"github.com/coder/coder/v2/coderd/rbac"
|
|
"github.com/coder/coder/v2/coderd/rbac/policy"
|
|
"github.com/coder/coder/v2/coderd/telemetry"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/enterprise/coderd/license"
|
|
"github.com/coder/coder/v2/enterprise/trialer"
|
|
)
|
|
|
|
const (
|
|
// PubsubEventLicenses is the pubsub event that tells other replicas to
|
|
// re-read licenses from the database and recompute entitlements.
|
|
//
|
|
// It is published and subscribed on api.ReplicaSyncPubsub (always Postgres),
|
|
// not api.Pubsub. When the NATS pubsub experiment is enabled, api.Pubsub is
|
|
// the embedded NATS pubsub whose cluster mesh only forms once a replica is
|
|
// HA-licensed, so propagating license changes over it is circular: a fresh
|
|
// replica could not learn about the license that would let it join the mesh.
|
|
// ReplicaSyncPubsub is available as soon as the DB connection is, independent
|
|
// of clustering or licensing.
|
|
PubsubEventLicenses = "licenses"
|
|
)
|
|
|
|
// key20220812 is the Coder license public key with id 2022-08-12 used to validate licenses signed
|
|
// by our signing infrastructure
|
|
//
|
|
//go:embed keys/2022-08-12
|
|
var key20220812 []byte
|
|
|
|
var Keys = map[string]ed25519.PublicKey{"2022-08-12": ed25519.PublicKey(key20220812)}
|
|
|
|
// postLicense adds a new Enterprise license to the cluster. We allow multiple different licenses
|
|
// in the cluster at one time for several reasons:
|
|
//
|
|
// 1. Upgrades --- if the license format changes from one version of Coder to the next, during a
|
|
// rolling update you will have different Coder servers that need different licenses to function.
|
|
// 2. Avoid abrupt feature breakage --- when an admin uploads a new license with different features
|
|
// we generally don't want the old features to immediately break without warning. With a grace
|
|
// period on the license, features will continue to work from the old license until its grace
|
|
// period, then the users will get a warning allowing them to gracefully stop using the feature.
|
|
//
|
|
// @Summary Add new license
|
|
// @ID add-new-license
|
|
// @Security CoderSessionToken
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Tags Enterprise
|
|
// @Param request body codersdk.AddLicenseRequest true "Add license request"
|
|
// @Success 201 {object} codersdk.License
|
|
// @Router /api/v2/licenses [post]
|
|
func (api *API) postLicense(rw http.ResponseWriter, r *http.Request) {
|
|
var (
|
|
ctx = r.Context()
|
|
auditor = api.AGPL.Auditor.Load()
|
|
aReq, commitAudit = audit.InitRequest[database.License](rw, &audit.RequestParams{
|
|
Audit: *auditor,
|
|
Log: api.Logger,
|
|
Request: r,
|
|
Action: database.AuditActionCreate,
|
|
})
|
|
)
|
|
defer commitAudit()
|
|
|
|
if !api.Authorize(r, policy.ActionCreate, rbac.ResourceLicense) {
|
|
httpapi.Forbidden(rw)
|
|
return
|
|
}
|
|
|
|
var addLicense codersdk.AddLicenseRequest
|
|
if !httpapi.Read(ctx, rw, r, &addLicense) {
|
|
return
|
|
}
|
|
|
|
claims, err := license.ParseClaimsIgnoreNbf(addLicense.License, api.LicenseKeys)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "Invalid license",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
if len(claims.DeploymentIDs) > 0 && !slices.Contains(claims.DeploymentIDs, api.AGPL.DeploymentID) {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "License cannot be used on this deployment!",
|
|
Detail: fmt.Sprintf("The provided license is locked to the following deployments: %q. "+
|
|
"Your deployment identifier is %q. Please contact sales.", claims.DeploymentIDs, api.AGPL.DeploymentID),
|
|
})
|
|
return
|
|
}
|
|
|
|
lic, err := api.installLicense(ctx, aReq, addLicense.License, claims)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Failed to install license",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
httpapi.Write(ctx, rw, http.StatusCreated, lic)
|
|
}
|
|
|
|
// @Summary Request a trial license
|
|
// @ID request-a-trial-license
|
|
// @Security CoderSessionToken
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Tags Enterprise
|
|
// @Param request body codersdk.CreateTrialLicenseRequest true "Trial license request"
|
|
// @Success 201 {object} codersdk.License
|
|
// @Router /api/v2/licenses/trial [post]
|
|
func (api *API) postTrialLicense(rw http.ResponseWriter, r *http.Request) {
|
|
var (
|
|
ctx = r.Context()
|
|
auditor = api.AGPL.Auditor.Load()
|
|
aReq, commitAudit = audit.InitRequest[database.License](rw, &audit.RequestParams{
|
|
Audit: *auditor,
|
|
Log: api.Logger,
|
|
Request: r,
|
|
Action: database.AuditActionCreate,
|
|
})
|
|
)
|
|
defer commitAudit()
|
|
|
|
if !api.Authorize(r, policy.ActionCreate, rbac.ResourceLicense) {
|
|
httpapi.Forbidden(rw)
|
|
return
|
|
}
|
|
|
|
var req codersdk.CreateTrialLicenseRequest
|
|
if !httpapi.Read(ctx, rw, r, &req) {
|
|
return
|
|
}
|
|
|
|
// Prevent overwriting existing license
|
|
if api.Entitlements.HasLicense() {
|
|
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
|
Message: "This deployment already has a license.",
|
|
Detail: "Remove the existing license before requesting a trial.",
|
|
})
|
|
return
|
|
}
|
|
|
|
rawLicense, err := api.trialer.Request(ctx, codersdk.LicensorTrialRequest{
|
|
DeploymentID: api.AGPL.DeploymentID,
|
|
Email: req.Email,
|
|
FirstName: req.FirstName,
|
|
LastName: req.LastName,
|
|
PhoneNumber: req.PhoneNumber,
|
|
JobTitle: req.JobTitle,
|
|
CompanyName: req.CompanyName,
|
|
Country: req.Country,
|
|
Developers: req.Developers,
|
|
})
|
|
if err != nil {
|
|
if licensorErr, ok := errors.AsType[*trialer.LicensorError](err); ok {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "Unable to issue a trial license.",
|
|
Detail: licensorErr.Message,
|
|
})
|
|
return
|
|
}
|
|
httpapi.Write(ctx, rw, http.StatusBadGateway, codersdk.Response{
|
|
Message: "Failed to reach the Coder license server.",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
// The deployment ID was supplied by us, so unlike postLicense there is no
|
|
// need to check the license against claims.DeploymentIDs.
|
|
claims, err := license.ParseClaimsIgnoreNbf(rawLicense, api.LicenseKeys)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusBadGateway, codersdk.Response{
|
|
Message: "The Coder license server returned an invalid license.",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
lic, err := api.installLicense(ctx, aReq, rawLicense, claims)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Failed to install license",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
// Reported here rather than from the browser so that a conversion is only
|
|
// counted when a license was actually issued.
|
|
source := req.Source
|
|
if !source.Valid() {
|
|
source = codersdk.PremiumFunnelSourceDirect
|
|
}
|
|
api.Telemetry.Report(&telemetry.Snapshot{
|
|
PremiumFunnelEvents: []telemetry.PremiumFunnelEvent{
|
|
{
|
|
ID: uuid.New(),
|
|
EventType: telemetry.PremiumFunnelEventTrialSignup,
|
|
Source: string(source),
|
|
AttributionID: req.AttributionID,
|
|
UserID: httpmw.APIKey(r).UserID,
|
|
CreatedAt: dbtime.Now(),
|
|
},
|
|
},
|
|
})
|
|
|
|
httpapi.Write(ctx, rw, http.StatusCreated, lic)
|
|
}
|
|
|
|
// installLicense persists a parsed license and brings the deployment up to date
|
|
// with it: the row is recorded on the audit request, entitlements are recomputed
|
|
// so the caller's response reflects the new features, and other replicas are
|
|
// told to recompute their own.
|
|
//
|
|
// Entitlements are refreshed here rather than through postRefreshEntitlements
|
|
// because that path is rate limited and would reject a refresh immediately after
|
|
// a license lands.
|
|
//
|
|
// Every failure is a server-side fault; callers should map a non-nil error to a
|
|
// 500.
|
|
func (api *API) installLicense(
|
|
ctx context.Context,
|
|
aReq *audit.Request[database.License],
|
|
rawLicense string,
|
|
claims *license.Claims,
|
|
) (codersdk.License, error) {
|
|
id, err := uuid.Parse(claims.ID)
|
|
if err != nil {
|
|
// See postLicense: licenses are not guaranteed to carry a uuid.
|
|
id = uuid.New()
|
|
}
|
|
|
|
dl, err := api.Database.InsertLicense(ctx, database.InsertLicenseParams{
|
|
UploadedAt: dbtime.Now(),
|
|
JWT: rawLicense,
|
|
Exp: claims.ExpiresAt.Time,
|
|
UUID: id,
|
|
})
|
|
if err != nil {
|
|
return codersdk.License{}, xerrors.Errorf("add license to database: %w", err)
|
|
}
|
|
aReq.New = dl
|
|
|
|
err = api.updateEntitlements(ctx)
|
|
if err != nil {
|
|
return codersdk.License{}, xerrors.Errorf("update entitlements: %w", err)
|
|
}
|
|
// Postgres pubsub; see PubsubEventLicenses.
|
|
err = api.ReplicaSyncPubsub.Publish(PubsubEventLicenses, []byte("add"))
|
|
if err != nil {
|
|
api.Logger.Error(context.Background(), "failed to publish license add", slog.Error(err))
|
|
// don't fail the HTTP request, since we did write it successfully to the database
|
|
}
|
|
|
|
c, err := decodeClaims(dl)
|
|
if err != nil {
|
|
return codersdk.License{}, xerrors.Errorf("decode database response: %w", err)
|
|
}
|
|
return convertLicense(dl, c), nil
|
|
}
|
|
|
|
// postRefreshEntitlements forces an `updateEntitlements` call and publishes
|
|
// a message to the PubsubEventLicenses topic to force other replicas
|
|
// to update their entitlements.
|
|
// Updates happen automatically on a timer, however that time is every 10 minutes,
|
|
// and we want to be able to force an update immediately in some cases.
|
|
//
|
|
// @Summary Update license entitlements
|
|
// @ID update-license-entitlements
|
|
// @Security CoderSessionToken
|
|
// @Produce json
|
|
// @Tags Enterprise
|
|
// @Success 201 {object} codersdk.Response
|
|
// @Router /api/v2/licenses/refresh-entitlements [post]
|
|
func (api *API) postRefreshEntitlements(rw http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
// If the user cannot create a new license, then they cannot refresh entitlements.
|
|
// Refreshing entitlements is a way to force a refresh of the license, so it is
|
|
// equivalent to creating a new license.
|
|
if !api.Authorize(r, policy.ActionCreate, rbac.ResourceLicense) {
|
|
httpapi.Forbidden(rw)
|
|
return
|
|
}
|
|
|
|
// Prevent abuse by limiting how often we allow a forced refresh.
|
|
now := time.Now()
|
|
if ok, wait := api.Entitlements.AllowRefresh(now); !ok {
|
|
rw.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())))
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: fmt.Sprintf("Entitlements already recently refreshed, please wait %d seconds to force a new refresh", int(wait.Seconds())),
|
|
})
|
|
return
|
|
}
|
|
|
|
err := api.replicaManager.UpdateNow(ctx)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Failed to sync replicas",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
err = api.refreshEntitlements(ctx)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Failed to refresh entitlements",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{
|
|
Message: "Entitlements updated",
|
|
})
|
|
}
|
|
|
|
func (api *API) refreshEntitlements(ctx context.Context) error {
|
|
api.Logger.Info(ctx, "refresh entitlements now")
|
|
|
|
err := api.updateEntitlements(ctx)
|
|
if err != nil {
|
|
return xerrors.Errorf("failed to update entitlements: %w", err)
|
|
}
|
|
// Postgres pubsub; see PubsubEventLicenses.
|
|
err = api.ReplicaSyncPubsub.Publish(PubsubEventLicenses, []byte("refresh"))
|
|
if err != nil {
|
|
api.Logger.Error(ctx, "failed to publish forced entitlement update", slog.Error(err))
|
|
return xerrors.Errorf("failed to publish forced entitlement update, other replicas might not be updated: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// @Summary Get licenses
|
|
// @ID get-licenses
|
|
// @Security CoderSessionToken
|
|
// @Produce json
|
|
// @Tags Enterprise
|
|
// @Success 200 {array} codersdk.License
|
|
// @Router /api/v2/licenses [get]
|
|
func (api *API) licenses(rw http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
licenses, err := api.Database.GetLicenses(ctx)
|
|
if xerrors.Is(err, sql.ErrNoRows) {
|
|
httpapi.Write(ctx, rw, http.StatusOK, []codersdk.License{})
|
|
return
|
|
}
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Internal error fetching licenses.",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
licenses, err = coderd.AuthorizeFilter(api.AGPL.HTTPAuth, r, policy.ActionRead, licenses)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Internal error fetching licenses.",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
sdkLicenses, err := convertLicenses(licenses)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Internal error parsing licenses.",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
httpapi.Write(ctx, rw, http.StatusOK, sdkLicenses)
|
|
}
|
|
|
|
// @Summary Delete license
|
|
// @ID delete-license
|
|
// @Security CoderSessionToken
|
|
// @Produce json
|
|
// @Tags Enterprise
|
|
// @Param id path string true "License ID" format(number)
|
|
// @Success 200
|
|
// @Router /api/v2/licenses/{id} [delete]
|
|
func (api *API) deleteLicense(rw http.ResponseWriter, r *http.Request) {
|
|
var (
|
|
ctx = r.Context()
|
|
auditor = api.AGPL.Auditor.Load()
|
|
)
|
|
|
|
idStr := chi.URLParam(r, "id")
|
|
id, err := strconv.ParseInt(idStr, 10, 32)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
|
|
Message: "License ID must be an integer",
|
|
})
|
|
return
|
|
}
|
|
|
|
dl, err := api.Database.GetLicenseByID(ctx, int32(id))
|
|
if err != nil {
|
|
// don't fail the HTTP request simply because we cannot audit
|
|
api.Logger.Warn(context.Background(), "could not retrieve license; cannot audit", slog.Error(err))
|
|
}
|
|
|
|
aReq, commitAudit := audit.InitRequest[database.License](rw, &audit.RequestParams{
|
|
Audit: *auditor,
|
|
Log: api.Logger,
|
|
Request: r,
|
|
Action: database.AuditActionDelete,
|
|
})
|
|
defer commitAudit()
|
|
aReq.Old = dl
|
|
|
|
if !api.Authorize(r, policy.ActionDelete, rbac.ResourceLicense) {
|
|
httpapi.Forbidden(rw)
|
|
return
|
|
}
|
|
|
|
_, err = api.Database.DeleteLicense(ctx, int32(id))
|
|
if httpapi.Is404Error(err) {
|
|
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
|
|
Message: "Unknown license ID",
|
|
})
|
|
return
|
|
}
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Internal error deleting license",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
err = api.updateEntitlements(ctx)
|
|
if err != nil {
|
|
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Failed to update entitlements",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
// Postgres pubsub; see PubsubEventLicenses.
|
|
err = api.ReplicaSyncPubsub.Publish(PubsubEventLicenses, []byte("delete"))
|
|
if err != nil {
|
|
api.Logger.Error(context.Background(), "failed to publish license delete", slog.Error(err))
|
|
// don't fail the HTTP request, since we did write it successfully to the database
|
|
}
|
|
rw.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func convertLicense(dl database.License, c jwt.MapClaims) codersdk.License {
|
|
return codersdk.License{
|
|
ID: dl.ID,
|
|
UUID: dl.UUID,
|
|
UploadedAt: dl.UploadedAt,
|
|
Claims: c,
|
|
}
|
|
}
|
|
|
|
func convertLicenses(licenses []database.License) ([]codersdk.License, error) {
|
|
out := make([]codersdk.License, 0, len(licenses))
|
|
for _, l := range licenses {
|
|
c, err := decodeClaims(l)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, convertLicense(l, c))
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// decodeClaims decodes the JWT claims from the stored JWT. Note here we do not validate the JWT
|
|
// and just return the claims verbatim. We want to include all licenses on the GET response, even
|
|
// if they are expired, or signed by a key this version of Coder no longer considers valid.
|
|
//
|
|
// Also, we do not return the whole JWT itself because a signed JWT is a bearer token and we
|
|
// want to limit the chance of it being accidentally leaked.
|
|
func decodeClaims(l database.License) (jwt.MapClaims, error) {
|
|
parts := strings.Split(l.JWT, ".")
|
|
if len(parts) != 3 {
|
|
return nil, xerrors.Errorf("Unable to parse license %d as JWT", l.ID)
|
|
}
|
|
cb, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("Unable to decode license %d claims: %w", l.ID, err)
|
|
}
|
|
c := make(jwt.MapClaims)
|
|
d := json.NewDecoder(bytes.NewBuffer(cb))
|
|
d.UseNumber()
|
|
err = d.Decode(&c)
|
|
return c, err
|
|
}
|