sectigo

package
v0.0.0-...-0abef86 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 30, 2020 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package sectigo provides API access to the Sectigo IoT Manager 20.7, which is used to sign certificate requests for directory service certificate issuance.

Index

Constants

View Source
const (
	UsernameEnv = "SECTIGO_USERNAME"
	PasswordEnv = "SECTIGO_PASSWORD"
)

Environment variables that are loaded into credentials.

Variables

View Source
var (
	ErrNotAuthenticated     = errors.New("not authenticated")
	ErrCredentialsMismatch  = errors.New("requires both username and password")
	ErrTokensMismatch       = errors.New("both access and refresh tokens required")
	ErrNoCredentials        = errors.New("no API access credentials")
	ErrInvalidCredentials   = errors.New("could not authenticate credentials")
	ErrNotAuthorized        = errors.New("user is not authorized for this endpoint")
	ErrTokensExpired        = errors.New("access and refresh tokens have expired")
	ErrInvalidClaims        = errors.New("jwt claims do not have required timestamps")
	ErrMustUseTLSAuth       = errors.New("account requires TLS client authentication")
	ErrPKCSPasswordRequired = errors.New("pkcs12 password required for cert params")
)

Standard errors issued by the Sectigo client.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Status    int    `json:"status"`
	Message   string `json:"message"`
	ErrorCode int    `json:"errorCode"`
	Timestamp int    `json:"timestamp"`
}

APIError is unmarshalled from the JSON response of the Sectigo API and implements the error interface to correctly return error messages.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

type AuthenticationReply

type AuthenticationReply struct {
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken"`
}

AuthenticationReply received from both Authenticate and Refresh

type AuthenticationRequest

type AuthenticationRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

AuthenticationRequest to POST data to the authenticateEP

type AuthorityResponse

type AuthorityResponse struct {
	ID                  int    `json:"id"`
	EcosystemID         int    `json:"ecosystemId"`
	SignerCertificateID int    `json:"signerCertificateId"`
	EcosystemName       string `json:"ecosystemName"`
	Balance             int    `json:"balance"`
	Enabled             bool   `json:"enabled"`
	ProfileID           int    `json:"profileId"`
	ProfileName         string `json:"profileName"`
}

AuthorityResponse received from userAuthoritiesEP

type BatchResponse

type BatchResponse struct {
	BatchID         int         `json:"batchId"`
	OrderNumber     int         `json:"orderNumber"`
	CreationDate    string      `json:"creationDate"`
	Profile         string      `json:"profile"`
	Size            int         `json:"size"`
	Status          string      `json:"status"`
	Active          bool        `json:"active"`
	BatchName       string      `json:"batchName"`
	RejectReason    string      `json:"rejectReason"`
	GeneratorValues interface{} `json:"generatorParametersValues"`
	UserID          int         `json:"userId"`
	Downloadable    bool        `json:"downloadable"`
	Rejectable      bool        `json:"rejectable"`
}

BatchResponse received from createSingleCertBatchEP and batchDetailEP

type CRLReason

type CRLReason int

CRLReason specifies the RFC 5280 certificate revocation reason codes.

const (
	CRLRUnspecified          CRLReason = 0
	CRLRKeyCompromise        CRLReason = 1
	CRLRCACompromise         CRLReason = 2
	CRLRAffiliationChanged   CRLReason = 3
	CRLRSuperseded           CRLReason = 4
	CRLRCessationOfOperation CRLReason = 5
	CRLRCertificateHold      CRLReason = 6
	CRLRRemoveFromCRL        CRLReason = 8
	CRLRPrivilegeWithdrawn   CRLReason = 9
	CRLRAACompromise         CRLReason = 10
)

CRL reason codes for RFC 5280 certifcate revokation.

func RevokeReasonCode

func RevokeReasonCode(reason string) (code CRLReason, err error)

RevokeReasonCode translates a human readable string to a RFC 5280 reason code.

func (CRLReason) String

func (c CRLReason) String() string

type CreateSingleCertBatchRequest

type CreateSingleCertBatchRequest struct {
	AuthorityID   int               `json:"authorityId"`
	BatchName     string            `json:"batchName"`
	ProfileParams map[string]string `json:"profileParams"` // should not be empty; represents the profile-specific params passed to batch request
}

CreateSingleCertBatchRequest to POST data to the createSingleCertBatchEP

type Credentials

type Credentials struct {
	Username     string    `yaml:"-" json:"-"`              // Username is fetched from environment or supplied by user (not stored in cache)
	Password     string    `yaml:"-" json:"-"`              // Password is fetched from environment or supplied by user (not stored in cache)
	AccessToken  string    `yaml:"access_token,omitempty"`  // Temporary bearer token to authenticate API calls; issued on login. Expires after 10 minutes.
	RefreshToken string    `yaml:"refresh_token,omitempty"` // Temporary refresh token to acquire a new access token without reauthentication.
	Subject      string    `yaml:"subject,omitempty"`       // The account and user detail endpoint, e.g. /account/:id/user/:id
	IssuedAt     time.Time `yaml:"issued_at,omitempty"`     // The timestamp the tokens were issued at
	ExpiresAt    time.Time `yaml:"expires_at,omitempty"`    // When the access token expires and needs to be refreshed
	NotBefore    time.Time `yaml:"not_before,omitempty"`    // The earliest timestamp that tokens can be refreshed
	RefreshBy    time.Time `yaml:"refresh_by,omitempty"`    // The latest timestamp that tokens can be refreshed
	// contains filtered or unexported fields
}

