sectigo

package
v1.7.7 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: MIT Imports: 19 Imported by: 0

README

Sectigo API

Go Reference

NOTE: This README is included with the source code to facilitate forks and code sharing. However, if you're using the Sectigo integration with the TRISA TestNet Directory Service, please reference the documentation at trisa.dev.

The directory service issues certificates using Sectigo, please refer to the API Documentation for more details on the endpoints and supported interactions. The sectigo package provides a simple client interface for interacting with the API; most of this code is handled by the server, but there is also a CLI interface that demonstrates usage.

To install the CLI server:

$ go install ./cmd/sectigo

This should add the sectigo command to your $PATH.

Authentication

The first step is authentication, you should set your username and password in the $SECTIGO_USERNAME and $SECTIGO_PASSWORD environment variables (alternatively you can pass them as parameters on the command line). To verify your authentication status you can use:

$ sectigo auth

The API authenticates by username and password then returns acess and refresh tokens which are stored in a local cache file. To see where your cache is stored:

$ sectigo auth --cache

If you'd like to check your credentials state, e.g. if the access tokens are valid, refreshable, or expired, use:

$ sectigo auth --debug

Authorities and Profiles

To begin to interact with certificates you need to list the authorities and profiles that your user account has access to.

$ sectigo authorities
[
  {
    "id": 1,
    "ecosystemId": 100,
    "signerCertificateId": 0,
    "ecosystemName": "TRISA",
    "balance": 10,
    "enabled": true,
    "profileId": 42,
    "profileName": "TRISA Profile"
  }
]

The authority displays the methods and profiles that certificates are created under. Here the profileId field is very important for use in subsequent calls. You can also view how many licenses have been ordered/issued across all authorities as follows:

$ sectigo licenses
{
  "ordered": 2,
  "issued": 2
}

To get detail information for a profile, use the profile ID with the following command:

$ sectigo profiles -i 42

This will return the raw profile configuration. Before creating certificates with the authority, you'll need to know the required profile parameters:

$ sectigo profile -i 42 --params

Creating Certificates

You can request a certificate to be created with the commonName and pkcs12Password params as follows (note for profiles that require other params, you'll have to use the code base directly and implement your own method):

$ sectigo create -a 42 -d example.com -p secrtpasswrd -b "example.com certs"
{
  "batchId": 24,
  "orderNumber": 1024,
  "creationDate": "2020-12-10T16:35:32.805+0000",
  "profile": "TRISA Profile",
  "size": 1,
  "status": "CREATED",
  "active": false,
  "batchName": "example.com certs",
  "rejectReason": "",
  "generatorParametersValues": null,
  "userId": 10,
  "downloadable": true,
  "rejectable": true
}

The -a flag specifies the authority, but should be a profile id. The domain must be a valid domain. If you don't specify a password, one is generated for you and printed on the CLI before exit. The -b flag gives a human readable name for the batch creation. The return data shows detail about the batch certificate job that was created; you can fetch the data to keep checking on the status as follows:

$ sectigo batches -i 24

You can also get processing information for the batch:

$ sectigo batches -i 24 --status

Once the batch is created, it's time to download the certificates in a ZIP file:

$ sectigo download -i 24 -o certs/

This will download the batch file (usually batchId.zip, 24.zip in this case) to the certs/ directory. Unzip the certs then decrypt the .pem file as follows:

$ unzip certs/24.zip
$ openssl pkcs12 -in certs/example.com.p12 -out certs/example.com.pem -nodes

For more on working with the PKCS12 file, see Export Certificates and Private Key from a PKCS#12 File with OpenSSL.

Uploading a CSR

An alternative to certificate creation is to upload a certificate signing request (CSR). This mechanism is often preferable because it means that no private key material has to be transmitted accross the network and the private key can remain on secure hardware.

To generate a CSR using openssl on the command line, first create a configuration file named trisa.conf in your current working directory, replacing example.com with the domain you plan to host your TRISA endpoint on:

[req]
distinguished_name = dn_req
req_extensions = v3ext_req
prompt = no
default_bits = 4096
[dn_req]
CN = example.com
O = [Organization]
L = [City]
ST = [State or Province (fully spelled out, no abbreviations)]
C = [2 digit country code]
[v3ext_req]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, nonRepudiation
extendedKeyUsage = clientAuth, serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = example.com

Please carefully fill out the configuration for your certificate, this information must be correct and cannot be changed without reissuing the certificate. Also make sure that there are no spaces after the entries in the configuration!

Then run the following command, replacing example.com with the domain name you will be using as your TRISA endpoint:

$ openssl req -new -newkey rsa:4096 -nodes -sha384 -config trisa.conf \
  -keyout example.com.key -out example.com.csr

You can then upload the CSR using the CLI program as follows:

$ sectigo upload -p 42 <common_name>.csr
{
  "batchId": 24,
  "orderNumber": 1024,
  "creationDate": "2020-12-10T16:35:32.805+0000",
  "profile": "TRISA Profile",
  "size": 1,
  "status": "CREATED",
  "active": false,
  "batchName": "example.com certs",
  "rejectReason": "",
  "generatorParametersValues": null,
  "userId": 10,
  "downloadable": true,
  "rejectable": true
}

The -p flag specifies the profile to use the CSR batch request with and must be a valid profileId. The uploaded CSRs can be a single text file with multiple CSRs in PEM form using standard BEGIN/END separators.

Possible CSR Errors:

  • BROKEN Error: Cert subject name error: SubjectAlternativeName dNSName value is missing

Managing Certificates

You can search for a certificate by name or serial number, but mostly commonly you search by the domain or common name to get the serial number:

$ sectigo find -n example.com

Once you've obtained the serial number you can revoke the certificate as follows:

$ sectigo revoke -p 42 -r "cessation of operation" -s 12345

This command expects the profile id that issued the certificate with the -p flag, an RFC 5280 reason code passed via the -r flag (unspecified by default), and the serial number of the certificate using the -s flag. If this command doesn't error, then the certificate has been successfully revoked.

The RFC 5280 reasons are:

  • "unspecified"
  • "keycompromise"
  • "ca compromise"
  • "affiliation changed"
  • "superseded"
  • "cessation of operation"
  • "certificate hold"
  • "remove from crl"
  • "privilege withdrawn"
  • "aa compromise"

Note that the reason is whitespace and case insensitive.

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"
	ProfileEnv     = "SECTIGO_PROFILE"
	EndpointEnv    = "SECTIGO_ENDPOINT"
	EnvironmentEnv = "SECTIGO_ENVIRONMENT"
)

