storage

package
v0.1.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package storage defines the persistence interface the Inkless service uses and a registry of drivers selected by URL scheme. Drivers register themselves from init, as database/sql drivers do; import them for their side effect (for example storage/sqlite).

Stability

This package is for driver authors and the Inkless service itself. The Store and Tx interfaces and the record types are not a stable API: they change whenever the service needs new queries, and may change incompatibly until v1. Applications should talk to Inkless through its HTTP API and the client package, not through this package.

Concurrency contract

A Store is safe for concurrent use by multiple goroutines. Every read and write goes through Store.Tx, which runs one function in one database transaction; concurrent Tx calls are independent and the contract does not rely on a particular isolation level.

A Tx value is valid only inside the function it is passed to and must be used by one goroutine at a time. Records are plain values: the store keeps no reference to a record after a call returns, and returned records are not shared with other callers.

Writes that change an existing request, session or challenge use optimistic concurrency. The record carries a Version that the update compares with the stored one; on a match the update is written and the Version of the record passed in is incremented, on a mismatch the call returns ErrConflict and nothing is written. Delivery updates compare the stored NextAttemptAt instead. Insertions of ids, event sequence numbers and idempotency keys rely on unique constraints, and a violation may also surface as ErrConflict. After ErrConflict the caller must discard its records and retry the whole transaction from fresh reads. Tx rolls back when the function returns an error, and ErrConflict and ErrNotFound are returned so that errors.Is matches them.

Index

Constants

View Source
const DefaultURL = "sqlite:inkless.db"

DefaultURL is used when no database URL is configured.

Variables

View Source
var (
	// ErrNotFound is returned when a looked-up record does not exist.
	ErrNotFound = errors.New("storage: not found")
	// ErrConflict means a concurrent change won; the caller retries the
	// whole transaction.
	ErrConflict = errors.New("storage: conflict")
)

Functions

func Drivers

func Drivers() []string

Drivers returns the registered schemes.

func Register

func Register(scheme string, open Opener)

Register makes a driver available for URLs with the given scheme. It panics if the scheme is already registered.

Types

type APIKey

type APIKey struct {
	// Hash is the digest of the secret key; the key itself is never stored.
	Hash          []byte
	ApplicationID string
	CreatedAt     time.Time
}

APIKey is a credential of an application. Only a hash of the key is stored.

type Application

type Application struct {
	ID   string
	Name string
	// BrandColor is the color of the signing pages, as a CSS hex value.
	BrandColor string
	// WebhookURL is where events are delivered; empty disables webhooks.
	WebhookURL string
	// AllowedOrigins are the origins a session's ReturnURL may point to.
	AllowedOrigins []string
	CreatedAt      time.Time
}

Application is a client of the service that creates signing requests.

type Artifacts

type Artifacts struct {
	RequestID string
	// FinalPDF is the sealed final.pdf and Evidence the evidence.zip bytes.
	FinalPDF  []byte
	Evidence  []byte
	CreatedAt time.Time
}

Artifacts are the downloadable results of a completed request. They are written once and never replaced.

type Challenge

type Challenge struct {
	ID        string
	SessionID string
	// CodeHash is the digest of the code; the code itself is not stored.
	CodeHash  []byte
	CreatedAt time.Time
	ExpiresAt time.Time
	// Attempts counts the codes the signer has entered.
	Attempts int
	// PassedAt is set when the signer entered the code correctly; UsedAt when
	// the passed challenge was consumed by signing.
	PassedAt *time.Time
	UsedAt   *time.Time
	// Version is the optimistic-concurrency counter: 1 after InsertChallenge
	// and incremented by each successful UpdateChallenge.
	Version int64
}

Challenge is an email code sent to a session's signer.

type Delivery