Credentials stores login and authentication information to connect to the Sectigo API. Its primary purpose is to cache access and refresh tokens to prevent multiple logins accross different API commands and to store user authentication data or to fetch it from the environment. It also provides helper methods for determining when tokens are expired by reading the JWT data that has been returned.

func (*Credentials) CacheFile

func (creds *Credentials) CacheFile() string

CacheFile returns the path to the credentials cache if it exists.

func (*Credentials) Check

func (creds *Credentials) Check() (err error)

Check reteurns an error if the access and refresh tokens are expired, clearing the tokens from the struct. It does not raise an error if no tokens are available.

func (*Credentials) Clear

func (creds *Credentials) Clear()

Clear the access and refresh tokens and reset all timestamps.

func (*Credentials) Current

func (creds *Credentials) Current() bool

Current returns true if the refresh tokens are unexpired.

func (*Credentials) Dump

func (creds *Credentials) Dump() (path string, err error)

Dump the credentials to a local cache file, usually $HOME/.cache or $HOME/Library/Caches for a specific user.

func (*Credentials) Load

func (creds *Credentials) Load(username, password string) (err error)

Load initializes a Credentials object. If the username and password are specified, they are populated into the credentials, otherwise they are fetched from the $SECTIGO_USERNAME and $SECTIGO_PASSWORD environment variables. Access and refresh tokens are loaded from an application and OS-specific configuration file if available. This method is best effort and does not return intermediate errors. It will return an error if the credentials are empty after being loaded.

func (*Credentials) Refreshable

func (creds *Credentials) Refreshable() bool

Refreshable returns true if the current time is after NotBefore and before RefreshBy.

func (*Credentials) Update

func (creds *Credentials) Update(accessToken, refreshToken string) (err error)

Update the credentials with new access and refresh tokens. Credentials are checked and if they're ok they are dumped to the cache on disk.

func (*Credentials) Valid

func (creds *Credentials) Valid() bool

Valid returns true if the access tokens are unexpired.

type FindCertificateRequest

type FindCertificateRequest struct {
	CommonName   string `json:"commonName,omitempty"`
	SerialNumber string `json:"serialNumber,omitempty"`
}

FindCertificateRequest to POST to the findCertificateEP

type FindCertificateResponse

type FindCertificateResponse struct {
	TotalCount int `json:"totalCount"`
	Items      []struct {
		DeviceID     int    `json:"deviceId"`
		CommonName   string `json:"commonName"`
		SerialNumber string `json:"serialNumber"`
		CreationDate string `json:"creationDate"`
		Status       string `json:"status"`
	} `json:"items"`
}

FindCertificateResponse from the findCertificateEP

type LicensesUsedResponse

type LicensesUsedResponse struct {
	Ordered int `json:"ordered"`
	Issued  int `json:"issued"`
}

LicensesUsedResponse received from devicesEP

type ProcessingInfoResponse

type ProcessingInfoResponse struct {
	Active  int `json:"active"`
	Success int `json:"success"`
	Failed  int `json:"failed"`
}

ProcessingInfoResponse received from batchProcessingInfoEP

type ProfileDetailResponse

type ProfileDetailResponse struct {
	ProfileName      string `json:"profileName"`
	ProfileID        int    `json:"profileId"`
	RawProfileConfig string `json:"rawProfileConfig"`
	Name             string `json:"name"`
	KeyAlgorithmInfo string `json:"keyAlgorithmInfo"`
}

ProfileDetailResponse received from profileDetailEP

type ProfileParamsResponse

type ProfileParamsResponse struct {
	Name              string      `json:"name"`
	InputType         string      `json:"inputType"`
	Required          bool        `json:"required"`
	Placeholder       interface{} `json:"placeholder"`
	ValidationPattern string      `json:"validationPattern"`
	Message           string      `json:"message"`
	Value             interface{} `json:"value"`
	Title             string      `json:"title"`
	Scopes            []string    `json:"scopes"`
	Dynamic           bool        `json:"dynamic"`
}

ProfileParamsResponse received from profileParametersEP

type ProfileResponse

type ProfileResponse struct {
	ProfileID  int      `json:"profileId"`
	Algorithms []string `json:"algorithms"`
	CA         string   `json:"ca"`
}

ProfileResponse received from profilesEP

type RevokeCertificateRequest

