engine

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 23 Imported by: ? modules, 0 packages

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

README

The k3ep library API: pkg/engine

This is the guide for someone writing k3ep against this fork. It covers what src/pkg/engine does, the exact calls to make, the eleven things about it that a reasonable developer would otherwise assume the opposite of, how to pin a release, and how to develop across both repositories with a Go workspace.

pkg/engine is the only package k3ep imports for backup work. Everything else in src/pkg is either a type pkg/engine needs as input (pkg/account, pkg/storage, pkg/credentials, pkg/control, pkg/selectors, pkg/logger) or the fork's older CLI-era surface. In particular pkg/repository is public but is not the k3ep entry point: it returns src/internal types from several of its methods, which a caller in another module cannot name, and it has none of pkg/engine's guard rails. Import pkg/engine.

  • Reference documentation: go doc github.com/twyouens/corso/src/pkg/engine (run cd src && GOWORK=off GO111MODULE=on go doc -all ./pkg/engine). Every type and field carries its own doc comment; this guide does not repeat them.
  • Compiled examples: src/pkg/engine/example_test.go. Every snippet below is copied from there, so the compiler keeps them honest.
  • A runnable, real end-to-end program: src/cmd/backupexample.

1. Pinning a release

The fork's module path is github.com/twyouens/corso/src and the module lives in the repository's src/ subdirectory, so its version tags carry a src/ prefix: the release this guide documents is the git tag

src/v0.1.0

which Go resolves as module version v0.1.0. A bare v0.1.0 tag would not be a version of this module at all — Go would ignore it. (The same rule gives go.uber.org/zap/exp its exp/v0.3.0 tags, if you want to see it in the wild.)

k3ep pins it with one command, run from the k3ep repository root:

go get github.com/twyouens/corso/src@v0.1.0

That records the pin in k3ep's go.mod (a require github.com/twyouens/corso/src v0.1.0 line) and its checksums in k3ep's go.sum. Those two files are the only place the engine version is recorded, and they are what CI builds from. Do not add a replace directive to k3ep's go.mod, and do not pin by commit pseudo-version: REPO-5 asks for a tagged release, and a replace or a local path would make k3ep's build depend on a working copy nobody else has.

Upgrading later is the same command with a later version. The fork is Apache 2.0 and the repository is public, so no GOPRIVATE or credential setup is needed.

Cutting a release (for whoever does the tagging)

Two different strings are involved, and conflating them is the one mistake that is expensive to undo:

Value
git tag that must exist src/v0.1.0
module version Go resolves it as v0.1.0
command a consumer runs go get github.com/twyouens/corso/src@v0.1.0

They differ because the module is defined in the repository's src/ subdirectory. Go's own module reference puts it plainly: the module subdirectory "also serves as a prefix for semantic version tags". A bare v0.1.0 tag is therefore not a version of github.com/twyouens/corso/src at all — Go ignores it, and go get …@v0.1.0 fails to resolve. (v0.1 is not a valid module version either: major, minor and patch are all required.)

The order matters, and so does the care:

  1. Merge the release's pull request and wait for CI to be green on main. The tag has to point at the released commit, so nothing is tagged before then.
  2. Tag that merge commit — src/v0.1.0 — and push the tag. A human does this; it is deliberately not an agent's job.
  3. Only then can k3ep run the go get line above.

A published module version is effectively impossible to withdraw. Once proxy.golang.org has served a version it keeps serving it — the mirror's own FAQ says it "aims to cache content in order to avoid breaking builds for people that depend on your package, so this bad release may still be available in the mirror even if it is not available at the origin" — and the checksum database has already recorded that version's hash, so re-pointing the tag at a different commit gives every later consumer a checksum mismatch rather than the new code. The supported remedy for a bad release is a retract directive plus a new version, never a deleted or moved tag. Which is why this step is done slowly.

2. Local development across both repositories (go.work)

A Go workspace lets a k3ep change and an engine change be developed together, without a replace directive and without pushing a tag for every experiment. From the workspace root that holds both checkouts:

go work init ./repos/corso/src ./repos/k3ep

which writes a go.work like:

go 1.27.2

use (
	./repos/corso/src
	./repos/k3ep
)

While that file is in scope, a build of k3ep uses the local fork checkout instead of the pinned module version, so an engine change is visible to k3ep immediately. go.work and go.work.sum are developer-local: they are not committed to either repository.

