government / ratify / validity.go

@ b16190dee4ae781544f8119bec44f00f5224c810 | history


package ratify

import (
	"crypto/x509"
	"time"
)

// Window is when the program is in force: from the latest notBefore to
// the earliest notAfter. Each cert carries its own validity window and all
// are checked at once, so the program's window is their overlap. The
// returned depths are the certs that set each end.
func Window(certs []*x509.Certificate) (takesEffect, expires time.Time, startDepth, endDepth int) {
	for i, c := range certs {
		if c.NotBefore.After(certs[startDepth].NotBefore) {
			startDepth = i
		}
		if c.NotAfter.Before(certs[endDepth].NotAfter) {
			endDepth = i
		}
	}
	return certs[startDepth].NotBefore, certs[endDepth].NotAfter, startDepth, endDepth
}

// CheckValidity checks that at falls inside every cert's validity window.
// RFC 5280 counts both ends as inside the window.
func CheckValidity(certs []*x509.Certificate, at time.Time) error {
	if len(certs) == 0 {
		return nil
	}
	takesEffect, expires, start, end := Window(certs)
	if takesEffect.After(expires) {
		return errorf(ErrLapsed, "never in force: depth %d expires %s, before depth %d takes effect %s",
			end, stamp(expires), start, stamp(takesEffect))
	}
	if at.Before(takesEffect) {
		return errorf(ErrNotInForce, "takes effect %s (depth %d)", stamp(takesEffect), start)
	}
	if at.After(expires) {
		return errorf(ErrLapsed, "expired %s (depth %d)", stamp(expires), end)
	}
	return nil
}

func stamp(t time.Time) string {
	return t.UTC().Format(time.RFC3339)
}