type RevokeCertificateRequest struct {
	ReasonCode   int    `json:"reasonCode"`   // Must be code from RFC 5280 between 0 and 10
	SerialNumber string `json:"serialNumber"` // Serial number of certificated signed by profile
}

RevokeCertificateRequest to POST to the revokeCertificateEP

type Sectigo

type Sectigo struct {
	// contains filtered or unexported fields
}

Sectigo provides authenticated http requests to the Sectigo IoT Manager 20.7 REST API. See documentation at: https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA01N000000bvCJ

Most endpoints require an JWT access token set in an Authorization: Bearer header to provide information about an authenticated user. The authenticate method will request access and refresh tokens based on user credentials. Each access token has a validity of 600 seconds, when the access token expires, the refresh token should be used to request a new access token without requiring the user to resupply credentials.

The client handles authentication by checking if the tokens are valid before every request, and if not either refreshes the token or reauthenticates using its credentials.

func New

func New(username, password string) (client *Sectigo, err error)

New creates a Sectigo client ready to make HTTP requests, but unauthenticated. The username and password will be loaded from the environment if not given - from $SECTIGO_USERNAME and $SECTIGO_PASSWORD respectively; alternatively if not given and not stored in the environment, as long as valid access credentials are cached the credentials will be loaded.

func (*Sectigo) Authenticate

func (s *Sectigo) Authenticate() (err error)

Authenticate the user with the specified credentials to get new access and refresh tokens. This method will replace the access tokens even if already present and valid. If certificate authentication is enabled then the response will be a 307 status code, if wrong user name and password a 401 status code and if a correct user name and password but the user does not have authority, a 403 status code.

func (*Sectigo) BatchDetail

func (s *Sectigo) BatchDetail(id int) (batch *BatchResponse, err error)

BatchDetail returns batch information by batch id. User must be authenticated with role 'USER' and has permission to read this batch.

func (*Sectigo) CreateSingleCertBatch

func (s *Sectigo) CreateSingleCertBatch(authority int, name string, params map[string]string) (batch *BatchResponse, err error)

CreateSingleCertBatch issues a new single certificate batch. User must be authenticated with role 'USER' and has permission to create request. You may get http code 400 if supplied values in profileParams fails to validate over rules specified in "profile".

func (*Sectigo) Creds

func (s *Sectigo) Creds() Credentials

Creds returns a copy of the underlying credentials object.

func (*Sectigo) Download

func (s *Sectigo) Download(batch int, dir string) (path string, err error)

Download batch as a ZIP file. Dir should be a directory, filename is detected from content-disposition. User must be authenticated with role 'USER' and batch must be readable.

func (*Sectigo) FindCertificate

func (s *Sectigo) FindCertificate(commonName, serialNumber string) (certs *FindCertificateResponse, err error)

FindCertificate searches for certificates by common name and serial number.

func (*Sectigo) LicensesUsed

func (s *Sectigo) LicensesUsed() (stats *LicensesUsedResponse, err error)

LicensesUsed returns statistic for Ordered/Issued certificates (licenses used) User must be authenticated with role 'USER'

func (*Sectigo) ProcessingInfo

func (s *Sectigo) ProcessingInfo(batch int) (status *ProcessingInfoResponse, err error)

ProcessingInfo returns batch processing status by batch id. User must be authenticated with role 'USER' and has permission to read this batch.

func (*Sectigo) ProfileDetail

func (s *Sectigo) ProfileDetail(id int) (profile *ProfileDetailResponse, err error)

ProfileDetail gets extended profile information. User must be authenticated with role 'ADMIN' or 'USER' and permission to read this profile.

func (*Sectigo) ProfileParams

func (s *Sectigo) ProfileParams(id int) (params []*ProfileParamsResponse, err error)

ProfileParams lists the parameters acceptable and required by profileId User must be authenticated with role 'ADMIN' or 'USER' and permission to read this profile

func (*Sectigo) Profiles

func (s *Sectigo) Profiles() (profiles []*ProfileResponse, err error)

Profiles returns a list of all profiles available to the user. User must be authenticated.

func (*Sectigo) Refresh

func (s *Sectigo) Refresh() (err error)

Refresh the access token using the refresh token. Note that this method does not check if the credentials are refreshable, it only issues the refresh request with the refresh access token if it exists. If the refresh token does not exist, then an error is returned.

func (*Sectigo) RevokeCertificate

func (s *Sectigo) RevokeCertificate(profileID, reasonCode int, serialNumber string) (err error)

RevokeCertificate by serial number if the certificate was signed by the given authority. A reason code from RFC 5280 must be given. This method revokes single certificates unlike the RevokeDeviceCertificates method which can revoke multiple certificates by their assignment to specific Device IDs. If no error is returned, the certificate revocation was successful. User must be authenticated and has permission to update profile.

func (*Sectigo) UserAuthorities

func (s *Sectigo) UserAuthorities() (authorities []*AuthorityResponse, err error)

UserAuthorities returns a list of all Authorities by Ecosystem and Current User User must be authenticated.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL