types

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package types is a package to provide the basic types to be used across client and server.

Package types provides type definitions and validation for Knox.

Index

Constants

View Source
const (
	// Unknown represents a bad PrincipalType that cannot be marshaled.
	Unknown PrincipalType = -1
	// User represents a single LDAP User.
	User = iota
	// UserGroup represents an LDAP security group.
	UserGroup
	// Machine represents the host of a machine.
	Machine
	// MachinePrefix represents a prefix to match multiple machines.
	MachinePrefix
	// Service represents a service via SPIFFE ID.
	Service
	// ServicePrefix represents a prefix to match multiple SPIFFE IDs.
	ServicePrefix
)
View Source
const (
	OKCode = iota
	InternalServerErrorCode
	KeyIdentifierExistsCode
	KeyVersionDoesNotExistCode
	KeyIdentifierDoesNotExistCode
	UnauthenticatedCode
	UnauthorizedCode
	NotYetImplementedCode
	NotFoundCode
	NoKeyIDCode
	NoKeyDataCode
	BadRequestDataCode
	BadKeyFormatCode
	BadPrincipalIdentifier
)

These are the error codes for use in server responses.

View Source
const (
	MaxKeyIDLength       = 256
	MaxPrincipalIDLength = 512
	MaxKeyDataSize       = 1024 * 1024      // 1MB
	MaxRequestBodySize   = 10 * 1024 * 1024 // 10MB
)

Constants for validation limits.

Variables

View Source
var (
	ErrACLDuplicateEntries = errors.New("duplicate entries in ACL")
	ErrACLContainsNone     = errors.New("ACL contains None access")
	ErrACLEmptyPrincipal   = errors.New("principals of type user, user group, machine, or machine prefix may not be empty")

	ErrACLInvalidService               = errors.New("service is invalid, must conform to 'spiffe://<domain>/<path>' format")
	ErrACLInvalidServicePrefixURL      = errors.New("service prefix is invalid URL, must conform to 'spiffe://<domain>/<path>/' format")
	ErrACLInvalidServicePrefixNoSlash  = errors.New("service prefix had no trailing slash, must conform to 'spiffe://<domain>/<path>/' format")
	ErrACLInvalidServicePrefixTooShort = errors.New("service prefix too short, path of namespace for prefix needs to be longer")

	ErrInvalidKeyID       = errors.New("key ID can only contain alphanumeric characters, colons, and underscores")
	ErrInvalidVersionHash = errors.New("hash does not match")

	ErrInactiveToPrimary = errors.New("version must be active to promote to primary")
	ErrPrimaryToActive   = errors.New("primary key cannot be demoted, specify active key to promote")
	ErrPrimaryToInactive = errors.New("version must be active to demote to inactive")

	ErrMulitplePrimary = errors.New("more than one primary key")
	ErrSameVersionID   = errors.New("repeated version ID")

	ErrInvalidStatus      = errors.New("invalid status")
	ErrKeyVersionNotFound = errors.New("key version not found")
	ErrKeyIDNotFound      = errors.New("key ID not found")
	ErrKeyExists          = errors.New("key exists")
)
View Source
var (
	ErrKeyIDTooLong       = errors.New("key ID too long (max 256 characters)")
	ErrKeyIDInvalidFormat = errors.New("key ID contains invalid characters")
	ErrKeyIDEmpty         = errors.New("key ID cannot be empty")
	ErrKeyDataTooLarge    = errors.New("key data too large (max 1MB)")
	ErrPrincipalIDTooLong = errors.New("principal ID too long (max 512 characters)")
	ErrPrincipalIDEmpty   = errors.New("principal ID cannot be empty")
	ErrInvalidSPIFFEURI   = errors.New("invalid SPIFFE URI format")
	ErrInvalidMachineID   = errors.New("invalid machine ID format")
	ErrInvalidUserID      = errors.New("invalid user ID format")
	ErrRequestTooLarge    = errors.New("request body too large (max 10MB)")
	ErrPathTraversal      = errors.New("path traversal attempt detected")
	ErrInvalidJSON        = errors.New("invalid JSON format")
	ErrUnsafeCharacters   = errors.New("input contains unsafe characters")
)

Validation errors.

Functions

func IsValidJSON

func IsValidJSON(data []byte) bool

IsValidJSON checks if data is valid JSON.

func SanitizeString