Pull requests must build without the workspace. A change that only compiles because of go.work is a change that breaks CI and breaks anyone else's clone, so before opening a pull request in either repository, run the build and tests with the workspace switched off:

GOWORK=off go build ./... && GOWORK=off go test ./...

In this fork those commands run from src/ (there is no go.mod at the repository root). Two local notes worth knowing:

  • On a machine whose global Go configuration sets GO111MODULE=off, add GO111MODULE=on to every command above, or module resolution silently falls back to GOPATH mode and every import fails to resolve. Several agents have lost an hour to this.
  • The fork's own make check (cd src && make check) is what CI runs: build, lint, staticcheck and unit tests, all with GOWORK=off.

3. The six capability areas

3.1 Opening a repository

Every setting comes from the caller. The pkg/engine package itself reads no environment variable, no configuration file and no flag, so there is nothing ambient to configure and nothing to get right by accident. The one exception is transitive and is the fork's logger, not this package: see §4.11.

acct, err := account.NewAccount(
	account.ProviderM365,
	account.M365Config{
		M365:          credentials.M365{AzureClientID: clientID, AzureClientSecret: clientSecret},
		AzureTenantID: tenantID,
	})

st, err := storage.NewStorage(
	storage.ProviderFilesystem,
	&storage.FilesystemConfig{Path: repoPath},
	storage.CommonConfig{
		Corso:       credentials.Corso{CorsoPassphrase: repositoryKey},
		KopiaCfgDir: repoPath + "/kopia-config",
	})

cfg := engine.RepositoryConfig{Storage: st, Account: acct, Options: control.DefaultOptions()}

repo, err := engine.InitializeRepository(ctx, cfg) // first use
repo, err := engine.OpenRepository(ctx, cfg)       // every later use
defer repo.Close(ctx)

For S3-compatible storage (including MinIO), swap the storage arguments:

st, err := storage.NewStorage(
	storage.ProviderS3,
	&storage.S3Config{
		AWS:      credentials.AWS{AccessKey: accessKey, SecretKey: secretKey},
		Bucket:   bucket,
		Endpoint: endpoint, // empty means AWS itself
		Prefix:   prefix,
	},
	storage.CommonConfig{Corso: credentials.Corso{CorsoPassphrase: repositoryKey}})

Notes that matter in production:

  • CorsoPassphrase is the repository's encryption key — ENC-1's tenant data key. The engine never generates, defaults or persists it. Lose it and the repository is unreadable.
  • Account is required even for a storage-only operation: the fork ties a repository's lifecycle to a verified Microsoft 365 connection and fetches a real access token while opening. That matches k3ep's model (one repository per tenant connection), so pkg/engine does not route around it.
  • InitializeRepository against a location that already holds a repository, with the same key, reconnects and returns the same repository rather than failing. engine.ErrRepositoryExists means the repository exists and the connection then failed — in practice, a wrong key.
  • Close releases the handle and leaves the stored data alone.

See ExampleInitializeRepository and ExampleOpenRepository.

3.2 Backing up, with caller tags and a progress callback
sel := selectors.NewExchangeBackup([]string{userID})
sel.Include(sel.MailFolders(selectors.Any(), selectors.PrefixMatch()))
sel.DiscreteOwner = userID

