irplib

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2021 License: Apache-2.0 Imports: 28 Imported by: 0

README

IRP Developer Library

This is the IRP Developer Library for performing native IRP operations using the HTTP REST API in your applications.

Create Authentication Information

An Authentication Response is needed for any admin action such as CREATE, UPDATE, REMOVE or DELETE. It is also needed for RESOLVE if wanting to retrieve values marked as private.

There is an option to pass a custom TLS configuration depending on the needs of the remote server. While the GHR and LHS utilize self-signed certs, having a custom TLS configuration option ensures some LHS may use their own certificates that are globally recognized or using custom CAs. This library does it's best to cater to these needs. At the least, provide the following TLS configuration, which skips certificate checking, as a default

&tls.Config{InsecureSkipVerify: true}

Create authentication for ADMIN requests

// create a default TLS configuration, which skips insecure and self-signed certs (needed for GHR and almost all LHS)
// other tls configuration with custom CA or keys can be added to `tlsConfig` as well
tlsConfig := &tls.Config{InsecureSkipVerify: true}

// start by getting site information for a given IRP ID, replace `irplib.ServerAdmin` with `irplib.ServerQuery` for resolve requests
server, err := irplib.GetPrefixSite(data.HandleID, irplib.ServerAdmin, tlsConfig)
if err != nil {
  log.Println(err)
  os.Exit(1)
}

// perform authentication using the given information
authResponse, err := irplib.Authenticate(server, data.Admin.Index, data.Admin.HandleID, data.PrivateKey.RSA)
if err != nil {
  log.Println(err)
  os.Exit(1)
}

defer irplib.EndSession(server, authResponse) // this ends the authenticated session once we're done with our operations

Create authentication for QUERY requests

// start by getting site information for a given IRP ID, replace `irplib.ServerQuery` with `irplib.ServerAdmin` for create, update, remove or delete requests
server, err := irplib.GetPrefixSite(data.HandleID, irplib.ServerQuery)
if err != nil {
  log.Println(err)
  os.Exit(1)
}

// perform authentication using the given information
authResponse, err := irplib.Authenticate(server, data.Admin.Index, data.Admin.HandleID, data.PrivateKey.RSA)
if err != nil {
  log.Println(err)
  os.Exit(1)
}

defer irplib.EndSession(server, authResponse) // this ends the authenticated session once we're done with our operations

Resolve operation

Unauthenticated resolve request - returns only values with PUBLIC read permission

// the last parameter is an `irplib.Parameter{}` struct used to list specific indexes or types to be returned, such as `irplib.Parameter{Indexes: []int{301, 1001}}` or `irplib.Parameter{Types: []string{"hs_pubkey", "custom value"}}`

irpResponse := irplib.Resolve(server, nil, data.HandleID, irplib.Parameter{})
fmt.Println(irpResponse.ResponseCode)

Authenticated resolve request - returns values with PUBLIC and PRIVATE read permission (assuming authenticated user has necessary permission)

// the last function parameter is for list of indexes to be returned

irpResponse := irplib.Resolve(server, authResponse, data.HandleID, irplib.Parameter{Types: []string{"hs_pubkey", "custom value"}})
fmt.Println(irpResponse.ResponseCode)

Create operation

Crates a new IRP record or replaces an existing one, presuming the authenticated user has permission to do so.


var values irplib.Values

// the last parameter for creating values indicate it it should be marked as private or not; true = mark as private, false = publicly viewable for unauthenticated requests

// don't forget to add an admin to the record
values.AddAdmin(101, data.Admin.Index, data.Admin.HandleID, irplib.DefaultTTL, true)

// add a string value
values.AddString(1234, "test", "hello, world!", irplib.DefaultTTL, false)

// add a VLIST
vlv := irplib.NewVList()
vlv.Add("11.5678/ABC", 301)
vlv.Add("11.5678/ABC", 301)
values.AddVList(5433, irplib.TypeVList, vlv, irplib.DefaultTTL, true)

j, err := irplib.NewJWKFromRSAPubKey(data.PrivateKey.RSA.PublicKey)
if nil != err {
  log.Println(err)
  os.Exit(1)
}

// addd a pubkey
values.AddKey(301, irplib.TypeHSPubKey, j, irplib.DefaultTTL, false)

// the last parameter for create indicates if the IRP record should be replaced if it already exists; true = replace, false = NO NOT replace
irpResponse := irplib.Create(server, authResponse, data.HandleID, values, true)
	fmt.Println(irpResponse.ResponseCode)

