sdk

package module
v0.3.21 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2024 License: BSD-3-Clause-Clear Imports: 52 Imported by: 9

README

OpenTDF Data Security SDK

A Go implementation of the OpenTDF protocol, and access library for services included in the Data Security Platform.

Note: if you are consuming the SDK as a submodule you may need to add replace directives as follows:

replace (
  github.com/opentdf/platform/service => ./opentdf/service
	github.com/opentdf/platform/lib/fixtures => ./opentdf/lib/fixtures
	github.com/opentdf/platform/protocol/go => ./opentdf/protocol/go
	github.com/opentdf/platform/lib/ocrypto => ./opentdf/lib/ocrypto
	github.com/opentdf/platform/sdk => ./opentdf/sdk
	github.com/opentdf/platform/service => ./opentdf/service
)

Quick Start of the Go SDK

package main

import "fmt"
import "bytes"
import "io"
import "os"
import "strings"
import "github.com/opentdf/platform/sdk"


func main() {
  s, _ := sdk.New(
    sdk.WithAuth(mtls.NewGRPCAuthorizer(creds) /* or OIDC or whatever */),
    sdk.WithDataSecurityConfig(/* attribute schemas, kas multi-attribute mapping */),
  )

  plaintext := strings.NewReader("Hello, world!")
  var ciphertext bytes.Buffer
  _, err := s.CreateTDF(
    ciphertext,
    plaintext,
    sdk.WithDataAttributes("https://example.com/attr/Classification/value/Open"),
  )
  if err != nil {
    panic(err)
  }

  fmt.Printf("Ciphertext is %s bytes long", ciphertext.Len())

  ct2 := make([]byte, ciphertext.Len())
  copy(ct2, ciphertext.Bytes())
  r, err := s.NewTDFReader(bytes.NewReader(ct2))
  f, err := os.Create("output.txt")
  if err != nil {
    panic(err)
  }
  io.Copy(f, r)
}

Development

To test, run

go test ./... -short -race -cover

Documentation

Index

Constants

View Source
const (
	// Failure while connecting to a service.
	// Check your configuration and/or retry.
	ErrGrpcDialFailed                 = Error("failed to dial grpc endpoint")
	ErrShutdownFailed                 = Error("failed to shutdown sdk")
	ErrPlatformConfigFailed           = Error("failed to retrieve platform configuration")
	ErrPlatformEndpointMalformed      = Error("platform endpoint is malformed")
	ErrPlatformIssuerNotFound         = Error("issuer not found in well-known idp configuration")
	ErrPlatformAuthzEndpointNotFound  = Error("authorization_endpoint not found in well-known idp configuration")
	ErrPlatformTokenEndpointNotFound  = Error("token_endpoint not found in well-known idp configuration")
	ErrPlatformPublicClientIDNotFound = Error("public_client_id not found in well-known idp configuration")
	ErrAccessTokenInvalid             = Error("access token is invalid")
)
View Source
const (
	JSONFormat = iota
	XMLFormat
)
View Source
const (
	HS256 = iota
	GMAC
)
View Source
const (
	ErrNanoTDFHeaderRead = Error("nanoTDF read error")
)

Variables

View Source
var (

	// Exposed tamper detection errors, Catch all possible tamper errors with errors.Is(ErrTampered)
	ErrTampered                = errors.New("tamper detected")
	ErrRootSigValidation       = fmt.Errorf("[%w] tdf: failed integrity check on root signature", ErrTampered)
	ErrSegSizeMismatch         = fmt.Errorf("[%w] tdf: mismatch encrypted segment size in manifest", ErrTampered)
	ErrSegSigValidation        = fmt.Errorf("[%w] tdf: failed integrity check on segment hash", ErrTampered)
	ErrTDFPayloadReadFail      = fmt.Errorf("[%w] tdf: fail to read payload from tdf", ErrTampered)
	ErrTDFPayloadInvalidOffset = fmt.Errorf("[%w] sdk.Reader.ReadAt: negative offset", ErrTampered)
	ErrRewrapBadRequest        = fmt.Errorf("[%w] tdf: rewrap request 400", ErrTampered)
	ErrRootSignatureFailure    = fmt.Errorf("[%w] tdf: issue verifying root signature", ErrTampered)
)
View Source
var (
	ErrInvalid = errors.New("invalid type")
)

Functions