point, err := repo.Backup(ctx, engine.BackupRequest{
	Selector: sel.Selector,
	Tags: map[string]string{
		"k3ep-tenant": tenantID,
		"k3ep-policy": policyID,
		"k3ep-object": objectID,
	},
	Progress: func(p engine.ProgressSnapshot) {
		// p.Counts is a map[string]int64 of real, server-confirmed counters.
		// p.Done is true on exactly one call: the last.
	},
})
  • The callback runs on a goroutine Backup owns and joins before returning, so no call arrives after Backup returns. Calls are never concurrent with each other. Nothing in pkg/engine writes to stdout; this callback is the only progress channel there is.

  • Counts keys vary by workload and are not guaranteed stable across engine versions. Treat an absent key as 0, never as an error. No count carries an item name, subject or content.

  • Tags are validated before any upload starts: reserved key (ErrReservedTagKey), reserved prefix (ErrReservedTagPrefix), more than 32 tags (ErrTooManyTags), a key over 256 bytes or value over 1024 bytes (ErrTagTooLarge), or more than 4096 bytes of keys and values combined (ErrTagsTooLarge). k3ep's real tags are nowhere near those bounds.

  • BackupPoint reports ID, Type, Tags, CreatedAt, ItemsRead, BytesUploaded and ErrorCount.

  • control.Options.FailureHandling decides what a recovered error does, and k3ep has to choose. It is a control.FailurePolicy on the Options passed in RepositoryConfig, and control.DefaultOptions() sets control.FailAfterRecovery:

    Policy A recoverable error (one throttled item, say) means
    control.FailAfterRecovery (the default) Backup returns an error and no BackupPoint — and an assist point carrying your tags has still been persisted, holding what did upload (§4.3)
    control.BestEffort Backup succeeds, returning a merge point with a non-zero ErrorCount: the point is independently restorable, and incomplete
    control.FailFast the run stops at the first failure

    So ErrorCount == 0 is not a completeness guarantee under BestEffort, and a returned error is not evidence that nothing was written under the default. The classification is the fork's isAssistBackup/isMergeBackup, which both branch on this policy.

  • A Backup call that returns an error may still have left a real backup point behind — see contract item 3 below. Record the tags you asked for, so you can find it.

See ExampleRepository_Backup, and src/cmd/backupexample for a version that really runs.

3.3 Listing and deleting backup points by tag
points, err := repo.ListBackupPoints(ctx, map[string]string{
	"k3ep-tenant": tenantID,
	"k3ep-object": objectID,
})

deleted, err := repo.DeleteBackupPoints(ctx, map[string]string{
	"k3ep-tenant": tenantID,
	"k3ep-object": objectID,
})
  • Matching is conjunctive, byte-exact and case-sensitive: a point matches only if it carries every key/value pair supplied. It was attacked with NUL bytes, newlines, embedded JSON and homoglyph values in review and held.
  • DeleteBackupPoints requires a non-empty filter (ErrEmptyTagFilter): there is no "delete everything" call, by design. It returns the IDs it actually deleted — use those for the audit event (AUD-1) rather than a separate, racy list-then-delete.
  • ListBackupPoints accepts an empty filter, and that is the dangerous case: see contract items 1 and 3.

See ExampleRepository_ListBackupPoints and ExampleRepository_DeleteBackupPoints.

3.4 Browsing a backup point's folder tree
tree, err := repo.ListFolders(ctx, engine.FolderTreeRequest{
	BackupPointID: pointID,
	// AllowIncompletePoint: false -> ErrIncompleteBackupPoint for an
	// assist, preview or unclassified point.
})

children := map[string][]engine.Folder{}
for _, f := range tree.Folders {
	children[f.ParentID] = append(children[f.ParentID], f)
}
  • Reads only the point's own details manifest: no Graph call, no item content fetched or decrypted. A mailbox that no longer exists in Microsoft 365 is still browsable.
  • Folders is flat and deterministically ordered by (Path, ID). Reconstruct the hierarchy from ParentID ("" means top level), not from Path: Path is a display string joined with / and a folder name may itself contain /.
  • Service and Category are load-bearing, not decoration. Exchange location prefixes are stripped, so a mail folder, a calendar and a contacts folder all arrive as top-level folders with nothing but a display name to tell them apart — and two of them may legitimately share that name.
  • A folder appears only if the point recorded at least one item at or below it: a folder that was empty at backup time is not in the manifest.
  • A OneDrive drive and a SharePoint document library are drives, not folder entries: each appears as a folder literally named root:, with the library's human name on DriveName.
  • A SharePoint list does get a container folder, named by the list's Microsoft 365 ID rather than its title — see contract item 10.
  • Folder.SizeBytes is a roll-up of everything at or below the folder, as the backup recorded it. It is 0 for item kinds that carry no size (Exchange calendars and contacts routinely), and for a folder of Teams chats it disagrees with the items beneath it, because the fork's roll-up counts a chat's messages rather than its bytes. Teams chats are outside k3ep's v1 workloads.

See ExampleRepository_ListFolders.

