mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
Licenses can now carry three agent runtime hour claims:
`agent_runtime_hours_allocation`, `agent_runtime_hours_limit_soft`, and
`agent_runtime_hours_limit_hard` (unit: hours). They surface as the new
usage-period feature `agent_runtime_hours` in `GET
/api/v2/entitlements`, where `limit` carries the allocation and the new
optional `soft_limit` / `hard_limit` fields on `codersdk.Feature` carry
the thresholds.
Invalid combinations reject the entire license via `validateClaims`
(both at upload and when computing entitlements for stored licenses):
soft/hard without allocation, negative allocation, soft outside `0 <=
soft < allocation`, or `hard < allocation`.
Soft and hard limits are not comparison inputs in `Feature.Compare`;
they ride along with whichever license wins (newest `iat`, existing
behavior). None of the three claim names is a feature name, so old
servers ignore them via the existing unknown-claim tolerance, protecting
rollout of licenses minted with the new claims.
The claim name constants defined in `enterprise/coderd/license` are the
canonical contract for `github.com/coder/license` (X1).
Part of
[CODAGT-837](https://linear.app/codercom/issue/CODAGT-837/a1-agent-runtime-license-claims-and-entitlement-feature).
Blocks B4 (usage wiring + warnings), C1 (hard-limit admission gate), F1
(licenses page), A4 (managed-agent coexistence), X1 (licensor).
Out of scope, handled by follow-up issues: `Actual` usage wiring,
threshold warnings, admission gating, premium defaults, and FE surfacing
beyond regenerated types.
<details>
<summary>Implementation plan and decision log</summary>
## Decisions (confirmed by jaayden, 2026-07-23)
1. **Claim names / unit:**
- `agent_runtime_hours_allocation` - allocation (unit: hours, int64)
- `agent_runtime_hours_limit_soft` - soft limit
- `agent_runtime_hours_limit_hard` - hard limit
- None of the three claim names is itself a `FeatureName`; all three map
to the single new usage-period feature `agent_runtime_hours`
(`FeatureAgentRuntimeHours`), mirroring how `managed_agent_limit_soft`
mapped onto `managed_agent_limit`. Old servers therefore ignore all
three claims via the `FeatureNamesMap` check.
2. **Reject-license.** Invalid claim combinations reject the whole
license via `validateClaims` (upload returns 400 via
`ParseClaimsIgnoreNbf`; already-stored licenses produce an `Invalid
license ... parsing claims` entitlements error and contribute nothing).
## Design notes
- `codersdk.Feature` had a `SoftLimit` field until 051ed34580 ("feat:
convert soft_limit to limit", #22048) collapsed managed-agent soft/hard
into a single `limit`. This reintroduces soft/hard as optional fields
without changing managed-agent behavior.
- Existing usage-period machinery populates `UsagePeriod` from
`nbf`/`exp` (`usagePeriodStart`/`usagePeriodEnd` in
`LicensesEntitlements`); reused unchanged, consistent with managed
agents.
- `Entitlements.AddFeature` replaces whole `Feature` structs (no
merging), so soft/hard automatically ride along with the winning
license. No `Feature.Compare` logic change; doc updates plus tests pin
that soft/hard are not comparison inputs.
- The feature name itself is not accepted as a claim; the allocation
must come from the dedicated claim so it is validated against soft/hard
(prevents a validation bypass where a direct feature-name claim could
win precedence with unvalidated thresholds).
- The generic "enabled but not entitled/expired" warning loop skips the
feature, mirroring `FeatureManagedAgentLimit`; usage-based warnings
arrive with B4.
- No premium default for this feature (unlike managed agents).
## Changes
1. `codersdk/deployment.go`: new `FeatureAgentRuntimeHours` (in
`FeatureNames`, `UsesLimit()`, `UsesUsagePeriod()`, keeping it out of
`FeatureSet` expansion); `Feature.SoftLimit`/`Feature.HardLimit`
(`soft_limit`/`hard_limit`, omitempty); doc updates for `UsagePeriod`
and `Compare`.
2. `enterprise/coderd/license/license.go`: canonical claim constants;
validation helper called from `validateClaims`; al-la-carte loop maps
the allocation claim to the feature and attaches soft/hard from the
companion claims; skips for the companion claims and the raw feature
name; generic warning loop skip.
3. `enterprise/coderd/coderdenttest`: `AgentRuntimeHours(allocation)`
builder.
4. Tests:
- `TestAgentRuntimeHoursLicenses`: entitled/grace round-trips (including
JSON field assertions), allocation-only, explicit zero,
`IssuedAtRanking` mirror, soft/hard ride-along with a newer
allocation-only license, direct feature-name claim ignored,
unknown-claims compatibility (old-server simulation).
- `TestAgentRuntimeHoursClaimValidation`: table of valid/invalid claim
combinations against `ParseClaims`, plus stored-license entitlements
error.
- `TestPostLicense`: API-level 400 rejection and a happy-path POST +
`GET /api/v2/entitlements` round-trip.
- `TestFeatureComparison`: soft/hard ignored in comparison; newest `iat`
wins over larger soft/hard.
5. `make gen`: regenerated `site/src/api/typesGenerated.ts`,
`coderd/apidoc/*`, `docs/reference/api/*`.
## Verification
- `go test ./enterprise/coderd/license/ ./codersdk/` and `go test
./enterprise/coderd/ -run 'TestPostLicense|TestEntitlements'` pass.
- `golangci-lint` clean on changed packages; `make lint/emdash` clean;
FE `tsc --noEmit` clean.
- Independent agent review of the diff found no blockers; its minor
findings (direct feature-name claim validation bypass, precedence test
gap, missing API happy-path test) were addressed.
</details>
> [!NOTE]
> Generated by Coder Agents on behalf of @jaaydenh (Linear CODAGT-837
agent session).
351 lines
12 KiB
Go
351 lines
12 KiB
Go
package coderd_test
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/database/dbtime"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/enterprise/coderd/coderdenttest"
|
|
"github.com/coder/coder/v2/enterprise/coderd/license"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
func TestPostLicense(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("Success", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
respLic := coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
AccountType: license.AccountTypeSalesforce,
|
|
AccountID: "testing",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
},
|
|
})
|
|
assert.GreaterOrEqual(t, respLic.ID, int32(0))
|
|
// just a couple spot checks for sanity
|
|
assert.Equal(t, "testing", respLic.Claims["account_id"])
|
|
features, err := respLic.FeaturesClaims()
|
|
require.NoError(t, err)
|
|
assert.EqualValues(t, 1, features[codersdk.FeatureAuditLog])
|
|
})
|
|
|
|
t.Run("InvalidDeploymentID", func(t *testing.T) {
|
|
t.Parallel()
|
|
// The generated deployment will start out with a different deployment ID.
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
license := coderdenttest.GenerateLicense(t, coderdenttest.LicenseOptions{
|
|
DeploymentIDs: []string{uuid.NewString()},
|
|
})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: license,
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
require.ErrorAs(t, err, &errResp)
|
|
require.Equal(t, http.StatusBadRequest, errResp.StatusCode())
|
|
require.Contains(t, errResp.Message, "License cannot be used on this deployment!")
|
|
})
|
|
|
|
t.Run("InvalidAccountID", func(t *testing.T) {
|
|
t.Parallel()
|
|
// The generated deployment will start out with a different deployment ID.
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
license := coderdenttest.GenerateLicense(t, coderdenttest.LicenseOptions{
|
|
AllowEmpty: true,
|
|
AccountID: "",
|
|
})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: license,
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
require.ErrorAs(t, err, &errResp)
|
|
require.Equal(t, http.StatusBadRequest, errResp.StatusCode())
|
|
require.Contains(t, errResp.Message, "Invalid license")
|
|
})
|
|
|
|
t.Run("InvalidAccountType", func(t *testing.T) {
|
|
t.Parallel()
|
|
// The generated deployment will start out with a different deployment ID.
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
license := coderdenttest.GenerateLicense(t, coderdenttest.LicenseOptions{
|
|
AllowEmpty: true,
|
|
AccountType: "",
|
|
})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: license,
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
require.ErrorAs(t, err, &errResp)
|
|
require.Equal(t, http.StatusBadRequest, errResp.StatusCode())
|
|
require.Contains(t, errResp.Message, "Invalid license")
|
|
})
|
|
|
|
t.Run("InvalidLicenseExpires", func(t *testing.T) {
|
|
t.Parallel()
|
|
// The generated deployment will start out with a different deployment ID.
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
license := coderdenttest.GenerateLicense(t, coderdenttest.LicenseOptions{
|
|
GraceAt: time.Unix(99999999999, 0),
|
|
})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: license,
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
require.ErrorAs(t, err, &errResp)
|
|
require.Equal(t, http.StatusBadRequest, errResp.StatusCode())
|
|
require.Contains(t, errResp.Message, "Invalid license")
|
|
})
|
|
|
|
t.Run("InvalidAgentRuntimeClaims", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
// A soft limit claim without an allocation claim rejects the whole
|
|
// license.
|
|
lic := coderdenttest.GenerateLicense(t, coderdenttest.LicenseOptions{
|
|
Features: license.Features{
|
|
license.ClaimAgentRuntimeHoursLimitSoft: 80,
|
|
},
|
|
})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: lic,
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
require.ErrorAs(t, err, &errResp)
|
|
require.Equal(t, http.StatusBadRequest, errResp.StatusCode())
|
|
require.Contains(t, errResp.Message, "Invalid license")
|
|
})
|
|
|
|
t.Run("AgentRuntimeClaims", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
Features: license.Features{
|
|
license.ClaimAgentRuntimeHoursAllocation: 100,
|
|
license.ClaimAgentRuntimeHoursLimitSoft: 80,
|
|
license.ClaimAgentRuntimeHoursLimitHard: 120,
|
|
},
|
|
})
|
|
// The claims round-trip through GET /api/v2/entitlements.
|
|
//nolint:gocritic // This test asserts license state, not authz behavior.
|
|
entitlements, err := client.Entitlements(context.Background())
|
|
require.NoError(t, err)
|
|
feature := entitlements.Features[codersdk.FeatureAgentRuntimeHours]
|
|
require.Equal(t, codersdk.EntitlementEntitled, feature.Entitlement)
|
|
require.True(t, feature.Enabled)
|
|
require.NotNil(t, feature.Limit)
|
|
require.EqualValues(t, 100, *feature.Limit)
|
|
require.NotNil(t, feature.SoftLimit)
|
|
require.EqualValues(t, 80, *feature.SoftLimit)
|
|
require.NotNil(t, feature.HardLimit)
|
|
require.EqualValues(t, 120, *feature.HardLimit)
|
|
require.NotNil(t, feature.UsagePeriod)
|
|
})
|
|
|
|
t.Run("Unauthorized", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
client.SetSessionToken("")
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: "content",
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
if xerrors.As(err, &errResp) {
|
|
assert.Equal(t, 401, errResp.StatusCode())
|
|
} else {
|
|
t.Error("expected to get error status 401")
|
|
}
|
|
})
|
|
|
|
t.Run("Corrupted", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: "invalid",
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
if xerrors.As(err, &errResp) {
|
|
assert.Equal(t, 400, errResp.StatusCode())
|
|
} else {
|
|
t.Error("expected to get error status 400")
|
|
}
|
|
})
|
|
|
|
// Test a license that isn't yet valid, but will be in the future. We should allow this so that
|
|
// operators can upload a license ahead of time.
|
|
t.Run("NotYet", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
respLic := coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
AccountType: license.AccountTypeSalesforce,
|
|
AccountID: "testing",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
},
|
|
NotBefore: dbtime.Now().Add(time.Hour),
|
|
GraceAt: time.Now().Add(2 * time.Hour),
|
|
ExpiresAt: time.Now().Add(3 * time.Hour),
|
|
})
|
|
assert.GreaterOrEqual(t, respLic.ID, int32(0))
|
|
// just a couple spot checks for sanity
|
|
assert.Equal(t, "testing", respLic.Claims["account_id"])
|
|
features, err := respLic.FeaturesClaims()
|
|
require.NoError(t, err)
|
|
assert.EqualValues(t, 1, features[codersdk.FeatureAuditLog])
|
|
})
|
|
|
|
// Test we still reject a license that isn't valid yet, but has other issues (e.g. expired
|
|
// before it starts).
|
|
t.Run("NotEver", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
lic := coderdenttest.GenerateLicense(t, coderdenttest.LicenseOptions{
|
|
AccountType: license.AccountTypeSalesforce,
|
|
AccountID: "testing",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
},
|
|
NotBefore: dbtime.Now().Add(time.Hour),
|
|
GraceAt: time.Now().Add(2 * time.Hour),
|
|
ExpiresAt: time.Now().Add(-time.Hour),
|
|
})
|
|
_, err := client.AddLicense(context.Background(), codersdk.AddLicenseRequest{
|
|
License: lic,
|
|
})
|
|
errResp := &codersdk.Error{}
|
|
require.ErrorAs(t, err, &errResp)
|
|
require.Equal(t, http.StatusBadRequest, errResp.StatusCode())
|
|
require.Contains(t, errResp.Detail, license.ErrMultipleIssues.Error())
|
|
})
|
|
}
|
|
|
|
func TestGetLicense(t *testing.T) {
|
|
t.Parallel()
|
|
t.Run("Success", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
|
|
defer cancel()
|
|
|
|
coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
AccountID: "testing",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
codersdk.FeatureSCIM: 1,
|
|
codersdk.FeatureBrowserOnly: 1,
|
|
codersdk.FeatureTemplateRBAC: 1,
|
|
},
|
|
})
|
|
|
|
coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
AccountID: "testing2",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
codersdk.FeatureSCIM: 1,
|
|
codersdk.FeatureBrowserOnly: 1,
|
|
codersdk.FeatureUserLimit: 200,
|
|
},
|
|
Trial: true,
|
|
})
|
|
|
|
licenses, err := client.Licenses(ctx)
|
|
require.NoError(t, err)
|
|
require.Len(t, licenses, 2)
|
|
assert.Equal(t, int32(1), licenses[0].ID)
|
|
assert.Equal(t, "testing", licenses[0].Claims["account_id"])
|
|
|
|
features, err := licenses[0].FeaturesClaims()
|
|
require.NoError(t, err)
|
|
assert.Equal(t, map[codersdk.FeatureName]int64{
|
|
codersdk.FeatureAuditLog: 1,
|
|
codersdk.FeatureSCIM: 1,
|
|
codersdk.FeatureBrowserOnly: 1,
|
|
codersdk.FeatureTemplateRBAC: 1,
|
|
}, features)
|
|
assert.Equal(t, int32(2), licenses[1].ID)
|
|
assert.Equal(t, "testing2", licenses[1].Claims["account_id"])
|
|
assert.Equal(t, true, licenses[1].Claims["trial"])
|
|
|
|
features, err = licenses[1].FeaturesClaims()
|
|
require.NoError(t, err)
|
|
assert.Equal(t, map[codersdk.FeatureName]int64{
|
|
codersdk.FeatureUserLimit: 200,
|
|
codersdk.FeatureAuditLog: 1,
|
|
codersdk.FeatureSCIM: 1,
|
|
codersdk.FeatureBrowserOnly: 1,
|
|
}, features)
|
|
})
|
|
}
|
|
|
|
func TestDeleteLicense(t *testing.T) {
|
|
t.Parallel()
|
|
t.Run("Empty", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
|
|
defer cancel()
|
|
|
|
err := client.DeleteLicense(ctx, 1)
|
|
errResp := &codersdk.Error{}
|
|
if xerrors.As(err, &errResp) {
|
|
assert.Equal(t, 404, errResp.StatusCode())
|
|
} else {
|
|
t.Error("expected to get error status 404")
|
|
}
|
|
})
|
|
|
|
t.Run("BadID", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
|
|
defer cancel()
|
|
|
|
//nolint:gocritic // RBAC is irrelevant here.
|
|
resp, err := client.Request(ctx, http.MethodDelete, "/api/v2/licenses/drivers", nil)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
|
|
require.NoError(t, resp.Body.Close())
|
|
})
|
|
|
|
t.Run("Success", func(t *testing.T) {
|
|
t.Parallel()
|
|
client, _ := coderdenttest.New(t, &coderdenttest.Options{DontAddLicense: true})
|
|
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
|
|
defer cancel()
|
|
|
|
coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
AccountID: "testing",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
},
|
|
})
|
|
coderdenttest.AddLicense(t, client, coderdenttest.LicenseOptions{
|
|
AccountID: "testing2",
|
|
Features: license.Features{
|
|
codersdk.FeatureAuditLog: 1,
|
|
codersdk.FeatureUserLimit: 200,
|
|
},
|
|
})
|
|
|
|
licenses, err := client.Licenses(ctx)
|
|
require.NoError(t, err)
|
|
assert.Len(t, licenses, 2)
|
|
for _, l := range licenses {
|
|
err = client.DeleteLicense(ctx, l.ID)
|
|
require.NoError(t, err)
|
|
}
|
|
licenses, err = client.Licenses(ctx)
|
|
require.NoError(t, err)
|
|
assert.Len(t, licenses, 0)
|
|
})
|
|
}
|