func IsValidNanoTdf added in v0.3.5

func IsValidNanoTdf(reader io.ReadSeeker) (bool, error)

IsValidNanoTdf detects whether, or not the reader is a valid Nano TDF. Reader is reset after the check.

func IsValidTdf added in v0.3.5

func IsValidTdf(reader io.ReadSeeker) (bool, error)

func NewCertExchangeTokenSource added in v0.2.1

func NewCertExchangeTokenSource(info oauth.CertExchangeInfo, credentials oauth.ClientCredentials, idpTokenEndpoint string, dpop *ocrypto.RsaKeyPair) (auth.AccessTokenSource, error)

func SanitizePlatformEndpoint added in v0.2.7

func SanitizePlatformEndpoint(e string) (string, error)

func SizeOfAuthTagForCipher added in v0.2.4

func SizeOfAuthTagForCipher(cipherType CipherMode) (int, error)

SizeOfAuthTagForCipher - Return the size in bytes of auth tag to be used for aes gcm encryption

Types

type AppliesToState added in v0.3.5

type AppliesToState string

AppliesToState indicates whether the assertion applies to encrypted or unencrypted data.

const (
	Encrypted   AppliesToState = "encrypted"
	Unencrypted AppliesToState = "unencrypted"
)

func (AppliesToState) String added in v0.3.5

func (ats AppliesToState) String() string

String returns the string representation of the applies to state.

type Assertion

type Assertion struct {
	ID             string         `json:"id"`
	Type           AssertionType  `json:"type"`
	Scope          Scope          `json:"scope"`
	AppliesToState AppliesToState `json:"appliesToState,omitempty"`
	Statement      Statement      `json:"statement"`
	Binding        Binding        `json:"binding,omitempty"`
}

func (Assertion) GetHash added in v0.3.5

func (a Assertion) GetHash() ([]byte, error)

GetHash returns the hash of the assertion in hex format.

func (*Assertion) Sign added in v0.3.5

func (a *Assertion) Sign(hash, sig string, key AssertionKey) error

Sign signs the assertion with the given hash and signature using the key. It returns an error if the signing fails. The assertion binding is updated with the method and the signature.

func (Assertion) Verify added in v0.3.5

func (a Assertion) Verify(key AssertionKey) (string, string, error)

Verify checks the binding signature of the assertion and returns the hash and the signature. It returns an error if the verification fails.

type AssertionConfig added in v0.3.5

type AssertionConfig struct {
	ID             string         `validate:"required"`
	Type           AssertionType  `validate:"required"`
	Scope          Scope          `validate:"required"`
	AppliesToState AppliesToState `validate:"required"`
	Statement      Statement
	SigningKey     AssertionKey
}

AssertionConfig is a shadow of Assertion with the addition of the signing key. It is used on creation

type AssertionKey added in v0.3.5

type AssertionKey struct {
	// Algorithm of the key.
	Alg AssertionKeyAlg
	// Key value.
	Key interface{}
}

AssertionKey represents a key for assertions.

func (AssertionKey) Algorithm added in v0.3.5

func (k AssertionKey) Algorithm() AssertionKeyAlg

Algorithm returns the algorithm of the key.

func (AssertionKey) IsEmpty added in v0.3.5

func (k AssertionKey) IsEmpty() bool

IsEmpty returns true if the key and the algorithm are empty.

type AssertionKeyAlg added in v0.3.5

type AssertionKeyAlg string

AssertionKeyAlg represents the algorithm of an assertion key.

const (
	AssertionKeyAlgRS256 AssertionKeyAlg = "RS256"
	AssertionKeyAlgHS256 AssertionKeyAlg = "HS256"
)

func (AssertionKeyAlg) String added in v0.3.5

func (a AssertionKeyAlg) String() string

String returns the string representation of the algorithm.

type AssertionType added in v0.3.5

type AssertionType string

AssertionType represents the type of the assertion.

const (
	HandlingAssertion AssertionType = "handling"
	BaseAssertion     AssertionType = "other"
)

func (AssertionType) String added in v0.3.5

func (at AssertionType) String() string

String returns the string representation of the assertion type.

type AssertionVerificationKeys added in v0.3.5

type AssertionVerificationKeys struct {
	// Default key to use if the key for the assertion ID is not found.
	DefaultKey AssertionKey
	// Map of assertion ID to key.
	Keys map[string]AssertionKey
}