3.5 Listing the items in a folder
list, err := repo.ListItems(ctx, engine.ItemsRequest{
	BackupPointID: pointID,
	FolderID:      folderID, // empty: every item in the whole point
})
  • Same reads as ListFolders: manifest only, no Graph, no content.
  • A FolderID the point does not contain is ErrFolderNotFound, never a silently empty list. Folder IDs are only valid within the point they were listed from.
  • Item.Name is the real display name — subject, filename, contact name, list title. Names belong in returned data: this code never puts one in an error or a log line, and k3ep should hold the same line.
  • Item.SizeBytes, CreatedAt and ModifiedAt are what the backup recorded. A zero date means "not recorded" (normal for Exchange calendars and contacts folders), not an error.
  • OneDrive permission sidecars and other metadata entries the fork stores alongside real items are never returned.
  • Store (BackupPointID, Item.ID) as the handle, never Item.ID alone — contract item 4.

See ExampleRepository_ListItems.

3.6 Finding items by name
res, err := repo.FindItemsByName(ctx, engine.FindItemsRequest{
	Tags:  map[string]string{"k3ep-tenant": tenantID, "k3ep-object": objectID},
	Name:  query,
	Match: engine.NameMatchContains, // zero value; NameMatchExact for whole-name
})

if len(res.UnreadableBackupPointIDs) > 0 {
	// The result is PARTIAL. Say so.
}
  • Searches names only — never message bodies, file contents or attachments. It reads the points' details manifests and decrypts nothing. Full-text search is out of scope for v1 and this call could not do it.
  • Tags is required and non-empty (ErrEmptyTagFilter), and Name is required (ErrEmptyNameQuery). An empty query never means "every item": call ListItems with no FolderID for that, so the intent is visible at the call site.
  • Matching is case-insensitive by simple Unicode lower-casing, not locale-aware collation.
  • By default only independently-restorable points are searched; points skipped for that reason are skipped silently, since one fragment among many points is not a reason to fail a search. AllowIncompletePoints includes them, and each result says which point it came from and what type that point is.
  • UnreadableBackupPointIDs must be surfaced — contract item 5.
  • Cost: one details manifest read per matching point. Scope the tags to one object; this is not a search box over a repository.

See ExampleRepository_FindItemsByName.

3.7 Maintenance
err := repo.RunMaintenance(ctx, engine.MaintenanceOptions{
	Metadata: true,  // cheap, metadata-only pass
	Force:    false, // skip the "not too often" safety check
})

Kopia garbage collection 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. Metadata-only passes are cheap and can run often; a full pass (Metadata: false) still has to run regularly for unreferenced blobs to actually be reclaimed.

See ExampleRepository_RunMaintenance.

3.8 The whole surface, at a glance

Types (go doc has the per-field detail):

Type What it is
Repository an open handle; InitializeRepository/OpenRepository return one, Close releases it
RepositoryConfig storage, account and control.Options; everything the caller supplies
BackupRequest, BackupPoint one backup's inputs and its result
BackupPointType merge, assist, preview, unknown; IsIndependentlyRestorable()
ProgressFunc, ProgressSnapshot the progress callback and the counters it receives
MaintenanceOptions Metadata and Force for RunMaintenance
FolderTreeRequest, FolderTree, Folder browsing one point's folder tree
ItemsRequest, ItemList, Item listing the items in a folder or a whole point
FindItemsRequest, FindItemsResult, FoundItem searching names across a tag-scoped set of points
NameMatch NameMatchContains (the zero value) or NameMatchExact

Errors, all matchable with errors.Is:

Error Returned when
ErrRepositoryExists InitializeRepository found a repository and then failed to connect to it — in practice a wrong key
ErrMissingStorageCredentials an S3 configuration with a blank or whitespace-only access or secret key
ErrReservedTagKey, ErrReservedTagPrefix a backup tag key the engine reserves (§4.2)
ErrTooManyTags, ErrTagTooLarge, ErrTagsTooLarge tag count, per-tag size, or total size over the bounds in §3.2
ErrEmptyTagFilter DeleteBackupPoints or FindItemsByName with no tags
ErrEmptyNameQuery FindItemsByName with an empty Name
ErrMissingBackupPointID ListFolders or ListItems with no backup point ID; an empty ID never means "the latest point"
ErrBackupPointNotFound no point in this repository has that ID
ErrIncompleteBackupPoint the point is not independently restorable and the request did not set AllowIncompletePoint
ErrFolderNotFound that folder ID is not in that backup point

