sdk

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: BSD-3-Clause-Clear Imports: 40 Imported by: 5

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.WithAttributes("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 (
	ErrGrpcDialFailed = Error("failed to dial grpc endpoint")
	ErrShutdownFailed = Error("failed to shutdown sdk")
)
View Source
const (
	JSONFormat = iota
	XMLFormat
)
View Source
const (
	HS256 = iota
	GMAC
)
View Source
const (
	ErrNanoTdfRead = Error("nanotdf read error")
)

Variables

This section is empty.

Functions

func ReadNanoTDFHeader

func ReadNanoTDFHeader(reader io.Reader) (*nanoTdf, error)

Types

type Assertion

type Assertion struct {
}

type AuthConfig

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

func NewAuthConfig

func NewAuthConfig() (*AuthConfig, error)

NewAuthConfig Create a new instance of authConfig

func NewOIDCAuthConfig

func NewOIDCAuthConfig(ctx context.Context, host, realm, clientID, clientSecret, subjectToken string) (*AuthConfig, error)

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 Error

type Error string

func (Error) Error

func (c Error) Error() string

type IDPAccessTokenSource

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

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) (*IDPAccessTokenSource, error)

func (*IDPAccessTokenSource) AccessToken

func (t *IDPAccessTokenSource) AccessToken() (auth.AccessToken, error)

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) (*IDPTokenExchangeTokenSource, error)

func (IDPTokenExchangeTokenSource) AccessToken

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
}

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     string `json:"policyBinding"`
	EncryptedMetadata string `json:"encryptedMetadata,omitempty"`
}

type Manifest

type Manifest struct {
	EncryptionInformation `json:"encryptionInformation"`
	Payload               `json:"payload"`
}

type Method

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

type Option

type Option func(*config)

func WithAuthConfig

func WithAuthConfig(authConfig AuthConfig) Option

temporary option to allow the for token exchange and the use of REST-ful KASs. this will likely change as we make these options more robust

func WithClientCredentials

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

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

func WithCustomAuthorizationConnection

func WithCustomAuthorizationConnection(conn *grpc.ClientConn) Option

func WithCustomPolicyConnection

func WithCustomPolicyConnection(conn *grpc.ClientConn) Option

func WithExtraDialOptions

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

func WithInsecureConn

func WithInsecureConn() Option

WithInsecureConn returns an Option that sets up an http connection.

func WithTokenEndpoint

func WithTokenEndpoint(tokenEndpoint string) Option

When we implement service discovery using a .well-known endpoint this option may become deprecated

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 PolicyBody

type PolicyBody interface {
	// contains filtered or unexported methods
}

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
}

func (*Reader) DataAttributes

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

DataAttributes return the data attributes present in tdf.

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

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

type SDK

type SDK struct {
	Namespaces              namespaces.NamespaceServiceClient
	Attributes              attributes.AttributesServiceClient
	ResourceMapping         resourcemapping.ResourceMappingServiceClient
	SubjectMapping          subjectmapping.SubjectMappingServiceClient
	KeyAccessServerRegistry kasregistry.KeyAccessServerRegistryServiceClient
	Authorization           authorization.AuthorizationServiceClient
	// contains filtered or unexported fields
}

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

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

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

type Segment

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

type TDFConfig

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

TDFConfig Internal config struct for building TDF options.

func NewTDFConfig

func NewTDFConfig(opt ...TDFOption) (*TDFConfig, error)

NewTDFConfig CreateTDF a new instance of tdf config.

type TDFFormat

type TDFFormat = int

type TDFObject

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

func (*TDFObject) Manifest

func (t *TDFObject) Manifest() Manifest

type TDFOption

type TDFOption func(*TDFConfig) error

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.

func WithMetaData

func WithMetaData(metaData string) TDFOption

WithMetaData returns an Option that add metadata to TDF.

func WithSegmentSize

func WithSegmentSize(size int64) TDFOption

WithSegmentSize returns an Option that set the default segment size to TDF.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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