AssertionVerificationKeys represents the verification keys for assertions.

func (AssertionVerificationKeys) Get added in v0.3.5

func (k AssertionVerificationKeys) Get(assertionID string) (AssertionKey, error)

Returns the key for the given assertion ID or the default key if the key is not found. If the default key is not set, it returns error.

func (AssertionVerificationKeys) IsEmpty added in v0.3.5

func (k AssertionVerificationKeys) IsEmpty() bool

IsEmpty returns true if the default key and the keys map are empty.

type AttributeNameFQN added in v0.3.9

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

AttributeNameFQN is a utility type to represent an FQN for an attribute.

func NewAttributeNameFQN added in v0.3.9

func NewAttributeNameFQN(u string) (AttributeNameFQN, error)

func (AttributeNameFQN) Authority added in v0.3.9

func (a AttributeNameFQN) Authority() string

func (AttributeNameFQN) Name added in v0.3.9

func (a AttributeNameFQN) Name() string

func (AttributeNameFQN) Prefix added in v0.3.9

func (a AttributeNameFQN) Prefix() string

func (AttributeNameFQN) Select added in v0.3.9

func (AttributeNameFQN) String added in v0.3.9

func (a AttributeNameFQN) String() string

type AttributeValueFQN added in v0.3.9

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

AttributeValueFQN is a utility type to represent an FQN for an attribute value.

func NewAttributeValueFQN added in v0.3.9

func NewAttributeValueFQN(u string) (AttributeValueFQN, error)

func (AttributeValueFQN) Authority added in v0.3.9

func (a AttributeValueFQN) Authority() string

func (AttributeValueFQN) Name added in v0.3.9

func (a AttributeValueFQN) Name() string

func (AttributeValueFQN) Prefix added in v0.3.9

func (AttributeValueFQN) String added in v0.3.9

func (a AttributeValueFQN) String() string

func (AttributeValueFQN) Value added in v0.3.9

func (a AttributeValueFQN) Value() string

type Binding added in v0.3.5

type Binding struct {
	// Method used to bind the assertion. (e.g. jws)
	Method string `json:"method,omitempty"`
	// Signature of the assertion.
	Signature string `json:"signature,omitempty"`
}

Binding enforces cryptographic integrity of the assertion. So the can't be modified or copied to another tdf.

type BindingMethod added in v0.3.5

type BindingMethod string

BindingMethod represents the method used to bind the assertion.

const (
	JWS BindingMethod = "jws"
)

func (BindingMethod) String added in v0.3.5

func (bm BindingMethod) String() string

String returns the string representation of the binding method.

type CertExchangeTokenSource added in v0.2.1

type CertExchangeTokenSource struct {
	auth.AccessTokenSource
	IdpEndpoint string
	// contains filtered or unexported fields
}

func (*CertExchangeTokenSource) AccessToken added in v0.2.1

func (*CertExchangeTokenSource) MakeToken added in v0.2.1

func (c *CertExchangeTokenSource) MakeToken(tokenMaker func(jwk.Key) ([]byte, error)) ([]byte, error)

type CipherMode added in v0.2.4

type CipherMode int

type EncryptedMetadata

type EncryptedMetadata struct {
	Cipher string `json:"ciphertext"`
	Iv     string `json:"iv"`
}

type EncryptionInformation

type EncryptionInformation struct {
	KeyAccessType        string      `json:"type"`
	Policy               string      `json:"policy"`
	KeyAccessObjs        []KeyAccess `json:"keyAccess"`
	Method               Method      `json:"method"`
	IntegrityInformation `json:"integrityInformation"`
}

type ErrAssertionFailure added in v0.3.16

type ErrAssertionFailure struct {
	ID string
}

Custom error struct for Assertion errors

func (ErrAssertionFailure) Error added in v0.3.16

func (e ErrAssertionFailure) Error() string

func (ErrAssertionFailure) Unwrap added in v0.3.16

func (e ErrAssertionFailure) Unwrap() error

type Error

type Error string

func (Error) Error

func (c Error) Error() string

type IDPAccessTokenSource

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

IDPAccessTokenSource credentials that allow us to connect to an IDP and obtain an access token that is bound to a DPoP key

func NewIDPAccessTokenSource

func NewIDPAccessTokenSource(
	credentials oauth.ClientCredentials, idpTokenEndpoint string, scopes []string, key *ocrypto.RsaKeyPair) (*IDPAccessTokenSource, error)

