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
- Variables
- func AllProfiles() []string
- func Endpoint(endpoint string, params ...interface{}) (u *url.URL, err error)
- func ResetBaseURL()
- func SetBaseURL(u *url.URL)
- type APIError
- type AuthenticationReply
- type AuthenticationRequest
- type AuthorityResponse
- type BatchResponse
- type CRLReason
- type Config
- type CreateSingleCertBatchRequest
- type Credentials
- func (creds *Credentials) CacheFile() string
- func (creds *Credentials) Check() (err error)
- func (creds *Credentials) Clear()
- func (creds *Credentials) Current() bool
- func (creds *Credentials) Dump() (path string, err error)
- func (creds *Credentials) Load(username, password string) (err error)
- func (creds *Credentials) Refreshable() bool
- func (creds *Credentials) Update(accessToken, refreshToken string) (err error)
- func (creds *Credentials) Valid() bool
- type FindCertificateRequest
- type FindCertificateResponse
- type LicensesUsedResponse
- type OrganizationResponse
- type ProcessingInfoResponse
- type ProfileDetailResponse
- type ProfileParamsResponse
- type ProfileResponse
- type RevokeCertificateRequest
- type Sectigo
- func (s *Sectigo) Authenticate() (err error)
- func (s *Sectigo) AuthorityAvailableBalance(id int) (balance int, err error)
- func (s *Sectigo) BatchDetail(id int) (batch *BatchResponse, err error)
- func (s *Sectigo) BatchStatus(batch int) (status string, err error)
- func (s *Sectigo) CreateSingleCertBatch(authority int, name string, params map[string]string) (batch *BatchResponse, err error)
- func (s *Sectigo) Creds() Credentials
- func (s *Sectigo) Do(req *http.Request) (*http.Response, error)
- func (s *Sectigo) Download(batch int, dir string) (path string, err error)
- func (s *Sectigo) FindCertificate(commonName, serialNumber string) (certs *FindCertificateResponse, err error)
- func (s *Sectigo) LicensesUsed() (stats *LicensesUsedResponse, err error)
- func (s *Sectigo) Organization() (org *OrganizationResponse, err error)
- func (s *Sectigo) ProcessingInfo(batch int) (status *ProcessingInfoResponse, err error)
- func (s *Sectigo) Profile() string
- func (s *Sectigo) ProfileDetail(id int) (profile *ProfileDetailResponse, err error)
- func (s *Sectigo) ProfileParams(id int) (params []*ProfileParamsResponse, err error)
- func (s *Sectigo) Profiles() (profiles []*ProfileResponse, err error)
- func (s *Sectigo) Refresh() (err error)
- func (s *Sectigo) RevokeCertificate(profileID, reasonCode int, serialNumber string) (err error)
- func (s *Sectigo) UploadCSRBatch(profileId int, filename string, csrData []byte, params map[string]string) (batch *BatchResponse, err error)
- func (s *Sectigo) UserAuthorities() (authorities []*AuthorityResponse, err error)
- type UploadCSRBatchRequest
Constants ¶
const ( UsernameEnv = "SECTIGO_USERNAME" PasswordEnv = "SECTIGO_PASSWORD" ProfileEnv = "SECTIGO_PROFILE" )
Environment variables that are loaded into credentials.
const ( VendorName = "trisa" ApplicationName = "sectigo" CredentialsCache = "credentials.yaml" MockUsername = "tester" MockPassword = "supersecretsquirrel" )
Cache directory configuration
const ( AuthenticateEP = "authenticate" RefreshEP = "refresh" BatchesEP = "batches" BatchDetailEP = "batchDetail" BatchStatusEP = "batchStatus" BatchAuditLogEP = "batchAuditLog" BatchProcessingInfoEP = "batchProcessingInfo" BatchDevicesAuditLogEP = "batchDevicesAuditLog" BatchPreviewEP = "batchPreview" CreateSingleCertBatchEP = "createSingleCertBatch" UploadEP = "upload" UploadCSREP = UploadEP UploadCSVEP = "uploadCSV" GeneratorsEP = "generators" DownloadEP = "download" DevicesEP = "devices" UserAuthoritiesEP = "userAuthorities" AuthorityBalanceUsedEP = "authorityBalanceUsed" AuthorityBalanceAvailableEP = "authorityBalanceAvailable" AuthorityUserBalanceAvailableEP = "authorityUserBalanceAvailable" UsersEP = "users" CheckEmailEP = "checkEmail" UserDetailEP = "userDetail" UserProfilesEP = "userProfiles" UsersOrganizationsEP = "usersOrganizations" RemoveUserEP = "removeUser" CurrentUserEP = "currentUser" UpdateEmailEP = "updateEmail" CheckUserEP = "checkUser" UserCredentialsEP = "userCredentials" ProfilesEP = "profiles" ProfileDetailEP = "profileDetail" ProfileBalanceEP = "profileBalance" ProfileParametersEP = "profileParameters" ProfileSubjectDNEP = "profileSubjectDN" OrganizationsEP = "organizations" OrganizationDetailEP = "organizationDetail" CurrentUserOrganizationEP = "currentUserOrganization" CheckOrganizationEP = "checkOrganization" UpdateAuthorityEP = "updateAuthority" OrganizationAuthoritiesEP = "organizationAuthorities" AuthorityDetailEP = "authorityDetail" AuthoritiesEP = "authorities" OrganizationListItemsEP = "organizationListItems" OrganizationParametersEP = "organizationParameters" EcosystemsEP = "ecosystems" UserEcosystemEP = "userEcosystem" EcosystemBalanceEP = "ecosystemBalance" EcosystemsStatisticsEP = "ecosystemsStatistics" EcosystemAdminDetailEP = "ecosystemAdminDetail" EcosystemAdminsEP = "ecosystemAdmins" FindCertificateEP = "findCertificate" RevokeDeviceCertificateEP = "revokeDeviceCertificate" RevokeCertificateEP = "revokeCertificate" )
endpoint name constants to prevent typos at compile time rather than at runtime.
const ( ProfileCipherTraceEE = "CipherTrace EE" ProfileIDCipherTraceEE = "17" ProfileCipherTraceEndEntityCertificate = "CipherTrace End Entity Certificate" ProfileIDCipherTraceEndEntityCertificate = "85" ParamOrganizationName = "organizationName" ParamLocalityName = "localityName" ParamStateOrProvinceName = "stateOrProvinceName" ParamCountryName = "countryName" ParamCommonName = "commonName" ParamDNSNames = "dNSName" ParamPassword = "pkcs12Password" )
Valid Sectigo Certificate Profile Names, IDs, and parameters. TODO: do not hardcode this, but get programatically from Sectigo API
const ( BatchStatusFailed = "FAILED" BatchStatusRejected = "REJECTED" BatchStatusProcessing = "PROCESSING" BatchStatusNotAcceptable = "NOT_ACCEPTABLE" BatchStatusReadyForDownload = "READY_FOR_DOWNLOAD" BatchStatusCollected = "COLLECTED" )
Batch Status Constants
Variables ¶
var ( ErrNotAuthenticated = errors.New("sectigo client error: not authenticated") ErrCredentialsMismatch = errors.New("sectigo client error: requires both username and password") ErrTokensMismatch = errors.New("sectigo client error: both access and refresh tokens required") ErrNoCredentials = errors.New("sectigo client error: no API access credentials") ErrInvalidCredentials = errors.New("sectigo client error: could not authenticate credentials") ErrNotAuthorized = errors.New("sectigo client error: user is not authorized for this endpoint") ErrTokensExpired = errors.New("sectigo client error: access and refresh tokens have expired") ErrInvalidClaims = errors.New("sectigo client error: jwt claims do not have required timestamps") ErrMustUseTLSAuth = errors.New("sectigo client error: account requires TLS client authentication") ErrPKCSPasswordRequired = errors.New("sectigo client error: pkcs12 password required for cert params") )
Standard errors issued by the Sectigo client.
var Defaults = map[string]string{ ParamOrganizationName: "TRISA Member VASP", ParamLocalityName: "Menlo Park", ParamStateOrProvinceName: "California", ParamCountryName: "US", }
var Profiles = map[string][]string{ ProfileCipherTraceEE: nameParams[:], ProfileIDCipherTraceEE: nameParams[:], ProfileCipherTraceEndEntityCertificate: append(nameParams[:], subjectParams[:]...), ProfileIDCipherTraceEndEntityCertificate: append(nameParams[:], subjectParams[:]...), }
Map containing all the supported Sectigo profiles and their required parameters. NOTE: these params are sorted by the init function to enable binary search.
Functions ¶
func AllProfiles ¶
func AllProfiles() []string
func SetBaseURL ¶
SetBaseURL updates Sectigo to use a different scheme and host to determine endpoints
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.
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 ¶
RevokeReasonCode translates a human readable string to a RFC 5280 reason code.
type Config ¶
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 ¶
LicensesUsedResponse received from devicesEP
type OrganizationResponse ¶
type OrganizationResponse struct { OrganizationID int `json:"organizationId"` OrganizationName string `json:"organizationName"` Address string `json:"address"` PrimaryContactName string `json:"primaryContactName"` PrimaryContactEmail string `json:"primaryContactEmail"` PrimaryContactPhone string `json:"primaryContactPhone"` ManufactureID string `json:"manufactureId"` Logo string `json:"logo"` Authorities []*AuthorityResponse `json:"authorities"` EcosystemID int `json:"ecosystemId"` Parameters map[string]string `json:"organizationParameters"` Status string `json:"orgStatus"` }
OrganizationResponse received from currentUserOrganizationEP
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 ¶
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 ¶
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 ¶
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) AuthorityAvailableBalance ¶
AuthorityAvailableBalance returns balance available for the specified user/authority User must be authenticated.
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) BatchStatus ¶
BatchStatus views batch status by batchId. User must be authenticated with role 'USER' and has permission to read this batch. Statuses can be: "Ready for download", "Processing", "Failed" or "Not Acceptable. Status: ".
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 ¶
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) Organization ¶
func (s *Sectigo) Organization() (org *OrganizationResponse, err error)
Organization returns the organization for the current user. User must be authorized.
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 ¶
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 ¶
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) UploadCSRBatch ¶
func (s *Sectigo) UploadCSRBatch(profileId int, filename string, csrData []byte, params map[string]string) (batch *BatchResponse, err error)
UploadCSRBatch CSR or bulk ZIP file. User must be authenticated with role 'USER' and must has permission to read this profile. That part contains the CSRs with a Content-Dispostion of form-data and a name parameter of files. The filename parameter is not used. The Content-Type of the part should match the uploaded file. The uploaded CSRs can be a single text file with multiple CSRs in PEM form using standard BEGIN/END separators or a zip file containing multiple CSRs files. When uploading a single text file the Content-Type can be text/plain, application/octet-stream or application/x-x509-ca-cert. When uploading a zip file the Content-Type must be application/zip. The zip file must contain each CSR in a file with the extension .csr or .pem.
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
* Package mock provides an httptest.Server that allows mock interactions with the * Sectigo API for both unit tests of the Sectigo package and integration tests with GDS * Sectigo/Certificate operations.
|
* Package mock provides an httptest.Server that allows mock interactions with the * Sectigo API for both unit tests of the Sectigo package and integration tests with GDS * Sectigo/Certificate operations. |