type Delivery struct {
	EventID       string
	ApplicationID string
	RequestID     string
	Type          string
	// Seq is the event's sequence number; deliveries of one request are sent
	// in this order.
	Seq int64
	// Payload is the JSON request body.
	Payload  []byte
	Attempts int
	// NextAttemptAt is when the next attempt is due. It doubles as the
	// concurrency token of UpdateDelivery.
	NextAttemptAt time.Time
	CreatedAt     time.Time
	DeliveredAt   *time.Time
	// FailedAt is set when retries are exhausted.
	FailedAt  *time.Time
	LastError string
}

Delivery is a webhook event queued for delivery to an application. A delivery is pending until DeliveredAt or FailedAt is set.

type Document

type Document struct {
	ID            string
	ApplicationID string
	// SHA256 is the lowercase hex SHA-256 of the PDF.
	SHA256 string
	// Size is the PDF size in bytes.
	Size      int64
	Pages     int
	CreatedAt time.Time
}

Document is the metadata of an uploaded PDF; its bytes are stored and read separately by InsertDocument and DocumentContent.

type Event

type Event struct {
	ID        string
	RequestID string
	// Seq is unique per request and starts at 1.
	Seq  int64
	Type string
	At   time.Time
	// Raw is the event's JSON exactly as hashed into the evidence chain.
	Raw []byte
}

Event is an entry of a request's hash-chained event log. Events are only inserted, never updated.

type Idempotency

type Idempotency struct {
	ApplicationID string
	Key           string
	// RequestHash is the digest of the request, to detect key reuse with a
	// different request.
	RequestHash []byte
	// Status is the HTTP status of the stored response, 0 while the first
	// request is in progress.
	Status int
	// Response is the stored response body.
	Response  []byte
	CreatedAt time.Time
}

Idempotency records the outcome of a request made with an Idempotency-Key, unique per (ApplicationID, Key).

type Opener

type Opener func(ctx context.Context, url string) (Store, error)

Opener opens a store from a URL whose scheme selected the driver. It creates or migrates the schema as needed.

type Request

type Request struct {
	ID            string
	ApplicationID string
	DocumentID    string
	// State is the request state, such as "draft" or "completed".
	State          string
	Routing        string
	Assurance      string
	ConsentVersion string
	Locale         string
	ExpiresAt      time.Time
	// ExternalRef is the application's reference; empty when not given.
	ExternalRef string
	// Metadata is the application's JSON object, stored as given.
	Metadata []byte
	// Sequence is the Seq of the latest Event; 0 for drafts.
	Sequence int64
	// LastHash is the hash of the latest Event, which the next Event chains to.
	LastHash     string
	RevokeReason string
	CreatedAt    time.Time
	UpdatedAt    time.Time
	IssuedAt     *time.Time
	EndedAt      *time.Time
	// Signers are ordered by (Order, Ref).
	Signers []Signer
	// Version is the optimistic-concurrency counter: 1 after InsertRequest
	// and incremented by each successful UpdateRequest. See the package
	// documentation.
	Version int64
}

Request is a signing request with its signers.

type Session

type Session struct {
	ID string
	// TokenHash is the digest of the one-use link token; the token itself is
	// not stored.
	TokenHash []byte
	RequestID string
	SignerRef string
	// Assertion is the application's JSON assertion about the signer.
	Assertion []byte
	ReturnURL string
	Nonce     string
	CreatedAt time.Time
	// LinkExpiresAt is when the link stops working if unopened.
	LinkExpiresAt time.Time
	// OpenedAt is set when the signer first opened the link.
	OpenedAt *time.Time
	// BrowserHash is the digest of the secret that binds the session to the
	// browser that opened it.
	BrowserHash []byte
	// CeremonyExpiresAt is when an opened session must be finished by.
	CeremonyExpiresAt *time.Time
	// IP and UserAgent are the signer's, captured when the session is opened.
	IP        string
	UserAgent string
	// CodeSends counts the verification codes sent.
	CodeSends int
	// Outcome is empty while the session is open, then the final result such
	// as "signed" or "declined", with OutcomeAt.
	Outcome   string
	OutcomeAt *time.Time
	// Version is the optimistic-concurrency counter: 1 after InsertSession
	// and incremented by each successful UpdateSession.
	Version int64
}