func (*IDPAccessTokenSource) AccessToken

func (t *IDPAccessTokenSource) AccessToken(ctx context.Context, client *http.Client) (auth.AccessToken, error)

AccessToken use a pointer receiver so that the token state is shared

func (*IDPAccessTokenSource) MakeToken

func (t *IDPAccessTokenSource) MakeToken(tokenMaker func(jwk.Key) ([]byte, error)) ([]byte, error)

type IDPTokenExchangeTokenSource

type IDPTokenExchangeTokenSource struct {
	IDPAccessTokenSource
	oauth.TokenExchangeInfo
}

func NewIDPTokenExchangeTokenSource

func NewIDPTokenExchangeTokenSource(exchangeInfo oauth.TokenExchangeInfo, credentials oauth.ClientCredentials, idpTokenEndpoint string, scopes []string, key *ocrypto.RsaKeyPair) (*IDPTokenExchangeTokenSource, error)

func (*IDPTokenExchangeTokenSource) AccessToken

func (i *IDPTokenExchangeTokenSource) AccessToken(ctx context.Context, client *http.Client) (auth.AccessToken, error)

func (*IDPTokenExchangeTokenSource) MakeToken

func (i *IDPTokenExchangeTokenSource) MakeToken(keyMaker func(jwk.Key) ([]byte, error)) ([]byte, error)

type IntegrityAlgorithm

type IntegrityAlgorithm = int

type IntegrityInformation

type IntegrityInformation struct {
	RootSignature           `json:"rootSignature"`
	SegmentHashAlgorithm    string    `json:"segmentHashAlg"`
	DefaultSegmentSize      int64     `json:"segmentSizeDefault"`
	DefaultEncryptedSegSize int64     `json:"encryptedSegmentSizeDefault"`
	Segments                []Segment `json:"segments"`
}

type KASClient

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

type KASInfo

type KASInfo struct {
	// URL of the KAS server
	URL string
	// Public key can be empty.
	// If it is empty, the public key will be fetched from the KAS server.
	PublicKey string
	// Key identifier associated with the given key, if present.
	KID string
	// The algorithm associated with this key
	Algorithm string
	// If this KAS should be used as the default for 'encrypt' calls
	Default bool
}

KASInfo contains Key Access Server information.

type KeyAccess

type KeyAccess struct {
	KeyType           string      `json:"type"`
	KasURL            string      `json:"url"`
	Protocol          string      `json:"protocol"`
	WrappedKey        string      `json:"wrappedKey"`
	PolicyBinding     interface{} `json:"policyBinding"`
	EncryptedMetadata string      `json:"encryptedMetadata,omitempty"`
	KID               string      `json:"kid,omitempty"`
	SplitID           string      `json:"sid,omitempty"`
}

type Manifest

type Manifest struct {
	EncryptionInformation `json:"encryptionInformation"`
	Payload               `json:"payload"`
	Assertions            []Assertion `json:"assertions,omitempty"`
}

type Method

type Method struct {
	Algorithm    string `json:"algorithm"`
	IV           string `json:"iv"`
	IsStreamable bool   `json:"isStreamable"`
}

type NanoTDFConfig added in v0.2.4

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

func (*NanoTDFConfig) EnableCollection added in v0.3.21

func (config *NanoTDFConfig) EnableCollection()

EnableCollection Experimental: Enables Collection in NanoTDFConfig. Reuse NanoTDFConfig to add nTDFs to a Collection.

func (*NanoTDFConfig) EnableECDSAPolicyBinding added in v0.2.5

func (config *NanoTDFConfig) EnableECDSAPolicyBinding()

EnableECDSAPolicyBinding enable ecdsa policy binding

func (*NanoTDFConfig) SetAttributes added in v0.2.4

func (config *NanoTDFConfig) SetAttributes(attributes []string) error

SetAttributes - set the attributes to be used for this nanoTDF

func (*NanoTDFConfig) SetKasURL added in v0.2.4

func (config *NanoTDFConfig) SetKasURL(url string) error

SetKasURL - set the URL of the KAS endpoint to be used for this nanoTDF

type NanoTDFHeader added in v0.2.4

type NanoTDFHeader struct {
	EphemeralKey        []byte
	EncryptedPolicyBody []byte
	// contains filtered or unexported fields
}

