File: license.go

package info (click to toggle)
golang-github-minio-pkg 3.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,500 kB
  • sloc: xml: 37; makefile: 35; asm: 22
file content (233 lines) | stat: -rw-r--r-- 7,253 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package subnet

import (
	"context"
	"crypto/tls"
	"fmt"
	"net"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/lestrrat-go/jwx/v2/jwt"
	"github.com/minio/pkg/v3/licverifier"
)

const (
	publicKeyPath = "/downloads/license-pubkey.pem"

	// https://subnet.min.io/downloads/license-pubkey.pem
	publicKeyProd = `-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEaK31xujr6/rZ7ZfXZh3SlwovjC+X8wGq
qkltaKyTLRENd4w3IRktYYCRgzpDLPn/nrf7snV/ERO5qcI7fkEES34IVEr+2Uff
JkO2PfyyAYEO/5dBlPh1Undu9WQl6J7B
-----END PUBLIC KEY-----`
	// https://localhost:9000/downloads/license-pubkey.pem
	publicKeyDev = `-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEbo+e1wpBY4tBq9AONKww3Kq7m6QP/TBQ
mr/cKCUyBL7rcAvg0zNq1vcSrUSGlAmY3SEDCu3GOKnjG/U4E7+p957ocWSV+mQU
9NKlTdQFGF3+aO6jbQ4hX/S5qPyF+a3z
-----END PUBLIC KEY-----`
)

// LicenseValidator validates the MinIO license.
type LicenseValidator struct {
	Client            http.Client
	LicenseFilePath   string
	pubKeyURL         string
	offlinePubKey     []byte
	LicenseToken      string
	ExpiryGracePeriod time.Duration
}

// LicenseValidatorParams holds parameters for creating a new LicenseValidator.
type LicenseValidatorParams struct {
	TLSClientConfig   *tls.Config
	LicenseFilePath   string
	LicenseToken      string
	ExpiryGracePeriod time.Duration
	DevMode           bool
}

// BaseURL returns the base URL for subnet.
func BaseURL(devMode bool) string {
	if devMode {
		subnetURLDev := os.Getenv("SUBNET_URL_DEV")
		if len(subnetURLDev) > 0 {
			return subnetURLDev
		}
		return "http://localhost:9000"
	}

	return "https://subnet.min.io"
}

// NewLicenseValidator returns a new LicenseValidator using the provided tls client Config,
// and license file path. If the path is empty,  it will look for minio.license in the
// current working directory. If `devMode` is true, the validator will connect to locally
// running SUBNET instance to download the public key or use the bundled dev key.
func NewLicenseValidator(params LicenseValidatorParams) (*LicenseValidator, error) {
	licPath := params.LicenseFilePath
	licToken := params.LicenseToken
	if licToken == "" {
		licToken = os.Getenv("MINIO_LICENSE")
	}
	if licPath == "" && licToken == "" {
		// if license file path is not provided, and also
		// not set in env variable, expect it to be present
		// in the current working directory
		pwd, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		licPath = pwd + "/minio.license"
	}
	client := http.Client{
		Timeout: 0,
		Transport: &http.Transport{
			DialContext: (&net.Dialer{
				Timeout: 10 * time.Second,
			}).DialContext,
			Proxy:                 http.ProxyFromEnvironment,
			TLSClientConfig:       params.TLSClientConfig,
			IdleConnTimeout:       90 * time.Second,
			TLSHandshakeTimeout:   10 * time.Second,
			ExpectContinueTimeout: 10 * time.Second,
		},
	}
	lv := LicenseValidator{
		Client:            client,
		LicenseFilePath:   licPath,
		LicenseToken:      licToken,
		ExpiryGracePeriod: params.ExpiryGracePeriod,
	}
	lv.Init(params.DevMode)
	return &lv, nil
}

// Init initializes the LicenseValidator.
func (lv *LicenseValidator) Init(devMode bool) {
	lv.pubKeyURL = fmt.Sprintf("%s%s", BaseURL(devMode), publicKeyPath)
	lv.offlinePubKey = []byte(publicKeyProd)
	if devMode {
		lv.offlinePubKey = []byte(publicKeyDev)
	}
}

// ParseLicense parses the license with the public key and return it's information.
// Public key is downloaded from subnet. If there is an error downloading the public key
// it will use the bundled public key instead.
func (lv *LicenseValidator) ParseLicense(license string) (*licverifier.LicenseInfo, error) {
	lvr, e := licverifier.NewLicenseVerifier(lv.offlinePubKey)
	if e != nil {
		return nil, e
	}

	li, e := lvr.Verify(license, jwt.WithAcceptableSkew(lv.ExpiryGracePeriod))
	return &li, e
}

// ValidateLicense validates the license file.
func (lv *LicenseValidator) ValidateLicense() (*licverifier.LicenseInfo, error) {
	if lv.LicenseToken == "" && lv.LicenseFilePath == "" {
		return nil, fmt.Errorf("MinIO license not found")
	}

	if lv.LicenseToken == "" {
		licData, err := os.ReadFile(lv.LicenseFilePath)
		if err != nil {
			return nil, err
		}
		lv.LicenseToken = strings.TrimSpace(string(licData))
	}

	return lv.ParseLicense(lv.LicenseToken)
}

func getDurationForNextLicenseCheck(li *licverifier.LicenseInfo) time.Duration {
	if li.ExpiresAt.Before(time.Now()) {
		// expired, within grace period. schedule daily
		return time.Hour * 24
	}
	// not expired, schedule to check just after expiry
	return time.Until(li.ExpiresAt.Add(time.Second))
}

func (lv *LicenseValidator) scheduleNextLicenseCheck(li *licverifier.LicenseInfo, acceptedPlans []string, licExpiredChan chan<- string) {
	duration := getDurationForNextLicenseCheck(li)
	timer := time.NewTimer(duration)
	defer timer.Stop()

	ctxt := context.Background()
	for {
		select {
		case <-timer.C:
			li, err := lv.ValidateEnterpriseLicense(acceptedPlans, licExpiredChan)
			if err != nil {
				licExpiredChan <- err.Error()
				return
			}
			timer.Reset(getDurationForNextLicenseCheck(li))
		case <-ctxt.Done():
			return
		}
	}
}

// ValidateEnterpriseLicense validates the ENTERPRISE license file.
// Since there are multiple variants of ENTERPRISE licenses, ones
// accepted by the application can be passed as `acceptedPlans`.
// TRIAL licenses do not get grace period after expiry.
func (lv *LicenseValidator) ValidateEnterpriseLicense(acceptedPlans []string, licExpiredChan chan<- string) (*licverifier.LicenseInfo, error) {
	li, err := lv.ValidateLicense()
	if err != nil {
		return nil, err
	}

	accepted := false
	for _, plan := range acceptedPlans {
		if plan == li.Plan {
			accepted = true
			break
		}
	}
	if !accepted {
		return nil, fmt.Errorf("this software is only available for license plans %v", strings.Join(acceptedPlans, ", "))
	}

	if li.ExpiresAt.Before(time.Now()) {
		if li.IsTrial || li.Plan == "TRIAL" {
			// no grace period for trial
			return nil, fmt.Errorf("trial license has expired on %v", li.ExpiresAt)
		}
	}

	// validation successful. start a background routine to validate the license
	// - daily if already expired (within grace period)
	// - just after expiry if not expired
	if licExpiredChan != nil {
		// if the expiry channel is nil, it means client doesn't want to be notified
		// when license expires. In that case we don't schedule the background check.
		go lv.scheduleNextLicenseCheck(li, acceptedPlans, licExpiredChan)
	}

	return li, nil
}