Documentation
¶
Overview ¶
Package engine is the single public surface k3ep (or any other caller in a different Go module) uses to open an encrypted Kopia repository, back up Microsoft 365 data into it with caller-supplied tags, list, delete or run maintenance on the resulting backup points, and browse what those points contain - a folder tree, the items in a folder, and finding an item by name (RES-1, RES-2; see browse.go).
It exists because Go forbids importing another module's internal packages (REPO-2): the lower-level pkg/repository package - the fork's original, CLI-oriented entry point - returns several types from src/internal/operations (operations.BackupOperation, operations.MaintenanceOperation, and friends) from its own exported methods. A caller in another module can only use those methods' return values through Go's type-inference "escape hatch" (never writing the import, never naming the type) - which works for calling a method, but breaks the moment that caller wants to store the value in a struct field, pass it to a function with a named parameter type, or do anything else that requires writing the type name. That is not a deliberate public API; it is an accident of Go's internal-import enforcement being a property of import statements, not of value usage. This package is the deliberate promotion REPO-2 and REPO-3 call for: every exported type and function signature here uses only plain Go types (string, []byte, time.Time, map[string]string, bool) or other src/pkg types that are themselves part of this fork's existing public contract (pkg/account, pkg/storage, pkg/control, pkg/selectors). Nothing in this package's own exported API ever requires - or permits - a caller to name a type from src/internal/anything. src/cmd/backupexample is the fork's own proof of that: see its package-level doc comment and TestExample_ImportsNoInternalPackage for how that is checked mechanically, not just by inspection.
Every setting (storage location and encryption key, Microsoft 365 credentials, tags, progress reporting) is supplied by the caller, as the fork's own CLAUDE.md requires of every src/pkg entry point: this package reads no environment variable, config file or flag, and it never writes to stdout. It never logs, prints or returns a repository key, Microsoft 365 secret or item content; errors name objects by backup ID or tag key only, never by subject, filename or file content.
Index ¶
- Variables
- type BackupPoint
- type BackupPointType
- type BackupRequest
- type FindItemsRequest
- type FindItemsResult
- type Folder
- type FolderTree
- type FolderTreeRequest
- type FoundItem
- type Item
- type ItemList
- type ItemsRequest
- type MaintenanceOptions
- type NameMatch
- type ProgressFunc
- type ProgressSnapshot
- type Repository
- func (r *Repository) Backup(ctx context.Context, req BackupRequest) (BackupPoint, error)
- func (r *Repository) Close(ctx context.Context) error
- func (r *Repository) DeleteBackupPoints(ctx context.Context, tags map[string]string) ([]string, error)
- func (r *Repository) FindItemsByName(ctx context.Context, req FindItemsRequest) (FindItemsResult, error)
- func (r *Repository) ID() string
- func (r *Repository) ListBackupPoints(ctx context.Context, tags map[string]string) ([]BackupPoint, error)
- func (r *Repository) ListFolders(ctx context.Context, req FolderTreeRequest) (FolderTree, error)
- func (r *Repository) ListItems(ctx context.Context, req ItemsRequest) (ItemList, error)
- func (r *Repository) RunMaintenance(ctx context.Context, opts MaintenanceOptions) error
- type RepositoryConfig
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrBackupPointNotFound = errors.New("engine: no backup point exists with that id")
ErrBackupPointNotFound is returned by ListFolders and ListItems when no backup point in this repository has the requested ID. It wraps the fork's own pkg/repository.ErrorBackupNotFound, so errors.Is also matches that, but callers outside this module can only name (and so should only depend on) this exported error.
var ErrEmptyNameQuery = errors.New("engine: FindItemsByName requires a non-empty name")
ErrEmptyNameQuery is returned by FindItemsByName when Name is empty. An empty query never means "every item": a caller that wants every item in a point calls ListItems with no FolderID, so that intent is visible at the call site. (Same reasoning as ErrEmptyTagFilter.)
var ErrEmptyTagFilter = errors.New("engine: this operation requires at least one tag")
ErrEmptyTagFilter is returned by DeleteBackupPoints, and by FindItemsByName (added in chunk 0.7), when called with no tags.
Deleting "every backup point with no particular tag" is never implied by an empty filter: a caller that genuinely wants that iterates ListBackupPoints(ctx, nil) themselves and deletes each ID explicitly, so that intent is visible at the call site rather than hidden behind an empty map. FindItemsByName refuses an empty filter for the related reason that an unscoped search would reach every object - and, if a repository ever held more than one, every tenant - in the repository, where RES-2 asks only for a search within one object's backup points. ListBackupPoints is the deliberate exception: a nil filter there means "every point", which is how a caller discovers what exists at all.
var ErrFolderNotFound = errors.New("engine: no folder with that id in that backup point")
ErrFolderNotFound is returned by ListItems when FolderID names no folder in the requested backup point. A caller gets folder IDs from ListFolders on the same backup point; an ID from a different point is not valid here even if the two points cover the same object, because an ID is only meaningful within the point it was listed from (see Folder.ID).
var ErrIncompleteBackupPoint = errors.New("engine: backup point is not independently restorable")
ErrIncompleteBackupPoint is returned by ListFolders and ListItems when the requested backup point is not independently restorable - an assist, preview or unclassified point (see BackupPointType) - and the request did not set AllowIncompletePoint.
This is the deliberate guard against the mistake browse exists to make easy: ListBackupPoints returns every point in the repository, assist and preview points included (0.6 made that so on purpose, because an assist point left behind by one throttled item is real, tagged, storage-occupying content a tenant must be able to find and delete). But an assist point holds only the items that one interrupted backup managed to upload. Its folder tree is a *fragment* of the object, with no marker inside the data saying so. Rendered in a browse UI next to a merge point's tree, it looks exactly like a complete point in time - and an admin picking "restore this folder" from it would silently restore a subset. So browsing one is refused by default, and the caller has to say AllowIncompletePoint to get it.
AllowIncompletePoint exists, rather than browse simply refusing these points outright, because erasure needs it: GDPR-2 requires erased items to disappear from every affected backup point, which means a future erasure chunk has to be able to enumerate the items inside an assist point in order to name them for removal. A flat refusal here would have re-created 0.6's own HIGH finding (content that exists but cannot be reached) one layer up. When it is set, FolderTree.IndependentlyRestorable and ItemList.IndependentlyRestorable report false and PointType says which kind of point it is, so a caller that opted in still cannot mistake the result for a complete tree.
var ErrMissingBackupPointID = errors.New("engine: a backup point id is required")
ErrMissingBackupPointID is returned by ListFolders and ListItems when the request carries no backup point ID. An empty ID never means "any point" or "the latest point": a caller picks a point explicitly with ListBackupPoints first, which is also the only way to know whether the point it picked is independently restorable.
var ErrMissingStorageCredentials = errors.New(
"engine: S3 storage requires an explicit, non-blank access key and secret key; " +
"this package never falls back to ambient AWS credentials")
ErrMissingStorageCredentials is returned by InitializeRepository and OpenRepository when cfg.Storage is an S3-compatible configuration with a blank (or whitespace-only - " " and "\t" are not valid AWS credentials either) access key or secret key.
Kopia's own S3 blob storage, given no static credentials, falls back to its AWS SDK's ambient credential chain: environment variables, then the EC2/ECS/IMDS instance role. That used to be treated as the right behaviour for the fork's CLI, running under a human's or a CI job's own AWS identity; chunk 0.9 dropped that, so it is now the wrong behaviour everywhere in this fork. It was always wrong for this package: a caller-chosen bucket, prefix and endpoint silently reaching the *platform's own* ambient AWS identity - because a caller forgot an access key, or some other part of the config was tenant-influenced - is exactly the kind of storage access ENC-4 ("storage providers never see plaintext", and by extension never see more than the one tenant's data they were explicitly handed) exists to prevent. Proven live: with no caller-chosen credentials, a MinIO bucket was reachable using this machine's own ambient AWS identity.
pkg/storage.S3Config.validate() (the shared validator) enforces this same requirement, for every caller, with no opt-out - chunk 0.6's security reviewer proved the condition was reachable even through pkg/repository.New + Initialize directly, bypassing this package entirely, since pkg/repository is itself public (REPO-2 permits k3ep to import it; only prose steered callers to this facade instead). Chunk 0.6 first added an opt-out so the fork's CLI could keep connecting with no explicit keys; chunk 0.9 deleted that capability outright, on the user's decision, so explicit S3 credentials are now required everywhere in this fork.
This function remains, as a second, earlier layer: it fails fast, before any Microsoft 365 connection is attempted, with this package's own named error, rather than failing later (after an M365 round trip) with pkg/storage's more generic one. It is deliberately independent of whether the shared validator already caught the same problem (see its own body): the two may give different feedback, but a caller going through this package always sees ErrMissingStorageCredentials for this specific condition, never a leftover ambiguity about which layer enforced it.
var ErrRepositoryExists = errors.New("engine: a repository already exists with that configuration")
ErrRepositoryExists is returned by InitializeRepository when a repository already exists at the given storage location with the given key. It wraps the fork's own pkg/repository.ErrorRepoAlreadyExists, so errors.Is also matches that, but callers outside this module can only name (and so should only depend on) this exported error.
var ErrReservedTagKey = errors.New("engine: tag key is reserved by the backup engine")
ErrReservedTagKey is returned by Backup when a BackupRequest.Tags key collides with a tag key the fork's own bookkeeping, Kopia's model store, or the fork's backup garbage collector reserves for itself. Those reserved keys drive logic this package cannot let a caller influence by accident, or - the adversarial case - by deliberately forging a tag that is supposed to be reserved. See reservedTagKeys' doc comment above for exactly which keys and why.
var ErrReservedTagPrefix = errors.New("engine: tag key uses a prefix reserved by the backup engine")
ErrReservedTagPrefix is returned by Backup when a BackupRequest.Tags key starts with a prefix the fork's backup garbage collector reserves for itself ("sc-"). See reservedTagKeys' doc comment above.
var ErrTagTooLarge = errors.New("engine: tag key or value is too large")
ErrTagTooLarge is returned by Backup when a BackupRequest.Tags key or value exceeds maxTagKeyBytes/maxTagValueBytes.
var ErrTagsTooLarge = errors.New("engine: tags are too large in total")
ErrTagsTooLarge is returned by Backup when a BackupRequest.Tags map's combined key and value bytes exceed maxTagTotalBytes, even though every individual key and value is within its own per-tag bound. See maxTagTotalBytes' doc comment above for why this bound exists separately from the per-key/per-value ones.
var ErrTooManyTags = errors.New("engine: too many tags")
ErrTooManyTags is returned by Backup when a BackupRequest.Tags has more than maxTagCount entries.
Functions ¶
This section is empty.
Types ¶
type BackupPoint ¶
type BackupPoint struct {
// ID identifies this backup point for later use with
// DeleteBackupPoints or a future chunk's browse/restore API. Never a
// secret.
ID string
// Type classifies this backup point - see BackupPointType's own doc
// comment for what each value means and, in particular, why only
// BackupPointTypeMerge is independently restorable.
Type BackupPointType
// Tags are exactly the tags this backup was created with (via
// BackupRequest.Tags), plus the fork's own "service" and
// "backup-type" bookkeeping tags. Type above is derived from the
// "backup-type" entry here (via pkg/backup.Backup.Type(), not by this
// package re-reading the tag itself); both are provided because a
// caller may still want the raw string for display or audit
// purposes, even though Type is what any logic should branch on.
Tags map[string]string
// CreatedAt is when this backup point was created.
CreatedAt time.Time
// ItemsRead is the number of M365 items read during this backup.
ItemsRead int64
// BytesUploaded is the number of bytes this backup point added to the
// repository (after dedupe/compression).
BytesUploaded int64
// ErrorCount is the number of recoverable errors this backup
// encountered. Zero does not guarantee the backup is complete -
// Backup itself returns a non-nil error for anything worse.
ErrorCount int
}
BackupPoint is everything this package exposes about one completed backup, in plain Go types only.
type BackupPointType ¶
type BackupPointType string
BackupPointType classifies a BackupPoint by the fork's own internal merge/assist/preview distinction, exposed here as a typed, documented value specifically so a caller outside this module never has to hardcode the literal tag value ("backup-type") or the literal strings the fork's internal/model package uses ("merge-backup", "assist-backup", "preview-backup") to tell them apart - both of which a k3ep build cannot name directly (internal/model is not importable from outside this module), so without this type, the only way to interpret BackupPoint.Tags["backup-type"] from k3ep would be to hardcode those exact literals against a key this very package simultaneously reserves callers from setting (see tags.go) - a direct, if accidental, coupling to an internal implementation detail REPO-2 exists to prevent. It also captures pkg/backup.Backup.Type()'s version-aware default for backups older than v8, which never persisted a backup-type tag at all; reading BackupPoint.Tags directly would miss that.
const ( // BackupPointTypeMerge is a complete backup: the only type this // package guarantees is independently restorable. A future restore // chunk should treat any other type as not restorable on its own. BackupPointTypeMerge BackupPointType = "merge" // BackupPointTypeAssist is a partial result from kopia-assisted // incremental backup - typically left behind by a recoverable error // partway through a real backup (see ListBackupPoints' doc comment). // Not independently restorable; useful as a base for a future // backup's own incremental logic, not as a restore target. BackupPointTypeAssist BackupPointType = "assist" // BackupPointTypePreview is a deliberately partial backup (see // control.Options.PreviewLimits). Not independently restorable in // the same sense as a merge backup - it was never meant to be a // complete copy of the source data. BackupPointTypePreview BackupPointType = "preview" // BackupPointTypeUnknown covers any value the fork's own // pkg/backup.Backup.Type() returns that this package does not // recognize - including, deliberately, the empty string Type() // itself documents returning when no backup-type tag is present and // the model's own Version is either the zero value (version.NoBackup - // never a real backup) or newer than v8's migration point (a case // Type()'s own comment says "should not happen" for a genuine // backup, since every version from v8 onward sets the tag). A // genuinely pre-v8 backup with no tag is Type()'s one deliberate // exception: Corso only ever persisted MergeBackup models before v8, // so Type() defaults a missing tag to "merge-backup" there - handled // above by BackupPointTypeMerge, not here. Treat // BackupPointTypeUnknown as "do not assume restorable." BackupPointTypeUnknown BackupPointType = "unknown" )
func (BackupPointType) IsIndependentlyRestorable ¶
func (t BackupPointType) IsIndependentlyRestorable() bool
IsIndependentlyRestorable reports whether a BackupPoint of this type can be restored on its own, with no other backup point involved. Only BackupPointTypeMerge qualifies today; every other value - including any future type this package has not yet defined - is conservatively not restorable. Added per a round-4 review suggestion so a later chunk (browse, restore) has a single typed comparison to call rather than re-deriving "only merge is restorable" from this type's own doc comments at each call site.
type BackupRequest ¶
type BackupRequest struct {
// Selector picks what to back up - which service (Exchange, OneDrive,
// SharePoint, ...) and which resource owner(s) - built with
// pkg/selectors. See that package's own documentation and
// src/cmd/backupexample for a worked example.
Selector selectors.Selector
// Tags are stored on the resulting backup point and are later used to
// list or delete it (ListBackupPoints, DeleteBackupPoints) - k3ep uses
// its own "k3ep-tenant", "k3ep-policy" and "k3ep-object" keys,
// deliberately namespaced so they can never collide with a key this
// package reserves for itself (see tags.go). This package stores and
// filters by tags; it never interprets their values. Rejected outright,
// before any backup work starts, and before anything is uploaded: a
// key that collides with a reserved key or prefix (ErrReservedTagKey,
// ErrReservedTagPrefix), more than maxTagCount tags (ErrTooManyTags),
// a key or value over the per-tag byte limits in tags.go
// (ErrTagTooLarge), or a map whose combined key and value bytes
// exceed maxTagTotalBytes even though every individual tag is within
// its own limit (ErrTagsTooLarge).
Tags map[string]string
// Progress, if non-nil, is called periodically during the backup and
// exactly once more at the end - see ProgressFunc.
Progress ProgressFunc
}
BackupRequest describes one backup.
type FindItemsRequest ¶
type FindItemsRequest struct {
// Tags scopes the search to the backup points carrying all of these
// key/value pairs - for k3ep, its own "k3ep-object" (and
// "k3ep-tenant") tag, which is what makes this "within one object's
// backup points" rather than a repository-wide search. Required and
// non-empty: see ErrEmptyTagFilter. Matching is exactly
// ListBackupPoints' matching.
Tags map[string]string
// Name is the name to look for. Required: see ErrEmptyNameQuery.
// Compared case-insensitively (by simple Unicode lower-casing, not
// locale-aware collation) against item names only - never content.
Name string
// Match selects substring or whole-name comparison. Its zero value
// is NameMatchContains.
Match NameMatch
// AllowIncompletePoints includes backup points that are not
// independently restorable in the search. Default false, which
// searches only merge points; see ErrIncompleteBackupPoint for why
// this is opt-in. Unlike ListFolders and ListItems, this never
// returns ErrIncompleteBackupPoint - a find spans many points, so a
// non-restorable one is skipped rather than failing the whole search.
// Each result says which point it came from and what type that point
// is.
AllowIncompletePoints bool
}
FindItemsRequest asks for the items matching a name across one object's backup points (RES-2).
type FindItemsResult ¶
type FindItemsResult struct {
// Items is every match found, ordered newest backup point first (by
// that point's own creation time, then its ID to break ties), and
// within a point by (FolderPath, Name, ID).
Items []FoundItem
// UnreadableBackupPointIDs lists the backup points that matched
// req.Tags but whose details manifest could not be read, so were not
// searched. Normally empty. A point deleted between this call's own
// listing step and its read lands here, as does one whose manifest
// is genuinely damaged or whose storage is unreachable.
//
// When this is non-empty the result is PARTIAL: Items holds every
// match from the points that were readable, and a caller must
// surface that rather than presenting the result as complete. The
// IDs are safe to log and are what a caller needs in order to
// retry, audit or report the gap.
UnreadableBackupPointIDs []string
}
FindItemsResult is what one FindItemsByName call matched.
It is a struct rather than a bare []FoundItem because a search spans many backup points and some of them may not be readable, and a caller has to be able to tell "nothing matches" from "not everything was searched". Showing an admin an empty result when a point was skipped would be a quiet wrong answer in exactly the situation - erasure verification, a legal-hold check - where a wrong answer costs most.
type Folder ¶
type Folder struct {
// ID identifies this folder within this backup point, stably: the
// same folder in the same backup point is the same ID on every call,
// because it is derived (by the fork, when the backup was written)
// from the folder's immutable storage path and stored in the point's
// own details manifest - not generated per call and not dependent on
// listing order. It is an opaque, hashed, non-reversible value: safe
// to log, store and put in a URL, and it reveals no folder name.
//
// Not an ID a caller should reuse across backup points: the same
// mail folder in two different points may well have the same ID
// (the storage path it hashes is the same), but nothing guarantees
// that - a renamed or moved drive folder gets a different one, for
// the reasons set out on Item.ID - and ListItems rejects an ID that
// is not in the point being listed (ErrFolderNotFound).
ID string
// ParentID is the ID of the Folder this one sits inside, or "" when
// this folder is at the top of what the backup point recorded. Use
// this, not Path, to reconstruct the tree: Path is a display string
// and is ambiguous if any folder name contains a "/".
ParentID string
// Name is the folder's Microsoft 365 display name, exactly as the
// backup recorded it. Real content: see this file's note on names.
//
// One documented exception, confirmed against the real test tenant
// rather than assumed: for a SharePoint list's container (Category
// "lists") the backup records no display name, only the list's own
// Microsoft 365 list ID, so that ID is what Name and Path carry. The
// list's human title is on the Item inside it - there is exactly one,
// the list itself. A caller rendering a tree should label a "lists"
// container from the item inside it, not from this field.
Name string
// Path is Name prefixed by every ancestor folder's display name,
// joined with "/" - for display to an admin. Display names are not
// escaped, so a folder whose own name contains "/" produces an
// ambiguous Path; ParentID is the unambiguous structure.
//
// For OneDrive and SharePoint library folders the first element is
// the drive's own root ("root:"), because that is genuinely how the
// backup records a drive's folder tree. DriveName below is the
// human-readable name of the drive (for SharePoint, the document
// library) that root belongs to.
Path string
// Service is the Microsoft 365 service this folder belongs to, as the
// fork's own stable wire name: "exchange", "onedrive", "sharepoint",
// "groups" or "teamsChats".
Service string
// Category is the data category within Service, as the fork's own
// stable wire name: "email", "contacts", "events", "files",
// "libraries", "lists" or "pages". This is what tells a mail folder
// from a calendar from a contacts folder, all three of which can be
// top-level folders in one Exchange backup point with nothing in
// their names to distinguish them.
Category string
// DriveID and DriveName identify the OneDrive drive or SharePoint
// document library this folder lives in. Both are empty for Exchange
// folders, which are not drive-backed. DriveName is the library's
// display name, which for SharePoint is how an admin recognises which
// document library they are browsing - the library itself is a drive,
// not a Folder entry of its own.
DriveID string
DriveName string
// SizeBytes is the total size of every item at or below this folder,
// as the backup point itself recorded it - a roll-up, not the size of
// this folder's direct children only. Zero for a folder whose items
// carry no size (Exchange calendars and contacts folders routinely
// do).
//
// One inherited inconsistency, documented rather than corrected: the
// roll-up is computed by the fork when it writes the backup, using
// its own per-item size accessor, which for a Teams chat contributes
// the chat's MESSAGE COUNT rather than a byte count. Item.SizeBytes
// deliberately reports 0 for a Teams chat instead (see itemSize), so
// for a folder of chats this roll-up and the items beneath it would
// disagree. Teams chats are outside k3ep's v1 workloads, so nothing
// browse returns today is affected; recomputing the roll-up here
// instead of reporting what the backup recorded would be a bigger
// and less honest change than saying so.
SizeBytes int64
// ModifiedAt is the most recent modification time of any item at or
// below this folder, as the backup point recorded it, or the zero
// time if none of them carried one.
ModifiedAt time.Time
}
Folder is one container inside a backup point: a mail folder, a calendar, a contacts folder, a OneDrive folder, a folder inside a SharePoint document library, or a SharePoint list's own container (RES-1). Every field is a plain Go type.
type FolderTree ¶
type FolderTree struct {
// BackupPointID is the point this tree came from.
BackupPointID string
// PointType is that point's type, so a caller that set
// AllowIncompletePoint can see what it actually got.
PointType BackupPointType
// IndependentlyRestorable is PointType.IsIndependentlyRestorable().
// When false, Folders is a *fragment* of the object - whatever one
// interrupted or deliberately partial backup managed to record - and
// must not be presented as a complete point in time.
IndependentlyRestorable bool
// Folders is every folder the backup point recorded, flattened into
// one slice rather than nested: reconstruct the hierarchy with
// Folder.ParentID, whose "" value marks a top-level folder. Flat
// because a backup point mixes several services and categories, so
// there is no single root to nest under, and because a caller
// rendering a tree lazily wants to index by ID anyway.
//
// Deterministically ordered by (Path, ID), on every call. The
// underlying details manifest stores folder entries in a
// map-iteration order that genuinely varies between calls, so this
// ordering is applied here rather than inherited.
Folders []Folder
}
FolderTree is one backup point's complete folder tree, flattened.
type FolderTreeRequest ¶
type FolderTreeRequest struct {
// BackupPointID is the BackupPoint.ID to browse, from
// ListBackupPoints. Required: see ErrMissingBackupPointID.
BackupPointID string
// AllowIncompletePoint permits browsing a backup point that is not
// independently restorable. Leave it false for anything an admin will
// restore from; see ErrIncompleteBackupPoint for the full reasoning
// and for why this escape hatch exists at all.
AllowIncompletePoint bool
}
FolderTreeRequest asks for one backup point's folder tree.
Tenancy is the caller's responsibility, not this package's. Unlike ListBackupPoints, DeleteBackupPoints and FindItemsByName, which take a tag filter, this takes a bare backup point ID and does NOT check the point's tags against anything: a backup point ID is not self-authorising, and holding one is not evidence of being entitled to read it. That is deliberate and consistent with this package never interpreting tags (see RepositoryConfig's trust-model note: tags are not an authorization boundary and this package has no notion of "my" tenant), but it means k3ep's own API layer must establish that the point belongs to the requesting tenant - by listing it through that tenant's own tag filter, or by checking the returned FolderTree/ItemList's point against its own records - before handing an ID here. A repository holding exactly one tenant's data (which is k3ep's model) makes this moot; a shared one would not.
type FoundItem ¶
type FoundItem struct {
// Item is the matched item, exactly as ListItems would report it.
Item Item
// BackupPointID is the point this item was found in. Item.ID is only
// meaningful together with it.
BackupPointID string
// BackupPointType and BackupPointIndependentlyRestorable describe
// that point, so a caller that set AllowIncompletePoints can tell a
// hit in a complete point from a hit in a fragment.
BackupPointType BackupPointType
BackupPointIndependentlyRestorable bool
// BackupPointCreatedAt is when that backup point was created - the
// "point in time" an admin chose in RES-1, as opposed to
// Item.CreatedAt, which is when Microsoft 365 created the item.
BackupPointCreatedAt time.Time
}
FoundItem is one item FindItemsByName matched, with the backup point it was found in.
type Item ¶
type Item struct {
// ID identifies this item within this backup point. It is derived (by
// the fork, when the backup was written) from the item's storage path
// and stored in the point's own details manifest, so browse generates
// nothing: the same item in the same backup point is the same ID on
// every call, across a Close and OpenRepository, and across a later
// incremental backup that does not move it. It is the value the
// fork's own item selectors accept as an item reference, so it is the
// handle a later restore (5.1) or erasure (7.3) takes as input.
//
// The durable handle is the PAIR (backup point ID, Item.ID). Item.ID
// alone is not a cross-point identity, and a caller must not use it
// as a primary key for "this item" across points:
//
// - For OneDrive and SharePoint library items the storage path is
// built from the folder chain's DISPLAY NAMES (see
// internal/m365/collection/drive's getCollectionPath, which reads
// the item's parent reference path). Renaming OR moving any
// ancestor folder therefore gives the same file a different ID in
// the next backup point.
// - For Exchange the path elements are container IDs, so renaming a
// mail folder, calendar or contacts folder does not change its
// items' IDs - but moving one does, because its parent chain does.
//
// None of that invalidates an already-listed ID: a backup point is
// immutable, so an ID listed from one point keeps identifying that
// item in that point forever. It only means an ID from point A may
// not resolve in point B, which is why FoundItem carries the point it
// came from and why ListItems rejects a folder ID from another point.
//
// Opaque, hashed and non-reversible: safe to log, store and put in a
// URL, and it reveals no item name, subject or filename. It is not
// the item's Microsoft 365 ID and is not meaningful outside this
// repository.
ID string
// FolderID is the ID of the Folder this item sits in, or "" for an
// item the backup point recorded outside any folder. Every item every
// v1 workload produces does sit in a folder - including a SharePoint
// list, whose container is named by its list ID (see Folder.Name) -
// so "" here means the backup recorded no location for this item, not
// that it belongs at the top of the tree. ListFolders on the same
// backup point returns the matching Folder.
FolderID string
// FolderPath is that folder's Path - repeated here so a caller
// rendering search results does not have to join them against a
// folder listing. Empty when FolderID is empty. Real content: see
// this file's note on names.
FolderPath string
// Name is the item's human name as the backup recorded it: a mail
// message's or calendar event's subject, a contact's display name, a
// file's filename, a list's title. Empty if the backup point recorded
// none. Real content: see this file's note on names.
Name string
// SizeBytes is the item's size in bytes as the backup recorded it, or
// 0 for an item kind that carries no size. Exchange calendar events
// and contacts commonly report 0; it means "not recorded", not
// "empty".
SizeBytes int64
// CreatedAt and ModifiedAt are the item's own Microsoft 365
// creation and last-modified times as the backup recorded them, not
// the time it was backed up (BackupPoint.CreatedAt is that). Either
// is the zero time when the backup point recorded none - which is
// normal, not an error: Microsoft Graph does not return a date for
// every kind of object (see 0.3's seed manifest, where mail folders,
// calendars and contacts folders are genuinely dateless).
CreatedAt time.Time
ModifiedAt time.Time
// ItemCount is how many child objects this item itself contains, and
// is non-zero only for a SharePoint list (Category "lists").
//
// It exists because the fork records a whole list as a *single*
// backed-up item - one entry carrying the list's name, dates and the
// number of list items inside it - rather than one entry per list
// item. So a list's own rows are not individually browsable, and not
// individually addressable by Item.ID either: the list is the unit
// that can be listed here (and, when 5.1 and 7.3 arrive, the unit
// they will be handed). This count is the only thing browse can say
// about what is inside one, and it is what an admin needs in order to
// recognise the list they are looking at. Confirmed live: a list
// seeded with two rows reports ItemCount 2 and lists as one item.
// Zero for every other kind of item, where it means nothing rather
// than "empty".
ItemCount int64
// Service and Category are as described on Folder.
Service string
Category string
// DriveID and DriveName are as described on Folder: set for OneDrive
// and SharePoint library items, empty for Exchange items.
DriveID string
DriveName string
}
Item is one backed-up object inside a Folder: a mail message, a calendar event, a contact, a file in OneDrive or a SharePoint document library, or a SharePoint list. Every field is a plain Go type.
type ItemList ¶
type ItemList struct {
// BackupPointID, PointType and IndependentlyRestorable are as
// described on FolderTree.
BackupPointID string
PointType BackupPointType
IndependentlyRestorable bool
// Items is the matching items, deterministically ordered by
// (FolderPath, Name, ID) on every call.
Items []Item
}
ItemList is the items one ItemsRequest matched.
type ItemsRequest ¶
type ItemsRequest struct {
// BackupPointID is the BackupPoint.ID to browse, from
// ListBackupPoints. Required: see ErrMissingBackupPointID.
BackupPointID string
// FolderID limits the result to the items directly inside that one
// folder - not its subfolders' items. Leave it empty to get every
// item in the whole backup point, across every service and category
// it covers. A FolderID that is not in this backup point is
// ErrFolderNotFound, never silently empty.
FolderID string
// AllowIncompletePoint is as described on FolderTreeRequest.
AllowIncompletePoint bool
}
ItemsRequest asks for the items in one folder, or in one whole backup point.
Tenancy is the caller's responsibility, not this package's. Unlike ListBackupPoints, DeleteBackupPoints and FindItemsByName, which take a tag filter, this takes a bare backup point ID and does NOT check the point's tags against anything: a backup point ID is not self-authorising, and holding one is not evidence of being entitled to read it. That is deliberate and consistent with this package never interpreting tags (see RepositoryConfig's trust-model note: tags are not an authorization boundary and this package has no notion of "my" tenant), but it means k3ep's own API layer must establish that the point belongs to the requesting tenant - by listing it through that tenant's own tag filter, or by checking the returned FolderTree/ItemList's point against its own records - before handing an ID here. A repository holding exactly one tenant's data (which is k3ep's model) makes this moot; a shared one would not.
type MaintenanceOptions ¶
type MaintenanceOptions struct {
// Metadata, if true, runs a cheaper, metadata-only maintenance pass
// instead of the full, complete pass. See Kopia's own documentation
// for the difference; a full pass should be run regularly even if
// metadata-only passes run more often in between.
Metadata bool
// Force skips the fork's own "don't run full maintenance too often"
// safety check. Only needed for tests or deliberate off-schedule
// runs.
Force bool
}
MaintenanceOptions configures one maintenance run.
type NameMatch ¶
type NameMatch string
NameMatch selects how FindItemsByName compares its Name query against an item's name. Both modes compare *names only* - never message bodies, file contents, attachments or any other item content. RES-2 rules full-text content search out of scope, and nothing in this package reads an item's content at all: matching runs entirely against the names already recorded in the backup point's own details manifest, so a find never touches the stored data and never decrypts anything.
const ( // NameMatchContains matches an item whose name contains the query as // a substring. This is NameMatch's zero value, so a caller that // leaves FindItemsRequest.Match unset gets substring matching - // chosen as the default because an admin searching for an item by // name rarely knows its exact full subject or filename. NameMatchContains NameMatch = "" // NameMatchExact matches an item whose whole name equals the query. NameMatchExact NameMatch = "exact" )
type ProgressFunc ¶
type ProgressFunc func(ProgressSnapshot)
ProgressFunc is invoked periodically while a backup runs, and exactly once more, with Done true, when it finishes. It runs on a background goroutine that Backup owns and joins before returning, so by the time Backup returns no further call will happen; implementations should return quickly and must be safe to call repeatedly (never concurrently with themselves - calls are always sequential). This is the only progress channel this package has: nothing it does writes to stdout.
type ProgressSnapshot ¶
type ProgressSnapshot struct {
// Counts maps a pkg/count key to its current value for this backup.
// Keys present vary by workload and are not guaranteed stable across
// fork versions; treat an absent key as 0, not as an error.
Counts map[string]int64
// Done is true on exactly one call per Backup invocation: the last
// one, delivered once the backup has finished (successfully or not).
Done bool
}
ProgressSnapshot is a point-in-time view of a running backup's progress, delivered to a BackupRequest's Progress callback. Counts are cumulative, real, server-confirmed counters (see pkg/count's key documentation for the full set of keys the fork tracks, e.g. "items-added", "persisted-uploaded-bytes") measured from the start of this specific Backup call, never a fabricated estimate, and never including an item name, subject or any other content.
type Repository ¶
type Repository struct {
// contains filtered or unexported fields
}
Repository is an open handle to a Kopia repository. Obtain one with InitializeRepository (first use) or OpenRepository (every later use), and release it with Close when done.
func InitializeRepository ¶
func InitializeRepository(ctx context.Context, cfg RepositoryConfig) (*Repository, error)
InitializeRepository creates a brand-new repository at cfg.Storage, encrypted with cfg.Storage's CorsoPassphrase, and connects to it.
Like every repository operation in the underlying fork, this also connects to Microsoft 365 using cfg.Account and verifies that connection (fetches a real access token) before touching the storage backend - the fork's pkg/repository ties a repository's lifecycle to a verified M365 account unconditionally, which happens to fit k3ep's own domain model (ENC-1: a repository belongs to exactly one tenant's M365 connection) exactly, so this package does not try to route around it. A test that only cares about the storage round trip still needs a valid cfg.Account.
Calling this again at a configuration that already has a repository is safe as long as cfg.Storage's CorsoPassphrase is the same one the repository was created with: the fork's own Initialize treats that as a reconnect, not an error, so this returns the same repository (same ID) rather than failing - confirmed live against the test tenant. It is ErrRepositoryExists (wrapping the fork's own repository.ErrorRepoAlreadyExists) only when the repository already exists AND the connection that follows fails - in practice, a wrong CorsoPassphrase for an existing repository. OpenRepository is still the right call when the caller already knows a repository exists; this behavior exists so a caller unsure whether it does can use InitializeRepository either way without special-casing "already exists".
Example ¶
ExampleInitializeRepository creates a tenant's repository, with every setting - storage location, encryption key, Microsoft 365 credentials - supplied by the caller. pkg/engine reads no environment variable, configuration file or flag, so there is no ambient value to fall back on and nothing to misconfigure by omission.
One repository holds exactly one tenant: tags are a label, not an authorisation boundary, so tenant separation is this choice of storage location and key, not the tags on the points inside it.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
func main() {
ctx := context.Background()
tenantID, clientID, clientSecret := m365AppCredentials()
acct, err := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
if err != nil {
fmt.Println("building the M365 account:", err)
return
}
// A mounted filesystem path. For S3-compatible storage, swap in:
//
// storage.ProviderS3,
// &storage.S3Config{
// AWS: credentials.AWS{AccessKey: ak, SecretKey: sk},
// Bucket: bucket,
// Endpoint: endpoint,
// Prefix: prefix,
// },
//
// AccessKey and SecretKey are required and are never inferred: there
// is no instance-role, shared-credentials-file or SDK-fallback path
// in this fork, and a blank or whitespace-only key is rejected before
// any network call with engine.ErrMissingStorageCredentials.
st, err := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
// The repository's own encryption key. Lose it and the
// repository is unreadable; log it and the whole repository is
// compromised. Never format a Storage, an Account or a
// RepositoryConfig with anything but their own String/LogValue/
// MarshalJSON methods - and never with YAML or encoding/gob,
// which walk the credential maps those methods protect.
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
if err != nil {
fmt.Println("building the storage configuration:", err)
return
}
cfg := engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
// Opening a repository also connects and verifies the Microsoft 365
// account, and installs a process-global Graph concurrency clamp that
// the first open in this process latches for every later one - see
// this package's README.md.
repo, err := engine.InitializeRepository(ctx, cfg)
if err != nil {
fmt.Println("initialising the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
fmt.Println("repository ID:", repo.ID())
}
Output:
func OpenRepository ¶
func OpenRepository(ctx context.Context, cfg RepositoryConfig) (*Repository, error)
OpenRepository connects to a repository previously created with InitializeRepository, at the same cfg.Storage location and with the same CorsoPassphrase key. See InitializeRepository's doc comment for why cfg.Account is required even for a storage-only use.
Example ¶
ExampleOpenRepository connects to a repository that already exists, at the same storage location and with the same key it was created with.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
fmt.Println("repository ID:", repo.ID())
}
Output:
func (*Repository) Backup ¶
func (r *Repository) Backup(ctx context.Context, req BackupRequest) (BackupPoint, error)
Backup runs one backup and returns the resulting BackupPoint once it completes. It connects to Microsoft 365 using the Account the repository was opened with (see InitializeRepository/OpenRepository) and reports progress through req.Progress, never to stdout.
Example ¶
ExampleRepository_Backup runs one backup with caller-supplied tags and a progress callback.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/selectors"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// tenantTags are the tags k3ep puts on every backup point and uses to
// scope every later list, delete or search. The keys are namespaced:
// pkg/engine rejects the bare key "tenant" and any key starting with
// "sc-", because the fork's own garbage collector reads those to decide
// which assist bases survive. The values are k3ep's own IDs, generated
// server-side - never a string a tenant supplied.
func tenantTags() map[string]string {
return map[string]string{
"k3ep-tenant": "tenant-uuid",
"k3ep-policy": "policy-uuid",
"k3ep-object": "object-uuid",
}
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
sel := selectors.NewExchangeBackup([]string{"user@example.test"})
sel.Include(sel.MailFolders(selectors.Any(), selectors.PrefixMatch()))
sel.DiscreteOwner = "user@example.test"
point, err := repo.Backup(ctx, engine.BackupRequest{
Selector: sel.Selector,
Tags: tenantTags(),
// Called periodically on a goroutine Backup owns and joins before
// returning, and exactly once more with Done true. Counts are real
// server-confirmed counters and carry no item name or content.
// Nothing in pkg/engine writes to stdout; this callback is the only
// progress channel there is.
Progress: func(p engine.ProgressSnapshot) {
fmt.Println("progress:", p.Counts, "done:", p.Done)
},
})
if err != nil {
// A backup that returns an error may still have persisted an
// assist point carrying these tags, holding real content that
// occupies storage. It is listable and deletable through the tag
// filter below; it is not restorable.
fmt.Println("running the backup:", err)
return
}
fmt.Println(point.ID, point.Type, point.ItemsRead, point.BytesUploaded, point.ErrorCount)
}
Output:
func (*Repository) Close ¶
func (r *Repository) Close(ctx context.Context) error
Close releases the repository handle. Safe to call once after a successful InitializeRepository or OpenRepository call; it does not affect the underlying stored data.
func (*Repository) DeleteBackupPoints ¶
func (r *Repository) DeleteBackupPoints(ctx context.Context, tags map[string]string) ([]string, error)
DeleteBackupPoints deletes every backup point carrying all the key/value pairs in tags, and only those - never a point whose tags don't match every one supplied, and never silently skipping one that does: see ListBackupPoints' doc comment for why this also reaches an assist base a caller might otherwise never learn exists, let alone delete. It returns the IDs of every backup point actually deleted, so a caller can record exactly what happened (k3ep's AUD-1 audit event) without a separate, racy list-then-delete round trip.
tags must be non-empty: see ErrEmptyTagFilter. This is a deliberate guard rail, not a limitation worked around elsewhere - there is no way to delete "everything" through this function, by design.
Example ¶
ExampleRepository_DeleteBackupPoints deletes the points matching a tag filter and returns the IDs it actually deleted, which is what k3ep records in its audit event (AUD-1).
The filter must be non-empty (engine.ErrEmptyTagFilter): there is no "delete everything" call. Matching is conjunctive and byte-exact, so include the tenant tag in every delete, not just the object tag.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// tenantTags are the tags k3ep puts on every backup point and uses to
// scope every later list, delete or search. The keys are namespaced:
// pkg/engine rejects the bare key "tenant" and any key starting with
// "sc-", because the fork's own garbage collector reads those to decide
// which assist bases survive. The values are k3ep's own IDs, generated
// server-side - never a string a tenant supplied.
func tenantTags() map[string]string {
return map[string]string{
"k3ep-tenant": "tenant-uuid",
"k3ep-policy": "policy-uuid",
"k3ep-object": "object-uuid",
}
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
deleted, err := repo.DeleteBackupPoints(ctx, map[string]string{
"k3ep-tenant": tenantTags()["k3ep-tenant"],
"k3ep-object": tenantTags()["k3ep-object"],
})
if err != nil {
fmt.Println("deleting backup points:", err)
return
}
fmt.Println("deleted", len(deleted), "backup point(s):", deleted)
}
Output:
func (*Repository) FindItemsByName ¶
func (r *Repository) FindItemsByName( ctx context.Context, req FindItemsRequest, ) (FindItemsResult, error)
FindItemsByName returns every item whose name matches req.Name, across every backup point carrying req.Tags (RES-2). It is name matching only: full-text search of message bodies or file contents is explicitly out of scope for v1, and this function could not do it anyway - it reads each point's details manifest and never opens stored item data.
req.Tags is how "within one object's backup points" is expressed, and is required (ErrEmptyTagFilter): k3ep passes its own object tag. The search covers only independently-restorable points unless AllowIncompletePoints is set; points it skips for that reason are skipped silently, since a find spans many points and one fragment among them is not a reason to fail the search.
A backup point whose details manifest cannot be read does NOT fail the call either. It is recorded in FindItemsResult.UnreadableBackupPointIDs and the search continues through the rest. Failing outright would have made one bad point enough to render an entire object unsearchable - including the ordinary, benign race where a point is deleted (by retention, or by a concurrent DeleteBackupPoints) between this call's own listing step and its read. A caller must check that field: a non-empty one means the result is partial. Only a failure of the listing step itself, which yields no points to search at all, returns an error.
Cost: this reads one details manifest per matching backup point, so it is linear in the number of points the tags select, not in the size of the repository. Scope the tags to one object.
Example ¶
ExampleRepository_FindItemsByName finds items by name across one object's backup points. It matches names only - never message bodies, file contents or attachments - against what the points' details manifests already recorded, so it decrypts nothing.
The result is a struct rather than a slice for one reason, and it is the reason this example exists: a search that could not read every matching point must say so. Ignore UnreadableBackupPointIDs and an incomplete search renders as a confident "nothing found", which is exactly the wrong answer when the question is whether an erasure actually took effect.
package main
import (
"context"
"fmt"
"sort"
"time"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// tenantTags are the tags k3ep puts on every backup point and uses to
// scope every later list, delete or search. The keys are namespaced:
// pkg/engine rejects the bare key "tenant" and any key starting with
// "sc-", because the fork's own garbage collector reads those to decide
// which assist bases survive. The values are k3ep's own IDs, generated
// server-side - never a string a tenant supplied.
func tenantTags() map[string]string {
return map[string]string{
"k3ep-tenant": "tenant-uuid",
"k3ep-policy": "policy-uuid",
"k3ep-object": "object-uuid",
}
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
res, err := repo.FindItemsByName(ctx, engine.FindItemsRequest{
// Required and non-empty (engine.ErrEmptyTagFilter), and scoped to
// one tenant and one object: the search reads one details manifest
// per matching point, so its cost is the number of points the tags
// select.
Tags: tenantTags(),
Name: "quarterly report",
Match: engine.NameMatchContains,
})
if err != nil {
fmt.Println("finding items:", err)
return
}
if len(res.UnreadableBackupPointIDs) > 0 {
// Surface this to the caller and to the audit record. The result
// is PARTIAL: these points matched the tags and were not searched.
sort.Strings(res.UnreadableBackupPointIDs)
fmt.Println("search incomplete; unsearched points:", res.UnreadableBackupPointIDs)
}
for _, f := range res.Items {
fmt.Println(
f.BackupPointID,
f.Item.ID,
f.Item.Name,
f.Item.FolderPath,
f.BackupPointType,
f.BackupPointIndependentlyRestorable,
f.BackupPointCreatedAt.Format(time.RFC3339))
}
}
Output:
func (*Repository) ID ¶
func (r *Repository) ID() string
ID returns the repository's own stable identifier. Never a secret: callers can log or store this freely.
func (*Repository) ListBackupPoints ¶
func (r *Repository) ListBackupPoints(ctx context.Context, tags map[string]string) ([]BackupPoint, error)
ListBackupPoints returns every backup point carrying all the key/value pairs in tags - a nil or empty tags returns every backup point in the repository, across every tenant if the repository ever holds more than one (see ErrEmptyTagFilter's and RepositoryConfig's doc comments: this package has no notion of "my" tenant, and tags are not an authorization boundary).
This includes every backup point that exists, regardless of the fork's own internal merge/assist/preview classification - deliberately, and unlike the fork's CLI, which has never displayed an assist base specifically (the only type pkg/repository's own BackupsByTag ever filtered; a preview base was never hidden by that method and so was always CLI-visible too - an earlier version of this comment claimed otherwise for preview, incorrectly). From this package's point of view a backup point is "real" the moment Backup's caller sees its tags (BackupPoint.Tags carries whatever the fork classified it as, in the "backup-type" key, same as any other tag), whether or not the fork's own base-selection logic later folds it into another backup: a recoverable error partway through a real backup is enough to leave one tagged assist, still genuinely yours, still genuinely occupying storage, and this method is how a caller finds out it is there. A future browse/restore chunk should keep this in mind: not every listed point is necessarily a complete, independently restorable backup the way a merge base is.
Example ¶
ExampleRepository_ListBackupPoints lists one tenant's backup points.
The tag filter is not optional in practice: ListBackupPoints(ctx, nil) enumerates every point in the repository, so a tenant-scoped filter, built from values k3ep generated server-side, is what makes the result one tenant's. The listing includes assist and preview points, which are real and occupy storage but are not restorable on their own - Type and IsIndependentlyRestorable are how a caller tells them apart.
package main
import (
"context"
"fmt"
"time"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// tenantTags are the tags k3ep puts on every backup point and uses to
// scope every later list, delete or search. The keys are namespaced:
// pkg/engine rejects the bare key "tenant" and any key starting with
// "sc-", because the fork's own garbage collector reads those to decide
// which assist bases survive. The values are k3ep's own IDs, generated
// server-side - never a string a tenant supplied.
func tenantTags() map[string]string {
return map[string]string{
"k3ep-tenant": "tenant-uuid",
"k3ep-policy": "policy-uuid",
"k3ep-object": "object-uuid",
}
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
points, err := repo.ListBackupPoints(ctx, map[string]string{
"k3ep-tenant": tenantTags()["k3ep-tenant"],
"k3ep-object": tenantTags()["k3ep-object"],
})
if err != nil {
fmt.Println("listing backup points:", err)
return
}
for _, p := range points {
if !p.Type.IsIndependentlyRestorable() {
// Show it (it is the tenant's data, and deletable), but never
// offer it as a point in time to restore from.
fmt.Println(p.ID, "incomplete:", p.Type)
continue
}
fmt.Println(p.ID, p.CreatedAt.Format(time.RFC3339), p.ItemsRead)
}
}
Output:
func (*Repository) ListFolders ¶
func (r *Repository) ListFolders(ctx context.Context, req FolderTreeRequest) (FolderTree, error)
ListFolders returns the folder tree a single backup point recorded: Exchange mail folders, calendars and contacts folders, OneDrive folders, and the folders inside SharePoint document libraries (RES-1). It reads only the point's own details manifest - the index the backup wrote describing what it captured - so it never fetches, decrypts or returns item content, and it makes no Microsoft Graph call at all: the object no longer has to exist in Microsoft 365 for its backup to be browsable.
The tree is exactly what the backup point recorded, not a tidied version of it. In particular:
- A folder only appears if the backup point recorded at least one item at or below it. The fork derives folder entries from item entries when it writes a backup, so a folder that was empty at backup time is not in the manifest and cannot be listed here.
- For OneDrive and SharePoint libraries the top of each drive's tree is the drive's own root element ("root:"), with the drive named in Folder.DriveName.
- A SharePoint document library is a drive, not a folder entry: it is identified by the DriveID/DriveName on the folders and items inside it, whose own top-level folder is the drive's "root:".
- A SharePoint list does get a container folder, but one named by the list's own Microsoft 365 ID rather than its title (see Folder.Name), holding exactly one item: the list itself, whose Name is the title and whose ItemCount is how many rows it holds.
Returns ErrIncompleteBackupPoint for a point that is not independently restorable unless the request opts in - read that error's doc comment before setting AllowIncompletePoint.
Example ¶
ExampleRepository_ListFolders browses one backup point's folder tree. It reads the point's own details manifest only: no Graph call, no item content fetched or decrypted, so a mailbox that no longer exists in Microsoft 365 is still browsable.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// tenantTags are the tags k3ep puts on every backup point and uses to
// scope every later list, delete or search. The keys are namespaced:
// pkg/engine rejects the bare key "tenant" and any key starting with
// "sc-", because the fork's own garbage collector reads those to decide
// which assist bases survive. The values are k3ep's own IDs, generated
// server-side - never a string a tenant supplied.
func tenantTags() map[string]string {
return map[string]string{
"k3ep-tenant": "tenant-uuid",
"k3ep-policy": "policy-uuid",
"k3ep-object": "object-uuid",
}
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
// A point ID is not self-authorising. Get it from a tenant-scoped
// ListBackupPoints call (or check it against k3ep's own records)
// before browsing it: ListFolders and ListItems take a bare ID and
// check no tags at all.
points, err := repo.ListBackupPoints(ctx, tenantTags())
if err != nil || len(points) == 0 {
fmt.Println("listing backup points:", err)
return
}
tree, err := repo.ListFolders(ctx, engine.FolderTreeRequest{
BackupPointID: points[0].ID,
// Left false, an assist or preview point is refused with
// engine.ErrIncompleteBackupPoint rather than returning a fragment
// of a tree that looks complete. Set it only where a partial tree
// is the point, such as enumerating an assist point for erasure,
// and then check tree.IndependentlyRestorable before presenting it.
AllowIncompletePoint: false,
})
if err != nil {
fmt.Println("listing folders:", err)
return
}
// Folders is flat and deterministically ordered. Build the hierarchy
// from ParentID ("" is top level), not from Path: Path is a display
// string joined with "/" and folder names may contain "/".
children := map[string][]engine.Folder{}
for _, f := range tree.Folders {
children[f.ParentID] = append(children[f.ParentID], f)
}
for _, f := range children[""] {
// Service and Category are load-bearing, not decoration: a mail
// folder, a calendar and a contacts folder all arrive as top-level
// Exchange folders with nothing but a display name to tell them
// apart, and two of them may share that name. A SharePoint list's
// container is named by the list's Microsoft 365 ID, not its
// title, so label a Category "lists" folder from the single item
// inside it instead.
fmt.Println(f.Name, f.Service, f.Category, f.DriveName, len(children[f.ID]))
}
}
Output:
func (*Repository) ListItems ¶
func (r *Repository) ListItems(ctx context.Context, req ItemsRequest) (ItemList, error)
ListItems returns the items one backup point recorded, each with a stable ID, a name, a size and its own creation and modification dates (RES-1). With req.FolderID set it returns the items directly inside that folder; with it empty, every item in the point.
Like ListFolders it reads only the point's details manifest: no item content is fetched or decrypted, and no Graph call is made. Metadata entries the fork stores alongside real items (OneDrive permission sidecars) are never returned - they are not items an admin backed up.
Returns ErrIncompleteBackupPoint for a point that is not independently restorable unless the request opts in, and ErrFolderNotFound for a FolderID the point does not contain.
Example ¶
ExampleRepository_ListItems lists the items in one folder of one backup point, each with the stable ID a later restore or erasure is handed.
The durable handle is the pair (backup point ID, item ID). An item ID is only meaningful inside the point it was listed from: for OneDrive and SharePoint the ID is derived from the folder chain's display names, so renaming or moving an ancestor folder changes every item ID beneath it in the next point; for Exchange the chain is container IDs, so a rename is safe but a move is not.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// tenantTags are the tags k3ep puts on every backup point and uses to
// scope every later list, delete or search. The keys are namespaced:
// pkg/engine rejects the bare key "tenant" and any key starting with
// "sc-", because the fork's own garbage collector reads those to decide
// which assist bases survive. The values are k3ep's own IDs, generated
// server-side - never a string a tenant supplied.
func tenantTags() map[string]string {
return map[string]string{
"k3ep-tenant": "tenant-uuid",
"k3ep-policy": "policy-uuid",
"k3ep-object": "object-uuid",
}
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
points, err := repo.ListBackupPoints(ctx, tenantTags())
if err != nil || len(points) == 0 {
fmt.Println("listing backup points:", err)
return
}
pointID := points[0].ID
list, err := repo.ListItems(ctx, engine.ItemsRequest{
BackupPointID: pointID,
// Empty FolderID returns every item in the point; a FolderID from
// another point is engine.ErrFolderNotFound, never silently empty.
FolderID: "",
})
if err != nil {
fmt.Println("listing items:", err)
return
}
for _, it := range list.Items {
// Store the pair, not it.ID alone.
handle := struct{ BackupPointID, ItemID string }{list.BackupPointID, it.ID}
// A SharePoint list is one item: its rows are not individually
// addressable, so ItemCount is all browse can say about what is
// inside it, and restore and erasure are list-granular in v1.
fmt.Println(handle, it.Name, it.SizeBytes, it.ItemCount, it.Service, it.Category)
}
}
Output:
func (*Repository) RunMaintenance ¶
func (r *Repository) RunMaintenance(ctx context.Context, opts MaintenanceOptions) error
RunMaintenance runs Kopia repository maintenance (garbage collection of unreferenced blobs, index compaction) and blocks until it finishes. The repository remains fully readable throughout and afterwards: maintenance never deletes a blob a current backup point still references.
Example ¶
ExampleRepository_RunMaintenance runs Kopia maintenance: garbage collection of unreferenced blobs and index compaction. It blocks until it finishes, and the repository stays readable throughout - maintenance never drops a blob a current backup point still references.
package main
import (
"context"
"fmt"
"github.com/twyouens/corso/src/pkg/account"
"github.com/twyouens/corso/src/pkg/control"
"github.com/twyouens/corso/src/pkg/credentials"
"github.com/twyouens/corso/src/pkg/engine"
"github.com/twyouens/corso/src/pkg/storage"
)
// The values below stand in for the ones k3ep derives server-side, for
// one tenant, before any engine call. They are function calls rather than
// string literals on purpose: a repository key or client secret in an
// example is the thing that gets copied into real code (chunk 0.6's
// review found exactly that in src/cmd/backupexample), and a storage
// location or credential that a tenant could influence is the whole of
// the trust-model warning in RepositoryConfig's own doc comment.
//
// Each returns an empty string here because these examples are compiled,
// never run.
func repositoryKeyFromKeyManager() string { return "" }
func storagePathForTenant() string { return "" }
func m365AppCredentials() (string, string, string) {
return "", "", ""
}
// exampleConfig builds the RepositoryConfig the examples below reuse.
// ExampleInitializeRepository shows the same thing in full, including the
// S3 variant.
func exampleConfig() engine.RepositoryConfig {
tenantID, clientID, clientSecret := m365AppCredentials()
acct, _ := account.NewAccount(
account.ProviderM365,
account.M365Config{
M365: credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
AzureTenantID: tenantID,
})
st, _ := storage.NewStorage(
storage.ProviderFilesystem,
&storage.FilesystemConfig{Path: storagePathForTenant()},
storage.CommonConfig{
Corso: credentials.Corso{CorsoPassphrase: repositoryKeyFromKeyManager()},
KopiaCfgDir: storagePathForTenant() + "/kopia-config",
})
return engine.RepositoryConfig{
Storage: st,
Account: acct,
Options: control.DefaultOptions(),
}
}
func main() {
ctx := context.Background()
repo, err := engine.OpenRepository(ctx, exampleConfig())
if err != nil {
fmt.Println("opening the repository:", err)
return
}
defer func() { _ = repo.Close(ctx) }()
// Metadata-only passes are cheap and can run often; a full pass
// (Metadata false) still has to run regularly for blobs to be
// reclaimed. Force skips the fork's "not too often" safety check and
// is for tests and deliberate off-schedule runs.
if err := repo.RunMaintenance(ctx, engine.MaintenanceOptions{
Metadata: true,
Force: false,
}); err != nil {
fmt.Println("running maintenance:", err)
return
}
fmt.Println("maintenance finished")
}
Output:
type RepositoryConfig ¶
type RepositoryConfig struct {
// Storage names the repository's storage destination - a mounted
// filesystem path or an S3-compatible bucket (for example MinIO) -
// built with storage.NewStorage. Its CommonConfig.CorsoPassphrase is
// the repository's own encryption key (ENC-1's tenant data key, in
// k3ep's terms): this package never generates, defaults or persists
// that value itself, and never logs, prints or returns it. Losing it
// means losing the repository; k3ep's own key management (wrapping it
// with a platform master key, ENC-1) happens entirely above this
// package.
//
// For S3-compatible storage, AccessKey and SecretKey are required:
// this package rejects an S3 Storage with either empty outright (see
// ErrMissingStorageCredentials) rather than letting Kopia fall
// through to the platform's own ambient AWS identity.
Storage storage.Storage
// Account carries the Microsoft 365 application credentials this
// repository's backups will use to call Graph. Required for both
// Initialize and Open - see their doc comments for why this package
// cannot make that optional - and for every call to (*Repository).Backup.
Account account.Account
// Options are passed straight through to the fork's operation layer
// (parallelism, delta page size, feature toggles). Pass
// control.DefaultOptions() for the fork's own defaults; this package
// supplies none of its own.
Options control.Options
}
RepositoryConfig is everything OpenRepository and InitializeRepository need. The caller supplies every field explicitly; this package never reads an environment variable, config file or flag to fill one in.
Trust model: this package trusts RepositoryConfig completely and enforces almost nothing about where Storage points or what Account authenticates as (beyond ErrMissingStorageCredentials below) - it cannot know, and does not try to guess, whether a given value is correct for the caller's own tenant. Concretely, and by review: this package gives a caller holding (or guessing) a storage location and key an existence-and-key oracle (its errors distinguish "wrong password" from "not initialized"), an arbitrary-write primitive at any filesystem path the caller can reach (InitializeRepository creates it, files included, if nothing is there yet), and an unvalidated outbound connection to any S3-compatible endpoint it is given, including an internal or loopback address, with the responder's own error body reflected back. None of that is a bug in this package to fix - it is the direct consequence of "the caller supplies everything" (REPO-3), which k3ep needs to open its own tenants' own repositories. It is k3ep's obligation, not this package's, to derive Storage's location and credentials and Account's identity entirely server-side, before a tenant-influenced value could ever reach this struct's fields.
Tags are not an authorization boundary either: a single Repository handle (and the storage location/key behind it) must hold exactly one tenant's data for tag-based filtering (BackupRequest.Tags, ListBackupPoints, DeleteBackupPoints) to be a meaningful boundary at all. This package enforces the matching logic correctly - see store.Tags and BackupOperation.AdditionalTags - but has no concept of "my tenant" to check tags against; that separation is k3ep's to keep by construction (one repository per tenant), not something a tag value can create on its own.
Never log, print or format a RepositoryConfig (or a Storage or Account value) with the standard library's default formatting: Storage and Account each carry a credential (the repository's own encryption key, and the Microsoft 365 application's client secret) in a map[string]string field with no special treatment from fmt. This type's String, GoString and LogValue methods (redact.go) exist exactly to make %v/%+v/%#v/%s and slog logging safe; nothing else here does. Separately, and by design of the fork underneath this package rather than anything pkg/engine adds: with no logger configured, the fork's own singleton logger writes info-level logs to the process user's home directory, and clues.Hide(...)-wrapped values (such as a tenant or resource owner ID this package's own ctx-building does not add, but the fork's lower layers do) go out in plaintext unless the caller's own logging setup configures PII hashing. This package cannot change that default without changing the CLI's own logging behavior, which is out of scope here; k3ep must configure its own logger and PII handling before relying on this package in a context subject to retention or access-control requirements.
func (RepositoryConfig) GoString ¶
func (cfg RepositoryConfig) GoString() string
GoString implements fmt.GoStringer, covering %#v specifically: fmt checks GoStringer separately from Stringer for that verb, so String above does not cover it on its own.
func (RepositoryConfig) LogValue ¶
func (cfg RepositoryConfig) LogValue() slog.Value
LogValue implements log/slog.LogValuer, so a RepositoryConfig passed to slog (slog.Any("config", cfg), or embedded in a struct some other value logged with slog) is redacted the same way String is, rather than slog's default reflection-based formatting walking into Storage.Config and Account.Config.
func (RepositoryConfig) MarshalJSON ¶
func (cfg RepositoryConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. encoding/json does not consult Stringer or LogValuer at all, so without this, json.Marshal(cfg) - or marshalling any struct that embeds or contains a RepositoryConfig field, such as a job payload persisted to a queue - would fall back to encoding Storage and Account as plain structs. As of this fix, Storage and Account (pkg/storage, pkg/account) each implement their own MarshalJSON too, so this override is defense in depth rather than the only thing standing between a RepositoryConfig and a leaked credential; it also exists so this type's JSON shape does not depend on whichever casing convention Storage's and Account's own exported field names happen to use.
func (RepositoryConfig) String ¶
func (cfg RepositoryConfig) String() string
String implements fmt.Stringer, covering the %v, %+v, %s and %q verbs: Go's fmt package prefers Stringer over its own default struct/map formatting for all of them. Without this, RepositoryConfig's embedded Storage.Config and Account.Config maps - which hold the repository's encryption key and the Microsoft 365 application's client secret respectively, as plain map[string]string entries with no special treatment from fmt - print in full under every one of those verbs. See RepositoryConfig's own doc comment.