func NewNanoTDFHeaderFromReader added in v0.2.4

func NewNanoTDFHeaderFromReader(reader io.Reader) (NanoTDFHeader, uint32, error)

func (*NanoTDFHeader) ECCurve added in v0.2.5

func (header *NanoTDFHeader) ECCurve() (elliptic.Curve, error)

func (*NanoTDFHeader) GetCipher added in v0.2.4

func (header *NanoTDFHeader) GetCipher() CipherMode

GetCipher -- get the cipher from the nano tdf header

func (*NanoTDFHeader) GetKasURL added in v0.3.12

func (header *NanoTDFHeader) GetKasURL() ResourceLocator

func (*NanoTDFHeader) IsEcdsaBindingEnabled added in v0.2.5

func (header *NanoTDFHeader) IsEcdsaBindingEnabled() bool

func (*NanoTDFHeader) VerifyPolicyBinding added in v0.2.5

func (header *NanoTDFHeader) VerifyPolicyBinding() (bool, error)

type NanoTDFOption added in v0.2.4

type NanoTDFOption func(*NanoTDFConfig) error

func WithECDSAPolicyBinding added in v0.2.5

func WithECDSAPolicyBinding() NanoTDFOption

WithECDSAPolicyBinding enable ecdsa policy binding

func WithNanoDataAttributes added in v0.2.4

func WithNanoDataAttributes(attributes ...string) NanoTDFOption

WithNanoDataAttributes appends the given data attributes to the bound policy

type OAuthAccessTokenSource added in v0.3.9

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

OAuthAccessTokenSource allow connecting to an IDP and obtain a DPoP bound access token

func NewOAuthAccessTokenSource added in v0.3.9

func NewOAuthAccessTokenSource(
	source oauth2.TokenSource, scopes []string, key *ocrypto.RsaKeyPair,
) (*OAuthAccessTokenSource, error)

func (*OAuthAccessTokenSource) AccessToken added in v0.3.9

AccessToken use a pointer receiver so that the token state is shared

func (*OAuthAccessTokenSource) MakeToken added in v0.3.9

func (t *OAuthAccessTokenSource) MakeToken(tokenMaker func(jwk.Key) ([]byte, error)) ([]byte, error)

type Option

type Option func(*config)

func WithClientCredentials

func WithClientCredentials(clientID, clientSecret string, scopes []string) Option

WithClientCredentials returns an Option that sets up authentication with client credentials.

func WithCustomAuthorizationConnection deprecated

func WithCustomAuthorizationConnection(conn *grpc.ClientConn) Option

Deprecated: Use WithCustomCoreConnection instead

func WithCustomCoreConnection added in v0.3.7

func WithCustomCoreConnection(conn *grpc.ClientConn) Option

WithCoreConnection returns an Option that sets up a connection to the core platform

func WithCustomEntityResolutionConnection deprecated added in v0.2.3

func WithCustomEntityResolutionConnection(conn *grpc.ClientConn) Option

Deprecated: Use WithCustomCoreConnection instead

func WithCustomPolicyConnection deprecated

func WithCustomPolicyConnection(conn *grpc.ClientConn) Option

Deprecated: Use WithCustomCoreConnection instead

func WithCustomWellknownConnection added in v0.2.5

func WithCustomWellknownConnection(conn *grpc.ClientConn) Option

func WithExtraDialOptions

func WithExtraDialOptions(dialOptions ...grpc.DialOption) Option

func WithIPC added in v0.2.7

func WithIPC() Option

WithIPC returns an Option that indicates the SDK should use IPC for communication this will allow the platform endpoint to be an empty string

func WithInsecurePlaintextConn added in v0.2.1

func WithInsecurePlaintextConn() Option

WithInsecurePlaintextConn returns an Option that sets up HTTP connection sent in the clear.

func WithInsecureSkipVerifyConn added in v0.2.1

func WithInsecureSkipVerifyConn() Option

WithInsecureSkipVerifyConn returns an Option that sets up HTTPS connection without verification.

func WithNoKIDInKAO added in v0.2.8

func WithNoKIDInKAO() Option

WithNoKIDInKAO disables storing the KID in the KAO. This allows generating TDF files that are compatible with legacy file formats (no KID).

func WithNoKIDInNano added in v0.3.12

func WithNoKIDInNano() Option

