istio.io/istio@v0.0.0-20240520182934-d79c90f27776/security/pkg/util/certutil.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package util 16 17 import ( 18 "fmt" 19 "time" 20 21 "istio.io/istio/security/pkg/pki/util" 22 ) 23 24 // CertUtil is an interface for utility functions on certificate. 25 type CertUtil interface { 26 // GetWaitTime returns the waiting time before renewing the certificate. 27 GetWaitTime([]byte, time.Time) (time.Duration, error) 28 } 29 30 // CertUtilImpl is the implementation of CertUtil, for production use. 31 type CertUtilImpl struct { 32 gracePeriodPercentage int 33 } 34 35 // NewCertUtil returns a new CertUtilImpl 36 func NewCertUtil(gracePeriodPercentage int) CertUtilImpl { 37 return CertUtilImpl{ 38 gracePeriodPercentage: gracePeriodPercentage, 39 } 40 } 41 42 // GetWaitTime returns the waiting time before renewing the cert, based on current time, the timestamps in cert and 43 // grace period. 44 func (cu CertUtilImpl) GetWaitTime(certBytes []byte, now time.Time) (time.Duration, error) { 45 cert, certErr := util.ParsePemEncodedCertificate(certBytes) 46 if certErr != nil { 47 return time.Duration(0), certErr 48 } 49 timeToExpire := cert.NotAfter.Sub(now) 50 if timeToExpire < 0 { 51 return time.Duration(0), fmt.Errorf("certificate already expired at %s, but now is %s", 52 cert.NotAfter, now) 53 } 54 // Note: multiply time.Duration(int64) by an int (gracePeriodPercentage) will cause overflow (e.g., 55 // when duration is time.Hour * 90000). So float64 is used instead. 56 gracePeriod := time.Duration(float64(cert.NotAfter.Sub(cert.NotBefore)) * (float64(cu.gracePeriodPercentage) / 100)) 57 // waitTime is the duration between now and the grace period starts. 58 // It is the time until cert expiration minus the length of grace period. 59 waitTime := timeToExpire - gracePeriod 60 if waitTime < 0 { 61 // We are within the grace period. 62 return time.Duration(0), fmt.Errorf("got a certificate that should be renewed now") 63 } 64 return waitTime, nil 65 }