Update operation

Adds or updates specified indexes in the IRP Record, presuming the authenticated user has permission to do so.


var values irplib.Values

// add a new string value
values.AddString(12890, "hash", "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728", irplib.DefaultTTL, false)

// the last parameter for update indicates if the new IRP value can replace existing values at the given index; true = replace, false = DO NOT replace
irpResponse := irplib.Update(server, authResponse, data.HandleID, values, true)
fmt.Println(irpResponse.ResponseCode)


Remove operation

Removes specified indexes from the IRP Record, presuming the authenticated user has permission to do so.


// the last parameter is a slice of indexes to be removed
irpResponse := irplib.Remove(server, authResponse, data.HandleID, []int{12890})
fmt.Println(irpResponse.ResponseCode)

Delete operation

Completely deletes an IRP Record, presuming the authenticated user has permission to do so.


irpResponse := irplib.Delete(server, authResponse, data.HandleID)

Documentation

Index

Constants

View Source
const (

	// AdminRead - Permission index for admin read
	AdminRead = iota

	// AdminWrite - Permission index for admin write
	AdminWrite

	// PublicRead - Permission index for public read
	PublicRead

	// PublicWrite - Permission index for public read, this library does not support setting public write
	PublicWrite
)
View Source
const DefaultTTL = 86400

DefaultTTL - Default TTL of a IRP type/value. Used by LHS to determine cache lifetime.

View Source
const (
	EncodingRSA = "RSA_PUB_KEY"
)
View Source
const FormatAdmin = "admin"

FormatAdmin - IRP format for storing admin entry

View Source
const FormatBase64 = "base64"

FormatBase64 - IRP format for storing base64 entry

View Source
const FormatKey = "key"

FormatKey - IRP format for storing public keys

View Source
const FormatSite = "site"

FormatSite - IRP format for storing site information

View Source
const FormatString = "string"

FormatString - IRP format for storing string entry

View Source
const FormatVList = "vlist"

FormatVList - IRP format for storing vlist entry

View Source
const ResponseCodeAccessDenied = 401

ResponseCodeAccessDenied - Authentication required

View Source
const ResponseCodeAuthNeeded = 402

ResponseCodeAuthNeeded - No access to data

View Source
const ResponseCodeAuthenFailed = 403

ResponseCodeAuthenFailed - Failed to authenticate

View Source
const ResponseCodeError = 2

ResponseCodeError - IRP responseCode for general error

View Source
const ResponseCodeIRPAlreadyExist = 101

ResponseCodeIRPAlreadyExist - IRP already exists

View Source
const ResponseCodeInvalidIRP = 102

ResponseCodeInvalidIRP - Encoding (or syntax) error

View Source
const ResponseCodeNotAuthorized = 400

ResponseCodeNotAuthorized - Not authorized/permitted

View Source
const ResponseCodeNotFound = 100

ResponseCodeNotFound - IRP responseCode for IRP ID not found

View Source
const ResponseCodeServerNotResp = 301

ResponseCodeServerNotResp - Server not responsible

View Source
const ResponseCodeSuccess = 1

ResponseCodeSuccess - IRP responseCode for success

View Source
const ResponseCodeUnableToAuthen = 406

ResponseCodeUnableToAuthen - Unable to authenticate

View Source
const ResponseCodeValueNotFound = 200

ResponseCodeValueNotFound - Value not found

View Source
const ServerAdmin = int8(2)

ServerAdmin - seek admin server

View Source
const ServerQuery = int8(1)

ServerQuery - seek query server

View Source
const TypeHSAdmin = "HS_ADMIN"

TypeHSAdmin - IRP type/value pair for storing admins

View Source
const TypeHSPubKey = "HS_PUBKEY"

TypeHSPubKey - IRP type/value pair for storing public keys

View Source
const TypeHSSignature = "HS_SIGNATURE"

TypeHSSignature - IRP type/value pair for digital signature of this IRP Record

View Source
const TypeHSSite = "HS_SITE"

TypeHSSite - IRP type/value pair for storing site information

View Source
const TypeVList = "HS_VLIST"

TypeVList - IRP type/value pair for virtual lists, pointing to other IDs and indexes

Variables

This section is empty.

Functions

func AddGHR

func AddGHR(address string, port int)

AddGHR - adds a GHR to the list

func ClearGHR

func ClearGHR()

ClearGHR - clears GHR list

func CurrentTS

func CurrentTS() (ts int64)

CurrentTS - returns current UNIX timestamp

func EndSession