WithNoKIDInNano disables storing the KID in the KAS ResourceLocator. This allows generating NanoTDF files that are compatible with legacy file formats (no KID).

func WithOAuthAccessTokenSource added in v0.3.9

func WithOAuthAccessTokenSource(t oauth2.TokenSource) Option

WithOAuthAccessTokenSource directs the SDK to use a standard OAuth2 token source for authentication

func WithPlatformConfiguration added in v0.2.5

func WithPlatformConfiguration(platformConfiguration PlatformConfiguration) Option

WithPlatformConfiguration allows you to override the remote platform configuration Use this option with caution, as it may lead to unexpected behavior

func WithSessionEncryptionRSA added in v0.2.4

func WithSessionEncryptionRSA(key *rsa.PrivateKey) Option

The session key pair is used to encrypt responses from KAS for a given session and can be reused across an entire session. Please use with caution.

func WithSessionSignerRSA added in v0.2.4

func WithSessionSignerRSA(key *rsa.PrivateKey) Option

The DPoP key pair is used to implement sender constrained tokens from the identity provider, and should be associated with the lifetime of a session for a given identity. Please use with caution.

func WithStoreCollectionHeaders added in v0.3.21

func WithStoreCollectionHeaders() Option

WithStoreCollectionHeaders Experimental: returns an Option that sets up storing dataset keys for nTDFs

func WithTLSCredentials added in v0.2.1

func WithTLSCredentials(tls *tls.Config, audience []string) Option

func WithTokenEndpoint

func WithTokenEndpoint(tokenEndpoint string) Option

WithTokenEndpoint When we implement service discovery using a .well-known endpoint this option may become deprecated Deprecated: SDK will discover the token endpoint from the platform configuration

func WithTokenExchange

func WithTokenExchange(subjectToken string, audience []string) Option

WithTokenExchange specifies that the SDK should obtain its access token by exchanging the given token for a new one

type Payload

type Payload struct {
	Type        string `json:"type"`
	URL         string `json:"url"`
	Protocol    string `json:"protocol"`
	MimeType    string `json:"mimeType"`
	IsEncrypted bool   `json:"isEncrypted"`
}

type PlatformConfiguration added in v0.2.5

type PlatformConfiguration map[string]interface{}

func (PlatformConfiguration) AuthzEndpoint added in v0.3.8

func (c PlatformConfiguration) AuthzEndpoint() (string, error)

func (PlatformConfiguration) Issuer added in v0.3.8

func (c PlatformConfiguration) Issuer() (string, error)

func (PlatformConfiguration) PublicClientID added in v0.3.8

func (c PlatformConfiguration) PublicClientID() (string, error)

func (PlatformConfiguration) TokenEndpoint added in v0.3.8

func (c PlatformConfiguration) TokenEndpoint() (string, error)

type PolicyBinding added in v0.3.3

type PolicyBinding struct {
	Alg  string `json:"alg"`
	Hash string `json:"hash"`
}

type PolicyBody

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

type PolicyObject

type PolicyObject struct {
	UUID string `json:"uuid"`
	Body struct {
		DataAttributes []attributeObject `json:"dataAttributes"`
		Dissem         []string          `json:"dissem"`
	} `json:"body"`
}

type Reader

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

Loads and reads ZTDF files

func (*Reader) DataAttributes

func (r *Reader) DataAttributes() ([]string, error)

DataAttributes return the data attributes present in tdf.

func (*Reader) Init added in v0.2.11

func (r *Reader) Init(ctx context.Context) error

Do any network based operations required. This allows making the requests cancellable

func (*Reader) Manifest

func (r *Reader) Manifest() Manifest

func (*Reader) Policy

func (r *Reader) Policy() (PolicyObject, error)

Policy returns a copy of the policy object in manifest, if it is valid. Otherwise, returns an error.

func (*Reader) Read

func (r *Reader) Read(p []byte) (int, error)

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. It returns an io.EOF error when the stream ends.

func (*Reader) ReadAt

func (r *Reader) ReadAt(buf []byte, offset int64) (int, error)

ReadAt reads len(p) bytes into p starting at offset off in the underlying input source. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. It returns an io.EOF error when the stream ends. NOTE: For larger tdf sizes use sdk.GetTDFPayload for better performance

func (*Reader) UnencryptedMetadata

func (r *Reader) UnencryptedMetadata() ([]byte, error)