4. The operational contract

Eleven things this library does that are not what you would guess. Each one cost a review round, or an adversarial attack, to establish. They are the reason this document exists.

4.1 Tags are a label, not an authorisation boundary

One repository must hold exactly one tenant. The engine has no concept of "my tenant": it stores and filters tags, and never interprets them. Tenant separation is the storage location and the encryption key, not the tags on the points inside.

ListBackupPoints(ctx, nil) — or with an empty map — returns every backup point in the repository. That is deliberate (it is how a caller discovers what exists at all) and it is the one call in the package with no tag-filter guard.

What k3ep must do:

  • One repository per tenant, always.
  • Generate every tag value server-side, from k3ep's own records. Never put a tenant-supplied string into a tag value or a filter.
  • Pass a tenant-scoped filter on every ListBackupPoints, DeleteBackupPoints and FindItemsByName call. Treat an unfiltered list as an administrative, platform-level operation, not a tenant-facing one.
  • ListFolders and ListItems take a bare backup point ID and check no tags at all. A point ID is not self-authorising; holding one is not evidence of being entitled to read it. Establish that the point belongs to the requesting tenant — by listing it through that tenant's filter, or against k3ep's own records — before passing an ID in.
4.2 Tag keys are namespaced, and some keys are refused

k3ep's tag keys are k3ep-tenant, k3ep-policy and k3ep-object. The namespacing is not style. These keys are rejected outright, before any backup work starts:

Rejected Why
tenant the fork's backup garbage collector reads it to decide which assist bases survive collection
any key starting with sc- same garbage collector, for service/category
service, backup-type drive the fork's merge/assist/preview base selection for every backup in the repository
type, stableID, storeVersion Kopia's own model store rejects them — but only after a backup has uploaded a snapshot, orphaning it until a full maintenance pass collects it

A caller tag on a reserved key would let the caller silently influence which of its own content a later maintenance run keeps, which would make the engine's "it never interprets tags" promise false. So the engine refuses up front with ErrReservedTagKey or ErrReservedTagPrefix rather than letting a backup run and then disappear.

Note the mismatch with the PRD and plan, which say "tenant, policy and object": the keys on the wire are the namespaced ones.

4.3 ListBackupPoints returns assist and preview points, and only merge points are restorable

The listing is deliberately everything, not just complete backups. A single recoverable error partway through a real backup — one throttled item — is enough to persist an assist point carrying your tags and occupying real storage, while Backup itself returns an error and no point. That is the behaviour of the default control.FailAfterRecovery policy; under control.BestEffort the same backup returns a merge point with a non-zero ErrorCount instead, and no assist point is created. §3.2 has the table. Hiding such points once made a tenant's own data undeletable; that was a HIGH finding, and this is the fix.

So: BackupPoint.Type is one of engine.BackupPointTypeMerge, engine.BackupPointTypeAssist, engine.BackupPointTypePreview or engine.BackupPointTypeUnknown, and BackupPointType.IsIndependentlyRestorable() is true for merge only — including for any future type the engine has not defined yet, which is conservatively not restorable. An unversioned, untagged model classifies as unknown, deliberately: a genuinely pre-v8 backup with no tag defaults to merge, but a model whose version was never set is not trusted.

What k3ep must do:

  • Never present a non-merge point as a point in time to restore from. Check IsIndependentlyRestorable(), not a type string comparison of your own.
  • Do list and delete them: they are the tenant's data and they occupy storage. A retention or erasure job that filters them out leaves data behind permanently.
  • ListFolders and ListItems refuse them by default with ErrIncompleteBackupPoint. AllowIncompletePoint exists because erasure needs to enumerate an assist point's items in order to name them; when it is set, check FolderTree.IndependentlyRestorable before showing the tree to anyone.
4.4 The durable item handle is (BackupPointID, Item.ID)

Item.ID alone is not an identity for "this item". It is derived at backup time from the item's storage path and stored in that point's manifest, which means:

  • OneDrive and SharePoint: the path is built from the folder chain's display names. Renaming or moving any ancestor folder gives the same file a different ID in the next backup point.
  • Exchange: the path elements are container IDs, so renaming a mail folder, calendar or contacts folder is safe — but moving one is not, because its parent chain changes.

