Documentation
¶
Overview ¶
Package sites publishes static sites: a site is a name in a space, a deployment is an immutable snapshot of files (a manifest of path → sha256 and blobs addressed by that hash), and the site's "current" alias points at one deployment. The same code runs inside the hub and, with its own database, as a standalone server.
Index ¶
- Constants
- Variables
- func CleanPath(p string) (string, error)
- func HostName(host string) string
- func ScanContent(b []byte) string
- func ValidHash(s string) bool
- func ValidSiteName(s string) error
- func ValidSpaceLabel(s string) error
- type Addr
- type Authority
- type Blobs
- type Config
- type Deployment
- type Deps
- type File
- type Finding
- type FolderBlobs
- func (f *FolderBlobs) Delete(_ context.Context, hash string) error
- func (f *FolderBlobs) Has(_ context.Context, hash string) (bool, error)
- func (f *FolderBlobs) Open(_ context.Context, hash string) (io.ReadCloser, int64, error)
- func (f *FolderBlobs) Put(_ context.Context, hash string, r io.Reader, size int64) error
- type GatewayAuthority
- func (g *GatewayAuthority) CanView(context.Context, string, string) (bool, error)
- func (g *GatewayAuthority) IssueTicket(personID, host string) string
- func (g *GatewayAuthority) MachineOK(context.Context, string, string, string) bool
- func (g *GatewayAuthority) Person(r *http.Request) (*Person, error)
- func (g *GatewayAuthority) Role(context.Context, string, string) (string, error)
- func (g *GatewayAuthority) ViewerEntry(host, returnURL string) string
- type HMACTickets
- type HashReader
- type Kind
- type Limits
- type MachineSession
- type Manifest
- type MigrateReport
- type Pending
- type Person
- type S3Blobs
- func (s *S3Blobs) Check(ctx context.Context) error
- func (s *S3Blobs) Delete(ctx context.Context, hash string) error
- func (s *S3Blobs) Has(ctx context.Context, hash string) (bool, error)
- func (s *S3Blobs) Open(ctx context.Context, hash string) (io.ReadCloser, int64, error)
- func (s *S3Blobs) Put(ctx context.Context, hash string, r io.Reader, size int64) error
- type S3Config
- type Service
- func (s *Service) Begin(ctx context.Context, site Site, m Manifest, source, by string, ...) (Pending, []string, error)
- func (s *Service) Commit(ctx context.Context, site Site, pendingID, by string, makeCurrent bool) (Deployment, error)
- func (s *Service) Config() Config
- func (s *Service) CreateSite(ctx context.Context, space, name, access string, spa *bool, ...) (Site, error)
- func (s *Service) Delete(ctx context.Context, site Site) error
- func (s *Service) DeployZip(ctx context.Context, site Site, body io.Reader, by string, allowSecrets bool) (Deployment, error)
- func (s *Service) Edge() http.Handler
- func (s *Service) Exists(ctx context.Context, host string) bool
- func (s *Service) IsSiteHost(host string) bool
- func (s *Service) Mount(mux *http.ServeMux)
- func (s *Service) NewMachineSession(m MachineSession) (string, time.Time)
- func (s *Service) NewToken(ctx context.Context, site Site, name, by string) (Token, string, error)
- func (s *Service) PathEdge() http.Handler
- func (s *Service) PutBlob(ctx context.Context, site Site, pendingID, hash string, body io.Reader) error
- func (s *Service) RevokeToken(ctx context.Context, site Site, id string) error
- func (s *Service) Run(ctx context.Context)
- func (s *Service) SetCurrent(ctx context.Context, site Site, version int, by string) (Site, error)
- func (s *Service) Site(ctx context.Context, space, name string) (Site, error)
- func (s *Service) SiteURL(site Site) string
- func (s *Service) Sites(ctx context.Context, space string) ([]Site, error)
- func (s *Service) Subdomains() bool
- func (s *Service) Sweep(ctx context.Context) (int, error)
- func (s *Service) TokenSite(ctx context.Context, secret string) (Site, Token, error)
- func (s *Service) Tokens(ctx context.Context, site Site) ([]Token, error)
- func (s *Service) URL(a Addr) string
- func (s *Service) Update(ctx context.Context, site Site, access *string, spa *bool, by string) (Site, error)
- func (s *Service) Versions(ctx context.Context, site Site) ([]Deployment, error)
- type Sessions
- type Site
- type SiteView
- type Tickets
- type Token
- type TokenView
- type VersionView
Constants ¶
const ( RoleOwner = store.RoleOwner RoleMember = store.RoleMember )
Role names, as the hub spells them.
const ( // AccessTeam is the default: only people of the site's space. AccessTeam = "team" // AccessLink is «все, у кого есть ссылка»: anyone with the address. AccessLink = "link" )
Access says who may open a site.
const ( // MachineSessionTTL is how long a publishing session lasts. MachineSessionTTL = 30 * time.Minute // MachineIDPrefix starts the id sites made by a machine carry, apart from every person's id. MachineIDPrefix = "machine:" )
const ( MaxSiteName = 30 MaxSpaceLabel = 20 )
const MaxScanBytes = 2 << 20
MaxScanBytes is how much of a file is read for secrets; the scan is for text, which sites are mostly made of.
const PathCSP = "sandbox allow-scripts allow-forms allow-popups allow-modals"
PathCSP is what the path fallback sends with every page: the site runs on the server's own origin, so it is sandboxed into an opaque one (no allow-same-origin) and cannot touch the server's cookies or API.
const SessionTTL = 12 * time.Hour
SessionTTL is how long a site's cookie holds.
const TicketParam = "hl_site_ticket"
TicketParam is the query parameter a ticket arrives in.
const TicketTTL = 60 * time.Second
TicketTTL is how long a ticket can be redeemed; a ticket opens one host, once.
Variables ¶
var DefaultLimits = Limits{
MaxDeployBytes: 100 << 20,
MaxFileBytes: 32 << 20,
MaxFiles: 5000,
MaxSitesPerSpace: 50,
KeepVersions: 20,
}
DefaultLimits are the limits of v1.
var ErrBlobNotFound = errors.New("blob not found")
ErrBlobNotFound is what Open returns for a hash the store does not hold.
var ErrNotFound = store.ErrNotFound
ErrNotFound is what a lookup that finds nothing returns.
Functions ¶
func CleanPath ¶
CleanPath turns a path of an upload into the manifest's form or refuses it: no absolute paths, no "..", no empty segments, no backslashes, no control characters, nothing under .git.
func ScanContent ¶
ScanContent says which rule a file's content breaks, or "". Binary files (a NUL in the first bytes) are skipped.
func ValidSiteName ¶
ValidSiteName checks a site's name: 1–30 of [a-z0-9-], no "--", not a reserved word.
func ValidSpaceLabel ¶
ValidSpaceLabel checks the space part of an address: 1–20 of [a-z0-9-], no "--".
Types ¶
type Addr ¶
Addr is a parsed site address.
func ParseHost ¶
ParseHost reads a site address out of a request host: exactly one label in front of the domain.
type Authority ¶
type Authority interface {
// Person is the signed-in person behind a management request; nil, nil when there is none.
Person(r *http.Request) (*Person, error)
// Role is the person's role in the space («owner», «member») and "" when they have none.
Role(ctx context.Context, personID, space string) (string, error)
// MachineOK says whether the machine is still one of the space's and, when the session names a person it publishes for,
// whether that person is still a member. A removed machine ends its sessions through this.
MachineOK(ctx context.Context, machineID, personID, space string) bool
// CanView says whether the person may open the space's team-only sites.
CanView(ctx context.Context, personID, space string) (bool, error)
// ViewerEntry is where an anonymous visitor of a team-only site is sent to sign in; the entry sends them back to
// returnURL with a ticket.
ViewerEntry(host, returnURL string) string
Tickets
// IssueTicket makes a ticket for the person to open host.
IssueTicket(personID, host string) string
}
Authority is what the sites service asks of its host: who is calling, what a person may do in a space, and how a person who is not signed in at a site gets a ticket. The hub implements it with its sessions and spaces; a standalone server with an admin token and a trusted gateway.
type Blobs ¶
type Blobs interface {
Has(ctx context.Context, hash string) (bool, error)
// Put stores exactly size bytes read from r under hash. The caller has checked that they hash to it.
Put(ctx context.Context, hash string, r io.Reader, size int64) error
// Open returns the content and its size; ErrBlobNotFound when there is none.
Open(ctx context.Context, hash string) (io.ReadCloser, int64, error)
Delete(ctx context.Context, hash string) error
}
Blobs holds the content of files by the sha256 of that content. A blob is immutable: putting the same hash twice is the same file.
type Config ¶
type Config struct {
// Domain is the wildcard domain sites live under (sites.example.com), with :port when it is not the default. Empty:
// the path fallback only.
Domain string
// PublicURL is the address of the server itself (https://hub.example.com), without a trailing slash; the path
// fallback and the sign-in entry hang off it.
PublicURL string
// Secure says that sites are served over https.
Secure bool
Limits Limits
// AbuseURL is where the 404 page of the bare domain sends a complaint.
AbuseURL string
// StripHeaderPrefixes are the lower-case prefixes of request headers the edge drops: the ones a gateway in front uses
// to carry identity must never reach a site, nor be forged by a visitor. Empty means the default, x-preview-.
StripHeaderPrefixes []string
// Key signs the sites' cookies; at least 32 bytes.
Key []byte
// SPAFallback is the default for a new site.
SPAFallback bool
}
Config is how the service is set up.
type Deployment ¶
type Deployment struct {
ID string
SiteID string
Version int
Manifest Manifest
FileCount int
TotalBytes int64
Source string
CreatedBy string
CreatedAt time.Time
}
Deployment is one immutable snapshot of a site.
type Deps ¶
type Deps struct {
DB *store.DB
Blobs Blobs
Auth Authority
Config Config
Log *slog.Logger
// Now is the clock; nil means time.Now.
Now func() time.Time
}
Deps are what the service is built from.
type Finding ¶
Finding is a file that looks like it holds a secret. It never carries the secret itself.
type FolderBlobs ¶
type FolderBlobs struct{ Root string }
FolderBlobs keeps blobs as files in a folder (the self-hosted default): <root>/ab/abcdef….
func NewFolderBlobs ¶
func NewFolderBlobs(root string) (*FolderBlobs, error)
NewFolderBlobs makes the folder store, creating the folder.
func (*FolderBlobs) Open ¶
func (f *FolderBlobs) Open(_ context.Context, hash string) (io.ReadCloser, int64, error)
type GatewayAuthority ¶
type GatewayAuthority struct {
// AdminToken is the bearer secret that may manage every space's sites. Empty: no management over HTTP.
AdminToken string
// LoginURL is the gateway's entry for a visitor who is not signed in; it gets ?host=…&return=….
LoginURL string
*HMACTickets
}
GatewayAuthority is the authority of a standalone sites server: management requests carry an admin token, and visitors of team-only sites come with tickets that the gateway in front of it signs (HMACTickets). The gateway signs the person in by its own means and decides who may open which site; the server only trusts its tickets.
func (*GatewayAuthority) IssueTicket ¶
func (g *GatewayAuthority) IssueTicket(personID, host string) string
func (*GatewayAuthority) Person ¶
func (g *GatewayAuthority) Person(r *http.Request) (*Person, error)
func (*GatewayAuthority) ViewerEntry ¶
func (g *GatewayAuthority) ViewerEntry(host, returnURL string) string
type HMACTickets ¶
type HMACTickets struct {
// contains filtered or unexported fields
}
HMACTickets are tickets signed with a key the gateway and the sites server share. The gateway authenticates the person by its own means, checks that they may open the site, and sends the browser to the site's address with the ticket; the server redeems it for a cookie.
func NewHMACTickets ¶
func NewHMACTickets(key []byte, now func() time.Time) *HMACTickets
NewHMACTickets makes the ticket service; now may be nil.
func (*HMACTickets) Issue ¶
func (t *HMACTickets) Issue(userID, host string) string
Issue makes a ticket for userID to open host.
type HashReader ¶
type HashReader struct {
N int64
// contains filtered or unexported fields
}
HashReader hashes what is read through it.
func (*HashReader) Sum ¶
func (h *HashReader) Sum() string
Sum is the hex sha256 of what has been read.
type Limits ¶
type Limits struct {
MaxDeployBytes int64
MaxFileBytes int64
MaxFiles int
MaxSitesPerSpace int
KeepVersions int
}
Limits bound one deployment and one space.
type MachineSession ¶
type MachineSession struct {
Space string
MachineID string
// PersonID is the member of the space the machine publishes for; empty when the machine did not say.
PersonID string
// Name is what is shown as the author: the person's, else the machine's.
Name string
}
MachineSession is who a publishing session stands for.
func (MachineSession) ID ¶
func (m MachineSession) ID() string
ID is the stable id of the sites this machine makes.
type Manifest ¶
Manifest is a deployment: path (slash separated, relative) → file.
func (Manifest) Hashes ¶
Hashes are the distinct content hashes, sorted (descending, only to be stable).
func (Manifest) TotalBytes ¶
TotalBytes is the sum of the file sizes.
type MigrateReport ¶ added in v0.16.154
type MigrateReport struct {
Found int // blob files in the folder
Copied int // put into the destination
Present int // already there, left as they were
Bytes int64 // bytes copied
Removed int // source files removed (only with removeSource)
Skipped []string
}
MigrateReport is what Migrate did.
func Migrate ¶ added in v0.16.154
func Migrate(ctx context.Context, root string, dst Blobs, dry, removeSource bool) (MigrateReport, error)
Migrate copies every blob of the folder store at root into dst: the move of a hub's sites from its data folder to a bucket. It is safe to run again, and to run while the hub runs on the folder: a blob already in dst is left alone, and a file whose content does not hash to its name is skipped and reported, never copied. With dry nothing is written. With removeSource a blob is removed from the folder once the destination has it.
type Pending ¶
type Pending struct {
ID string
SiteID string
Manifest Manifest
Source string
CreatedBy string
CreatedAt time.Time
ExpiresAt time.Time
// AllowSecrets is the uploader's «yes, I know» to the secret scan.
AllowSecrets bool
}
Pending is an upload announced and not yet committed.
type S3Blobs ¶
type S3Blobs struct {
// contains filtered or unexported fields
}
S3Blobs keeps blobs in an S3 bucket. Path-style addressing, which every S3-compatible service takes.
func NewS3Blobs ¶
NewS3Blobs makes the store. It does not touch the bucket; Check does.
type S3Config ¶
type S3Config struct {
Endpoint string // https://s3.example.com (or http://minio:9000)
Region string // empty: the service's default
Bucket string
Prefix string // keys are <prefix>blobs/ab/abcdef…
AccessKey string
SecretKey string
}
S3Config is an S3-compatible bucket: MinIO for a self-hosted install, Selectel for the cloud.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the sites module.
func (*Service) Begin ¶
func (s *Service) Begin(ctx context.Context, site Site, m Manifest, source, by string, allowSecrets bool) (Pending, []string, error)
Begin announces a deployment: the manifest is checked (paths, hashes, sizes, limits, secret-looking names), and the answer lists the hashes the store does not have yet.
func (*Service) Commit ¶
func (s *Service) Commit(ctx context.Context, site Site, pendingID, by string, makeCurrent bool) (Deployment, error)
Commit finishes a deployment: every blob must be in the store, then the manifest becomes the site's next version and, unless asked not to, the current one, in one step. Old versions beyond the keep limit go.
func (*Service) CreateSite ¶
func (s *Service) CreateSite(ctx context.Context, space, name, access string, spa *bool, by, byID, origin string) (Site, error)
CreateSite makes an empty site. A taken name in the space is a conflict.
func (*Service) Delete ¶
Delete removes a site with all its versions and tokens; its blobs go with the next sweep.
func (*Service) DeployZip ¶
func (s *Service) DeployZip(ctx context.Context, site Site, body io.Reader, by string, allowSecrets bool) (Deployment, error)
DeployZip makes a deployment out of a zip archive in one request: the archive is unpacked here, safely.
func (*Service) Edge ¶
Edge serves the sites at their own addresses (<site>--<space>.<domain>). The host that is the bare domain, or a label that is not a site, gets the 404 page with the complaint link.
func (*Service) Exists ¶
Exists says whether the host is the bare sites domain or the address of a site that exists: what a certificate may be issued for on demand.
func (*Service) IsSiteHost ¶
IsSiteHost says whether a request host is an address of this service (a label under its domain).
func (*Service) NewMachineSession ¶
func (s *Service) NewMachineSession(m MachineSession) (string, time.Time)
NewMachineSession makes the token of a machine for its space; it works until the returned time.
func (*Service) NewToken ¶
NewToken makes a deploy token for the site. The secret is returned once; only its hash is kept.
func (*Service) PathEdge ¶
PathEdge serves the path fallback: /sites/<site>--<space>/… on the server's own origin.
func (*Service) PutBlob ¶
func (s *Service) PutBlob(ctx context.Context, site Site, pendingID, hash string, body io.Reader) error
PutBlob takes the content of one file of a pending deployment. The content must hash to the announced sha256 and size; a file that looks like a secret is refused unless the uploader allowed it.
func (*Service) RevokeToken ¶
RevokeToken removes a deploy token.
func (*Service) SetCurrent ¶
SetCurrent makes a version the one the site serves: the rollback, and «Сделать текущей».
func (*Service) Subdomains ¶
Subdomains says whether sites get addresses of their own under a wildcard domain; false is the path fallback.
func (*Service) Sweep ¶
Sweep forgets the uploads that expired and removes the blobs nothing refers to (and that are old enough not to be somebody's upload in flight). It returns how many blobs went.
func (*Service) TokenSite ¶
TokenSite is the site a deploy token belongs to; ErrNotFound for an unknown token.
type Sessions ¶
type Sessions struct {
// contains filtered or unexported fields
}
Sessions are the cookies a site's origin keeps after a ticket: host-only, signed, bound to the host they were made for.
func NewSessions ¶
NewSessions makes the cookie service; now may be nil.
func (*Sessions) CookieName ¶
CookieName is __Host-hl_site on https (host-only, Path=/, Secure: a sibling site cannot plant it), hl_site on http.
type Site ¶
type Site struct {
ID, Space, Name string
Access string
SPA bool
CurrentVersion int
NextVersion int
CreatedBy string // the name shown
CreatedByID string // who made it, for rights: a person's id or machine:<id>
Origin string // what it was made from (sinopia:<project>), empty for the rest
UpdatedBy string
CreatedAt time.Time
UpdatedAt time.Time
}
Site is a name in a space.
type SiteView ¶
type SiteView struct {
ID string `json:"id"`
Space string `json:"space"`
Name string `json:"name"`
Address string `json:"address"`
Access string `json:"access"`
SPA bool `json:"spa"`
CurrentVersion int `json:"currentVersion"`
CreatedBy string `json:"createdBy"`
Origin string `json:"origin,omitempty"`
UpdatedBy string `json:"updatedBy"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
Versions []VersionView `json:"versions,omitempty"`
}
SiteView is a site as the API sends it.
type Tickets ¶
type Tickets interface {
// Redeem is true once, for the host the ticket was made for.
Redeem(ticket, host string) (userID string, ok bool)
}
Tickets trades a one-time ticket for the person it was made for. The hub backs it with its in-memory ticket store; a standalone server verifies tickets signed by the gateway that did the signing in (HMACTickets).
type TokenView ¶
type TokenView struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedBy string `json:"createdBy"`
CreatedAt string `json:"createdAt"`
LastUsedAt *string `json:"lastUsedAt"`
// Token is the secret, in the answer that makes it and nowhere else.
Token string `json:"token,omitempty"`
}
TokenView is a deploy token as the API sends it.
type VersionView ¶
type VersionView struct {
Version int `json:"version"`
URL string `json:"url"`
FileCount int `json:"fileCount"`
TotalBytes int64 `json:"totalBytes"`
Source string `json:"source"`
CreatedBy string `json:"createdBy"`
CreatedAt string `json:"createdAt"`
Current bool `json:"current"`
}
VersionView is one deployment of a site.