UnencryptedMetadata return decrypted metadata in manifest.

func (*Reader) UnsafePayloadKeyRetrieval added in v0.3.5

func (r *Reader) UnsafePayloadKeyRetrieval() ([]byte, error)

*WARNING:* Using this function is unsafe since KAS will no longer be able to prevent access to the key.

Retrieve the payload key, either from performing an unwrap or from a previous unwrap, and write it to a user buffer.

OUTPUTS:

  • []byte - Byte array containing the DEK.
  • error - If an error occurred while processing

func (*Reader) WriteTo

func (r *Reader) WriteTo(writer io.Writer) (int64, error)

WriteTo writes data to writer until there's no more data to write or when an error occurs. This implements the io.WriterTo interface.

type RequestBody

type RequestBody struct {
	KeyAccess       `json:"keyAccess"`
	ClientPublicKey string `json:"clientPublicKey"`
	Policy          string `json:"policy"`
}

type ResourceLocator added in v0.2.4

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

ResourceLocator - structure to contain a protocol + body comprising an URL

func NewResourceLocator added in v0.2.4

func NewResourceLocator(url string) (*ResourceLocator, error)

func NewResourceLocatorFromReader added in v0.2.4

func NewResourceLocatorFromReader(reader io.Reader) (*ResourceLocator, error)

func (ResourceLocator) GetIdentifier added in v0.3.12

func (rl ResourceLocator) GetIdentifier() (string, error)

GetIdentifier - identifier is returned if the correct protocol enum is set else error padding is removed unlike rl.identifier direct access

func (ResourceLocator) GetURL added in v0.3.12

func (rl ResourceLocator) GetURL() (string, error)

GetURL - Retrieve a fully qualified protocol+body URL string from a ResourceLocator struct

type RootSignature

type RootSignature struct {
	Algorithm string `json:"alg"`
	Signature string `json:"sig"`
}

type SDK

func New

func New(platformEndpoint string, opts ...Option) (*SDK, error)

func (SDK) Close

func (s SDK) Close() error

Close closes the underlying grpc.ClientConn.

func (SDK) Conn

func (s SDK) Conn() *grpc.ClientConn

Conn returns the underlying grpc.ClientConn.

func (SDK) CreateNanoTDF added in v0.2.4

func (s SDK) CreateNanoTDF(writer io.Writer, reader io.Reader, config NanoTDFConfig) (uint32, error)

CreateNanoTDF - reads plain text from the given reader and saves it to the writer, subject to the given options

func (SDK) CreateTDF

func (s SDK) CreateTDF(writer io.Writer, reader io.ReadSeeker, opts ...TDFOption) (*TDFObject, error)

CreateTDF reads plain text from the given reader and saves it to the writer, subject to the given options

func (SDK) CreateTDFContext added in v0.3.0

func (s SDK) CreateTDFContext(ctx context.Context, writer io.Writer, reader io.ReadSeeker, opts ...TDFOption) (*TDFObject, error)

CreateTDFContext reads plain text from the given reader and saves it to the writer, subject to the given options

func (SDK) LoadTDF

func (s SDK) LoadTDF(reader io.ReadSeeker, opts ...TDFReaderOption) (*Reader, error)

LoadTDF loads the tdf and prepare for reading the payload from TDF

func (SDK) NewNanoTDFConfig added in v0.2.4

func (s SDK) NewNanoTDFConfig() (*NanoTDFConfig, error)

NewNanoTDFConfig - Create a new instance of a nanoTDF config

func (SDK) ReadNanoTDF added in v0.2.4

func (s SDK) ReadNanoTDF(writer io.Writer, reader io.ReadSeeker) (uint32, error)

ReadNanoTDF - read the nano tdf and return the decrypted data from it

func (SDK) ReadNanoTDFContext added in v0.2.11

func (s SDK) ReadNanoTDFContext(ctx context.Context, writer io.Writer, reader io.ReadSeeker) (uint32, error)

ReadNanoTDFContext - allows cancelling the reader

func (*SDK) StoreKASKeys added in v0.3.14

func (s *SDK) StoreKASKeys(url string, keys *policy.KasPublicKeySet) error

StoreKASKeys caches the given values as the public keys associated with the KAS at the given URL, replacing any existing keys that are cached for that URL with the same algorithm and URL. Only one key per url and algorithm is stored in the cache, so only store the most recent known key per url & algorithm pair.