A backup point is immutable, so an ID listed from a point keeps identifying that item in that point forever. What changes is whether the same ID means anything in a different point.

What k3ep must do: store the pair. Never use Item.ID as a primary key for an item across points, never resolve an ID against a point it was not listed from, and expect "the same file" to have different IDs in successive points after a rename. Folder IDs behave the same way (ListItems returns ErrFolderNotFound for a folder ID from another point).

Related ceiling, inherited from the fork rather than introduced here: these IDs are sha256 over the concatenated path elements truncated to 12 hex characters (48 bits), with no separator between elements. Collisions are theoretically reachable. Anything that deletes by ID should decide whether 48 bits is enough for it.

4.5 FindItemsResult.UnreadableBackupPointIDs must be surfaced

FindItemsByName does not fail when a matching point cannot be read — a point deleted by retention between the listing step and the read, a damaged manifest, unreachable storage. It searches the rest and names the ones it skipped.

That means an incomplete search returns successfully. A UI that ignores the field shows a confident, empty, wrong answer, in exactly the situation where a wrong answer costs most: verifying that an erasure actually took effect, or answering a legal-hold question.

What k3ep must do: treat a non-empty UnreadableBackupPointIDs as a partial result everywhere it appears — in the API response, in the UI, and in the audit record. The IDs are safe to log and are what an operator needs to retry or report the gap. res.Items holds every match from the points that were readable; that is still useful, as long as nobody mistakes it for the whole answer.

4.6 Opening a repository installs a process-global Graph concurrency clamp

InitializeRepository and OpenRepository call the fork's graph.InitializeConcurrencyLimiter, which is a sync.Once. Measured consequences:

  • The limiter is one process-global semaphore, shared by every Microsoft 365 service, every tenant and every concurrent backup in the process. It is not per client, per tenant or per call.
  • Its width comes from RepositoryConfig.Options.Parallelism.ItemFetch, clamped to 1–4 in-flight requests: a value below 1 or above 4 becomes 4, and control.DefaultOptions() is 4.
  • The first repository opened in the process latches it for the process's lifetime — including an open that then fails Microsoft 365 authentication entirely. Later opens with different options change nothing.
  • The cost is real, not theoretical: 24 concurrent Graph calls took ~400 ms with the limiter off, ~745 ms clamped to 4, ~1.647 s clamped to 1.

The engine takes this on deliberately, because the alternative was worse: the fork's own code disables the limiter entirely for a non-Exchange service, and whichever call wins the sync.Once decides for everything afterwards. If anything in the process calls api.InitConcurrencyLimit for a non-Exchange service first, every Graph client in that process ends up with no limiter at all.

What k3ep must do: assume one worker process shares one clamp of at most four in-flight Graph requests across all of its tenants, and size workers by process rather than by goroutine until a per-client limiter lands (a separate, approved chunk). Do not expect Options.Parallelism on a later OpenRepository to widen it.

4.7 S3 requires explicit credentials; there is no fallback path

AccessKey and SecretKey are required for every S3 configuration, for every caller in this fork, with no opt-out anywhere — no flag, no config-map key, no field. A blank or whitespace-only credential is rejected before any network call, with engine.ErrMissingStorageCredentials from pkg/engine and a pkg/storage validation error from everything else.