func EndSession(server Server, authResponse *AuthResponse) (err error)

EndSession - deletes a given session ID. If no logout is performed, a session ID is valid for 30 minutes of inactivity.

func ExpiredValue

func ExpiredValue(givenTimeStr string, ttl int64) (valid bool)

ExpiredValue - checks if a given time and the ttl is within current time

func RandomInt

func RandomInt(min, max int) int

RandomInt - generates a random number between the given range

func ReadPrivateRSAKey

func ReadPrivateRSAKey(rsaPrivBytes []byte, password string) (privateKey *rsa.PrivateKey, err error)

ReadPrivateRSAKey - reads a given private key bytes

func ReadYaml

func ReadYaml(inputFile string, inputStruct interface{}) (fileErr error)

ReadYaml - reads a given input YAML file and returns the struct mapped from the file

func SetCustomIRPSvc

func SetCustomIRPSvc(prefix, address string, port int, desc string)

SetCustomIRPSvc - sets a custom IRP service for connection

func TSNow

func TSNow() (timestamp int64)

TSNow - return the current timestamp in UTC for consistency

func TimeUTC

func TimeUTC() (timeStr string)

TimeUTC - return the current time in UTC for consistency

func WriteYaml

func WriteYaml(outputFile string, outputStruct interface{})

WriteYaml - writes a given struct to the given filename

Types

type Admin

type Admin struct {
	Handle string `json:"handle"`
	Index  int    `json:"index"`

	Permissions string `json:"permissions"`
	// contains filtered or unexported fields
}

Admin - admin IRP value format

func NewAdmin

func NewAdmin(adminIndex int, adminID string) (admin *Admin, err error)

NewAdmin - creates a new IRP Admin structure

func (*Admin) ClearPermission

func (admin *Admin) ClearPermission()

ClearPermission - clears all permissions to start afresh

func (*Admin) HasPermission

func (admin *Admin) HasPermission(permission AdminPerm) (hasPermission bool)

HasPermission - checks if admin has requested permission

func (*Admin) SetDefaultPermission

func (admin *Admin) SetDefaultPermission()

SetDefaultPermission - default permission for a IRP Admin

func (*Admin) SetPermission

func (admin *Admin) SetPermission(permission AdminPerm, hasPermission bool)

SetPermission - sets permission for a IRP Admin

type AdminPerm

type AdminPerm int
const (

	// PermReadValues - Permission index for reading private values
	PermReadValues AdminPerm = iota + 1

	// PermAdminAdd - Permission index for adding new admins to THIS IRP Record
	PermAdminAdd

	// PermAdminRemove - Permission index for removing existing admins from THIS IRP Record
	PermAdminRemove

	// PermAdminModify - Permission index for modifying existing admins from THIS IRP Record
	PermAdminModify

	// PermValueAdd - Permission index for adding new values to THIS IRP Record
	PermValueAdd

	// PermValueRemove - Permission index for removing existing values from THIS IRP Record
	PermValueRemove

	// PermValueModify - Permission index for modifying existing values from THIS IRP Record
	PermValueModify

	// PermDeleteIRP - Permission index for deleting THIS IRP Record
	PermDeleteIRP AdminPerm = iota + 3
)

func (AdminPerm) ToInt

func (p AdminPerm) ToInt() int

type Attribute

type Attribute struct {
	Name  string `yaml:"name" json:"name"`
	Value string `yaml:"value" json:"value"`
}

Attribute - attributes for site information

func NewAttribute

func NewAttribute(name, value string) (sa Attribute)

NewAttribute - creates a new instance of attribute

type AuthResponse

type AuthResponse struct {
	Error         string `json:"error"`
	Authenticated bool   `json:"authenticated"`
	Nonce         string `json:"nonce"`
	SessionID     string `json:"sessionId"`
	LastAccess    int64  `json:"-"`
}

AuthResponse - response from LHS for authentication

func Authenticate

func Authenticate(server Server, authIndex int, authIRP string, j *JWK) (authResponse *AuthResponse, err error)

Authenticate - performs IRP Authentication and returns a valid response

type Config

type Config struct {
	Directory           string `yaml:"-"`
	ServerInfoDirectory string `yaml:"-"`
	//LibraryDirectory    string    `yaml:"-"`
	GHR []*Server `yaml:"-"`
}

Config - configuration information to this IRP Bridge

type Digest

type Digest struct {
	Index  int    `json:"index"`
	Digest string `json:"digest"`
}

Digest - stores a digest of a IRP index

type IRP

