swift

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2022 License: Apache-2.0 Imports: 41 Imported by: 3

README

Shared Web InFormaTion

Shared Web InFormaTion (SWIFT) - Go

Shared Web InFormaTion (SWIFT) - an open source cryptographically secure web solution for sharing information across domains implemented in Go

Storage Implementation

See the [https://github.com/SWAN-community/swift/blob/main/storage.md](SWIFT storage explainer) in the SWIFT repo for how node details are stored.

Storage Setup

See the [https://github.com/SWAN-community/swan-demo-go/blob/main/README.md](SWAN Demo Go) repo for instructions on how to configure storage.

Documentation

Overview

**************************************************************************** * Copyright 2020 51 Degrees Mobile Experts Limited (51degrees.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * **************************************************************************

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddHandlers

func AddHandlers(
	services *Services,
	malformedHandler func(w http.ResponseWriter, r *http.Request))

AddHandlers to the http default mux for shared web state. The malformedHandler is used to tailor the response when a storage operation is invalid. If not provided then the default handler is used.

func Create

func Create(s *Services, h string, q url.Values) (string, error)

Create creates a storage operation URL from the parameters passed to the method for the node associated with the host. s an instance of swift.Services h the name of the SWIFT internet domain q the form paramters to be used to create the storage operation URL

func HandlerCreate

func HandlerCreate(s *Services) http.HandlerFunc

HandlerCreate takes a Services pointer and returns a HTTP handler used by an Access Node to obtain the initial URL for a storage operation.

func HandlerDecodeAsJSON

func HandlerDecodeAsJSON(s *Services) http.HandlerFunc

HandlerDecodeAsJSON returns the incoming request as JSON data. The query string contains the data which must be turned into a byte array, decryped and the resulting data turned into JSON.

func HandlerDecrypt

func HandlerDecrypt(s *Services) http.HandlerFunc

HandlerDecrypt takes a Services pointer and returns a HTTP handler used to decrypt the result of a storage operation provided in the raw query parameter to the return URL.

func HandlerEncrypt

func HandlerEncrypt(s *Services) http.HandlerFunc

HandlerEncrypt takes a Services pointer and returns a HTTP handler used to encrypt the result of a storage operation ready to be provided to the return URL.

func HandlerNodes

func HandlerNodes(s *Services) http.HandlerFunc

HandlerNodes is a handler that returns a list of all the known nodes, each node is converted into a NodeView item which is then used to populate an HTML template.

func HandlerNodesJSON

func HandlerNodesJSON(s *Services) http.HandlerFunc

HandlerNodesJSON is a handler that returns a list of all the alive nodes which is then used to serialize to JSON.

func HandlerRegister

func HandlerRegister(s *Services) http.HandlerFunc

HandlerRegister takes a Services pointer and returns a HTTP handler used to register a domain as an Access Node or a Storage Node. Does not work after the domain has been registered in the storage service.

func HandlerShare

func HandlerShare(s *Services) http.HandlerFunc

HandlerShare returns an encrypted json document which contains details for all known active nodes.

func HandlerStore

func HandlerStore(
	s *Services,
	e func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc

HandlerStore takes a Services pointer and returns a HTTP handler used to respond to a storage operation. Should not be assigned to an end point as the table name is the first segment of the URL path, and the encrypted operation data the second segment. The second optional parameter is used to handle responses that do not contain a valid operation request due to data corruption.

func NewStorageService

func NewStorageService(c Configuration, sts ...Store) storageService

NewStorageService creates a new instance of storageService and creates the initial instance of storageManager, a go routine is then started which will periodically refresh the storageManager reference with a new instance.

func SetHomeNodeHeaders

func SetHomeNodeHeaders(r *http.Request, q *url.Values)

SetHomeNodeHeaders adds the HTTP headers from the request that are relevant to the calculation of the home node to the values collection.

func SetURL

func SetURL(sourceKey string, destKey string, values *url.Values) error

SetURL take the value of key s, validates the value is a URL, and the sets the value of key d to the validated value. If the value is not a URL then an error is returned.

func ValidateURL

func ValidateURL(name string, value string) (*url.URL, error)

ValidateURL confirms that the parameter is a valid URL and then returns the URL ready for use with SWIFT if valid. The method checks that the SWIFT encrypted data can be appended to the end of the string as an identifiable segment if there is now query string in the URL. An error is returned if the URL is not validate for use with SWIFT.

Types

type AWS

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

AWS is a implementation of sws.Store for AWS DynamoDB.

func NewAWS

func NewAWS() (*AWS, error)

NewAWS creates a new instance of the AWS structure

func (*AWS) GetAccessNode

func (c *AWS) GetAccessNode(network string) (string, error)

GetAccessNode returns an access node for the network, or null if there is no access node available.

type Azure

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

Azure is a implementation of sws.Store for Microsoft's Azure table storage.

func NewAzure

func NewAzure(account string, accessKey string) (*Azure, error)

NewAzure creates a new client for accessing table storage with the credentials supplied.

func (*Azure) GetAccessNode

func (c *Azure) GetAccessNode(network string) (string, error)

GetAccessNode returns an access node for the network, or null if there is no access node available.

type BrowserDetector

type BrowserDetector interface {
	GetWarningHTML(r *http.Request) string // Returns a warning HTML snippet for the browser
}

BrowserDetector is used to identify the browser and return an HTML snippet that can be used to provide a warning to the user about the browsers support for shared web state.

type BrowserRegexes

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

BrowserRegexes is a concrete implementation of the interface sws.BrowserDetector

func NewBrowserRegexes

func NewBrowserRegexes() (*BrowserRegexes, error)

NewBrowserRegexes creates a new implementation of sws.BrowserDetector configured with default regular expressions and messages.

func (*BrowserRegexes) GetWarningHTML

func (b *BrowserRegexes) GetWarningHTML(r *http.Request) string

GetWarningHTML returns the warning text for the browser if the User-Agent HTTP matches a regular expression.

type Configuration

type Configuration struct {
	config.Base `mapstructure:",squash"`
	// If a local file with SWIFT node information is to be used the path to the
	// file.
	SwiftFile string `mapstructure:"swiftFile"`
	// The number of seconds between polling operations for alive checks. This
	// is supplement to the passive check so if a node has not been accessed for
	// more than this then it is eligible for polling.
	AlivePollingSeconds int `mapstructure:"alivePollingSeconds"`
	// The number of seconds from creation of an operation that it is valid for.
	// Used to prevent repeated processing of the same operation.
	StorageOperationTimeout int `mapstructure:"storageOperationTimeout"`
	// The number of minutes between refreshes of the storage manager.
	StorageManagerRefreshMinutes int `mapstructure:"storageManagerRefreshMinutes"`
	// The maximum number of Store instances that can be referenced by a storage
	// manager.
	MaxStores int `mapstructure:"maxStores"`
	// The length of time in seconds values stored in SWIFT nodes can be relied
	// upon to be current. Used by the home node to determine if it should
	// consult other nodes in the network before returning it's current values.
	HomeNodeTimeout int `mapstructure:"homeNodeTimeout"`
	// The default message to display in the user interface if one is not
	// provided by the requestor of the storage operation.
	Message string `mapstructure:"message"`
	// The title of the web page to use in the user interface if one is not
	// provided by the requestor of the storage operation.
	Title string `mapstructure:"title"`
	// The background color of the web page to use in the user interface if one
	// is not provided by the requestor of the storage operation.
	BackgroundColor string `mapstructure:"backgroundColor"`
	// The message color to use in the user interface if one is not provided by
	// the requestor of the storage operation.
	MessageColor string `mapstructure:"messageColor"`
	// The progress circle color to use in the user interface if one is not
	// provided by the requestor of the storage operation.
	ProgressColor string `mapstructure:"progressColor"`
	// The HTTP scheme to use (HTTP for development and HTTPS for production).
	Scheme string `mapstructure:"scheme"`
	// The number of nodes to consult when accessing the SWIFT network.
	NodeCount byte `mapstructure:"nodeCount"`
	// True to enable debug logging and user interfaces.
	Debug bool `mapstructure:"debug"`
}

Configuration maps to the appsettings.json settings file.

func NewConfig

func NewConfig(file string) Configuration

NewConfig creates a new instance of configuration from the file provided.

func (*Configuration) HomeNodeTimeoutDuration

func (c *Configuration) HomeNodeTimeoutDuration() time.Duration

HomeNodeTimeoutDuration the home node timeout as a time.Duration

func (*Configuration) StorageOperationTimeoutDuration

func (c *Configuration) StorageOperationTimeoutDuration() time.Duration

StorageOperationTimeoutDuration the storage operation timeout as a time.Duration

func (*Configuration) Validate

func (c *Configuration) Validate() error

Validate confirms that the configuration is usable.

type Firebase

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

Firebase is a implementation of owid.Store for GCP's Firebase.

func NewFirebase

func NewFirebase(project string) (*Firebase, error)

NewFirebase creates a new instance of the Firebase structure

func (*Firebase) GetAccessNode

func (c *Firebase) GetAccessNode(network string) (string, error)

GetAccessNode returns an access node for the network, or null if there is no access node available.

type HTML

type HTML struct {
	Title           string // Window title
	Message         string // Message to display
	BackgroundColor string // Background color of the window
	MessageColor    string // Color of the message text
	ProgressColor   string // Color of the progress line
	// contains filtered or unexported fields
}

HTML parameters that control the function and display of the user interface.

func (*HTML) DisplayUserInterface

func (h *HTML) DisplayUserInterface() bool

DisplayUserInterface true if a UI should be displayed during the storage operation, otherwise false.

func (*HTML) DisplayUserInterfaceAsString

func (h *HTML) DisplayUserInterfaceAsString() string

DisplayUserInterfaceAsString returns the flag as string either "true" or "false".

func (*HTML) JavaScript

func (h *HTML) JavaScript() bool

JavaScript true if the response for storage operations should be JavaScript include that will continue the operation. This feature requires cookies to be sent for DOM inserted JavaScript elements.

func (*HTML) PostMessageOnComplete

func (h *HTML) PostMessageOnComplete() bool

PostMessageOnComplete true if at the end of the operation the resulting data should be returned to the parent using JavaScript postMessage, otherwise false. parent.postMessage("swan","[Encrypted SWAN data]");

func (*HTML) PostMessageOnCompleteAsString

func (h *HTML) PostMessageOnCompleteAsString() string

PostMessageOnCompleteAsString returns the flag as string either "true" or "false".

func (*HTML) SetDisplayUserInterface

func (h *HTML) SetDisplayUserInterface(v bool)

SetDisplayUserInterface sets the flag to true or false.

func (*HTML) SetJavaScript

func (h *HTML) SetJavaScript(v bool)

SetJavaScript sets the flag to true or false.

func (*HTML) SetPostMessageOnComplete

func (h *HTML) SetPostMessageOnComplete(v bool)

SetPostMessageOnComplete sets the flag to true or false.

func (*HTML) SetUseHomeNode

func (h *HTML) SetUseHomeNode(v bool)

SetUseHomeNode sets the flag to true or false.

func (*HTML) UseHomeNode

func (h *HTML) UseHomeNode() bool

UseHomeNode true if the home node can be used if it contains current data. False if the SWAN network should be consulted irrespective of the state of data held on the home node.

func (*HTML) UseHomeNodeAsString

func (h *HTML) UseHomeNodeAsString() string

UseHomeNodeAsString returns the flag as a string. Either "true" or "false".

func (*HTML) UseJavaScriptAsString

func (h *HTML) UseJavaScriptAsString() string

UseJavaScriptAsString returns the flag as a string. Either "true" or "false".

type Local

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

Local store implementation for SWIFT - data is stored in maps in memory and persisted on disk in JSON files.

func NewLocalStore

func NewLocalStore(nodesFile string) (*Local, error)

NewLocalStore creates a new instance of Local and configures the path for the persistent JSON file.

func (*Local) GetAccessNode

func (c *Local) GetAccessNode(network string) (string, error)

GetAccessNode returns an access node for the network, or null if there is no access node available.

type NodeItem

type NodeItem struct {
	Network      string    // The name of the network the node belongs to
	Domain       string    // The domain name associated with the node
	Created      time.Time // The time that the node was created
	Starts       time.Time // The time that the node goes online
	Expires      int64     `json:"expires"` // The time that the node will retire from the network
	Role         int       // The role the node has in the network
	ScramblerKey string    // Secret used to scramble data with fixed nonce
	CookieDomain string    // The domain to use with cookies
}

NodeItem is the dynamodb table item representation of a node

type NodeView

type NodeView struct {
	Network  string    // The name of the network the node belongs to
	Domain   string    // The domain name associated with the node
	Created  time.Time // The time that the node first came online
	Starts   time.Time // The time that the node will begin operation
	Expires  time.Time // The time that the node will retire from the network
	Role     int       // The role the node has in the network
	Accessed time.Time // The time the node was last accessed
	Alive    bool      // True if the node is reachable via a HTTP request
}

NodeView is a struct containing the node fields to display in the nodes swiftNodesTemplate

type NodeViews

type NodeViews struct {
	Nodes []NodeView
}

NodeViews is a struct which contains an array of NodeView which is used to display a list of nodes using the swiftNodesTemplate

func (*NodeViews) NodeViewItems

func (nv *NodeViews) NodeViewItems() []NodeView

Get the NodeView

type Pair

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

Pair from a storage operation.

func (*Pair) Created

func (p *Pair) Created() time.Time

Created readonly accessor to the pair's created time.

func (*Pair) Expires

func (p *Pair) Expires() time.Time

Expires readonly accessor to the pair's expiry time.

func (*Pair) Key

func (p *Pair) Key() string

Key readonly accessor to the pair's key.

func (*Pair) Value

func (p *Pair) Value() string

Value returns the value as string. Used with HTML templates or JSON serialization.

func (*Pair) Values

func (p *Pair) Values() [][]byte

Value readonly accessor to the pair's value.

type Register

type Register struct {
	Services      *Services
	StoreNames    []string
	Store         string
	Domain        string
	Network       string
	Starts        time.Time
	Expires       time.Time
	Role          int
	Scramble      bool
	Secret        bool
	CookieDomain  string
	Error         string
	NetworkError  string
	ExpiresError  string
	StartsError   string
	StoreError    string
	RoleError     string
	ReadOnly      bool
	DisplayErrors bool
	// contains filtered or unexported fields
}

Register contains HTML template data used to register a node with the network

func (*Register) BackgroundColor

func (r *Register) BackgroundColor() string

BackgroundColor returns the background color associated with the service config

func (*Register) ExpiresString

func (r *Register) ExpiresString() string

ExpiresString returns the expires date as a string

func (*Register) Language

func (r *Register) Language() string

Language returns the language code associated with the web page.

func (*Register) MessageColor

func (r *Register) MessageColor() string

MessageColor returns the message color associated with the service config

func (*Register) StartsString

func (r *Register) StartsString() string

StartsString returns the start date as a string

type Results

type Results struct {
	HTML // Include the common HTML UI members.
	// contains filtered or unexported fields
}

Results from a storage operation.

func DecodeResults

func DecodeResults(d []byte) (*Results, error)

DecodeResults turns a byte array into a results data structure.

func (*Results) Get

func (r *Results) Get(key string) *Pair

Get returns the result for the key provided, or nil if the key does not exist.

func (*Results) IsTimeStampValid

func (r *Results) IsTimeStampValid() bool

IsTimeStampValid returns true if the time stamp of the result is valid.

func (*Results) Map

func (r *Results) Map() map[string]*Pair

Map returns the results as a map, keyed on the pair key.

func (*Results) Pairs

func (r *Results) Pairs() []*Pair

Pairs common.Readonly accessor to the results's key value pairs.

func (*Results) State

func (r *Results) State() []string

State common.Readonly accessor to the results's state array.

type SecretItem

type SecretItem struct {
	Domain       string
	TimeStamp    time.Time
	Expires      int64 `json:"expires"`
	ScramblerKey string
}

SecretItem is the dynamodb table item representation of a secret

type Services

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

Services references all the information needed for every method.

func NewServices

func NewServices(
	config Configuration,
	store storageService,
	access access.Access,
	browser BrowserDetector) *Services

NewServices a set of services to use with SWIFT. These provide defaults via the configuration parameter, and access to persistent storage via the store parameter.

func (*Services) Config

func (s *Services) Config() *Configuration

Config returns the configuration service.

func (*Services) GetAccessNodeForHost

func (s *Services) GetAccessNodeForHost(h string) (*node, error)

GetAccessNodeForHost returns the access node, if there is one, for the host name provided. If the host does not exist then an error is returned. If the host exists, but is not an access node then an error is returned. h is the internet domain of the SWIFT access node host

func (*Services) GetAliveNodesCount

func (s *Services) GetAliveNodesCount() (uint32, error)

GetAliveNodesCount returns the number of nodes reported as alive currently.

func (*Services) GetHomeNode

func (s *Services) GetHomeNode(r *http.Request) (*node, error)

GetHomeNode returns the home node for the web browser associated with the access node processing the request. If the current request is not to an access node then an error will be returned.

type Store

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

Store interface for persistent data shared across instances operated.

func NewStore

func NewStore(c Configuration) []Store

NewStore returns a work implementation of the Store interface for the configuration supplied.

type Volatile

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

Volatile localstorage implementation

func (*Volatile) GetAccessNode

func (c *Volatile) GetAccessNode(network string) (string, error)

GetAccessNode returns an access node for the network, or null if there is no access node available.

Jump to

Keyboard shortcuts

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