There is no ambient path: no EC2/ECS instance role via IMDS, no shared credentials file, no AWS_PROFILE, no SSO, no web identity. Environment variables work in the CLI only because the CLI reads AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY itself and the values are then validated. No code path in pkg/engine reads either variable, or any other credential from the environment (the fork's logger does read the environment for its own file location — §4.11).

This was not a precaution. Kopia's S3 blob store falls through its AWS SDK's own credential chain for any credential left blank, and a review proved it live: a caller-chosen bucket, prefix and endpoint served by the platform's identity, 13 requests signed with a credential the caller never supplied.

What k3ep must do: always pass real, server-derived credentials. If a credential is missing, fail the operation — the engine has already failed it for you.

4.8 RepositoryConfig must never be logged or serialised casually

RepositoryConfig embeds storage.Storage and account.Account, each of which carries a credential — the repository's encryption key and the Microsoft 365 client secret — in a plain exported map[string]string.

Redaction is per-encoder, and only these encoders are covered. Measured from outside the module, against a config carrying a marked fake key and secret:

Encoder Result
fmt %v, %+v, %#v, %s redacted (String, GoString)
encoding/json, directly or embedded in another struct redacted (MarshalJSON)
log/slog redacted (LogValue)
zap, clues redacted (they route through Stringer/LogValuer)
gopkg.in/yaml.v3, directly or embedded leaks the key and the secret
encoding/gob leaks the key and the secret

YAML and gob walk the exported maps and consult none of those methods. Nothing in the fork marshals either, so this is k3ep's constraint to keep.

What k3ep must do: persist an opaque reference, not the config. Store a storage-destination record plus a key reference, and rebuild the RepositoryConfig from the key manager at the moment of use — which is what ENC-1 implies anyway. This matters most where a config might get swept into a job payload: k3ep's job queue persists payloads to Postgres. If something must be serialised, JSON only, never YAML, never gob, and never a format added later without re-running this check.

Two related defaults, inherited from the fork rather than added by pkg/engine:

  • With no logger configured, the fork's own singleton logger writes info-level logs to a file under the process user's log directory, and its PII handling defaults to plaintext, so clues.Hide(...)-wrapped values (tenant and resource owner IDs the fork's lower layers add) go out in the clear.

  • Configure logging before the first engine call and pass the returned context in:

    ctx, _ = logger.Seed(ctx, logger.Settings{
    	File:        logger.Stderr,
    	Format:      logger.LFJSON,
    	Level:       logger.LLInfo,
    	PIIHandling: logger.PIIHash,
    })
    
4.9 k3ep must derive storage location and credentials server-side

The engine trusts RepositoryConfig completely. It cannot know whether a value is correct for the caller's tenant, and it does not guess. Stated plainly, by review, this is what the struct hands whoever fills it in:

  • a repository-existence and key-validity oracle — its errors distinguish "wrong key" from "not initialised";
  • an arbitrary-write primitive at any filesystem path the process can reach: InitializeRepository creates the repository, files and all, if nothing is there yet;
  • an unvalidated outbound connection to any S3-compatible endpoint it is given, including an internal, loopback or link-local address, with the responder's own error body reflected back to the caller.

None of that is a defect in the engine to fix: it is the direct consequence of "the caller supplies everything" (REPO-3), which k3ep needs in order to open its own tenants' repositories.

What k3ep must do: derive every part of Storage and Account server-side — provider, path or bucket, endpoint, prefix, credentials, key, tenant ID — from its own records, and let no tenant-supplied value reach any of those fields, not even indirectly as a path or prefix fragment. If a deployment ever needs operator-configurable endpoints, allowlist them (and block loopback and link-local) on k3ep's side; the engine will not. Two further enforcement measures belong to k3ep rather than here: a CI check forbidding pkg/repository imports, and a configured logger with PII hashing.

4.10 A SharePoint list is one item

The fork records a whole SharePoint list as a single backed-up item carrying the list's name, dates and the number of rows it held (Item.ItemCount). Rows are not individually browsable and not individually addressable: the list is the unit that is listed, restored and erased. Browse, restore and erasure are therefore list-granular for lists in v1 — a decided scope change, with a spike to follow before restore is built, not an oversight.

A list's container folder is named by the list's Microsoft 365 ID, not its title (Category is "lists"). A naive tree UI shows a GUID.

What k3ep must do: label a "lists" container from the single item inside it, not from the folder's name; show ItemCount so an admin can recognise the list; and do not offer row-level selection for lists. Mail, calendar, contacts, OneDrive and document libraries are unaffected — this is SharePoint lists only.

4.11 The engine reads nothing ambient — except the logger it inherits

Everything the engine itself needs comes from the caller: storage destination, credentials, the repository key, Microsoft 365 application credentials, tags, parallelism and the progress callback. pkg/engine's own source contains no os.Getenv, no configuration-file read and no flag registration, and it never writes to stdout.

One thing underneath it is environment-derived, and it is the logger. On a context that has not been seeded with a logger, the fork's lower layers call logger.Ctx, which falls through to a process-wide singleton built from Settings{}.EnsureDefaults() — and that path reads the environment and touches the filesystem (pkg/logger/logger.go):

  • GetLogFile("") reads CORSO_LOG_FILE;
  • failing that, defaultLogLocation() builds a path under a per-user log directory taken from $HOME (macOS: $HOME/Library/Logs), $LOCALAPPDATA (Windows) or $XDG_CACHE_HOME, falling back to $HOME/.cache (other Unix);
  • and GetLogFile then creates that directory with os.MkdirAll, so a first engine call on an unseeded context writes a log file into the process user's home directory;
  • PIIHandling defaults to PIIPlainText, so clues.Hide(...) values go out in the clear (§4.8).

So the precise claim is: the engine reads nothing ambient, but a process using it without configuring logging does. Seed a logger before the first engine call (§4.8 has the call) and all four of those go away: the context carries your logger, your destination, your format and your PII handling.

The rest of the obligation is the mirror image of the upside: there is no ambient state to misconfigure and nothing environment-dependent to reproduce, but if k3ep does not supply a value, no default rescues it.


5. What v0.1 deliberately does not do

  • No restore and no export. pkg/engine reads backup metadata and nothing else. The fork's older pkg/repository can restore, but it is not the k3ep API and returns internal types; k3ep's restore arrives as its own chunk, behind pkg/engine.
  • No item-level erasure or snapshot rewriting. Deleting a whole backup point by tag is all that exists today.
  • No row-level SharePoint list handling (item 10).
  • No full-text search. Names only, and nothing in the browse API opens item content.
  • No scheduling, no retention policy, no catalogue, no multi-tenancy. The engine has no notion of a tenant, a policy, a schedule or a database. Tags are strings it stores for you.
  • No per-client Graph concurrency control (item 6).
  • No ambient credential discovery of any kind (items 7 and 11).
  • No S3 AssumeRole, and S3 TLS handshakes use Go's default 10-second timeout rather than the 60 seconds Alcion's Kopia fork used to force; current upstream Kopia offers no injection point for it.
  • No usage telemetry. It was removed outright; there is nothing to opt out of.

6. Verifying the surface yourself

Go's own rule — a module may not import another module's internal packages — is what REPO-2 actually rests on, and it only fires across module boundaries. The fork's in-repo checks (src/cmd/backupexample/import_test.go, src/pkg/engine/exported_api_test.go) are syntactic and complementary; the compiler is the authority. To reproduce that authority against this release, build a throwaway module outside the fork:

mkdir /tmp/enginecheck && cd /tmp/enginecheck
cat > go.mod <<'EOF'
module enginecheck

go 1.27

require github.com/twyouens/corso/src v0.1.0
EOF
cat > main.go <<'EOF'
package main

import (
	"context"
	"fmt"

	"github.com/twyouens/corso/src/pkg/engine"
)

func main() {
	var (
		open  func(context.Context, engine.RepositoryConfig) (*engine.Repository, error) = engine.OpenRepository
		find  func(context.Context, engine.FindItemsRequest) (engine.FindItemsResult, error)
		merge engine.BackupPointType = engine.BackupPointTypeMerge
	)

	fmt.Println(open != nil, find == nil, merge.IsIndependentlyRestorable())
}
EOF
GOWORK=off GO111MODULE=on go mod tidy && GOWORK=off GO111MODULE=on go build ./...

Declaring each symbol with its type written out — rather than letting := infer it — is the point: inference is the "escape hatch" that lets a caller use a value of an unnameable type without ever importing it, so a documented signature is only really proven by naming it.

Then prove the other half, that the boundary holds:

cat > internal_probe.go <<'EOF'
package main

import _ "github.com/twyouens/corso/src/internal/model"
EOF
GOWORK=off GO111MODULE=on go build ./...   # must fail

It fails with use of internal package github.com/twyouens/corso/src/internal/model not allowed.

Chunk 0.8 ran exactly this against the release candidate, naming every exported symbol in pkg/engine — all 13 error values, both constructors, all nine *Repository methods, every exported type with each of its documented fields read through a named type, BackupPointType.IsIndependentlyRestorable and RepositoryConfig's four redaction methods — plus a deliberately wrong symbol as a negative control, to prove the build would have noticed. The surface compiled, the wrong symbol failed, and both internal imports were refused.

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

Examples

Constants

This section is empty.

Variables

View Source
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.

View Source
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.)

View Source
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.

View Source
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).

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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())
}

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())
}

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

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

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

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

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]))
	}
}

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

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")
}

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.

Jump to

Keyboard shortcuts

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