type IRP struct {
	ResponseCode int    `json:"responseCode,omitempty"`
	Handle       string `json:"handle,omitempty"`
	Values       Values `json:"values,omitempty"`
	Message      string `json:"message,omitempty"`
}

IRP - IRP Record structure for IRP HTTP REST

func Create

func Create(server Server, authResponse *AuthResponse, handleid string, irpValues Values, overwrite bool) (irpResponse IRP)

Create - creates a IRP ID with given values

func Delete

func Delete(server Server, authResponse *AuthResponse, handleid string) (irpResponse IRP)

Delete - deletes a given IRP Record

func Remove

func Remove(server Server, authResponse *AuthResponse, handleid string, indexes []int) (irpResponse IRP)

Remove - removes given indexes from a IRP Record

func Resolve

func Resolve(server Server, authResponse *AuthResponse, handleid string, param Parameter) (irpResponse IRP)

Resolve - resolves a given IRP ID using authentication

func Update

func Update(server Server, authResponse *AuthResponse, handleid string, irpValues Values, overwrite bool) (irpResponse IRP)

Update - updates a IRP ID with given values

func (*IRP) GetByIndex

func (irp *IRP) GetByIndex(irpIndex int) (value Value)

GetByIndex - returns a IRP Value by index

func (*IRP) GetByType

func (irp *IRP) GetByType(irpType string) (values []Value)

GetByType - returns a list of IRP Values by type

type Interface

type Interface struct {
	Admin    bool   `yaml:"admin" json:"admin"`
	Query    bool   `yaml:"query" json:"query"`
	Port     int    `yaml:"port" json:"port"`
	Protocol string `yaml:"protocol" json:"protocol"`
}

Interface - interface information for the site server

func NewInterface

func NewInterface(protocol string, port int, admin, query bool) (i *Interface)

NewInterface - creates a new instance of site interface

type JWK added in v1.1.0

type JWK signedtoken.JWK // create a new type based on `signedtoken.JWK` for reference in this library

func NewJWK

func NewJWK(key interface{}) (j *JWK, err error)

NewJWK - creates a new `JWK` istance from a given key

type Parameter

type Parameter struct {
	Indexes []int
	Types   []string
	// contains filtered or unexported fields
}

Parameter - optional parameters to send to the Connect function to not clutter up the input variables

type Server

type Server struct {
	Address    string      `json:"address"`
	Interfaces []Interface `yaml:"interfaces" json:"interfaces"`
	ServerID   int         `yaml:"serverId,omitempty" json:"serverId,omitempty"`
	PublicKey  struct {
		Format string `yaml:"format,omitempty" json:"format,omitempty"`
		Value  JWK    `yaml:"value,omitempty" json:"value,omitempty"`
	} `yaml:"publicKey,omitempty" json:"publicKey,omitempty"`
	// contains filtered or unexported fields
}

Server - server information stored in the site information

func GetPrefixSite

func GetPrefixSite(handleid string, srvType int8, tlsConfig *tls.Config) (server Server, err error)

GetPrefixSite - get where this prefix lives from the MPA

func NewServer

func NewServer(serverId int, address string, i *Interface) (s *Server)

func (*Server) AddInterface

func (s *Server) AddInterface(i *Interface)

AddInterface - adds a new interface for this server

func (*Server) AddPubKey

func (s *Server) AddPubKey(k *JWK)

AddPubKey - adds public key for this site information

func (*Server) GetHTTP

func (s *Server) GetHTTP() (i *Interface)

GetHTTP - returns the HTTP interface information

func (*Server) IsIPv4

func (s *Server) IsIPv4() bool

IsIPv4 - check if the string is an IP version 4 by checking number of colon

func (*Server) IsIPv6

func (s *Server) IsIPv6() bool

IsIPv6 - check if the string is an IP version 6 by checking number of colon

type SiteInfo

type SiteInfo struct {
	Attributes      []Attribute `yaml:"attributes" json:"attributes,omitempty"`
	MultiPrimary    bool        `yaml:"multiPrimary,omitempty" json:"multiPrimary"`
	PrimarySite     bool        `yaml:"primarySite,omitempty" json:"primarySite"`
	ProtocolVersion string      `yaml:"protocolVersion,omitempty" json:"protocolVersion"`
	SerialNumber    int         `yaml:"serialNumber,omitempty" json:"serialNumber"`
	Servers         []Server    `yaml:"servers,omitempty" json:"servers,omitempty"`
	Version         int         `yaml:"version,omitempty" json:"version,omitempty"`
	TTL             int64       `yaml:"ttl" json:"ttl"`                // we keep TTL here to be used by the library or applications
	LastUpdate      string      `yaml:"lastupdate,omitempty" json:"-"` // used by library to know if the cached site information is still valid
}