func SanitizeString(input string) string

SanitizeString removes potentially dangerous characters from a string.

func ValidateACL

func ValidateACL(acl ACL) error

ValidateACL validates an ACL.

func ValidateAccess

func ValidateAccess(access Access) error

ValidateAccess validates an access entry.

func ValidateKeyCreation

func ValidateKeyCreation(keyID string, data []byte, acl ACL) error

ValidateKeyCreation validates all parameters for key creation.

func ValidateKeyData

func ValidateKeyData(data []byte) error

ValidateKeyData validates key data size.

func ValidateKeyID

func ValidateKeyID(keyID string) error

ValidateKeyID validates a key ID according to security requirements.

func ValidatePrincipalID

func ValidatePrincipalID(principalType PrincipalType, id string) error

ValidatePrincipalID validates a principal ID based on its type.

func ValidateRequestBodySize

func ValidateRequestBodySize(size int64) error

ValidateRequestBodySize validates that request body size is within limits.

Types

type ACL

type ACL []Access

ACL is a list of access information that provides authorization information for a specific key.

func (ACL) Add

func (acl ACL) Add(a Access) ACL

Add appends an access to the ACL. It does so by overwriting any existing access that principal or group may have had.

func (ACL) Validate

func (acl ACL) Validate() error

Validate ensures the ACL is of valid form. Not specifying the same group or id more than once.

type Access

type Access struct {
	Type       PrincipalType `json:"type"`
	ID         string        `json:"id"`
	AccessType AccessType    `json:"access"`
}

Access is a specific access grant as a part of an ACL specifying one principal's or a group of principals' granted acccess.

type AccessCallbackInput

type AccessCallbackInput struct {
	Key        Key            `json:"key"`
	Principals []RawPrincipal `json:"principals"`
	AccessType AccessType     `json:"access_type"`
}

AccessCallbackInput is the input to the access callback function.

type AccessType

type AccessType int

AccessType represents what kind of Access is granted in a key's ACL.

const (
	// None denotes no access.
	None AccessType = iota
	// Read denotes the ability to read key data.
	Read
	// Write denotes the ability to add key versions and perform rotation.
	Write
	// Admin denotes the ability to delete the key and modify the ACL.
	Admin
)

func (AccessType) CanAccess

func (s AccessType) CanAccess(resource AccessType) bool

CanAccess uses a principal's AccessType to determine if the principal can access a given resource.

func (AccessType) MarshalJSON

func (s AccessType) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of an AccessType.

func (*AccessType) UnmarshalJSON

func (s *AccessType) UnmarshalJSON(b []byte) error

UnmarshalJSON parses JSON input to set an AccessType.

type Key

type Key struct {
	ID          string         `json:"id"`
	ACL         ACL            `json:"acl"`
	VersionList KeyVersionList `json:"versions"`
	VersionHash string         `json:"hash"`
	Path        string         `json:"path,omitempty"`
	TinkKeyset  string         `json:"tinkKeyset,omitempty"`
}

Key represents the Primary element of Knox.

func (Key) Validate

func (k Key) Validate() error

Validate calls makes sure all attributes of key are in good state.

type KeyVersion

type KeyVersion struct {
	ID           uint64        `json:"id"`
	Data         []byte        `json:"data"`
	Status       VersionStatus `json:"status"`
	CreationTime int64         `json:"ts"`
}

KeyVersion is a specific version of a Key. All attributes should be immutable except status.

type KeyVersionList

type KeyVersionList []KeyVersion

KeyVersionList represents the list of versions of a key. This will grow as the key is rotated.

func (KeyVersionList) GetActive

func (kvl KeyVersionList) GetActive() KeyVersionList

GetActive returns the active keys in a KeyVersionList.

func (KeyVersionList) GetPrimary

func (kvl KeyVersionList) GetPrimary() *KeyVersion

GetPrimary returns the primary key in a KeyVersionList.

func (KeyVersionList) Hash

func (kvl KeyVersionList) Hash() string

Hash computes the Sha256 hash of the ordered key versions. The hash ordering is the Primary version id followed by all Active version id in numeric order.

func (KeyVersionList) Len

func (kvl KeyVersionList) Len() int

Len returns the length of the key version list.

func (KeyVersionList) Less

func (kvl KeyVersionList) Less(i, j int) bool

Less determines where a key version is in an ordered list.