type Scope added in v0.3.5

type Scope string

Scope represents the object which the assertion applies to.

const (
	TrustedDataObj Scope = "tdo"
	Paylaod        Scope = "payload"
)

func (Scope) String added in v0.3.5

func (s Scope) String() string

String returns the string representation of the scope.

type Segment

type Segment struct {
	Hash          string `json:"hash"`
	Size          int64  `json:"segmentSize"`
	EncryptedSize int64  `json:"encryptedSegmentSize"`
}

type Statement added in v0.3.5

type Statement struct {
	// Format describes the payload encoding format. (e.g. json)
	Format string `json:"format,omitempty" validate:"required"`
	// Schema describes the schema of the payload. (e.g. tdf)
	Schema string `json:"schema,omitempty" validate:"required"`
	// Value is the payload of the assertion.
	Value string `json:"value,omitempty"  validate:"required"`
}

Statement includes information applying to the scope of the assertion. It could contain rights, handling instructions, or general metadata.

type TDFConfig

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

TDFConfig Internal config struct for building TDF options.

type TDFFormat

type TDFFormat = int

type TDFObject

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

func (*TDFObject) Manifest

func (t *TDFObject) Manifest() Manifest

func (TDFObject) Size added in v0.2.11

func (t TDFObject) Size() int64

type TDFOption

type TDFOption func(*TDFConfig) error

func WithAssertions added in v0.3.5

func WithAssertions(assertionList ...AssertionConfig) TDFOption

WithAssertions returns an Option that add assertions to TDF.

func WithAutoconfigure added in v0.3.0

func WithAutoconfigure(enable bool) TDFOption

WithAutoconfigure toggles inferring KAS info for encrypt from data attributes. This will use the Attributes service to look up key access grants. These are KAS URLs associated with attributes. Defaults to enabled.

func WithDataAttributeValues added in v0.3.0

func WithDataAttributeValues(attributes ...*policy.Value) TDFOption

WithDataAttributeValues appends the given data attributes to the bound policy. Unlike `WithDataAttributes`, this will not trigger an attribute definition lookup during autoconfigure. That is, to use autoconfigure in an 'offline' context, you must first store the relevant attribute information locally and load it to the `CreateTDF` method with this option.

func WithDataAttributes

func WithDataAttributes(attributes ...string) TDFOption

WithDataAttributes appends the given data attributes to the bound policy

func WithKasInformation

func WithKasInformation(kasInfoList ...KASInfo) TDFOption

WithKasInformation adds all the kas urls and their corresponding public keys that is required to create and read the tdf. For writing TDFs, this is optional, but adding it can bypass key lookup.

During creation, if the public key is set, the kas will not be contacted for the latest key. Please make sure to set the KID if the PublicKey is set to include a KID in any key wrappers.

func WithMetaData

func WithMetaData(metaData string) TDFOption

WithMetaData returns an Option that add metadata to TDF.

func WithMimeType added in v0.2.3

func WithMimeType(mimeType string) TDFOption

func WithSegmentSize

func WithSegmentSize(size int64) TDFOption

WithSegmentSize returns an Option that set the default segment size within the TDF. Any excessively large or small values will be replaced with a supported value.

type TDFReaderConfig added in v0.3.5

type TDFReaderConfig struct {
	// Optional Map of Assertion Verification Keys
	AssertionVerificationKeys AssertionVerificationKeys
	// contains filtered or unexported fields
}

type TDFReaderOption added in v0.3.5

type TDFReaderOption func(*TDFReaderConfig) error

func WithAssertionVerificationKeys added in v0.3.5

func WithAssertionVerificationKeys(keys AssertionVerificationKeys) TDFReaderOption

func WithDisableAssertionVerification added in v0.3.17

func WithDisableAssertionVerification(disable bool) TDFReaderOption

type TdfType added in v0.3.5

type TdfType string
const (
	Invalid  TdfType = "Invalid"
	Nano     TdfType = "Nano"
	Standard TdfType = "Standard"
)

func GetTdfType added in v0.3.5

func GetTdfType(reader io.ReadSeeker) TdfType

GetTdfType returns the type of TDF based on the reader. Reader is reset after the check.

func (TdfType) String added in v0.3.5

func (t TdfType) String() string

String returns the string representation of the applies to state.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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