SiteInfo - Handle data for sites

func NewSiteInfo

func NewSiteInfo() (siteInfo *SiteInfo)

NewSiteInfo - creates a new instance of site information

func (*SiteInfo) AddServer

func (si *SiteInfo) AddServer(server *Server)

AddServer - add new server instance to this siteinfo

func (*SiteInfo) GetServers

func (si *SiteInfo) GetServers() (servers []Server)

GetServers - returns list of servers configured for this prefix

type VList

type VList struct {
	Index  int `json:"index"`
	Values []struct {
		IRP   string `json:"handle"`
		Index int    `json:"index"`
	} `json:"values"`
	TTL       int64 `json:"ttl"`        // optional. default value will be used if this is not given
	AdminOnly bool  `json:"admin_only"` // optional. sane public permissions will be set if not given
}

VList - format for IRP Request storing HS_VLIST information

type VListValue

type VListValue struct {
	Handle string `json:"handle"`
	Index  int    `json:"index"`
}

VListValue - stores VList values

type VListValues

type VListValues []VListValue

VListValues - array of VList values for storage in an Handle Record

func NewVList

func NewVList() (vListValues *VListValues)

NewVList - creates a new instance of `VListValues`

func (*VListValues) Add

func (vListValues *VListValues) Add(handleid string, index int) (err error)

Add - adds a puid and index to the `VListValues` instance

func (*VListValues) Remove

func (vListValues *VListValues) Remove(handleid string, index int) (err error)

Remove - removes a puid and index from the `VListValues` instance

type Value

type Value struct {
	Index int    `json:"index"`
	Type  string `json:"type"`

	Data struct {
		Format string      `json:"format"`
		Value  interface{} `json:"value"`
	} `json:"data"`

	Permissions string `json:"permissions,omitempty"`
	TTL         int64  `json:"ttl"`
	Timestamp   string `json:"timestamp,omitempty"`
	// contains filtered or unexported fields
}

Value - IRP value structure

func CreateDigest

func CreateDigest(handleid string, index int, expires int64, irpValues Values, authIndex int, authIRP string, j *JWK) (dgValue *Value, err error)

CreateDigest - creates digests of given IRP values

func (*Value) OK

func (value *Value) OK() (ok bool)

OK - checks to make sure a value is ok to be used

func (*Value) SetPermPrivateRW

func (value *Value) SetPermPrivateRW()

SetPermPrivateRW - sets permission for a IRP Value for admin only

func (*Value) SetPermPublicRead

func (value *Value) SetPermPublicRead(hasPerm bool)

SetPermPublicRead - sets permission for a IRP Value for public read

type ValuePerm

type ValuePerm int

type Values

type Values []Value

Values - array of values for a IRP Request

func (*Values) Add

func (irpValues *Values) Add(index int, irpType string, irpFormat string, irpValue interface{}, ttl int64, isPrivate bool)

Add - generic add value to an IRP Request

func (*Values) AddAdmin

func (irpValues *Values) AddAdmin(index int, adminIndex int, adminID string, ttl int64, isPrivate bool) (err error)

AddAdmin - adds an admin value to an IRP Request Values

func (*Values) AddBase64

func (irpValues *Values) AddBase64(index int, irpType string, input []byte, ttl int64, isPrivate bool)

AddBase64 - adds a base64 (standard encoding) value to an IRP Request Values

func (*Values) AddKey

func (irpValues *Values) AddKey(index int, irpType string, j *JWK, ttl int64, isPrivate bool)

AddKey - adds a JWK key value to an IRP Request Values

func (*Values) AddSite

func (irpValues *Values) AddSite(index int, irpType string, si *SiteInfo, ttl int64, isPrivate bool)

AddSite - adds a site information value to an IRP Request Values

func (*Values) AddString

func (irpValues *Values) AddString(index int, irpType string, str string, ttl int64, isPrivate bool)

AddString - adds a string value to an IRP Request Values

func (*Values) AddVList

func (irpValues *Values) AddVList(index int, irpValue *VListValues, ttl int64, isPrivate bool)

AddVList - adds a VLIST value to an IRP Request Values

func (*Values) AddValue

func (irpValues *Values) AddValue(value *Value)

AddValue - adds a value to an IRP Request

Jump to

Keyboard shortcuts

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