Environment variables that are loaded into credentials.

View Source
const (
	VendorName       = "trisa"
	ApplicationName  = "sectigo"
	CredentialsCache = "credentials.yaml"
	MockUsername     = "tester"
	MockPassword     = "supersecretsquirrel"
)

Cache directory configuration

View Source
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.

View Source
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

View Source
const (
	BatchStatusFailed           = "FAILED"
	BatchStatusRejected         = "REJECTED"
	BatchStatusProcessing       = "PROCESSING"
	BatchStatusNotAcceptable    = "NOT_ACCEPTABLE"
	BatchStatusReadyForDownload = "READY_FOR_DOWNLOAD"
	BatchStatusCollected        = "COLLECTED"
	BatchStatusExpired          = "REMOVED_AFTER_EXPIRATION"
	BatchStatusBroken           = "BROKEN"
	BatchStatusRevoked          = "REVOKED"
)

Batch Status Constants

Variables

View Source
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.

View Source
var Defaults = map[string]string{
	ParamOrganizationName:    "TRISA Member VASP",
	ParamLocalityName:        "Menlo Park",
	ParamStateOrProvinceName: "California",
	ParamCountryName:         "US",
}
View Source
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 Endpoint

func Endpoint(endpoint string, params ...interface{}) (u *url.URL, err error)

Endpoint returns the resolved URL for the named endpoint

func ResetBaseURL

func ResetBaseURL()

ResetBaseURL to the default Sectigo API endpoint

func SetBaseURL

func SetBaseURL(u *url.URL)

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.

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 Config

type Config struct {
	Username    string `envconfig:"SECTIGO_USERNAME" required:"false"`
	Password    string `envconfig:"SECTIGO_PASSWORD" required:"false"`
	Profile     string `envconfig:"SECTIGO_PROFILE" default:"CipherTrace EE"`
	Endpoint    string `envconfig:"SECTIGO_ENDPOINT" default:"https://iot.sectigo.com"`
	Environment string `envconfig:"SECTIGO_ENVIRONMENT" default:"production"`
}

func (Config) GetEnvironment added in v1.7.1

func (c Config) GetEnvironment() string

func (Config) Testing

func (c Config) Testing() bool

func (Config) Validate

func (c Config) Validate() error

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 FindCertificateItem added in v1.6.0

type FindCertificateItem struct {
	DeviceID     string `json:"deviceId"`
	CommonName   string `json:"commonName"`
	SerialNumber string `json:"serialNumber"`
	CreationDate string `json:"creationDate"`
	Status       string `json:"status"`
}

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      []*FindCertificateItem `json:"items"`
}

FindCertificateResponse from the findCertificateEP

type LicensesUsedResponse

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

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"`
	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

type Sectigo struct {
	sync.RWMutex
	// 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(conf Config) (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) AuthorityAvailableBalance

func (s *Sectigo) AuthorityAvailableBalance(id int) (balance int, err error)

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

func (s *Sectigo) BatchStatus(batch int) (status string, err error)

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) Do added in v1.3.1

func (s *Sectigo) Do(req *http.Request) (*http.Response, error)

Do performs a Sectigo client request and returns the response.

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) 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) Profile

func (s *Sectigo) Profile() string

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) 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.

type UploadCSRBatchRequest

type UploadCSRBatchRequest struct {
	ProfileID     int               `json:"profileId"`
	BatchType     string            `json:"batchType"`
	ProfileParams map[string]string `json:"profileParams"`
}

UploadCSRBatchRequest to POST data to the uploadCSREP

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.
Package server implements a lightweight Sectigo mock server that can be used in staging to issue mock certificates and perform integration tests.
Package server implements a lightweight Sectigo mock server that can be used in staging to issue mock certificates and perform integration tests.

Jump to

Keyboard shortcuts

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