Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: completed license service
=44bbfc080eaa
diff --git a/backend-go/cmd/infisical/main.go b/backend-go/cmd/infisical/main.goindex 7522cb506a..b690bb9baa 100644--- a/backend-go/cmd/infisical/main.go+++ b/backend-go/cmd/infisical/main.go@@ -52,7 +52,8 @@ func main() {dbReport := bootstrap.CheckDBConnection(ctx, db)dbReport.PrintReport(logger)- svc, err := services.NewRegistry(logger, db, shared.SharedServicesDeps{+ svc, err := services.NewRegistry(ctx, logger, db, shared.SharedServicesDeps{+ Logger: logger,Config: cfg,DB: db,})diff --git a/backend-go/internal/services/services.go b/backend-go/internal/services/services.goindex a5f8f7280f..d106e357ab 100644--- a/backend-go/internal/services/services.go+++ b/backend-go/internal/services/services.go@@ -1,6 +1,7 @@package servicesimport (+ "context""fmt""log/slog"@@ -16,8 +17,8 @@ type Registry struct {Libs *shared.SharedServices}-func NewRegistry(logger *slog.Logger, db pg.DB, sharedDeps shared.SharedServicesDeps) (*Registry, error) {- sharedLibs, err := shared.NewSharedServices(sharedDeps)+func NewRegistry(ctx context.Context, logger *slog.Logger, db pg.DB, sharedDeps shared.SharedServicesDeps) (*Registry, error) {+ sharedLibs, err := shared.NewSharedServices(ctx, sharedDeps)if err != nil {return nil, fmt.Errorf("shared services: %w", err)}diff --git a/backend-go/internal/services/shared/libs.go b/backend-go/internal/services/shared/libs.goindex f27cfdf2f9..0c761b9e06 100644--- a/backend-go/internal/services/shared/libs.go+++ b/backend-go/internal/services/shared/libs.go@@ -1,17 +1,21 @@package sharedimport (+ "context""fmt"+ "log/slog""github.com/infisical/api/internal/config""github.com/infisical/api/internal/database/pg""github.com/infisical/api/internal/keystore""github.com/infisical/api/internal/services/shared/kms"+ "github.com/infisical/api/internal/services/shared/license""github.com/infisical/api/internal/services/shared/permission")// SharedServicesDeps holds the external dependencies needed to construct shared services.type SharedServicesDeps struct {+ Logger *slog.LoggerConfig *config.ConfigDB pg.DB // primary DB connection (writes)HSM kms.HsmService // nil when HSM is not configured@@ -22,9 +26,10 @@ type SharedServices struct {Config *config.ConfigPermission *permission.SharedServiceKMS *kms.SharedService+ License *license.SharedService}-func NewSharedServices(deps SharedServicesDeps) (*SharedServices, error) {+func NewSharedServices(ctx context.Context, deps SharedServicesDeps) (*SharedServices, error) {permissionDAL := permission.NewDAL()kmsDAL := kms.NewDAL(deps.DB, deps.KeyStore)@@ -33,9 +38,13 @@ func NewSharedServices(deps SharedServicesDeps) (*SharedServices, error) {return nil, fmt.Errorf("kms: %w", err)}+ licenseDAL := license.NewDAL(deps.DB)+ licenseSvc := license.NewSharedService(ctx, deps.Logger, deps.Config, deps.KeyStore, licenseDAL)+return &SharedServices{Config: deps.Config,Permission: permission.NewSharedService(permissionDAL),KMS: kmsSvc,+ License: licenseSvc,}, nil}diff --git a/backend-go/internal/services/shared/license/dal.go b/backend-go/internal/services/shared/license/dal.gonew file mode 100644index 0000000000..374cab0588--- /dev/null+++ b/backend-go/internal/services/shared/license/dal.go@@ -0,0 +1,65 @@+package license++import (+ "context"+ "database/sql"++ "github.com/go-jet/jet/v2/postgres"+ "github.com/go-jet/jet/v2/qrm"++ "github.com/infisical/api/internal/database/pg"+ "github.com/infisical/api/internal/database/pg/gen/table"+)++type orgRow struct {+ ID string `alias:"organizations.id"`+ CustomerID sql.NullString `alias:"organizations.customerId"`+ RootOrgID sql.NullString `alias:"organizations.rootOrgId"`+}++type DAL struct {+ db pg.DB+}++func NewDAL(db pg.DB) *DAL {+ return &DAL{db: db}+}++// FindRootOrgDetails resolves the root org for the given orgID and returns its customer ID.+// If the org has a rootOrgId, the root org is returned instead.+func (d *DAL) FindRootOrgDetails(ctx context.Context, orgID string) (*orgRow, error) {+ o := table.Organizations++ // First fetch the org to check if it has a rootOrgId.+ stmt := postgres.SELECT(o.ID, o.CustomerId, o.RootOrgId).+ FROM(o).+ WHERE(o.ID.EQ(postgres.String(orgID)))++ var row orgRow+ err := stmt.QueryContext(ctx, d.db.Primary(), &row)+ if err != nil {+ if err == qrm.ErrNoRows {+ return nil, nil+ }+ return nil, err+ }++ // If the org has a root org, resolve it.+ if row.RootOrgID.Valid && row.RootOrgID.String != "" && row.RootOrgID.String != row.ID {+ rootStmt := postgres.SELECT(o.ID, o.CustomerId, o.RootOrgId).+ FROM(o).+ WHERE(o.ID.EQ(postgres.String(row.RootOrgID.String)))++ var rootRow orgRow+ err := rootStmt.QueryContext(ctx, d.db.Primary(), &rootRow)+ if err != nil {+ if err == qrm.ErrNoRows {+ return nil, nil+ }+ return nil, err+ }+ return &rootRow, nil+ }++ return &row, nil+}diff --git a/backend-go/internal/services/shared/license/license.go b/backend-go/internal/services/shared/license/license.gonew file mode 100644index 0000000000..be8726295b--- /dev/null+++ b/backend-go/internal/services/shared/license/license.go@@ -0,0 +1,405 @@+package license++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "log/slog"+ "sync"+ "time"++ "github.com/go-resty/resty/v2"++ "github.com/infisical/api/internal/config"+)++const (+ cloudLoginPath = "/api/auth/v1/license-server-login"+ onPremLoginPath = "/api/auth/v1/license-login"++ cloudPlanTTL = 5 * time.Minute+ planCachePrefix = "infisical-cloud-plan-"+)++// keyStore is the narrow interface this service needs for caching.+type keyStore interface {+ GetItem(ctx context.Context, key string) (string, error)+ SetItemWithExpiry(ctx context.Context, key string, expiry time.Duration, value string) error+ DeleteItem(ctx context.Context, key string) (int64, error)+}++// dal is the narrow interface for org lookups needed by getPlan.+type dal interface {+ FindRootOrgDetails(ctx context.Context, orgID string) (*orgRow, error)+}++// licenseAPI wraps a resty client with token-based auth and auto-refresh.+type licenseAPI struct {+ client *resty.Client+ serverURL string+ loginPath string+ apiKey string+ mu sync.Mutex+}++func newLicenseAPI(serverURL, loginPath, apiKey, region string) *licenseAPI {+ api := &licenseAPI{+ serverURL: serverURL,+ loginPath: loginPath,+ apiKey: apiKey,+ }++ api.client = resty.New().+ SetBaseURL(serverURL).+ SetTimeout(35 * time.Second)++ if region != "" {+ api.client.SetHeader("x-region", region)+ }++ return api+}++// refreshToken authenticates with the license server and stores the token.+func (api *licenseAPI) refreshToken(ctx context.Context) (string, error) {+ api.mu.Lock()+ defer api.mu.Unlock()++ var result struct {+ Token string `json:"token"`+ }++ resp, err := resty.New().R().+ SetContext(ctx).+ SetHeader("X-API-KEY", api.apiKey).+ SetResult(&result).+ Post(api.serverURL + api.loginPath)+ if err != nil {+ return "", fmt.Errorf("license token refresh: %w", err)+ }+ if resp.IsError() {+ return "", fmt.Errorf("license token refresh: status %d", resp.StatusCode())+ }++ api.client.SetAuthToken(result.Token)+ return result.Token, nil+}++// get performs a GET with a single retry on 401/403 (token refresh).+func (api *licenseAPI) get(ctx context.Context, path string, result interface{}) error {+ resp, err := api.client.R().SetContext(ctx).SetResult(result).Get(path)+ if err != nil {+ return err+ }++ if resp.StatusCode() == 401 || resp.StatusCode() == 403 {+ if _, refreshErr := api.refreshToken(ctx); refreshErr != nil {+ return refreshErr+ }+ resp, err = api.client.R().SetContext(ctx).SetResult(result).Get(path)+ if err != nil {+ return err+ }+ }++ if resp.IsError() {+ return fmt.Errorf("license server GET %s: status %d", path, resp.StatusCode())+ }+ return nil+}++const syncInterval = 10 * time.Minute++// SharedService manages license validation and feature gating.+type SharedService struct {+ logger *slog.Logger+ instanceType InstanceType+ isValid bool+ onPremFeatures FeatureSet+ offlineLicense *OfflineLicenseInfo++ keyStore keyStore+ dal dal+ cloudAPI *licenseAPI+ onPremAPI *licenseAPI++ stopSync context.CancelFunc+}++func NewSharedService(ctx context.Context, logger *slog.Logger, cfg *config.Config, ks keyStore, d dal) *SharedService {+ svc := &SharedService{+ logger: logger.With("svc", "license"),+ onPremFeatures: DefaultFeatures(),+ keyStore: ks,+ dal: d,+ }++ serverURL := cfg.LicenseServerURL+ if serverURL == "" {+ serverURL = "https://portal.infisical.com"+ }++ svc.cloudAPI = newLicenseAPI(serverURL, cloudLoginPath, cfg.LicenseServerKey, "")+ svc.onPremAPI = newLicenseAPI(serverURL, onPremLoginPath, "", "")++ svc.init(ctx, cfg)+ svc.startBackgroundSync()+ return svc+}++func (s *SharedService) init(ctx context.Context, cfg *config.Config) {+ defer func() {+ if r := recover(); r != nil {+ s.logger.Error("panic during license init", "recover", r)+ }+ }()++ // 1. Cloud instance (LICENSE_SERVER_KEY is set).+ if cfg.LicenseServerKey != "" {+ token, err := s.cloudAPI.refreshToken(ctx)+ if err != nil {+ s.logger.Error("cloud license login failed", "error", err)+ s.isValid = true // allow OSS fallback+ return+ }+ if token != "" {+ s.instanceType = InstanceTypeCloud+ }+ s.logger.Info("license initialized", "instanceType", InstanceTypeCloud)+ s.isValid = true+ return+ }++ // Determine license key type.+ licenseKey, licenseType := detectLicenseKey(cfg)++ // 2. Online enterprise license.+ if licenseKey != "" && licenseType == OnlineLicenseType {+ s.onPremAPI.apiKey = licenseKey+ token, err := s.onPremAPI.refreshToken(ctx)+ if err != nil {+ s.logger.Error("on-prem license login failed", "error", err)+ s.isValid = true+ return+ }+ if token != "" {+ if err := s.syncOnPremFeatures(ctx); err != nil {+ s.logger.Error("initial on-prem feature sync failed", "error", err)+ }+ s.instanceType = InstanceTypeEnterpriseOnPrem+ s.logger.Info("license initialized", "instanceType", InstanceTypeEnterpriseOnPrem)+ s.isValid = true+ }+ return+ }++ // 3. Offline enterprise license.+ if licenseKey != "" && licenseType == OfflineLicenseType {+ if err := s.loadOfflineLicense(licenseKey); err != nil {+ s.logger.Warn("offline license validation failed", "error", err)+ } else {+ s.instanceType = InstanceTypeEnterpriseOnPremOffline+ s.logger.Info("license initialized", "instanceType", InstanceTypeEnterpriseOnPremOffline)+ s.isValid = true+ return+ }+ }++ // 4. Self-hosted OSS fallback.+ s.instanceType = InstanceTypeOnPrem+ s.isValid = true+ s.logger.Info("license initialized", "instanceType", InstanceTypeOnPrem)+}++// detectLicenseKey determines the license key and its type (online/offline).+func detectLicenseKey(cfg *config.Config) (key string, typ LicenseType) {+ raw := cfg.LicenseKey+ if raw == "" {+ raw = cfg.LicenseKeyOffline+ }+ if raw == "" {+ return "", ""+ }++ if isOfflineKey(raw) {+ return raw, OfflineLicenseType+ }+ return raw, OnlineLicenseType+}++// isOfflineKey checks if the key is base64-encoded JSON containing "signature" and "license".+func isOfflineKey(key string) bool {+ decoded, err := base64.StdEncoding.DecodeString(key)+ if err != nil {+ return false+ }+ var contents struct {+ Signature string `json:"signature"`+ License json.RawMessage `json:"license"`+ }+ if err := json.Unmarshal(decoded, &contents); err != nil {+ return false+ }+ return contents.Signature != "" && len(contents.License) > 0+}++// loadOfflineLicense decodes a base64 offline license, checks expiration, and loads features.+func (s *SharedService) loadOfflineLicense(key string) error {+ decoded, err := base64.StdEncoding.DecodeString(key)+ if err != nil {+ return fmt.Errorf("decoding offline license: %w", err)+ }++ var contents OfflineLicenseContents+ if err := json.Unmarshal(decoded, &contents); err != nil {+ return fmt.Errorf("parsing offline license: %w", err)+ }++ // TODO: verify RSA signature against embedded public key.++ // Check termination date.+ if contents.License.TerminatesAt != nil {+ terminatesAt, err := time.Parse(time.RFC3339, *contents.License.TerminatesAt)+ if err != nil {+ return fmt.Errorf("parsing terminatesAt: %w", err)+ }+ if time.Now().After(terminatesAt) {+ return fmt.Errorf("offline license expired at %s", terminatesAt)+ }+ }++ // Unmarshal features from the license.+ var features FeatureSet+ if err := json.Unmarshal(contents.License.Features, &features); err != nil {+ return fmt.Errorf("parsing offline license features: %w", err)+ }+ enterprise := "enterprise"+ features.Slug = &enterprise++ s.onPremFeatures = features+ s.offlineLicense = &contents.License+ return nil+}++// syncOnPremFeatures fetches the current plan from the on-prem license server.+func (s *SharedService) syncOnPremFeatures(ctx context.Context) error {+ var resp struct {+ CurrentPlan FeatureSet `json:"currentPlan"`+ }+ if err := s.onPremAPI.get(ctx, "/api/license/v1/plan", &resp); err != nil {+ return err+ }+ s.onPremFeatures = resp.CurrentPlan+ return nil+}++// GetPlan returns the feature set for a given organization.+// For cloud instances it uses Redis caching + license server API.+// For on-prem instances it returns the in-memory feature set.+func (s *SharedService) GetPlan(ctx context.Context, orgID string) (*FeatureSet, error) {+ if s.instanceType != InstanceTypeCloud {+ features := s.onPremFeatures+ return &features, nil+ }++ // Cloud path: check cache first.+ cacheKey := planCachePrefix + orgID+ cached, err := s.keyStore.GetItem(ctx, cacheKey)+ if err == nil && cached != "" {+ var plan FeatureSet+ if err := json.Unmarshal([]byte(cached), &plan); err == nil {+ return &plan, nil+ }+ }++ // Cache miss — fetch from license server.+ org, err := s.dal.FindRootOrgDetails(ctx, orgID)+ if err != nil {+ return s.fallbackPlan(ctx, cacheKey), nil+ }+ if org == nil || !org.CustomerID.Valid || org.CustomerID.String == "" {+ return s.fallbackPlan(ctx, cacheKey), nil+ }++ var resp struct {+ CurrentPlan FeatureSet `json:"currentPlan"`+ }+ endpoint := fmt.Sprintf("/api/license-server/v1/customers/%s/cloud-plan", org.CustomerID.String)+ if err := s.cloudAPI.get(ctx, endpoint, &resp); err != nil {+ s.logger.Error("failed to fetch cloud plan", "orgID", orgID, "error", err)+ return s.fallbackPlan(ctx, cacheKey), nil+ }++ plan := resp.CurrentPlan++ // Cache the result.+ if planJSON, err := json.Marshal(plan); err == nil {+ _ = s.keyStore.SetItemWithExpiry(ctx, cacheKey, cloudPlanTTL, string(planJSON))+ }++ return &plan, nil+}++// fallbackPlan caches and returns the default on-prem features when cloud fetch fails.+func (s *SharedService) fallbackPlan(ctx context.Context, cacheKey string) *FeatureSet {+ features := s.onPremFeatures+ if planJSON, err := json.Marshal(features); err == nil {+ _ = s.keyStore.SetItemWithExpiry(ctx, cacheKey, cloudPlanTTL, string(planJSON))+ }+ return &features+}++// RefreshPlan clears the cached plan for an org and re-fetches it.+func (s *SharedService) RefreshPlan(ctx context.Context, orgID string) error {+ cacheKey := planCachePrefix + orgID+ _, _ = s.keyStore.DeleteItem(ctx, cacheKey)++ if s.instanceType == InstanceTypeCloud {+ _, err := s.GetPlan(ctx, orgID)+ return err+ }+ if s.instanceType == InstanceTypeEnterpriseOnPrem {+ return s.syncOnPremFeatures(ctx)+ }+ return nil+}++// startBackgroundSync launches a goroutine that re-syncs on-prem features+// every 10 minutes. Only runs for online enterprise on-prem instances.+func (s *SharedService) startBackgroundSync() {+ if s.instanceType != InstanceTypeEnterpriseOnPrem {+ return+ }++ ctx, cancel := context.WithCancel(context.Background())+ s.stopSync = cancel++ s.logger.Info("starting background license sync", "interval", syncInterval)+ go func() {+ ticker := time.NewTicker(syncInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ s.logger.Info("background license sync stopped")+ return+ case <-ticker.C:+ if err := s.syncOnPremFeatures(ctx); err != nil {+ s.logger.Error("background license sync failed", "error", err)+ }+ }+ }+ }()+}++// Close stops the background sync goroutine if running.+func (s *SharedService) Close() {+ if s.stopSync != nil {+ s.stopSync()+ }+}++func (s *SharedService) GetInstanceType() InstanceType { return s.instanceType }+func (s *SharedService) IsValidLicense() bool { return s.isValid }diff --git a/backend-go/internal/services/shared/license/types.go b/backend-go/internal/services/shared/license/types.gonew file mode 100644index 0000000000..7dd39518ac--- /dev/null+++ b/backend-go/internal/services/shared/license/types.go@@ -0,0 +1,114 @@+package license++import "encoding/json"++type LicenseType string++const (+ OnlineLicenseType LicenseType = "online"+ OfflineLicenseType LicenseType = "offline"+)++type InstanceType string++const (+ InstanceTypeOnPrem InstanceType = "self-hosted"+ InstanceTypeEnterpriseOnPrem InstanceType = "enterprise-self-hosted"+ InstanceTypeEnterpriseOnPremOffline InstanceType = "enterprise-self-hosted-offline"+ InstanceTypeCloud InstanceType = "cloud"+)++type RateLimits struct {+ ReadLimit int `json:"readLimit"`+ WriteLimit int `json:"writeLimit"`+ SecretsLimit int `json:"secretsLimit"`+}++type FeatureSet struct {+ ID *string `json:"_id"`+ Slug *string `json:"slug"`+ Tier int `json:"tier"`+ WorkspaceLimit *int `json:"workspaceLimit"`+ WorkspacesUsed int `json:"workspacesUsed"`+ MemberLimit *int `json:"memberLimit"`+ MembersUsed int `json:"membersUsed"`+ IdentityLimit *int `json:"identityLimit"`+ IdentitiesUsed int `json:"identitiesUsed"`+ EnvironmentLimit *int `json:"environmentLimit"`+ EnvironmentsUsed int `json:"environmentsUsed"`+ DynamicSecret bool `json:"dynamicSecret"`+ SecretVersioning bool `json:"secretVersioning"`+ PitRecovery bool `json:"pitRecovery"`+ IPAllowlisting bool `json:"ipAllowlisting"`+ RBAC bool `json:"rbac"`+ CustomRateLimits bool `json:"customRateLimits"`+ CustomAlerts bool `json:"customAlerts"`+ AuditLogs bool `json:"auditLogs"`+ AuditLogsRetentionDays int `json:"auditLogsRetentionDays"`+ AuditLogStreams bool `json:"auditLogStreams"`+ AuditLogStreamLimit int `json:"auditLogStreamLimit"`+ GithubOrgSync bool `json:"githubOrgSync"`+ SamlSSO bool `json:"samlSSO"`+ EnforceGoogleSSO bool `json:"enforceGoogleSSO"`+ HSM bool `json:"hsm"`+ OidcSSO bool `json:"oidcSSO"`+ SecretAccessInsights bool `json:"secretAccessInsights"`+ SCIM bool `json:"scim"`+ LDAP bool `json:"ldap"`+ Groups bool `json:"groups"`+ SubOrganization bool `json:"subOrganization"`+ Status *string `json:"status"`+ TrialEnd *string `json:"trial_end"`+ HasUsedTrial bool `json:"has_used_trial"`+ SecretApproval bool `json:"secretApproval"`+ SecretRotation bool `json:"secretRotation"`+ CaCrl bool `json:"caCrl"`+ InstanceUserManagement bool `json:"instanceUserManagement"`+ ExternalKMS bool `json:"externalKms"`+ RateLimits RateLimits `json:"rateLimits"`+ PkiEst bool `json:"pkiEst"`+ PkiAcme bool `json:"pkiAcme"`+ EnforceMfa bool `json:"enforceMfa"`+ ProjectTemplates bool `json:"projectTemplates"`+ KMIP bool `json:"kmip"`+ Gateway bool `json:"gateway"`+ SSHHostGroups bool `json:"sshHostGroups"`+ SecretScanning bool `json:"secretScanning"`+ EnterpriseSecretSyncs bool `json:"enterpriseSecretSyncs"`+ EnterpriseCertificateSyncs bool `json:"enterpriseCertificateSyncs"`+ EnterpriseAppConnections bool `json:"enterpriseAppConnections"`+ MachineIdentityAuthTemplates bool `json:"machineIdentityAuthTemplates"`+ PkiLegacyTemplates bool `json:"pkiLegacyTemplates"`+ FIPS bool `json:"fips"`+ EventSubscriptions bool `json:"eventSubscriptions"`+ SecretShareExternalBranding bool `json:"secretShareExternalBranding"`+}++func DefaultFeatures() FeatureSet {+ return FeatureSet{+ Tier: -1,+ SecretVersioning: true,+ HasUsedTrial: true,+ AuditLogStreamLimit: 3,+ RateLimits: RateLimits{+ ReadLimit: 60,+ WriteLimit: 200,+ SecretsLimit: 40,+ },+ }+}++type OfflineLicenseContents struct {+ License OfflineLicenseInfo `json:"license"`+ Signature string `json:"signature"`+}++type OfflineLicenseInfo struct {+ IssuedTo string `json:"issuedTo"`+ LicenseID string `json:"licenseId"`+ CustomerID *string `json:"customerId"`+ IssuedAt string `json:"issuedAt"`+ ExpiresAt *string `json:"expiresAt"`+ TerminatesAt *string `json:"terminatesAt"`+ Features json.RawMessage `json:"features"`+}