Session is a signing ceremony for one signer.

type Signer

type Signer struct {
	// Ref is unique within its request.
	Ref   string
	Name  string
	Email string
	// Order is the signing position for sequential routing.
	Order         int
	State         string
	SignedAt      *time.Time
	DeclinedAt    *time.Time
	DeclineReason string
}

Signer is a signer of a Request. UpdateRequest writes State, SignedAt, DeclinedAt and DeclineReason; the other fields are fixed at insertion.

type Store

type Store interface {
	// Tx runs fn in one transaction and commits when fn returns nil; if fn
	// returns an error the transaction is rolled back and the error is
	// returned. Every read and write happens through a Tx. Calls must not
	// nest. The Tx must not be used after fn returns or from other
	// goroutines while fn runs. fn may be retried by the caller after
	// ErrConflict, so it must not have effects outside the transaction that
	// cannot be repeated.
	Tx(ctx context.Context, fn func(Tx) error) error
	// Close releases the store's resources. No Tx may be running.
	Close() error
}

Store is a database holding Inkless state. It is safe for concurrent use.

func Open

func Open(ctx context.Context, url string) (Store, error)

Open opens the store for url (DefaultURL if empty) with the driver registered for its scheme.

type Tx

type Tx interface {
	// InsertApplication stores a new application.
	InsertApplication(ctx context.Context, a Application) error
	Application(ctx context.Context, id string) (*Application, error)
	Applications(ctx context.Context) ([]Application, error)
	UpdateApplication(ctx context.Context, a Application) error
	InsertAPIKey(ctx context.Context, k APIKey) error
	// APIKeyApplication returns the application of an unrevoked key hash.
	APIKeyApplication(ctx context.Context, hash []byte) (string, error)
	RevokeAPIKeys(ctx context.Context, appID string, at time.Time) error
	InsertWebhookSecret(ctx context.Context, s WebhookSecret) error
	// WebhookSecrets returns the application's secrets that have not expired
	// at now, oldest first.
	WebhookSecrets(ctx context.Context, appID string, now time.Time) ([]WebhookSecret, error)
	ExpireWebhookSecrets(ctx context.Context, appID string, at time.Time) error

	InsertDocument(ctx context.Context, d Document, content []byte) error
	Document(ctx context.Context, id string) (*Document, error)
	DocumentContent(ctx context.Context, id string) ([]byte, error)

	// InsertRequest stores a request and its signers with Version 1.
	InsertRequest(ctx context.Context, r *Request) error
	Request(ctx context.Context, id string) (*Request, error)
	// UpdateRequest writes r and its signers' mutable fields if the stored
	// version equals r.Version, then increments r.Version.
	UpdateRequest(ctx context.Context, r *Request) error
	// ListRequests returns ids of the application's requests ordered by
	// (UpdatedAt, ID) strictly after (after, afterID).
	ListRequests(ctx context.Context, appID string, after time.Time, afterID string, limit int) ([]string, error)
	// OverdueRequests returns ids of issued or partially signed requests
	// whose ExpiresAt is not after now.
	OverdueRequests(ctx context.Context, now time.Time, limit int) ([]string, error)
	// UnsealedRequests returns ids of completed requests without artifacts.
	UnsealedRequests(ctx context.Context, limit int) ([]string, error)

	InsertEvents(ctx context.Context, events []Event) error
	// Events returns a request's events in sequence order.
	Events(ctx context.Context, requestID string) ([]Event, error)

	InsertDeliveries(ctx context.Context, ds []Delivery) error
	// DueDeliveries returns pending deliveries with NextAttemptAt not after
	// now that are first in sequence among their request's pending
	// deliveries; request.completed only once the request has artifacts.
	DueDeliveries(ctx context.Context, now time.Time, limit int) ([]Delivery, error)
	// UpdateDelivery writes d if it is still pending and its stored
	// NextAttemptAt equals prevNextAttempt.
	UpdateDelivery(ctx context.Context, d *Delivery, prevNextAttempt time.Time) error
	FailedDeliveries(ctx context.Context, appID string, limit int) ([]Delivery, error)

	InsertSession(ctx context.Context, s *Session) error
	SessionByToken(ctx context.Context, tokenHash []byte) (*Session, error)
	SessionByBrowser(ctx context.Context, browserHash []byte) (*Session, error)
	// UpdateSession writes s if the stored version equals s.Version, then
	// increments s.Version.
	UpdateSession(ctx context.Context, s *Session) error
	InsertChallenge(ctx context.Context, c *Challenge) error
	// LatestChallenge returns the session's most recent challenge.
	LatestChallenge(ctx context.Context, sessionID string) (*Challenge, error)
	// UpdateChallenge writes c if the stored version equals c.Version, then
	// increments c.Version.
	UpdateChallenge(ctx context.Context, c *Challenge) error

	// InsertIdempotency stores k unless the (AppID, Key) pair exists, and
	// reports whether it was inserted.
	InsertIdempotency(ctx context.Context, k Idempotency) (bool, error)
	Idempotency(ctx context.Context, appID, key string) (*Idempotency, error)
	CompleteIdempotency(ctx context.Context, appID, key string, status int, response []byte) error
	DeleteIdempotency(ctx context.Context, appID, key string) error
	PruneIdempotency(ctx context.Context, before time.Time) error

	// InsertArtifacts stores a's files unless the request already has
	// artifacts, which are kept.
	InsertArtifacts(ctx context.Context, a Artifacts) error
	Artifacts(ctx context.Context, requestID string) (*Artifacts, error)
	HasArtifacts(ctx context.Context, requestID string) (bool, error)

	// Setting returns a named service setting, such as the server secret
	// or published key material.
	Setting(ctx context.Context, name string) ([]byte, error)
	// InsertSetting stores value unless name exists, and reports whether
	// it was inserted.
	InsertSetting(ctx context.Context, name string, value []byte) (bool, error)
	// PutSetting stores value, replacing any existing one.
	PutSetting(ctx context.Context, name string, value []byte) error
}