func (KeyVersionList) Swap

func (kvl KeyVersionList) Swap(i, j int)

Swap swaps two elements in the list.

func (KeyVersionList) Update

func (kvl KeyVersionList) Update(versionID uint64, s VersionStatus) (KeyVersionList, error)

Update changes the status of a particular key version. It also updates any other key versions that need to be updated. Acceptable changes are Active -> Primary, Active -> Inactive, and Inactive -> Active.

func (KeyVersionList) Validate

func (kvl KeyVersionList) Validate() error

Validate checks that key versions are unique and that there is exactly one Primary key.

type Principal

type Principal interface {
	CanAccess(ACL, AccessType) bool
	GetID() string
	Type() string
	Raw() []RawPrincipal
}

Principal is a person, machine, or process that accesses an object. This interface is currently defined for people and machines.

func NewPrincipalMux

func NewPrincipalMux(defaultPrincipal Principal, allPrincipals map[string]Principal) Principal

NewPrincipalMux returns a Principal that represents many principals.

type PrincipalMux

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

PrincipalMux provides a Principal Interface over multiple Principals.

func (PrincipalMux) CanAccess

func (p PrincipalMux) CanAccess(acl ACL, accessType AccessType) bool

CanAccess will check the principals in order of adding, and the first Principal that provides at least the AccessType requested will be used.

func (PrincipalMux) Default

func (p PrincipalMux) Default() Principal

Default returns the first registered Principal.

func (PrincipalMux) GetID

func (p PrincipalMux) GetID() string

GetID returns the ID of the default principal.

func (PrincipalMux) GetIDs

func (p PrincipalMux) GetIDs() []string

GetIDs returns all registered IDs from the principals that are muxed.

func (PrincipalMux) Raw

func (p PrincipalMux) Raw() []RawPrincipal

Raw returns the raw version of all the principals.

func (PrincipalMux) Type

func (p PrincipalMux) Type() string

Type returns the underlying type of a principal, for logging/debugging purposes.

type PrincipalType

type PrincipalType int

PrincipalType is an attribute of ACLs that specifies what type of Principal is represented. This allows for users and machines to be bucketed together.

func (PrincipalType) IsValidPrincipal

func (s PrincipalType) IsValidPrincipal(id string, extraValidators []PrincipalValidator) error

IsValidPrincipal verifies that the given id string matches our expectations for what a principal should look like given the principal type. For example, a service principal should be a valid SPIFFE ID.

func (PrincipalType) MarshalJSON

func (s PrincipalType) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of an PrincipalType.

func (*PrincipalType) UnmarshalJSON

func (s *PrincipalType) UnmarshalJSON(b []byte) error

UnmarshalJSON parses JSON input to set an PrincipalType.

type PrincipalValidator

type PrincipalValidator func(pt PrincipalType, id string) error

A PrincipalValidator is a function that applies to a principal type and string, and validates that the string is a valid principal for the given type.

func ServicePrefixPathComponentsValidator

func ServicePrefixPathComponentsValidator(minPathComponents int) PrincipalValidator

ServicePrefixPathComponentsValidator is an extra validator that can be applied to ensure that service prefixes have a certain minimum length, e.g. to prevent allow the prefix to be a full domain.

type RawPrincipal

type RawPrincipal struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

RawPrincipal is a serializable version of a principal for passing to access callbacks.

type Response

type Response struct {
	Status    string `json:"status"`
	Code      int    `json:"code"`
	Host      string `json:"host"`
	Timestamp int64  `json:"ts"`
	Message   string `json:"message"`
	Data      any    `json:"data"`
}

Response is the format for responses from the api server.

type VersionStatus

type VersionStatus int

VersionStatus is an enum to determine that state of a single Key Version. This is related to key rotation.

const (
	// Primary is the main key version. There is exactly one in a given KeyVersionList.
	Primary VersionStatus = iota
	// Active represents Key Versions still in use, but not Primary.
	Active
	// Inactive represents Key Versions no longer in use.
	Inactive
)

func (VersionStatus) MarshalJSON

func (s VersionStatus) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of an VersionStatus.

func (*VersionStatus) UnmarshalJSON

func (s *VersionStatus) UnmarshalJSON(b []byte) error

UnmarshalJSON parses JSON input to set an VersionStatus.

Jump to

Keyboard shortcuts

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