Tx is the set of operations available inside a transaction. Methods returning a single record return ErrNotFound when it does not exist.

type WebhookSecret

type WebhookSecret struct {
	ApplicationID string
	// Secret is the "whsec_<base64>" value.
	Secret    string
	CreatedAt time.Time
	// ExpiresAt is nil while the secret is current.
	ExpiresAt *time.Time
}

WebhookSecret is a secret that signs an application's webhooks. During rotation an application has several, and events are signed with all of the unexpired ones.

Directories

Path Synopsis
Package mysql registers the storage driver for mysql://user:password@host:port/database URLs, using go-sql-driver/mysql.
Package mysql registers the storage driver for mysql://user:password@host:port/database URLs, using go-sql-driver/mysql.
Package postgres registers the storage driver for postgres:// and postgresql:// URLs, using pgx.
Package postgres registers the storage driver for postgres:// and postgresql:// URLs, using pgx.
Package sqlite registers the default storage driver for URLs of the form sqlite:PATH (sqlite:inkless.db, sqlite:///var/lib/inkless.db).
Package sqlite registers the default storage driver for URLs of the form sqlite:PATH (sqlite:inkless.db, sqlite:///var/lib/inkless.db).
Package sqlstore implements storage.Store on database/sql.
Package sqlstore implements storage.Store on database/sql.
Package storagetest is the conformance suite for storage drivers.
Package storagetest is the conformance suite for storage drivers.

Jump to

Keyboard shortcuts

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