Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7713d071c2 | |||
| de5759ac77 | |||
| b9b9082008 | |||
| bd54491c1d | |||
| 57d252cee4 | |||
| 78030230c5 | |||
| adfb087037 | |||
| 5570f82eb4 | |||
| bffe7bde12 | |||
| 3e0aabef4a | |||
| 4ec71eae00 | |||
| d2161fdadc | |||
| cefa9b7970 | |||
| e37e788885 | |||
| 2ff9fe2f50 | |||
| 60c0c50acb | |||
| d4d1d316db | |||
| 589f76c10e | |||
| 7797de7d48 | |||
| c8281398d1 | |||
| 3cac9a3530 | |||
| 490db0599c | |||
| 5529fff649 | |||
| 3fabd86150 | |||
| c00d9c65c3 | |||
| d2bba75365 | |||
| 0cf81ab6a1 | |||
| 1eb801fe63 |
@@ -8,6 +8,11 @@ linters:
|
|||||||
- unused
|
- unused
|
||||||
- errorlint
|
- errorlint
|
||||||
- staticcheck
|
- staticcheck
|
||||||
|
- copyloopvar
|
||||||
|
- durationcheck
|
||||||
|
- makezero
|
||||||
|
- nilerr
|
||||||
|
- bodyclose
|
||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
errcheck:
|
errcheck:
|
||||||
|
|||||||
138
ARCHITECTURE.md
138
ARCHITECTURE.md
@@ -123,11 +123,14 @@ All commands operate on a repository directory (default: `~/.sgard`, override wi
|
|||||||
| `sgard restore [<path>...] [--force]` | Restore files from manifest to their original locations |
|
| `sgard restore [<path>...] [--force]` | Restore files from manifest to their original locations |
|
||||||
| `sgard status` | Compare current files against manifest: modified, missing, ok |
|
| `sgard status` | Compare current files against manifest: modified, missing, ok |
|
||||||
| `sgard verify` | Check all blobs against manifest hashes (integrity check) |
|
| `sgard verify` | Check all blobs against manifest hashes (integrity check) |
|
||||||
|
| `sgard info <path>` | Show detailed information about a tracked file |
|
||||||
| `sgard list` | List all tracked files |
|
| `sgard list` | List all tracked files |
|
||||||
| `sgard diff <path>` | Show content diff between current file and stored blob |
|
| `sgard diff <path>` | Show content diff between current file and stored blob |
|
||||||
| `sgard prune` | Remove orphaned blobs not referenced by the manifest |
|
| `sgard prune` | Remove orphaned blobs not referenced by the manifest |
|
||||||
| `sgard mirror up <path>...` | Sync filesystem → manifest (add new, remove deleted, rehash) |
|
| `sgard mirror up <path>...` | Sync filesystem → manifest (add new, remove deleted, rehash) |
|
||||||
| `sgard mirror down <path>... [--force]` | Sync manifest → filesystem (restore + delete untracked) |
|
| `sgard mirror down <path>... [--force]` | Sync manifest → filesystem (restore + delete untracked) |
|
||||||
|
| `sgard exclude <path>... [--list]` | Exclude paths from tracking; `--list` shows current exclusions |
|
||||||
|
| `sgard include <path>...` | Remove paths from the exclusion list |
|
||||||
|
|
||||||
**Workflow example:**
|
**Workflow example:**
|
||||||
|
|
||||||
@@ -563,7 +566,103 @@ new machine, the user runs `sgard encrypt add-fido2` which:
|
|||||||
On next push, the new slot propagates to the server and other machines.
|
On next push, the new slot propagates to the server and other machines.
|
||||||
Each machine accumulates its own FIDO2 slot over time.
|
Each machine accumulates its own FIDO2 slot over time.
|
||||||
|
|
||||||
### Future: Manifest Signing
|
### TLS Transport
|
||||||
|
|
||||||
|
sgardd supports optional TLS via `--tls-cert` and `--tls-key` flags.
|
||||||
|
When provided, the server uses `credentials.NewTLS()` with a minimum
|
||||||
|
of TLS 1.2. Without them, it runs insecure (for local/trusted networks).
|
||||||
|
|
||||||
|
The client gains `--tls` and `--tls-ca` flags:
|
||||||
|
- `--tls` — enables TLS transport (uses system CA pool by default)
|
||||||
|
- `--tls-ca <path>` — custom CA certificate for self-signed server certs
|
||||||
|
|
||||||
|
Both flags must be specified together on the server side; on the client
|
||||||
|
side `--tls` alone uses the system trust store, and `--tls-ca` adds a
|
||||||
|
custom root.
|
||||||
|
|
||||||
|
### FIDO2 Hardware Support
|
||||||
|
|
||||||
|
Real FIDO2 hardware support uses `go-libfido2` (CGo bindings to
|
||||||
|
Yubico's libfido2 C library). It is gated behind the `fido2` build
|
||||||
|
tag to avoid requiring CGo and libfido2 for users who don't need it:
|
||||||
|
|
||||||
|
- `go build ./...` — default build, no FIDO2 hardware support
|
||||||
|
- `go build -tags fido2 ./...` — links against libfido2 for real keys
|
||||||
|
|
||||||
|
The implementation (`garden/fido2_hardware.go`) wraps
|
||||||
|
`libfido2.Device.MakeCredential` and `Assertion` with the
|
||||||
|
`HMACSecretExtension` to derive 32-byte HMAC secrets from hardware
|
||||||
|
keys. A `--fido2-pin` flag is available for PIN-protected devices.
|
||||||
|
|
||||||
|
The Nix flake provides two packages: `sgard` (default, no CGo) and
|
||||||
|
`sgard-fido2` (links libfido2).
|
||||||
|
|
||||||
|
### DEK Rotation
|
||||||
|
|
||||||
|
`sgard encrypt rotate-dek` generates a new DEK, re-encrypts all
|
||||||
|
encrypted blobs with the new key, and re-wraps the new DEK with all
|
||||||
|
existing KEK slots. Required when the DEK is suspected compromised
|
||||||
|
(re-wrapping alone is insufficient since the old DEK could decrypt
|
||||||
|
the existing blobs).
|
||||||
|
|
||||||
|
The rotation process:
|
||||||
|
1. Generate a new random 256-bit DEK
|
||||||
|
2. For each encrypted entry: decrypt with old DEK, re-encrypt with new DEK,
|
||||||
|
write new blob to store, update manifest hash (plaintext hash unchanged)
|
||||||
|
3. Re-derive each KEK (passphrase via Argon2id, FIDO2 via device) and
|
||||||
|
re-wrap the new DEK. FIDO2 slots without a matching connected device
|
||||||
|
are dropped during rotation.
|
||||||
|
4. Save updated manifest
|
||||||
|
|
||||||
|
Plaintext entries are untouched.
|
||||||
|
|
||||||
|
### Per-Machine Targeting (Phase 5)
|
||||||
|
|
||||||
|
Entries can be targeted to specific machines using `only` and `never`
|
||||||
|
labels. A machine's identity is a set of labels computed at runtime:
|
||||||
|
|
||||||
|
- **Short hostname:** `vade` (before the first dot, lowercased)
|
||||||
|
- **OS:** `os:linux`, `os:darwin`, `os:windows` (from `runtime.GOOS`)
|
||||||
|
- **Architecture:** `arch:amd64`, `arch:arm64` (from `runtime.GOARCH`)
|
||||||
|
- **Tags:** `tag:work`, `tag:server` (from `<repo>/tags`, local-only)
|
||||||
|
|
||||||
|
**Manifest fields on Entry:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
files:
|
||||||
|
- path: ~/.bashrc.linux
|
||||||
|
only: [os:linux] # restore/checkpoint only on Linux
|
||||||
|
...
|
||||||
|
- path: ~/.ssh/work-config
|
||||||
|
only: [tag:work] # only on machines tagged "work"
|
||||||
|
...
|
||||||
|
- path: ~/.config/heavy
|
||||||
|
never: [arch:arm64] # everywhere except ARM
|
||||||
|
...
|
||||||
|
- path: ~/.special
|
||||||
|
only: [vade] # only on host "vade"
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
**Matching rules:**
|
||||||
|
- `only` set → entry applies if *any* label matches the machine
|
||||||
|
- `never` set → entry excluded if *any* label matches
|
||||||
|
- Both set → error (mutually exclusive)
|
||||||
|
- Neither set → applies everywhere (current behavior)
|
||||||
|
|
||||||
|
**Operations affected:**
|
||||||
|
- `restore` — skip non-matching entries
|
||||||
|
- `checkpoint` — skip non-matching entries (don't clobber stored version)
|
||||||
|
- `status` — report non-matching entries as `skipped`
|
||||||
|
- `add`, `list`, `verify`, `diff` — operate on all entries regardless
|
||||||
|
|
||||||
|
**Tags file:** `<repo>/tags`, one tag per line, not synced. Each
|
||||||
|
machine defines its own tags. `sgard init` adds `tags` to `.gitignore`.
|
||||||
|
|
||||||
|
**Label format:** bare string = hostname, `prefix:value` = typed matcher.
|
||||||
|
The `tag:` prefix in `only`/`never` maps to bare names in the tags file.
|
||||||
|
|
||||||
|
### Future: Manifest Signing (Phase 6)
|
||||||
|
|
||||||
Manifest signing (to detect tampering) is deferred. The challenge is
|
Manifest signing (to detect tampering) is deferred. The challenge is
|
||||||
the trust model: which key signs, and how does a pulling client verify
|
the trust model: which key signs, and how does a pulling client verify
|
||||||
@@ -575,20 +674,24 @@ the same server? This requires a proper trust/key-authority design.
|
|||||||
```
|
```
|
||||||
sgard/
|
sgard/
|
||||||
cmd/sgard/ # CLI entry point — one file per command
|
cmd/sgard/ # CLI entry point — one file per command
|
||||||
main.go # cobra root command, --repo/--remote/--ssh-key flags
|
main.go # cobra root command, --repo/--remote/--ssh-key/--tls/--tls-ca flags
|
||||||
encrypt.go # sgard encrypt init/add-fido2/remove-slot/list-slots/change-passphrase
|
encrypt.go # sgard encrypt init/add-fido2/remove-slot/list-slots/change-passphrase
|
||||||
|
exclude.go # sgard exclude/include
|
||||||
push.go pull.go prune.go mirror.go
|
push.go pull.go prune.go mirror.go
|
||||||
init.go add.go remove.go checkpoint.go
|
init.go add.go remove.go checkpoint.go
|
||||||
restore.go status.go verify.go list.go diff.go version.go
|
restore.go status.go verify.go list.go info.go diff.go version.go
|
||||||
|
|
||||||
cmd/sgardd/ # gRPC server daemon
|
cmd/sgardd/ # gRPC server daemon
|
||||||
main.go # --listen, --repo, --authorized-keys flags
|
main.go # --listen, --repo, --authorized-keys, --tls-cert, --tls-key flags
|
||||||
|
|
||||||
garden/ # Core business logic — one file per operation
|
garden/ # Core business logic — one file per operation
|
||||||
garden.go # Garden struct, Init, Open, Add, Checkpoint, Status, accessors
|
garden.go # Garden struct, Init, Open, Add, Checkpoint, Status, accessors
|
||||||
encrypt.go # EncryptInit, UnlockDEK, encrypt/decrypt blobs, slot management
|
encrypt.go # EncryptInit, UnlockDEK, RotateDEK, encrypt/decrypt blobs, slot mgmt
|
||||||
encrypt_fido2.go # FIDO2Device interface, AddFIDO2Slot, unlock resolution
|
encrypt_fido2.go # FIDO2Device interface, AddFIDO2Slot, unlock resolution
|
||||||
restore.go mirror.go prune.go remove.go verify.go list.go diff.go
|
fido2_hardware.go # Real FIDO2 via go-libfido2 (//go:build fido2)
|
||||||
|
fido2_nohardware.go # Stub returning nil (//go:build !fido2)
|
||||||
|
exclude.go # Exclude/Include methods
|
||||||
|
restore.go mirror.go prune.go remove.go verify.go list.go info.go diff.go
|
||||||
hasher.go # SHA-256 file hashing
|
hasher.go # SHA-256 file hashing
|
||||||
|
|
||||||
manifest/ # YAML manifest parsing
|
manifest/ # YAML manifest parsing
|
||||||
@@ -609,7 +712,8 @@ sgard/
|
|||||||
sgardpb/ # Generated protobuf + gRPC Go code
|
sgardpb/ # Generated protobuf + gRPC Go code
|
||||||
proto/sgard/v1/ # Proto source definitions
|
proto/sgard/v1/ # Proto source definitions
|
||||||
|
|
||||||
flake.nix # Nix flake (builds sgard + sgardd)
|
VERSION # Semver string, read by flake.nix; synced from latest git tag via `make version`
|
||||||
|
flake.nix # Nix flake (builds sgard + sgardd, version from VERSION file)
|
||||||
.goreleaser.yaml # GoReleaser (builds both binaries)
|
.goreleaser.yaml # GoReleaser (builds both binaries)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -629,21 +733,29 @@ type Garden struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Local operations
|
// Local operations
|
||||||
func (g *Garden) Add(paths []string, encrypt ...bool) error
|
func (g *Garden) Add(paths []string, opts ...AddOptions) error
|
||||||
func (g *Garden) Remove(paths []string) error
|
func (g *Garden) Remove(paths []string) error
|
||||||
func (g *Garden) Checkpoint(message string) error
|
func (g *Garden) Checkpoint(message string) error
|
||||||
func (g *Garden) Restore(paths []string, force bool, confirm func(string) bool) error
|
func (g *Garden) Restore(paths []string, force bool, confirm func(string) bool) error
|
||||||
func (g *Garden) Status() ([]FileStatus, error)
|
func (g *Garden) Status() ([]FileStatus, error)
|
||||||
func (g *Garden) Verify() ([]VerifyResult, error)
|
func (g *Garden) Verify() ([]VerifyResult, error)
|
||||||
func (g *Garden) List() []manifest.Entry
|
func (g *Garden) List() []manifest.Entry
|
||||||
|
func (g *Garden) Info(path string) (*FileInfo, error)
|
||||||
func (g *Garden) Diff(path string) (string, error)
|
func (g *Garden) Diff(path string) (string, error)
|
||||||
func (g *Garden) Prune() (int, error)
|
func (g *Garden) Prune() (int, error)
|
||||||
func (g *Garden) MirrorUp(paths []string) error
|
func (g *Garden) MirrorUp(paths []string) error
|
||||||
func (g *Garden) MirrorDown(paths []string, force bool, confirm func(string) bool) error
|
func (g *Garden) MirrorDown(paths []string, force bool, confirm func(string) bool) error
|
||||||
|
func (g *Garden) Lock(paths []string) error
|
||||||
|
func (g *Garden) Unlock(paths []string) error
|
||||||
|
func (g *Garden) Exclude(paths []string) error
|
||||||
|
func (g *Garden) Include(paths []string) error
|
||||||
|
|
||||||
// Encryption
|
// Encryption
|
||||||
func (g *Garden) EncryptInit(passphrase string) error
|
func (g *Garden) EncryptInit(passphrase string) error
|
||||||
func (g *Garden) UnlockDEK(prompt func() (string, error), fido2 ...FIDO2Device) error
|
func (g *Garden) UnlockDEK(prompt func() (string, error), fido2 ...FIDO2Device) error
|
||||||
|
func (g *Garden) HasEncryption() bool
|
||||||
|
func (g *Garden) NeedsDEK(entries []manifest.Entry) bool
|
||||||
|
func (g *Garden) RotateDEK(prompt func() (string, error), fido2 ...FIDO2Device) error
|
||||||
func (g *Garden) AddFIDO2Slot(device FIDO2Device, label string) error
|
func (g *Garden) AddFIDO2Slot(device FIDO2Device, label string) error
|
||||||
func (g *Garden) RemoveSlot(name string) error
|
func (g *Garden) RemoveSlot(name string) error
|
||||||
func (g *Garden) ListSlots() map[string]string
|
func (g *Garden) ListSlots() map[string]string
|
||||||
@@ -670,7 +782,15 @@ different usernames.
|
|||||||
|
|
||||||
**Adding a directory recurses.** `Add` walks directories and adds each
|
**Adding a directory recurses.** `Add` walks directories and adds each
|
||||||
file/symlink individually. Directories are not tracked as entries — only
|
file/symlink individually. Directories are not tracked as entries — only
|
||||||
leaf files and symlinks.
|
leaf files and symlinks. Excluded paths (see below) are skipped during walks.
|
||||||
|
|
||||||
|
**File exclusion.** The manifest stores an `exclude` list of tilde-form
|
||||||
|
paths that should never be tracked. Excluding a directory excludes
|
||||||
|
everything under it. Exclusions are checked during `Add` directory walks,
|
||||||
|
`MirrorUp` walks, and `MirrorDown` cleanup (excluded files are left alone
|
||||||
|
on disk). `sgard exclude` adds paths; `sgard include` removes them. When a
|
||||||
|
path is excluded, any already-tracked entries matching it are removed from
|
||||||
|
the manifest.
|
||||||
|
|
||||||
**No history.** Only the latest checkpoint is stored. For versioning, place
|
**No history.** Only the latest checkpoint is stored. For versioning, place
|
||||||
the repo under git — `sgard init` creates a `.gitignore` that excludes
|
the repo under git — `sgard init` creates a `.gitignore` that excludes
|
||||||
|
|||||||
@@ -22,11 +22,13 @@ Module: `github.com/kisom/sgard`. Author: K. Isom <kyle@imap.cc>.
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
go build ./... # both sgard and sgardd
|
go build ./... # both sgard and sgardd
|
||||||
|
go build -tags fido2 ./... # with real FIDO2 hardware support (requires libfido2)
|
||||||
```
|
```
|
||||||
|
|
||||||
Nix:
|
Nix:
|
||||||
```bash
|
```bash
|
||||||
nix build .#sgard # builds both binaries
|
nix build .#sgard # builds both binaries (no CGo)
|
||||||
|
nix build .#sgard-fido2 # with FIDO2 hardware support (links libfido2)
|
||||||
```
|
```
|
||||||
|
|
||||||
Run tests:
|
Run tests:
|
||||||
@@ -53,13 +55,14 @@ make proto
|
|||||||
- `google.golang.org/protobuf` — protobuf runtime
|
- `google.golang.org/protobuf` — protobuf runtime
|
||||||
- `golang.org/x/crypto` — SSH key auth (ssh, ssh/agent), Argon2id, XChaCha20-Poly1305
|
- `golang.org/x/crypto` — SSH key auth (ssh, ssh/agent), Argon2id, XChaCha20-Poly1305
|
||||||
- `github.com/golang-jwt/jwt/v5` — JWT token auth
|
- `github.com/golang-jwt/jwt/v5` — JWT token auth
|
||||||
|
- `github.com/keys-pub/go-libfido2` — FIDO2 hardware key support (build tag `fido2`, requires libfido2)
|
||||||
|
|
||||||
## Package Structure
|
## Package Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
cmd/sgard/ CLI entry point (cobra commands, pure wiring)
|
cmd/sgard/ CLI entry point (cobra commands, pure wiring)
|
||||||
cmd/sgardd/ gRPC server daemon
|
cmd/sgardd/ gRPC server daemon
|
||||||
garden/ Core business logic (Garden struct, encryption via encrypt.go/encrypt_fido2.go)
|
garden/ Core business logic (Garden struct, encryption, FIDO2 hardware via build tags)
|
||||||
manifest/ YAML manifest parsing (Manifest/Entry structs, Load/Save)
|
manifest/ YAML manifest parsing (Manifest/Entry structs, Load/Save)
|
||||||
store/ Content-addressable blob storage (SHA-256 keyed)
|
store/ Content-addressable blob storage (SHA-256 keyed)
|
||||||
server/ gRPC server (RPC handlers, JWT/SSH auth interceptor, proto conversion)
|
server/ gRPC server (RPC handlers, JWT/SSH auth interceptor, proto conversion)
|
||||||
|
|||||||
9
Makefile
9
Makefile
@@ -1,4 +1,6 @@
|
|||||||
.PHONY: proto build test lint clean
|
VERSION := $(shell git describe --tags --abbrev=0 | sed 's/^v//')
|
||||||
|
|
||||||
|
.PHONY: proto build test lint clean version
|
||||||
|
|
||||||
proto:
|
proto:
|
||||||
protoc \
|
protoc \
|
||||||
@@ -7,8 +9,11 @@ proto:
|
|||||||
-I proto \
|
-I proto \
|
||||||
proto/sgard/v1/sgard.proto
|
proto/sgard/v1/sgard.proto
|
||||||
|
|
||||||
|
version:
|
||||||
|
@echo $(VERSION) > VERSION
|
||||||
|
|
||||||
build:
|
build:
|
||||||
go build ./...
|
go build -ldflags "-X main.version=$(VERSION)" ./...
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test ./...
|
go test ./...
|
||||||
|
|||||||
39
PROGRESS.md
39
PROGRESS.md
@@ -7,9 +7,9 @@ ARCHITECTURE.md for design details.
|
|||||||
|
|
||||||
## Current Status
|
## Current Status
|
||||||
|
|
||||||
**Phase:** Phase 3 complete (Steps 17–20). Encryption fully implemented.
|
**Phase:** Phase 5 complete. File exclusion feature added. Add is now idempotent.
|
||||||
|
|
||||||
**Last updated:** 2026-03-24
|
**Last updated:** 2026-03-30
|
||||||
|
|
||||||
## Completed Steps
|
## Completed Steps
|
||||||
|
|
||||||
@@ -42,7 +42,18 @@ ARCHITECTURE.md for design details.
|
|||||||
|
|
||||||
## Up Next
|
## Up Next
|
||||||
|
|
||||||
Phase 3 complete. Future: TLS transport, shell completions, manifest signing, real FIDO2 hardware binding.
|
Phase 6: Manifest Signing (to be planned).
|
||||||
|
|
||||||
|
## Standalone Additions
|
||||||
|
|
||||||
|
- **Deployment to rift**: sgardd deployed as Podman container on rift behind
|
||||||
|
mc-proxy (L4 SNI passthrough on :9443, multiplexed with metacrypt gRPC).
|
||||||
|
TLS cert issued by Metacrypt, SSH-key auth. DNS at
|
||||||
|
`sgard.svc.mcp.metacircular.net`.
|
||||||
|
- **Default remote config**: `sgard remote set/show` commands. Saves addr,
|
||||||
|
TLS, and CA path to `<repo>/remote.yaml`. `dialRemote` merges saved config
|
||||||
|
with CLI flags (flags win). Removes need for `--remote`/`--tls` on every
|
||||||
|
push/pull.
|
||||||
|
|
||||||
## Known Issues / Decisions Deferred
|
## Known Issues / Decisions Deferred
|
||||||
|
|
||||||
@@ -82,3 +93,25 @@ Phase 3 complete. Future: TLS transport, shell completions, manifest signing, re
|
|||||||
| 2026-03-24 | 18 | FIDO2: FIDO2Device interface, AddFIDO2Slot, unlock resolution (fido2 first → passphrase fallback), mock device, 6 tests. |
|
| 2026-03-24 | 18 | FIDO2: FIDO2Device interface, AddFIDO2Slot, unlock resolution (fido2 first → passphrase fallback), mock device, 6 tests. |
|
||||||
| 2026-03-24 | 19 | Encryption CLI: encrypt init/add-fido2/remove-slot/list-slots/change-passphrase, --encrypt on add, proto + convert updates. |
|
| 2026-03-24 | 19 | Encryption CLI: encrypt init/add-fido2/remove-slot/list-slots/change-passphrase, --encrypt on add, proto + convert updates. |
|
||||||
| 2026-03-24 | 20 | Polish: encryption e2e test, all docs updated, flake vendorHash updated. |
|
| 2026-03-24 | 20 | Polish: encryption e2e test, all docs updated, flake vendorHash updated. |
|
||||||
|
| 2026-03-24 | — | Locked files + dir-only entries. v2.0.0 released. |
|
||||||
|
| 2026-03-24 | — | Phase 4 planned (Steps 21–27): lock/unlock, shell completion, TLS, DEK rotation, real FIDO2, test cleanup. |
|
||||||
|
| 2026-03-24 | 21 | Lock/unlock toggle commands. garden/lock.go, cmd/sgard/lock.go, 6 tests. |
|
||||||
|
| 2026-03-24 | 22 | Shell completion: cobra built-in, README docs for bash/zsh/fish. |
|
||||||
|
| 2026-03-24 | 23 | TLS transport: sgardd --tls-cert/--tls-key, sgard --tls/--tls-ca, 2 integration tests. |
|
||||||
|
| 2026-03-24 | 24 | DEK rotation: RotateDEK re-encrypts all blobs, re-wraps all slots, CLI command, 4 tests. |
|
||||||
|
| 2026-03-24 | 25 | Real FIDO2: go-libfido2 bindings, build tag gating, CLI wiring, nix sgard-fido2 package. |
|
||||||
|
| 2026-03-24 | 26 | Test cleanup: tightened lint, 3 combo tests (encrypted+locked, dir-only+locked, toggle), stale doc fixes. |
|
||||||
|
| 2026-03-24 | 27 | Phase 4 polish: e2e test (TLS+encryption+locked+push/pull), final doc review. Phase 4 complete. |
|
||||||
|
| 2026-03-24 | — | Phase 5 planned (Steps 28–32): machine identity, targeting, tags, proto update, polish. |
|
||||||
|
| 2026-03-24 | 28 | Machine identity + targeting core: Entry Only/Never, Identity(), EntryApplies(), tags file. 13 tests. |
|
||||||
|
| 2026-03-24 | 29 | Operations respect targeting: checkpoint/restore/status skip non-matching. 6 tests. |
|
||||||
|
| 2026-03-24 | 30 | Targeting CLI: tag add/remove/list, identity, --only/--never on add, target command. |
|
||||||
|
| 2026-03-24 | 31 | Proto + sync: only/never fields on ManifestEntry, conversion, round-trip test. |
|
||||||
|
| 2026-03-24 | 32 | Phase 5 polish: e2e test (targeting + push/pull + restore), docs updated. Phase 5 complete. |
|
||||||
|
| 2026-03-25 | — | `sgard info` command: shows detailed file information (status, hash, timestamps, mode, encryption, targeting). 5 tests. |
|
||||||
|
| 2026-03-25 | — | Deploy sgardd to rift: Dockerfile, docker-compose, mc-proxy L4 route on :9443, Metacrypt TLS cert, DNS. |
|
||||||
|
| 2026-03-25 | — | `sgard remote set/show`: persistent remote config in `<repo>/remote.yaml` (addr, tls, tls_ca). |
|
||||||
|
| 2026-03-26 | — | `sgard list` remote support: uses `resolveRemoteConfig()` to list server manifest via `PullManifest` RPC. Client `List()` method added. |
|
||||||
|
| 2026-03-26 | — | Version derived from git tags via `VERSION` file. flake.nix reads `VERSION`; Makefile `version` target syncs from latest tag, `build` injects via ldflags. |
|
||||||
|
| 2026-03-27 | — | File exclusion: `sgard exclude`/`include` commands, `Manifest.Exclude` field, Add/MirrorUp/MirrorDown respect exclusions, directory exclusion support. 8 tests. |
|
||||||
|
| 2026-03-30 | — | Idempotent add: `sgard add` silently skips already-tracked files/directories instead of erroring, enabling glob-based workflows. |
|
||||||
|
|||||||
114
PROJECT_PLAN.md
114
PROJECT_PLAN.md
@@ -222,8 +222,112 @@ Depends on Steps 17, 18.
|
|||||||
|
|
||||||
## Future Steps (Not Phase 3)
|
## Future Steps (Not Phase 3)
|
||||||
|
|
||||||
- Shell completion via cobra
|
## Phase 4: Hardening + Completeness
|
||||||
- TLS transport (optional --tls-cert/--tls-key on sgardd)
|
|
||||||
- Multiple repo support on server
|
### Step 21: Lock/Unlock Toggle Commands
|
||||||
- Manifest signing (requires trust model design)
|
|
||||||
- DEK rotation (`sgard encrypt rotate-dek` — re-encrypt all blobs)
|
- [x] `garden/lock.go`: `Lock(paths)`, `Unlock(paths)` — toggle locked flag on existing entries
|
||||||
|
- [x] `cmd/sgard/lock.go`: `sgard lock <path>...`, `sgard unlock <path>...`
|
||||||
|
- [x] Tests: lock/unlock existing entry, persist, error on untracked, checkpoint/status behavior changes (6 tests)
|
||||||
|
|
||||||
|
### Step 22: Shell Completion
|
||||||
|
|
||||||
|
- [x] Cobra provides built-in `sgard completion` for bash, zsh, fish, powershell — no code needed
|
||||||
|
- [x] README updated with shell completion installation instructions
|
||||||
|
|
||||||
|
### Step 23: TLS Transport for sgardd
|
||||||
|
|
||||||
|
- [x] `cmd/sgardd/main.go`: add `--tls-cert`, `--tls-key` flags
|
||||||
|
- [x] Server uses `credentials.NewTLS()` when cert/key provided, insecure otherwise
|
||||||
|
- [x] Client: add `--tls` flag and `--tls-ca` for custom CA
|
||||||
|
- [x] Update `cmd/sgard/main.go` and `dialRemote()` for TLS
|
||||||
|
- [x] Tests: TLS connection with self-signed cert (push/pull cycle, reject untrusted client)
|
||||||
|
- [x] Update ARCHITECTURE.md and README.md
|
||||||
|
|
||||||
|
### Step 24: DEK Rotation
|
||||||
|
|
||||||
|
- [x] `garden/encrypt.go`: `RotateDEK(promptPassphrase, fido2Device)` — generate new DEK, re-encrypt all encrypted blobs, re-wrap with all existing KEK slots
|
||||||
|
- [x] `cmd/sgard/encrypt.go`: `sgard encrypt rotate-dek`
|
||||||
|
- [x] Tests: rotate DEK, verify decryption, verify plaintext untouched, FIDO2 re-wrap, requires-unlock (4 tests)
|
||||||
|
|
||||||
|
### Step 25: Real FIDO2 Hardware Binding
|
||||||
|
|
||||||
|
- [x] Evaluate approach: go-libfido2 CGo bindings (keys-pub/go-libfido2 v1.5.3)
|
||||||
|
- [x] `garden/fido2_hardware.go`: HardwareFIDO2 implementing FIDO2Device via libfido2 (`//go:build fido2`)
|
||||||
|
- [x] `garden/fido2_nohardware.go`: stub returning nil (`//go:build !fido2`)
|
||||||
|
- [x] `cmd/sgard/fido2.go`: unlockDEK helper, --fido2-pin flag
|
||||||
|
- [x] `cmd/sgard/encrypt.go`: add-fido2 uses real hardware, encrypt init --fido2 registers slot, all unlock calls use FIDO2-first resolution
|
||||||
|
- [x] `flake.nix`: sgard-fido2 package variant, libfido2+pkg-config in devShell
|
||||||
|
- [x] Tests: existing mock-based tests still pass; hardware tests require manual testing with a FIDO2 key
|
||||||
|
|
||||||
|
### Step 26: Test Cleanup
|
||||||
|
|
||||||
|
- [x] Standardize all test calls — already use `AddOptions{}` struct consistently (no legacy variadic patterns found)
|
||||||
|
- [x] Ensure all tests use `t.TempDir()` consistently (audited, no `os.MkdirTemp`/`ioutil.Temp` usage)
|
||||||
|
- [x] Review lint config — added copyloopvar, durationcheck, makezero, nilerr, bodyclose linters
|
||||||
|
- [x] Verify test coverage — added 3 tests: encrypted+locked, dir-only+locked, lock/unlock toggle on encrypted
|
||||||
|
- [x] Fix stale API signatures in ARCHITECTURE.md (Add, Lock, Unlock, RotateDEK, HasEncryption, NeedsDEK)
|
||||||
|
|
||||||
|
### Step 27: Phase 4 Polish + Release
|
||||||
|
|
||||||
|
- [x] Update all docs (ARCHITECTURE.md, README.md, CLAUDE.md, PROGRESS.md)
|
||||||
|
- [x] Update flake.nix vendorHash (done in Step 25)
|
||||||
|
- [x] .goreleaser.yaml — no changes needed (CGO_ENABLED=0 is correct for release binaries)
|
||||||
|
- [x] E2e test: integration/phase4_test.go covering TLS + encryption + locked files + push/pull
|
||||||
|
- [x] Verify: all tests pass, lint clean, both binaries compile
|
||||||
|
|
||||||
|
## Phase 5: Per-Machine Targeting
|
||||||
|
|
||||||
|
### Step 28: Machine Identity + Targeting Core
|
||||||
|
|
||||||
|
- [x] `manifest/manifest.go`: add `Only []string` and `Never []string` to Entry
|
||||||
|
- [x] `garden/identity.go`: `Identity()` returns machine label set
|
||||||
|
- [x] `garden/targeting.go`: `EntryApplies(entry, labels)` match logic
|
||||||
|
- [x] `garden/tags.go`: `LoadTags`, `SaveTag`, `RemoveTag` for `<repo>/tags`
|
||||||
|
- [x] `garden/garden.go`: `Init` appends `tags` to `.gitignore`
|
||||||
|
- [x] Tests: 13 tests (identity, tags, matching: only, never, both-error, hostname, os, arch, tag, case-insensitive, multiple)
|
||||||
|
|
||||||
|
### Step 29: Operations Respect Targeting
|
||||||
|
|
||||||
|
- [x] `Checkpoint` skips entries where `!EntryApplies`
|
||||||
|
- [x] `Restore` skips entries where `!EntryApplies`
|
||||||
|
- [x] `Status` reports `skipped` for non-matching entries
|
||||||
|
- [x] `Add` accepts `Only`/`Never` in `AddOptions`, propagated through `addEntry`
|
||||||
|
- [x] Tests: 6 tests (checkpoint skip/process, status skipped, restore skip, add with only/never)
|
||||||
|
|
||||||
|
### Step 30: Targeting CLI Commands
|
||||||
|
|
||||||
|
- [x] `cmd/sgard/tag.go`: tag add/remove/list
|
||||||
|
- [x] `cmd/sgard/identity.go`: identity command
|
||||||
|
- [x] `cmd/sgard/add.go`: --only/--never flags
|
||||||
|
- [x] `cmd/sgard/target.go`: target command with --only/--never/--clear
|
||||||
|
- [x] `garden/target.go`: SetTargeting method
|
||||||
|
|
||||||
|
### Step 31: Proto + Sync Update
|
||||||
|
|
||||||
|
- [x] `proto/sgard/v1/sgard.proto`: only/never fields on ManifestEntry
|
||||||
|
- [x] `server/convert.go`: updated conversion
|
||||||
|
- [x] Regenerated proto
|
||||||
|
- [x] Tests: targeting round-trip test
|
||||||
|
|
||||||
|
### Step 32: Phase 5 Polish
|
||||||
|
|
||||||
|
- [x] Update ARCHITECTURE.md, README.md, CLAUDE.md, PROGRESS.md
|
||||||
|
- [x] E2e test: push/pull with targeting labels, restore respects targeting
|
||||||
|
- [x] Verify: all tests pass, lint clean, both binaries compile
|
||||||
|
|
||||||
|
## Standalone: File Exclusion
|
||||||
|
|
||||||
|
- [x] `manifest/manifest.go`: `Exclude []string` field on Manifest, `IsExcluded(tildePath)` method (exact match + directory prefix)
|
||||||
|
- [x] `garden/exclude.go`: `Exclude(paths)` and `Include(paths)` methods; Exclude removes already-tracked matching entries
|
||||||
|
- [x] `garden/garden.go`: Add's WalkDir checks `IsExcluded`, returns `filepath.SkipDir` for excluded directories
|
||||||
|
- [x] `garden/mirror.go`: MirrorUp skips excluded paths; MirrorDown leaves excluded files on disk
|
||||||
|
- [x] `cmd/sgard/exclude.go`: `sgard exclude <path>... [--list]`, `sgard include <path>...`
|
||||||
|
- [x] `proto/sgard/v1/sgard.proto`: `repeated string exclude = 7` on Manifest; regenerated
|
||||||
|
- [x] `server/convert.go`: round-trip Exclude field
|
||||||
|
- [x] `garden/exclude_test.go`: 8 tests (add/dedup/remove-tracked/include, Add skips file/dir, MirrorUp skips, MirrorDown leaves alone, IsExcluded prefix matching)
|
||||||
|
- [x] Update ARCHITECTURE.md, PROJECT_PLAN.md, PROGRESS.md
|
||||||
|
|
||||||
|
## Phase 6: Manifest Signing
|
||||||
|
|
||||||
|
(To be planned — requires trust model design)
|
||||||
|
|||||||
86
README.md
86
README.md
@@ -41,6 +41,21 @@ in your packages.
|
|||||||
Binaries are also available on the
|
Binaries are also available on the
|
||||||
[releases page](https://github.com/kisom/sgard/releases).
|
[releases page](https://github.com/kisom/sgard/releases).
|
||||||
|
|
||||||
|
### Shell completion
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Bash (add to ~/.bashrc)
|
||||||
|
source <(sgard completion bash)
|
||||||
|
|
||||||
|
# Zsh (add to ~/.zshrc)
|
||||||
|
source <(sgard completion zsh)
|
||||||
|
|
||||||
|
# Fish
|
||||||
|
sgard completion fish | source
|
||||||
|
# To load on startup:
|
||||||
|
sgard completion fish > ~/.config/fish/completions/sgard.fish
|
||||||
|
```
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -104,6 +119,37 @@ sgard add --dir ~/.local/share/applications
|
|||||||
On `restore`, sgard creates the directory with the correct permissions
|
On `restore`, sgard creates the directory with the correct permissions
|
||||||
but doesn't touch its contents.
|
but doesn't touch its contents.
|
||||||
|
|
||||||
|
### Per-machine targeting
|
||||||
|
|
||||||
|
Some files only apply to certain machines. Use `--only` and `--never`
|
||||||
|
to control where entries are active:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Only restore on Linux
|
||||||
|
sgard add --only os:linux ~/.bashrc.linux
|
||||||
|
|
||||||
|
# Never restore on ARM
|
||||||
|
sgard add --never arch:arm64 ~/.config/heavy-tool
|
||||||
|
|
||||||
|
# Only on machines tagged "work"
|
||||||
|
sgard tag add work
|
||||||
|
sgard add --only tag:work ~/.ssh/work-config
|
||||||
|
|
||||||
|
# Only on a specific host
|
||||||
|
sgard add --only vade ~/.special-config
|
||||||
|
|
||||||
|
# See this machine's identity
|
||||||
|
sgard identity
|
||||||
|
|
||||||
|
# Change targeting on an existing entry
|
||||||
|
sgard target ~/.bashrc.linux --only os:linux,tag:desktop
|
||||||
|
sgard target ~/.bashrc.linux --clear
|
||||||
|
```
|
||||||
|
|
||||||
|
Labels: bare string = hostname, `os:linux`/`os:darwin`, `arch:amd64`/`arch:arm64`,
|
||||||
|
`tag:<name>` from local `<repo>/tags` file. `checkpoint`, `restore`, and
|
||||||
|
`status` skip non-matching entries automatically.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
### Local
|
### Local
|
||||||
@@ -114,6 +160,11 @@ but doesn't touch its contents.
|
|||||||
| `add <path>...` | Track files, directories (recursed), or symlinks |
|
| `add <path>...` | Track files, directories (recursed), or symlinks |
|
||||||
| `add --lock <path>...` | Track as locked (repo-authoritative, auto-restores on drift) |
|
| `add --lock <path>...` | Track as locked (repo-authoritative, auto-restores on drift) |
|
||||||
| `add --dir <path>` | Track directory itself without recursing into contents |
|
| `add --dir <path>` | Track directory itself without recursing into contents |
|
||||||
|
| `add --only <labels>` | Track with per-machine targeting (only on matching) |
|
||||||
|
| `add --never <labels>` | Track with per-machine targeting (never on matching) |
|
||||||
|
| `target <path> --only/--never/--clear` | Set or clear targeting on existing entry |
|
||||||
|
| `tag add/remove/list` | Manage machine-local tags |
|
||||||
|
| `identity` | Show this machine's identity labels |
|
||||||
| `remove <path>...` | Stop tracking files |
|
| `remove <path>...` | Stop tracking files |
|
||||||
| `checkpoint [-m msg]` | Re-hash tracked files and update the manifest |
|
| `checkpoint [-m msg]` | Re-hash tracked files and update the manifest |
|
||||||
| `restore [path...] [-f]` | Restore files to their original locations |
|
| `restore [path...] [-f]` | Restore files to their original locations |
|
||||||
@@ -135,6 +186,7 @@ but doesn't touch its contents.
|
|||||||
| `encrypt remove-slot <name>` | Remove a KEK slot |
|
| `encrypt remove-slot <name>` | Remove a KEK slot |
|
||||||
| `encrypt list-slots` | List all KEK slots |
|
| `encrypt list-slots` | List all KEK slots |
|
||||||
| `encrypt change-passphrase` | Change the passphrase |
|
| `encrypt change-passphrase` | Change the passphrase |
|
||||||
|
| `encrypt rotate-dek` | Generate new DEK and re-encrypt all encrypted blobs |
|
||||||
| `add --encrypt <path>...` | Track files with encryption |
|
| `add --encrypt <path>...` | Track files with encryption |
|
||||||
|
|
||||||
### Remote sync
|
### Remote sync
|
||||||
@@ -170,6 +222,24 @@ sgard pull --remote myserver:9473
|
|||||||
Authentication uses your existing SSH keys (ssh-agent, `~/.ssh/id_ed25519`,
|
Authentication uses your existing SSH keys (ssh-agent, `~/.ssh/id_ed25519`,
|
||||||
or `--ssh-key`). No passwords or certificates to manage.
|
or `--ssh-key`). No passwords or certificates to manage.
|
||||||
|
|
||||||
|
### TLS
|
||||||
|
|
||||||
|
To encrypt the connection with TLS:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Server: provide cert and key
|
||||||
|
sgardd --tls-cert server.crt --tls-key server.key --authorized-keys ~/.ssh/authorized_keys
|
||||||
|
|
||||||
|
# Client: enable TLS (uses system CA pool)
|
||||||
|
sgard push --remote myserver:9473 --tls
|
||||||
|
|
||||||
|
# Client: with a custom/self-signed CA
|
||||||
|
sgard push --remote myserver:9473 --tls --tls-ca ca.crt
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `--tls-cert`/`--tls-key`, sgardd runs without TLS (suitable for
|
||||||
|
localhost or trusted networks).
|
||||||
|
|
||||||
## Encryption
|
## Encryption
|
||||||
|
|
||||||
Sensitive files can be encrypted individually:
|
Sensitive files can be encrypted individually:
|
||||||
@@ -190,6 +260,22 @@ is wrapped by a passphrase-derived key (Argon2id). FIDO2 hardware keys
|
|||||||
are also supported as an alternative KEK source — sgard tries FIDO2
|
are also supported as an alternative KEK source — sgard tries FIDO2
|
||||||
first and falls back to passphrase automatically.
|
first and falls back to passphrase automatically.
|
||||||
|
|
||||||
|
### FIDO2 hardware keys
|
||||||
|
|
||||||
|
Build with `-tags fido2` (requires libfido2) to enable real hardware
|
||||||
|
key support, or use `nix build .#sgard-fido2`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Register a FIDO2 key (touch required)
|
||||||
|
sgard encrypt add-fido2
|
||||||
|
|
||||||
|
# With a PIN-protected device
|
||||||
|
sgard encrypt add-fido2 --fido2-pin 1234
|
||||||
|
|
||||||
|
# Unlock is automatic — FIDO2 is tried first, passphrase as fallback
|
||||||
|
sgard restore # touch your key when prompted
|
||||||
|
```
|
||||||
|
|
||||||
The encryption config (wrapped DEKs, salts) lives in the manifest, so
|
The encryption config (wrapped DEKs, salts) lives in the manifest, so
|
||||||
it syncs with push/pull. The server never has the DEK.
|
it syncs with push/pull. The server never has the DEK.
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
|
|
||||||
"github.com/kisom/sgard/garden"
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/kisom/sgard/manifest"
|
||||||
"github.com/kisom/sgard/server"
|
"github.com/kisom/sgard/server"
|
||||||
"github.com/kisom/sgard/sgardpb"
|
"github.com/kisom/sgard/sgardpb"
|
||||||
"golang.org/x/crypto/ssh"
|
"golang.org/x/crypto/ssh"
|
||||||
@@ -205,8 +206,8 @@ func (c *Client) doPull(ctx context.Context, g *garden.Garden) (int, error) {
|
|||||||
serverManifest := server.ProtoToManifest(pullResp.GetManifest())
|
serverManifest := server.ProtoToManifest(pullResp.GetManifest())
|
||||||
localManifest := g.GetManifest()
|
localManifest := g.GetManifest()
|
||||||
|
|
||||||
// If local is newer or equal, nothing to do.
|
// If local has files and is newer or equal, nothing to do.
|
||||||
if !serverManifest.Updated.After(localManifest.Updated) {
|
if len(localManifest.Files) > 0 && !serverManifest.Updated.After(localManifest.Updated) {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,6 +274,22 @@ func (c *Client) doPull(ctx context.Context, g *garden.Garden) (int, error) {
|
|||||||
return blobCount, nil
|
return blobCount, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// List fetches the server's manifest and returns its entries without
|
||||||
|
// downloading any blobs. Automatically re-authenticates if needed.
|
||||||
|
func (c *Client) List(ctx context.Context) ([]manifest.Entry, error) {
|
||||||
|
var entries []manifest.Entry
|
||||||
|
err := c.retryOnAuth(ctx, func() error {
|
||||||
|
resp, err := c.rpc.PullManifest(ctx, &sgardpb.PullManifestRequest{})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list remote: %w", err)
|
||||||
|
}
|
||||||
|
m := server.ProtoToManifest(resp.GetManifest())
|
||||||
|
entries = m.Files
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
return entries, err
|
||||||
|
}
|
||||||
|
|
||||||
// Prune requests the server to remove orphaned blobs. Returns the count removed.
|
// Prune requests the server to remove orphaned blobs. Returns the count removed.
|
||||||
// Automatically re-authenticates if needed.
|
// Automatically re-authenticates if needed.
|
||||||
func (c *Client) Prune(ctx context.Context) (int, error) {
|
func (c *Client) Prune(ctx context.Context) (int, error) {
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/kisom/sgard/garden"
|
"github.com/kisom/sgard/garden"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
"golang.org/x/term"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
encryptFlag bool
|
encryptFlag bool
|
||||||
lockFlag bool
|
lockFlag bool
|
||||||
dirOnlyFlag bool
|
dirOnlyFlag bool
|
||||||
|
onlyFlag []string
|
||||||
|
neverFlag []string
|
||||||
)
|
)
|
||||||
|
|
||||||
var addCmd = &cobra.Command{
|
var addCmd = &cobra.Command{
|
||||||
@@ -30,15 +31,21 @@ var addCmd = &cobra.Command{
|
|||||||
if !g.HasEncryption() {
|
if !g.HasEncryption() {
|
||||||
return fmt.Errorf("encryption not initialized; run sgard encrypt init first")
|
return fmt.Errorf("encryption not initialized; run sgard encrypt init first")
|
||||||
}
|
}
|
||||||
if err := g.UnlockDEK(promptPassphrase); err != nil {
|
if err := unlockDEK(g); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(onlyFlag) > 0 && len(neverFlag) > 0 {
|
||||||
|
return fmt.Errorf("--only and --never are mutually exclusive")
|
||||||
|
}
|
||||||
|
|
||||||
opts := garden.AddOptions{
|
opts := garden.AddOptions{
|
||||||
Encrypt: encryptFlag,
|
Encrypt: encryptFlag,
|
||||||
Lock: lockFlag,
|
Lock: lockFlag,
|
||||||
DirOnly: dirOnlyFlag,
|
DirOnly: dirOnlyFlag,
|
||||||
|
Only: onlyFlag,
|
||||||
|
Never: neverFlag,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.Add(args, opts); err != nil {
|
if err := g.Add(args, opts); err != nil {
|
||||||
@@ -52,16 +59,23 @@ var addCmd = &cobra.Command{
|
|||||||
|
|
||||||
func promptPassphrase() (string, error) {
|
func promptPassphrase() (string, error) {
|
||||||
fmt.Fprint(os.Stderr, "Passphrase: ")
|
fmt.Fprint(os.Stderr, "Passphrase: ")
|
||||||
scanner := bufio.NewScanner(os.Stdin)
|
fd := int(os.Stdin.Fd())
|
||||||
if scanner.Scan() {
|
passphrase, err := term.ReadPassword(fd)
|
||||||
return strings.TrimSpace(scanner.Text()), nil
|
fmt.Fprintln(os.Stderr)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("reading passphrase: %w", err)
|
||||||
}
|
}
|
||||||
|
if len(passphrase) == 0 {
|
||||||
return "", fmt.Errorf("no passphrase provided")
|
return "", fmt.Errorf("no passphrase provided")
|
||||||
|
}
|
||||||
|
return string(passphrase), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
addCmd.Flags().BoolVar(&encryptFlag, "encrypt", false, "encrypt file contents before storing")
|
addCmd.Flags().BoolVar(&encryptFlag, "encrypt", false, "encrypt file contents before storing")
|
||||||
addCmd.Flags().BoolVar(&lockFlag, "lock", false, "mark as locked (repo-authoritative, restore always overwrites)")
|
addCmd.Flags().BoolVar(&lockFlag, "lock", false, "mark as locked (repo-authoritative, restore always overwrites)")
|
||||||
addCmd.Flags().BoolVar(&dirOnlyFlag, "dir", false, "track directory itself without recursing into contents")
|
addCmd.Flags().BoolVar(&dirOnlyFlag, "dir", false, "track directory itself without recursing into contents")
|
||||||
|
addCmd.Flags().StringSliceVar(&onlyFlag, "only", nil, "only apply on machines matching these labels (comma-separated)")
|
||||||
|
addCmd.Flags().StringSliceVar(&neverFlag, "never", nil, "never apply on machines matching these labels (comma-separated)")
|
||||||
rootCmd.AddCommand(addCmd)
|
rootCmd.AddCommand(addCmd)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ var checkpointCmd = &cobra.Command{
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if g.HasEncryption() && g.NeedsDEK(g.List()) {
|
||||||
|
if err := unlockDEK(g); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err := g.Checkpoint(checkpointMessage); err != nil {
|
if err := g.Checkpoint(checkpointMessage); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,12 @@ var diffCmd = &cobra.Command{
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if g.HasEncryption() && g.NeedsDEK(g.List()) {
|
||||||
|
if err := unlockDEK(g); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
d, err := g.Diff(args[0])
|
d, err := g.Diff(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -36,8 +36,16 @@ var encryptInitCmd = &cobra.Command{
|
|||||||
fmt.Println("Encryption initialized with passphrase slot.")
|
fmt.Println("Encryption initialized with passphrase slot.")
|
||||||
|
|
||||||
if fido2InitFlag {
|
if fido2InitFlag {
|
||||||
fmt.Println("FIDO2 support requires a hardware device implementation.")
|
device := garden.DetectHardwareFIDO2(fido2PinFlag)
|
||||||
fmt.Println("Run 'sgard encrypt add-fido2' when a FIDO2 device is available.")
|
if device == nil {
|
||||||
|
fmt.Println("No FIDO2 device detected. Run 'sgard encrypt add-fido2' when one is connected.")
|
||||||
|
} else {
|
||||||
|
fmt.Println("Touch your FIDO2 device to register...")
|
||||||
|
if err := g.AddFIDO2Slot(device, fido2LabelFlag); err != nil {
|
||||||
|
return fmt.Errorf("adding FIDO2 slot: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Println("FIDO2 slot added.")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -59,13 +67,22 @@ var addFido2Cmd = &cobra.Command{
|
|||||||
return fmt.Errorf("encryption not initialized; run sgard encrypt init first")
|
return fmt.Errorf("encryption not initialized; run sgard encrypt init first")
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.UnlockDEK(promptPassphrase); err != nil {
|
if err := unlockDEK(g); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Real FIDO2 device implementation would go here.
|
device := garden.DetectHardwareFIDO2(fido2PinFlag)
|
||||||
// For now, this is a placeholder that explains the requirement.
|
if device == nil {
|
||||||
return fmt.Errorf("FIDO2 hardware support not yet implemented; requires libfido2 binding")
|
return fmt.Errorf("no FIDO2 device detected; connect a FIDO2 key and try again")
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Touch your FIDO2 device to register...")
|
||||||
|
if err := g.AddFIDO2Slot(device, fido2LabelFlag); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("FIDO2 slot added.")
|
||||||
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,9 +147,8 @@ var changePassphraseCmd = &cobra.Command{
|
|||||||
return fmt.Errorf("encryption not initialized")
|
return fmt.Errorf("encryption not initialized")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unlock with current passphrase.
|
// Unlock with current credentials.
|
||||||
fmt.Println("Enter current passphrase:")
|
if err := unlockDEK(g); err != nil {
|
||||||
if err := g.UnlockDEK(promptPassphrase); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,8 +168,39 @@ var changePassphraseCmd = &cobra.Command{
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var rotateDEKCmd = &cobra.Command{
|
||||||
|
Use: "rotate-dek",
|
||||||
|
Short: "Generate a new DEK and re-encrypt all encrypted blobs",
|
||||||
|
Long: "Generates a new data encryption key, re-encrypts all encrypted blobs, and re-wraps the DEK with all KEK slots. Required when the DEK is suspected compromised.",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !g.HasEncryption() {
|
||||||
|
return fmt.Errorf("encryption not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlock with current credentials.
|
||||||
|
if err := unlockDEK(g); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate — re-prompts for passphrase to re-wrap slot.
|
||||||
|
fmt.Println("Enter passphrase to re-wrap DEK:")
|
||||||
|
device := garden.DetectHardwareFIDO2(fido2PinFlag)
|
||||||
|
if err := g.RotateDEK(promptPassphrase, device); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("DEK rotated. All encrypted blobs re-encrypted.")
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
encryptInitCmd.Flags().BoolVar(&fido2InitFlag, "fido2", false, "also set up FIDO2 (placeholder)")
|
encryptInitCmd.Flags().BoolVar(&fido2InitFlag, "fido2", false, "also register a FIDO2 hardware key")
|
||||||
addFido2Cmd.Flags().StringVar(&fido2LabelFlag, "label", "", "slot label (default: fido2/<hostname>)")
|
addFido2Cmd.Flags().StringVar(&fido2LabelFlag, "label", "", "slot label (default: fido2/<hostname>)")
|
||||||
|
|
||||||
encryptCmd.AddCommand(encryptInitCmd)
|
encryptCmd.AddCommand(encryptInitCmd)
|
||||||
@@ -161,6 +208,7 @@ func init() {
|
|||||||
encryptCmd.AddCommand(removeSlotCmd)
|
encryptCmd.AddCommand(removeSlotCmd)
|
||||||
encryptCmd.AddCommand(listSlotsCmd)
|
encryptCmd.AddCommand(listSlotsCmd)
|
||||||
encryptCmd.AddCommand(changePassphraseCmd)
|
encryptCmd.AddCommand(changePassphraseCmd)
|
||||||
|
encryptCmd.AddCommand(rotateDEKCmd)
|
||||||
|
|
||||||
rootCmd.AddCommand(encryptCmd)
|
rootCmd.AddCommand(encryptCmd)
|
||||||
}
|
}
|
||||||
|
|||||||
65
cmd/sgard/exclude.go
Normal file
65
cmd/sgard/exclude.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var listExclude bool
|
||||||
|
|
||||||
|
var excludeCmd = &cobra.Command{
|
||||||
|
Use: "exclude [path...]",
|
||||||
|
Short: "Exclude paths from tracking",
|
||||||
|
Long: "Add paths to the exclusion list. Excluded paths are skipped during add and mirror operations. Use --list to show current exclusions.",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if listExclude {
|
||||||
|
for _, p := range g.GetManifest().Exclude {
|
||||||
|
fmt.Println(p)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("provide paths to exclude, or use --list")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Exclude(args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Excluded %d path(s)\n", len(args))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var includeCmd = &cobra.Command{
|
||||||
|
Use: "include <path>...",
|
||||||
|
Short: "Remove paths from the exclusion list",
|
||||||
|
Args: cobra.MinimumNArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Include(args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Included %d path(s)\n", len(args))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
excludeCmd.Flags().BoolVarP(&listExclude, "list", "l", false, "list current exclusions")
|
||||||
|
rootCmd.AddCommand(excludeCmd)
|
||||||
|
rootCmd.AddCommand(includeCmd)
|
||||||
|
}
|
||||||
12
cmd/sgard/fido2.go
Normal file
12
cmd/sgard/fido2.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "github.com/kisom/sgard/garden"
|
||||||
|
|
||||||
|
var fido2PinFlag string
|
||||||
|
|
||||||
|
// unlockDEK attempts to unlock the DEK, trying FIDO2 hardware first
|
||||||
|
// (if available) and falling back to passphrase.
|
||||||
|
func unlockDEK(g *garden.Garden) error {
|
||||||
|
device := garden.DetectHardwareFIDO2(fido2PinFlag)
|
||||||
|
return g.UnlockDEK(promptPassphrase, device)
|
||||||
|
}
|
||||||
27
cmd/sgard/identity.go
Normal file
27
cmd/sgard/identity.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var identityCmd = &cobra.Command{
|
||||||
|
Use: "identity",
|
||||||
|
Short: "Show this machine's identity labels",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, label := range g.Identity() {
|
||||||
|
fmt.Println(label)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(identityCmd)
|
||||||
|
}
|
||||||
79
cmd/sgard/info.go
Normal file
79
cmd/sgard/info.go
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var infoCmd = &cobra.Command{
|
||||||
|
Use: "info <path>",
|
||||||
|
Short: "Show detailed information about a tracked file",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := g.Info(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Path: %s\n", fi.Path)
|
||||||
|
fmt.Printf("Type: %s\n", fi.Type)
|
||||||
|
fmt.Printf("Status: %s\n", fi.State)
|
||||||
|
fmt.Printf("Mode: %s\n", fi.Mode)
|
||||||
|
|
||||||
|
if fi.Locked {
|
||||||
|
fmt.Printf("Locked: yes\n")
|
||||||
|
}
|
||||||
|
if fi.Encrypted {
|
||||||
|
fmt.Printf("Encrypted: yes\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
if fi.Updated != "" {
|
||||||
|
fmt.Printf("Updated: %s\n", fi.Updated)
|
||||||
|
}
|
||||||
|
if fi.DiskModTime != "" {
|
||||||
|
fmt.Printf("Disk mtime: %s\n", fi.DiskModTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch fi.Type {
|
||||||
|
case "file":
|
||||||
|
fmt.Printf("Hash: %s\n", fi.Hash)
|
||||||
|
if fi.CurrentHash != "" && fi.CurrentHash != fi.Hash {
|
||||||
|
fmt.Printf("Disk hash: %s\n", fi.CurrentHash)
|
||||||
|
}
|
||||||
|
if fi.PlaintextHash != "" {
|
||||||
|
fmt.Printf("PT hash: %s\n", fi.PlaintextHash)
|
||||||
|
}
|
||||||
|
if fi.BlobStored {
|
||||||
|
fmt.Printf("Blob: stored\n")
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Blob: missing\n")
|
||||||
|
}
|
||||||
|
case "link":
|
||||||
|
fmt.Printf("Target: %s\n", fi.Target)
|
||||||
|
if fi.CurrentTarget != "" && fi.CurrentTarget != fi.Target {
|
||||||
|
fmt.Printf("Disk target: %s\n", fi.CurrentTarget)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(fi.Only) > 0 {
|
||||||
|
fmt.Printf("Only: %s\n", strings.Join(fi.Only, ", "))
|
||||||
|
}
|
||||||
|
if len(fi.Never) > 0 {
|
||||||
|
fmt.Printf("Never: %s\n", strings.Join(fi.Never, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(infoCmd)
|
||||||
|
}
|
||||||
@@ -1,22 +1,56 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/kisom/sgard/garden"
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/kisom/sgard/manifest"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
var listCmd = &cobra.Command{
|
var listCmd = &cobra.Command{
|
||||||
Use: "list",
|
Use: "list",
|
||||||
Short: "List all tracked files",
|
Short: "List all tracked files",
|
||||||
|
Long: "List all tracked files locally, or on the remote server with -r.",
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
addr, _, _, _ := resolveRemoteConfig()
|
||||||
|
if addr != "" {
|
||||||
|
return listRemote()
|
||||||
|
}
|
||||||
|
return listLocal()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func listLocal() error {
|
||||||
g, err := garden.Open(repoFlag)
|
g, err := garden.Open(repoFlag)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
entries := g.List()
|
printEntries(g.List())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func listRemote() error {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
c, cleanup, err := dialRemote(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
entries, err := c.List(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
printEntries(entries)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printEntries(entries []manifest.Entry) {
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
switch e.Type {
|
switch e.Type {
|
||||||
case "file":
|
case "file":
|
||||||
@@ -31,9 +65,6 @@ var listCmd = &cobra.Command{
|
|||||||
fmt.Printf("%-6s %s\n", "dir", e.Path)
|
fmt.Printf("%-6s %s\n", "dir", e.Path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
51
cmd/sgard/lock.go
Normal file
51
cmd/sgard/lock.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var lockCmd = &cobra.Command{
|
||||||
|
Use: "lock <path>...",
|
||||||
|
Short: "Mark tracked files as locked (repo-authoritative)",
|
||||||
|
Args: cobra.MinimumNArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Lock(args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Locked %d path(s).\n", len(args))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var unlockCmd = &cobra.Command{
|
||||||
|
Use: "unlock <path>...",
|
||||||
|
Short: "Remove locked flag from tracked files",
|
||||||
|
Args: cobra.MinimumNArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Unlock(args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Unlocked %d path(s).\n", len(args))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(lockCmd)
|
||||||
|
rootCmd.AddCommand(unlockCmd)
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -10,6 +12,7 @@ import (
|
|||||||
"github.com/kisom/sgard/client"
|
"github.com/kisom/sgard/client"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials"
|
||||||
"google.golang.org/grpc/credentials/insecure"
|
"google.golang.org/grpc/credentials/insecure"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,6 +20,8 @@ var (
|
|||||||
repoFlag string
|
repoFlag string
|
||||||
remoteFlag string
|
remoteFlag string
|
||||||
sshKeyFlag string
|
sshKeyFlag string
|
||||||
|
tlsFlag bool
|
||||||
|
tlsCAFlag string
|
||||||
)
|
)
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
@@ -32,28 +37,49 @@ func defaultRepo() string {
|
|||||||
return filepath.Join(home, ".sgard")
|
return filepath.Join(home, ".sgard")
|
||||||
}
|
}
|
||||||
|
|
||||||
// resolveRemote returns the remote address from flag, env, or repo config file.
|
// resolveRemoteConfig returns the effective remote address, TLS flag, and CA
|
||||||
func resolveRemote() (string, error) {
|
// path by merging CLI flags, environment, and the saved remote.yaml config.
|
||||||
if remoteFlag != "" {
|
// CLI flags take precedence, then env, then the saved config.
|
||||||
return remoteFlag, nil
|
func resolveRemoteConfig() (addr string, useTLS bool, caPath string, err error) {
|
||||||
|
// Start with saved config as baseline.
|
||||||
|
saved, _ := loadRemoteConfig()
|
||||||
|
|
||||||
|
// Address: flag > env > saved > legacy file.
|
||||||
|
addr = remoteFlag
|
||||||
|
if addr == "" {
|
||||||
|
addr = os.Getenv("SGARD_REMOTE")
|
||||||
}
|
}
|
||||||
if env := os.Getenv("SGARD_REMOTE"); env != "" {
|
if addr == "" && saved != nil {
|
||||||
return env, nil
|
addr = saved.Addr
|
||||||
}
|
}
|
||||||
// Try <repo>/remote file.
|
if addr == "" {
|
||||||
data, err := os.ReadFile(filepath.Join(repoFlag, "remote"))
|
data, ferr := os.ReadFile(filepath.Join(repoFlag, "remote"))
|
||||||
if err == nil {
|
if ferr == nil {
|
||||||
addr := strings.TrimSpace(string(data))
|
addr = strings.TrimSpace(string(data))
|
||||||
if addr != "" {
|
|
||||||
return addr, nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "", fmt.Errorf("no remote configured; use --remote, SGARD_REMOTE, or create %s/remote", repoFlag)
|
if addr == "" {
|
||||||
|
return "", false, "", fmt.Errorf("no remote configured; use 'sgard remote set' or --remote")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TLS: flag wins if explicitly set, otherwise use saved.
|
||||||
|
useTLS = tlsFlag
|
||||||
|
if !useTLS && saved != nil {
|
||||||
|
useTLS = saved.TLS
|
||||||
|
}
|
||||||
|
|
||||||
|
// CA: flag wins if set, otherwise use saved.
|
||||||
|
caPath = tlsCAFlag
|
||||||
|
if caPath == "" && saved != nil {
|
||||||
|
caPath = saved.TLSCA
|
||||||
|
}
|
||||||
|
|
||||||
|
return addr, useTLS, caPath, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// dialRemote creates a gRPC client with token-based auth and auto-renewal.
|
// dialRemote creates a gRPC client with token-based auth and auto-renewal.
|
||||||
func dialRemote(ctx context.Context) (*client.Client, func(), error) {
|
func dialRemote(ctx context.Context) (*client.Client, func(), error) {
|
||||||
addr, err := resolveRemote()
|
addr, useTLS, caPath, err := resolveRemoteConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
@@ -66,8 +92,27 @@ func dialRemote(ctx context.Context) (*client.Client, func(), error) {
|
|||||||
cachedToken := client.LoadCachedToken()
|
cachedToken := client.LoadCachedToken()
|
||||||
creds := client.NewTokenCredentials(cachedToken)
|
creds := client.NewTokenCredentials(cachedToken)
|
||||||
|
|
||||||
|
var transportCreds grpc.DialOption
|
||||||
|
if useTLS {
|
||||||
|
tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
|
||||||
|
if caPath != "" {
|
||||||
|
caPEM, err := os.ReadFile(caPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("reading CA cert: %w", err)
|
||||||
|
}
|
||||||
|
pool := x509.NewCertPool()
|
||||||
|
if !pool.AppendCertsFromPEM(caPEM) {
|
||||||
|
return nil, nil, fmt.Errorf("failed to parse CA cert %s", caPath)
|
||||||
|
}
|
||||||
|
tlsCfg.RootCAs = pool
|
||||||
|
}
|
||||||
|
transportCreds = grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg))
|
||||||
|
} else {
|
||||||
|
transportCreds = grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||||
|
}
|
||||||
|
|
||||||
conn, err := grpc.NewClient(addr,
|
conn, err := grpc.NewClient(addr,
|
||||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
transportCreds,
|
||||||
grpc.WithPerRPCCredentials(creds),
|
grpc.WithPerRPCCredentials(creds),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -88,8 +133,11 @@ func dialRemote(ctx context.Context) (*client.Client, func(), error) {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
rootCmd.PersistentFlags().StringVar(&repoFlag, "repo", defaultRepo(), "path to sgard repository")
|
rootCmd.PersistentFlags().StringVar(&repoFlag, "repo", defaultRepo(), "path to sgard repository")
|
||||||
rootCmd.PersistentFlags().StringVar(&remoteFlag, "remote", "", "gRPC server address (host:port)")
|
rootCmd.PersistentFlags().StringVarP(&remoteFlag, "remote", "r", "", "gRPC server address (host:port)")
|
||||||
rootCmd.PersistentFlags().StringVar(&sshKeyFlag, "ssh-key", "", "path to SSH private key")
|
rootCmd.PersistentFlags().StringVar(&sshKeyFlag, "ssh-key", "", "path to SSH private key")
|
||||||
|
rootCmd.PersistentFlags().BoolVar(&tlsFlag, "tls", false, "use TLS for remote connection")
|
||||||
|
rootCmd.PersistentFlags().StringVar(&tlsCAFlag, "tls-ca", "", "path to CA certificate for TLS verification")
|
||||||
|
rootCmd.PersistentFlags().StringVar(&fido2PinFlag, "fido2-pin", "", "PIN for FIDO2 device (if PIN-protected)")
|
||||||
|
|
||||||
if err := rootCmd.Execute(); err != nil {
|
if err := rootCmd.Execute(); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, err)
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ var pruneCmd = &cobra.Command{
|
|||||||
Short: "Remove orphaned blobs not referenced by the manifest",
|
Short: "Remove orphaned blobs not referenced by the manifest",
|
||||||
Long: "Remove orphaned blobs locally, or on the remote server with --remote.",
|
Long: "Remove orphaned blobs locally, or on the remote server with --remote.",
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
addr, _ := resolveRemote()
|
addr, _, _, _ := resolveRemoteConfig()
|
||||||
|
|
||||||
if addr != "" {
|
if addr != "" {
|
||||||
return pruneRemote()
|
return pruneRemote()
|
||||||
|
|||||||
@@ -10,13 +10,17 @@ import (
|
|||||||
|
|
||||||
var pullCmd = &cobra.Command{
|
var pullCmd = &cobra.Command{
|
||||||
Use: "pull",
|
Use: "pull",
|
||||||
Short: "Pull checkpoint from remote server",
|
Short: "Pull checkpoint from remote server and restore files",
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
g, err := garden.Open(repoFlag)
|
g, err := garden.Open(repoFlag)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
// Repo doesn't exist yet — init it so pull can populate it.
|
||||||
|
g, err = garden.Init(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("init repo for pull: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
c, cleanup, err := dialRemote(ctx)
|
c, cleanup, err := dialRemote(ctx)
|
||||||
@@ -32,9 +36,22 @@ var pullCmd = &cobra.Command{
|
|||||||
|
|
||||||
if pulled == 0 {
|
if pulled == 0 {
|
||||||
fmt.Println("Already up to date.")
|
fmt.Println("Already up to date.")
|
||||||
} else {
|
return nil
|
||||||
fmt.Printf("Pulled %d blob(s).\n", pulled)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Pulled %d blob(s).\n", pulled)
|
||||||
|
|
||||||
|
if g.HasEncryption() && g.NeedsDEK(g.List()) {
|
||||||
|
if err := unlockDEK(g); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Restore(nil, true, nil); err != nil {
|
||||||
|
return fmt.Errorf("restore after pull: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Restore complete.")
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
97
cmd/sgard/remote.go
Normal file
97
cmd/sgard/remote.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type remoteConfig struct {
|
||||||
|
Addr string `yaml:"addr"`
|
||||||
|
TLS bool `yaml:"tls"`
|
||||||
|
TLSCA string `yaml:"tls_ca,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func remoteConfigPath() string {
|
||||||
|
return filepath.Join(repoFlag, "remote.yaml")
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadRemoteConfig() (*remoteConfig, error) {
|
||||||
|
data, err := os.ReadFile(remoteConfigPath())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var cfg remoteConfig
|
||||||
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing remote config: %w", err)
|
||||||
|
}
|
||||||
|
return &cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveRemoteConfig(cfg *remoteConfig) error {
|
||||||
|
data, err := yaml.Marshal(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encoding remote config: %w", err)
|
||||||
|
}
|
||||||
|
return os.WriteFile(remoteConfigPath(), data, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
var remoteCmd = &cobra.Command{
|
||||||
|
Use: "remote",
|
||||||
|
Short: "Manage default remote server",
|
||||||
|
}
|
||||||
|
|
||||||
|
var remoteSetCmd = &cobra.Command{
|
||||||
|
Use: "set <addr>",
|
||||||
|
Short: "Set the default remote address",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
cfg := &remoteConfig{
|
||||||
|
Addr: args[0],
|
||||||
|
TLS: tlsFlag,
|
||||||
|
TLSCA: tlsCAFlag,
|
||||||
|
}
|
||||||
|
if err := saveRemoteConfig(cfg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("Remote set: %s", cfg.Addr)
|
||||||
|
if cfg.TLS {
|
||||||
|
fmt.Print(" (TLS")
|
||||||
|
if cfg.TLSCA != "" {
|
||||||
|
fmt.Printf(", CA: %s", cfg.TLSCA)
|
||||||
|
}
|
||||||
|
fmt.Print(")")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var remoteShowCmd = &cobra.Command{
|
||||||
|
Use: "show",
|
||||||
|
Short: "Show the configured remote",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
cfg, err := loadRemoteConfig()
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
fmt.Println("No remote configured.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("addr: %s\n", cfg.Addr)
|
||||||
|
fmt.Printf("tls: %v\n", cfg.TLS)
|
||||||
|
if cfg.TLSCA != "" {
|
||||||
|
fmt.Printf("tls-ca: %s\n", cfg.TLSCA)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
remoteCmd.AddCommand(remoteSetCmd, remoteShowCmd)
|
||||||
|
rootCmd.AddCommand(remoteCmd)
|
||||||
|
}
|
||||||
@@ -21,6 +21,12 @@ var restoreCmd = &cobra.Command{
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if g.HasEncryption() && g.NeedsDEK(g.List()) {
|
||||||
|
if err := unlockDEK(g); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
confirm := func(path string) bool {
|
confirm := func(path string) bool {
|
||||||
fmt.Printf("Overwrite %s? [y/N] ", path)
|
fmt.Printf("Overwrite %s? [y/N] ", path)
|
||||||
scanner := bufio.NewScanner(os.Stdin)
|
scanner := bufio.NewScanner(os.Stdin)
|
||||||
|
|||||||
76
cmd/sgard/tag.go
Normal file
76
cmd/sgard/tag.go
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var tagCmd = &cobra.Command{
|
||||||
|
Use: "tag",
|
||||||
|
Short: "Manage machine tags for per-machine targeting",
|
||||||
|
}
|
||||||
|
|
||||||
|
var tagAddCmd = &cobra.Command{
|
||||||
|
Use: "add <name>",
|
||||||
|
Short: "Add a tag to this machine",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := g.SaveTag(args[0]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("Tag %q added.\n", args[0])
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var tagRemoveCmd = &cobra.Command{
|
||||||
|
Use: "remove <name>",
|
||||||
|
Short: "Remove a tag from this machine",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := g.RemoveTag(args[0]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("Tag %q removed.\n", args[0])
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var tagListCmd = &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List tags on this machine",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tags := g.LoadTags()
|
||||||
|
if len(tags) == 0 {
|
||||||
|
fmt.Println("No tags set.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sort.Strings(tags)
|
||||||
|
for _, tag := range tags {
|
||||||
|
fmt.Println(tag)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
tagCmd.AddCommand(tagAddCmd)
|
||||||
|
tagCmd.AddCommand(tagRemoveCmd)
|
||||||
|
tagCmd.AddCommand(tagListCmd)
|
||||||
|
rootCmd.AddCommand(tagCmd)
|
||||||
|
}
|
||||||
48
cmd/sgard/target.go
Normal file
48
cmd/sgard/target.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
targetOnlyFlag []string
|
||||||
|
targetNeverFlag []string
|
||||||
|
targetClearFlag bool
|
||||||
|
)
|
||||||
|
|
||||||
|
var targetCmd = &cobra.Command{
|
||||||
|
Use: "target <path>",
|
||||||
|
Short: "Set or clear targeting labels on a tracked entry",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
g, err := garden.Open(repoFlag)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(targetOnlyFlag) > 0 && len(targetNeverFlag) > 0 {
|
||||||
|
return fmt.Errorf("--only and --never are mutually exclusive")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.SetTargeting(args[0], targetOnlyFlag, targetNeverFlag, targetClearFlag); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if targetClearFlag {
|
||||||
|
fmt.Printf("Cleared targeting for %s.\n", args[0])
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Updated targeting for %s.\n", args[0])
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
targetCmd.Flags().StringSliceVar(&targetOnlyFlag, "only", nil, "only apply on matching machines")
|
||||||
|
targetCmd.Flags().StringSliceVar(&targetNeverFlag, "never", nil, "never apply on matching machines")
|
||||||
|
targetCmd.Flags().BoolVar(&targetClearFlag, "clear", false, "remove all targeting labels")
|
||||||
|
rootCmd.AddCommand(targetCmd)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
@@ -10,12 +11,15 @@ import (
|
|||||||
"github.com/kisom/sgard/sgardpb"
|
"github.com/kisom/sgard/sgardpb"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
listenAddr string
|
listenAddr string
|
||||||
repoPath string
|
repoPath string
|
||||||
authKeysPath string
|
authKeysPath string
|
||||||
|
tlsCertPath string
|
||||||
|
tlsKeyPath string
|
||||||
)
|
)
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
@@ -28,6 +32,21 @@ var rootCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
var opts []grpc.ServerOption
|
var opts []grpc.ServerOption
|
||||||
|
|
||||||
|
if tlsCertPath != "" && tlsKeyPath != "" {
|
||||||
|
cert, err := tls.LoadX509KeyPair(tlsCertPath, tlsKeyPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("loading TLS cert/key: %w", err)
|
||||||
|
}
|
||||||
|
opts = append(opts, grpc.Creds(credentials.NewTLS(&tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})))
|
||||||
|
fmt.Println("TLS enabled")
|
||||||
|
} else if tlsCertPath != "" || tlsKeyPath != "" {
|
||||||
|
return fmt.Errorf("both --tls-cert and --tls-key must be specified together")
|
||||||
|
}
|
||||||
|
|
||||||
var srvInstance *server.Server
|
var srvInstance *server.Server
|
||||||
|
|
||||||
if authKeysPath != "" {
|
if authKeysPath != "" {
|
||||||
@@ -63,6 +82,8 @@ func main() {
|
|||||||
rootCmd.Flags().StringVar(&listenAddr, "listen", ":9473", "gRPC listen address")
|
rootCmd.Flags().StringVar(&listenAddr, "listen", ":9473", "gRPC listen address")
|
||||||
rootCmd.Flags().StringVar(&repoPath, "repo", "/srv/sgard", "path to sgard repository")
|
rootCmd.Flags().StringVar(&repoPath, "repo", "/srv/sgard", "path to sgard repository")
|
||||||
rootCmd.Flags().StringVar(&authKeysPath, "authorized-keys", "", "path to authorized SSH public keys file")
|
rootCmd.Flags().StringVar(&authKeysPath, "authorized-keys", "", "path to authorized SSH public keys file")
|
||||||
|
rootCmd.Flags().StringVar(&tlsCertPath, "tls-cert", "", "path to TLS certificate file")
|
||||||
|
rootCmd.Flags().StringVar(&tlsKeyPath, "tls-key", "", "path to TLS private key file")
|
||||||
|
|
||||||
if err := rootCmd.Execute(); err != nil {
|
if err := rootCmd.Execute(); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, err)
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
|||||||
30
deploy/docker/Dockerfile
Normal file
30
deploy/docker/Dockerfile
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Build stage
|
||||||
|
FROM golang:1.25-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /build
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
ARG VERSION=dev
|
||||||
|
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /sgardd ./cmd/sgardd
|
||||||
|
|
||||||
|
# Runtime stage
|
||||||
|
FROM alpine:3.21
|
||||||
|
|
||||||
|
RUN apk add --no-cache ca-certificates tzdata \
|
||||||
|
&& adduser -D -h /srv/sgard sgard
|
||||||
|
|
||||||
|
COPY --from=builder /sgardd /usr/local/bin/sgardd
|
||||||
|
|
||||||
|
VOLUME /srv/sgard
|
||||||
|
EXPOSE 9473
|
||||||
|
|
||||||
|
USER sgard
|
||||||
|
|
||||||
|
ENTRYPOINT ["sgardd", \
|
||||||
|
"--repo", "/srv/sgard", \
|
||||||
|
"--authorized-keys", "/srv/sgard/authorized_keys", \
|
||||||
|
"--tls-cert", "/srv/sgard/certs/sgard.pem", \
|
||||||
|
"--tls-key", "/srv/sgard/certs/sgard.key"]
|
||||||
16
deploy/docker/docker-compose-rift.yml
Normal file
16
deploy/docker/docker-compose-rift.yml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
services:
|
||||||
|
sgardd:
|
||||||
|
image: localhost/sgardd:latest
|
||||||
|
container_name: sgardd
|
||||||
|
restart: unless-stopped
|
||||||
|
user: "0:0"
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:19473:9473"
|
||||||
|
volumes:
|
||||||
|
- /srv/sgard:/srv/sgard
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "true"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
33
flake.nix
33
flake.nix
@@ -11,17 +11,20 @@
|
|||||||
let
|
let
|
||||||
pkgs = import nixpkgs { inherit system; };
|
pkgs = import nixpkgs { inherit system; };
|
||||||
in
|
in
|
||||||
|
let
|
||||||
|
version = builtins.replaceStrings [ "\n" ] [ "" ] (builtins.readFile ./VERSION);
|
||||||
|
in
|
||||||
{
|
{
|
||||||
packages = {
|
packages = {
|
||||||
sgard = pkgs.buildGoModule {
|
sgard = pkgs.buildGoModule rec {
|
||||||
pname = "sgard";
|
pname = "sgard";
|
||||||
version = "2.0.0";
|
inherit version;
|
||||||
src = pkgs.lib.cleanSource ./.;
|
src = pkgs.lib.cleanSource ./.;
|
||||||
subPackages = [ "cmd/sgard" "cmd/sgardd" ];
|
subPackages = [ "cmd/sgard" "cmd/sgardd" ];
|
||||||
|
|
||||||
vendorHash = "sha256-0YpP1YfpAIAgY8k+7DlWosYN6MT5a2KLtNhQFvKT7pM=";
|
vendorHash = "sha256-Z/Ja4j7YesNYefQQcWWRG2v8WuIL+UNqPGwYD5AipZY=";
|
||||||
|
|
||||||
ldflags = [ "-s" "-w" ];
|
ldflags = [ "-s" "-w" "-X main.version=${version}" ];
|
||||||
|
|
||||||
meta = {
|
meta = {
|
||||||
description = "Shimmering Clarity Gardener: dotfile management";
|
description = "Shimmering Clarity Gardener: dotfile management";
|
||||||
@@ -29,6 +32,26 @@
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
sgard-fido2 = pkgs.buildGoModule rec {
|
||||||
|
pname = "sgard-fido2";
|
||||||
|
inherit version;
|
||||||
|
src = pkgs.lib.cleanSource ./.;
|
||||||
|
subPackages = [ "cmd/sgard" "cmd/sgardd" ];
|
||||||
|
|
||||||
|
vendorHash = "sha256-Z/Ja4j7YesNYefQQcWWRG2v8WuIL+UNqPGwYD5AipZY=";
|
||||||
|
|
||||||
|
buildInputs = [ pkgs.libfido2 ];
|
||||||
|
nativeBuildInputs = [ pkgs.pkg-config ];
|
||||||
|
tags = [ "fido2" ];
|
||||||
|
|
||||||
|
ldflags = [ "-s" "-w" "-X main.version=${version}" ];
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
description = "Shimmering Clarity Gardener: dotfile management (with FIDO2 hardware support)";
|
||||||
|
mainProgram = "sgard";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
default = self.packages.${system}.sgard;
|
default = self.packages.${system}.sgard;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -39,6 +62,8 @@
|
|||||||
protobuf
|
protobuf
|
||||||
protoc-gen-go
|
protoc-gen-go
|
||||||
protoc-gen-go-grpc
|
protoc-gen-go-grpc
|
||||||
|
libfido2
|
||||||
|
pkg-config
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -213,6 +213,140 @@ func (g *Garden) ChangePassphrase(newPassphrase string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RotateDEK generates a new DEK, re-encrypts all encrypted blobs, and
|
||||||
|
// re-wraps the new DEK with all existing KEK slots. The old DEK must
|
||||||
|
// already be unlocked. A passphrase prompt is required to re-derive
|
||||||
|
// the KEK for the passphrase slot. An optional FIDO2 device re-wraps
|
||||||
|
// FIDO2 slots; FIDO2 slots without a matching device are dropped.
|
||||||
|
func (g *Garden) RotateDEK(promptPassphrase func() (string, error), fido2Device ...FIDO2Device) error {
|
||||||
|
if g.dek == nil {
|
||||||
|
return fmt.Errorf("DEK not unlocked")
|
||||||
|
}
|
||||||
|
|
||||||
|
enc := g.manifest.Encryption
|
||||||
|
if enc == nil {
|
||||||
|
return fmt.Errorf("encryption not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
oldDEK := g.dek
|
||||||
|
|
||||||
|
// Generate new DEK.
|
||||||
|
newDEK := make([]byte, dekSize)
|
||||||
|
if _, err := rand.Read(newDEK); err != nil {
|
||||||
|
return fmt.Errorf("generating new DEK: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-encrypt all encrypted blobs.
|
||||||
|
for i := range g.manifest.Files {
|
||||||
|
entry := &g.manifest.Files[i]
|
||||||
|
if !entry.Encrypted || entry.Hash == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read encrypted blob.
|
||||||
|
ciphertext, err := g.store.Read(entry.Hash)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("reading blob %s for %s: %w", entry.Hash, entry.Path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt with old DEK.
|
||||||
|
g.dek = oldDEK
|
||||||
|
plaintext, err := g.decryptBlob(ciphertext)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("decrypting %s: %w", entry.Path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-encrypt with new DEK.
|
||||||
|
g.dek = newDEK
|
||||||
|
newCiphertext, err := g.encryptBlob(plaintext)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("re-encrypting %s: %w", entry.Path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write new blob.
|
||||||
|
newHash, err := g.store.Write(newCiphertext)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("writing re-encrypted blob for %s: %w", entry.Path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.Hash = newHash
|
||||||
|
// PlaintextHash stays the same — the plaintext didn't change.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-wrap new DEK with all existing KEK slots.
|
||||||
|
for name, slot := range enc.KekSlots {
|
||||||
|
var kek []byte
|
||||||
|
|
||||||
|
switch slot.Type {
|
||||||
|
case "passphrase":
|
||||||
|
if promptPassphrase == nil {
|
||||||
|
return fmt.Errorf("passphrase required to re-wrap slot %q", name)
|
||||||
|
}
|
||||||
|
passphrase, err := promptPassphrase()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("reading passphrase: %w", err)
|
||||||
|
}
|
||||||
|
salt, err := base64.StdEncoding.DecodeString(slot.Salt)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("decoding salt for slot %q: %w", name, err)
|
||||||
|
}
|
||||||
|
kek = derivePassphraseKEK(passphrase, salt, slot.Argon2Time, slot.Argon2Memory, slot.Argon2Threads)
|
||||||
|
|
||||||
|
case "fido2":
|
||||||
|
var device FIDO2Device
|
||||||
|
if len(fido2Device) > 0 {
|
||||||
|
device = fido2Device[0]
|
||||||
|
}
|
||||||
|
if device == nil || !device.Available() {
|
||||||
|
// Drop FIDO2 slots without a matching device.
|
||||||
|
delete(enc.KekSlots, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
credID, err := base64.StdEncoding.DecodeString(slot.CredentialID)
|
||||||
|
if err != nil {
|
||||||
|
delete(enc.KekSlots, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !device.MatchesCredential(credID) {
|
||||||
|
delete(enc.KekSlots, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
salt, err := base64.StdEncoding.DecodeString(slot.Salt)
|
||||||
|
if err != nil {
|
||||||
|
delete(enc.KekSlots, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fido2KEK, err := device.Derive(credID, salt)
|
||||||
|
if err != nil {
|
||||||
|
delete(enc.KekSlots, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(fido2KEK) < dekSize {
|
||||||
|
delete(enc.KekSlots, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
kek = fido2KEK[:dekSize]
|
||||||
|
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown slot type %q for slot %q", slot.Type, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
wrappedDEK, err := wrapDEK(newDEK, kek)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("re-wrapping DEK for slot %q: %w", name, err)
|
||||||
|
}
|
||||||
|
slot.WrappedDEK = base64.StdEncoding.EncodeToString(wrappedDEK)
|
||||||
|
}
|
||||||
|
|
||||||
|
g.dek = newDEK
|
||||||
|
|
||||||
|
if err := g.manifest.Save(g.manifestPath); err != nil {
|
||||||
|
return fmt.Errorf("saving manifest: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// NeedsDEK reports whether any of the given entries are encrypted.
|
// NeedsDEK reports whether any of the given entries are encrypted.
|
||||||
func (g *Garden) NeedsDEK(entries []manifest.Entry) bool {
|
func (g *Garden) NeedsDEK(entries []manifest.Entry) bool {
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
|
|||||||
239
garden/encrypt_rotate_test.go
Normal file
239
garden/encrypt_rotate_test.go
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRotateDEK(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
passphrase := "test-passphrase"
|
||||||
|
if err := g.EncryptInit(passphrase); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add an encrypted file and a plaintext file.
|
||||||
|
secretFile := filepath.Join(root, "secret")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret: %v", err)
|
||||||
|
}
|
||||||
|
plainFile := filepath.Join(root, "plain")
|
||||||
|
if err := os.WriteFile(plainFile, []byte("plain data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing plain: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{secretFile}, AddOptions{Encrypt: true}); err != nil {
|
||||||
|
t.Fatalf("Add encrypted: %v", err)
|
||||||
|
}
|
||||||
|
if err := g.Add([]string{plainFile}); err != nil {
|
||||||
|
t.Fatalf("Add plain: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record pre-rotation state.
|
||||||
|
var origEncHash, origEncPtHash, origPlainHash string
|
||||||
|
for _, e := range g.manifest.Files {
|
||||||
|
if e.Encrypted {
|
||||||
|
origEncHash = e.Hash
|
||||||
|
origEncPtHash = e.PlaintextHash
|
||||||
|
} else {
|
||||||
|
origPlainHash = e.Hash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
oldDEK := make([]byte, len(g.dek))
|
||||||
|
copy(oldDEK, g.dek)
|
||||||
|
|
||||||
|
// Rotate.
|
||||||
|
prompt := func() (string, error) { return passphrase, nil }
|
||||||
|
if err := g.RotateDEK(prompt); err != nil {
|
||||||
|
t.Fatalf("RotateDEK: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DEK should have changed.
|
||||||
|
if string(g.dek) == string(oldDEK) {
|
||||||
|
t.Error("DEK should change after rotation")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check manifest entries.
|
||||||
|
for _, e := range g.manifest.Files {
|
||||||
|
if e.Encrypted {
|
||||||
|
// Ciphertext hash should change (new nonce + new key).
|
||||||
|
if e.Hash == origEncHash {
|
||||||
|
t.Error("encrypted entry hash should change after rotation")
|
||||||
|
}
|
||||||
|
// Plaintext hash should NOT change.
|
||||||
|
if e.PlaintextHash != origEncPtHash {
|
||||||
|
t.Errorf("plaintext hash changed: %s → %s", origEncPtHash, e.PlaintextHash)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Plaintext entry should be untouched.
|
||||||
|
if e.Hash != origPlainHash {
|
||||||
|
t.Errorf("plaintext entry hash changed: %s → %s", origPlainHash, e.Hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the new blob decrypts correctly.
|
||||||
|
_ = os.Remove(secretFile)
|
||||||
|
if err := g.Restore(nil, true, nil); err != nil {
|
||||||
|
t.Fatalf("Restore after rotation: %v", err)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(secretFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading restored file: %v", err)
|
||||||
|
}
|
||||||
|
if string(got) != "secret data" {
|
||||||
|
t.Errorf("restored content = %q, want %q", got, "secret data")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRotateDEK_UnlockWithNewPassphrase(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
passphrase := "original"
|
||||||
|
if err := g.EncryptInit(passphrase); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secretFile := filepath.Join(root, "secret")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
if err := g.Add([]string{secretFile}, AddOptions{Encrypt: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate with the same passphrase.
|
||||||
|
prompt := func() (string, error) { return passphrase, nil }
|
||||||
|
if err := g.RotateDEK(prompt); err != nil {
|
||||||
|
t.Fatalf("RotateDEK: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-open and verify unlock still works with the same passphrase.
|
||||||
|
g2, err := Open(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Open: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g2.UnlockDEK(prompt); err != nil {
|
||||||
|
t.Fatalf("UnlockDEK after rotation: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify restore works.
|
||||||
|
_ = os.Remove(secretFile)
|
||||||
|
if err := g2.Restore(nil, true, nil); err != nil {
|
||||||
|
t.Fatalf("Restore after re-open: %v", err)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(secretFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading: %v", err)
|
||||||
|
}
|
||||||
|
if string(got) != "data" {
|
||||||
|
t.Errorf("got %q, want %q", got, "data")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRotateDEK_WithFIDO2(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
passphrase := "passphrase"
|
||||||
|
if err := g.EncryptInit(passphrase); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a FIDO2 slot.
|
||||||
|
device := newMockFIDO2()
|
||||||
|
if err := g.AddFIDO2Slot(device, "testkey"); err != nil {
|
||||||
|
t.Fatalf("AddFIDO2Slot: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secretFile := filepath.Join(root, "secret")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("fido2 data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
if err := g.Add([]string{secretFile}, AddOptions{Encrypt: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate with both passphrase and FIDO2 device.
|
||||||
|
prompt := func() (string, error) { return passphrase, nil }
|
||||||
|
if err := g.RotateDEK(prompt, device); err != nil {
|
||||||
|
t.Fatalf("RotateDEK: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Both slots should still exist.
|
||||||
|
slots := g.ListSlots()
|
||||||
|
if _, ok := slots["passphrase"]; !ok {
|
||||||
|
t.Error("passphrase slot should still exist after rotation")
|
||||||
|
}
|
||||||
|
if _, ok := slots["fido2/testkey"]; !ok {
|
||||||
|
t.Error("fido2/testkey slot should still exist after rotation")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlock via FIDO2 should work.
|
||||||
|
g2, err := Open(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Open: %v", err)
|
||||||
|
}
|
||||||
|
if err := g2.UnlockDEK(nil, device); err != nil {
|
||||||
|
t.Fatalf("UnlockDEK via FIDO2 after rotation: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify decryption.
|
||||||
|
_ = os.Remove(secretFile)
|
||||||
|
if err := g2.Restore(nil, true, nil); err != nil {
|
||||||
|
t.Fatalf("Restore: %v", err)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(secretFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading: %v", err)
|
||||||
|
}
|
||||||
|
if string(got) != "fido2 data" {
|
||||||
|
t.Errorf("got %q, want %q", got, "fido2 data")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRotateDEK_RequiresUnlock(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.EncryptInit("pass"); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-open without unlocking.
|
||||||
|
g2, err := Open(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Open: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = g2.RotateDEK(func() (string, error) { return "pass", nil })
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("RotateDEK without unlock should fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
80
garden/exclude.go
Normal file
80
garden/exclude.go
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exclude adds the given paths to the manifest's exclusion list. Excluded
|
||||||
|
// paths are skipped during Add and MirrorUp directory walks. If any of the
|
||||||
|
// paths are already tracked, they are removed from the manifest.
|
||||||
|
func (g *Garden) Exclude(paths []string) error {
|
||||||
|
existing := make(map[string]bool, len(g.manifest.Exclude))
|
||||||
|
for _, e := range g.manifest.Exclude {
|
||||||
|
existing[e] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range paths {
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolving path %s: %w", p, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tilded := toTildePath(abs)
|
||||||
|
|
||||||
|
if existing[tilded] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
g.manifest.Exclude = append(g.manifest.Exclude, tilded)
|
||||||
|
existing[tilded] = true
|
||||||
|
|
||||||
|
// Remove any already-tracked entries that match this exclusion.
|
||||||
|
g.removeExcludedEntries(tilded)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.manifest.Save(g.manifestPath); err != nil {
|
||||||
|
return fmt.Errorf("saving manifest: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Include removes the given paths from the manifest's exclusion list,
|
||||||
|
// allowing them to be tracked again.
|
||||||
|
func (g *Garden) Include(paths []string) error {
|
||||||
|
remove := make(map[string]bool, len(paths))
|
||||||
|
for _, p := range paths {
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolving path %s: %w", p, err)
|
||||||
|
}
|
||||||
|
remove[toTildePath(abs)] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
filtered := g.manifest.Exclude[:0]
|
||||||
|
for _, e := range g.manifest.Exclude {
|
||||||
|
if !remove[e] {
|
||||||
|
filtered = append(filtered, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g.manifest.Exclude = filtered
|
||||||
|
|
||||||
|
if err := g.manifest.Save(g.manifestPath); err != nil {
|
||||||
|
return fmt.Errorf("saving manifest: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// removeExcludedEntries drops manifest entries that match the given
|
||||||
|
// exclusion path (exact match or under an excluded directory).
|
||||||
|
func (g *Garden) removeExcludedEntries(tildePath string) {
|
||||||
|
kept := g.manifest.Files[:0]
|
||||||
|
for _, e := range g.manifest.Files {
|
||||||
|
if !g.manifest.IsExcluded(e.Path) {
|
||||||
|
kept = append(kept, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g.manifest.Files = kept
|
||||||
|
}
|
||||||
331
garden/exclude_test.go
Normal file
331
garden/exclude_test.go
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExcludeAddsToManifest(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secretFile := filepath.Join(root, "secret.key")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(g.manifest.Exclude) != 1 {
|
||||||
|
t.Fatalf("expected 1 exclusion, got %d", len(g.manifest.Exclude))
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := toTildePath(secretFile)
|
||||||
|
if g.manifest.Exclude[0] != expected {
|
||||||
|
t.Errorf("exclude[0] = %q, want %q", g.manifest.Exclude[0], expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify persistence.
|
||||||
|
g2, err := Open(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("re-Open: %v", err)
|
||||||
|
}
|
||||||
|
if len(g2.manifest.Exclude) != 1 {
|
||||||
|
t.Errorf("persisted excludes = %d, want 1", len(g2.manifest.Exclude))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcludeDeduplicates(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secretFile := filepath.Join(root, "secret.key")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("first Exclude: %v", err)
|
||||||
|
}
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("second Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(g.manifest.Exclude) != 1 {
|
||||||
|
t.Errorf("expected 1 exclusion after dedup, got %d", len(g.manifest.Exclude))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcludeRemovesTrackedEntry(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secretFile := filepath.Join(root, "secret.key")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the file first.
|
||||||
|
if err := g.Add([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
if len(g.manifest.Files) != 1 {
|
||||||
|
t.Fatalf("expected 1 file, got %d", len(g.manifest.Files))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now exclude it — should remove from tracked files.
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(g.manifest.Files) != 0 {
|
||||||
|
t.Errorf("expected 0 files after exclude, got %d", len(g.manifest.Files))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIncludeRemovesFromExcludeList(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secretFile := filepath.Join(root, "secret.key")
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
if len(g.manifest.Exclude) != 1 {
|
||||||
|
t.Fatalf("expected 1 exclusion, got %d", len(g.manifest.Exclude))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Include([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Include: %v", err)
|
||||||
|
}
|
||||||
|
if len(g.manifest.Exclude) != 0 {
|
||||||
|
t.Errorf("expected 0 exclusions after include, got %d", len(g.manifest.Exclude))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddSkipsExcludedFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testDir := filepath.Join(root, "config")
|
||||||
|
if err := os.MkdirAll(testDir, 0o755); err != nil {
|
||||||
|
t.Fatalf("creating dir: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
normalFile := filepath.Join(testDir, "settings.yaml")
|
||||||
|
secretFile := filepath.Join(testDir, "credentials.key")
|
||||||
|
if err := os.WriteFile(normalFile, []byte("settings"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing normal file: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exclude the secret file before adding the directory.
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testDir}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(g.manifest.Files) != 1 {
|
||||||
|
t.Fatalf("expected 1 file, got %d", len(g.manifest.Files))
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedPath := toTildePath(normalFile)
|
||||||
|
if g.manifest.Files[0].Path != expectedPath {
|
||||||
|
t.Errorf("tracked file = %q, want %q", g.manifest.Files[0].Path, expectedPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddSkipsExcludedDirectory(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testDir := filepath.Join(root, "config")
|
||||||
|
subDir := filepath.Join(testDir, "secrets")
|
||||||
|
if err := os.MkdirAll(subDir, 0o755); err != nil {
|
||||||
|
t.Fatalf("creating dirs: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
normalFile := filepath.Join(testDir, "settings.yaml")
|
||||||
|
secretFile := filepath.Join(subDir, "token.key")
|
||||||
|
if err := os.WriteFile(normalFile, []byte("settings"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing normal file: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secretFile, []byte("token"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exclude the entire secrets subdirectory.
|
||||||
|
if err := g.Exclude([]string{subDir}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testDir}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(g.manifest.Files) != 1 {
|
||||||
|
t.Fatalf("expected 1 file, got %d", len(g.manifest.Files))
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedPath := toTildePath(normalFile)
|
||||||
|
if g.manifest.Files[0].Path != expectedPath {
|
||||||
|
t.Errorf("tracked file = %q, want %q", g.manifest.Files[0].Path, expectedPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMirrorUpSkipsExcluded(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testDir := filepath.Join(root, "config")
|
||||||
|
if err := os.MkdirAll(testDir, 0o755); err != nil {
|
||||||
|
t.Fatalf("creating dir: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
normalFile := filepath.Join(testDir, "settings.yaml")
|
||||||
|
secretFile := filepath.Join(testDir, "credentials.key")
|
||||||
|
if err := os.WriteFile(normalFile, []byte("settings"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing normal file: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exclude the secret file.
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.MirrorUp([]string{testDir}); err != nil {
|
||||||
|
t.Fatalf("MirrorUp: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the normal file should be tracked.
|
||||||
|
if len(g.manifest.Files) != 1 {
|
||||||
|
t.Fatalf("expected 1 file, got %d", len(g.manifest.Files))
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedPath := toTildePath(normalFile)
|
||||||
|
if g.manifest.Files[0].Path != expectedPath {
|
||||||
|
t.Errorf("tracked file = %q, want %q", g.manifest.Files[0].Path, expectedPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMirrorDownLeavesExcludedAlone(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testDir := filepath.Join(root, "config")
|
||||||
|
if err := os.MkdirAll(testDir, 0o755); err != nil {
|
||||||
|
t.Fatalf("creating dir: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
normalFile := filepath.Join(testDir, "settings.yaml")
|
||||||
|
secretFile := filepath.Join(testDir, "credentials.key")
|
||||||
|
if err := os.WriteFile(normalFile, []byte("settings"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing normal file: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing secret file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add only the normal file.
|
||||||
|
if err := g.Add([]string{normalFile}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exclude the secret file.
|
||||||
|
if err := g.Exclude([]string{secretFile}); err != nil {
|
||||||
|
t.Fatalf("Exclude: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MirrorDown with force — excluded file should NOT be deleted.
|
||||||
|
if err := g.MirrorDown([]string{testDir}, true, nil); err != nil {
|
||||||
|
t.Fatalf("MirrorDown: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(secretFile); err != nil {
|
||||||
|
t.Error("excluded file should not have been deleted by MirrorDown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsExcludedDirectoryPrefix(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exclude a directory.
|
||||||
|
g.manifest.Exclude = []string{"~/config/secrets"}
|
||||||
|
|
||||||
|
if !g.manifest.IsExcluded("~/config/secrets") {
|
||||||
|
t.Error("exact match should be excluded")
|
||||||
|
}
|
||||||
|
if !g.manifest.IsExcluded("~/config/secrets/token.key") {
|
||||||
|
t.Error("file under excluded dir should be excluded")
|
||||||
|
}
|
||||||
|
if !g.manifest.IsExcluded("~/config/secrets/nested/deep.key") {
|
||||||
|
t.Error("deeply nested file under excluded dir should be excluded")
|
||||||
|
}
|
||||||
|
if g.manifest.IsExcluded("~/config/secrets-backup/file.key") {
|
||||||
|
t.Error("path with similar prefix but different dir should not be excluded")
|
||||||
|
}
|
||||||
|
if g.manifest.IsExcluded("~/config/other.yaml") {
|
||||||
|
t.Error("unrelated path should not be excluded")
|
||||||
|
}
|
||||||
|
}
|
||||||
156
garden/fido2_hardware.go
Normal file
156
garden/fido2_hardware.go
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
//go:build fido2
|
||||||
|
|
||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
libfido2 "github.com/keys-pub/go-libfido2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const rpID = "sgard"
|
||||||
|
|
||||||
|
// HardwareFIDO2 implements FIDO2Device using a real hardware authenticator
|
||||||
|
// via libfido2.
|
||||||
|
type HardwareFIDO2 struct {
|
||||||
|
pin string // device PIN (empty if no PIN set)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHardwareFIDO2 creates a HardwareFIDO2 device. The PIN is needed for
|
||||||
|
// operations on PIN-protected authenticators.
|
||||||
|
func NewHardwareFIDO2(pin string) *HardwareFIDO2 {
|
||||||
|
return &HardwareFIDO2{pin: pin}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Available reports whether a FIDO2 device is connected.
|
||||||
|
func (h *HardwareFIDO2) Available() bool {
|
||||||
|
locs, err := libfido2.DeviceLocations()
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return len(locs) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register creates a new credential with the hmac-secret extension.
|
||||||
|
// Returns the credential ID and the HMAC-secret output for the given salt.
|
||||||
|
func (h *HardwareFIDO2) Register(salt []byte) ([]byte, []byte, error) {
|
||||||
|
dev, err := h.deviceForPath()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cdh := sha256.Sum256(salt)
|
||||||
|
// CTAP2 hmac-secret extension requires a 32-byte salt.
|
||||||
|
hmacSalt := fido2Salt(salt)
|
||||||
|
|
||||||
|
userID := sha256.Sum256([]byte("sgard-user"))
|
||||||
|
attest, err := dev.MakeCredential(
|
||||||
|
cdh[:],
|
||||||
|
libfido2.RelyingParty{ID: rpID, Name: "sgard"},
|
||||||
|
libfido2.User{ID: userID[:], Name: "sgard"},
|
||||||
|
libfido2.ES256,
|
||||||
|
h.pin,
|
||||||
|
&libfido2.MakeCredentialOpts{
|
||||||
|
Extensions: []libfido2.Extension{libfido2.HMACSecretExtension},
|
||||||
|
RK: libfido2.False,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("fido2 make credential: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do an assertion to get the HMAC-secret for this salt.
|
||||||
|
assertion, err := dev.Assertion(
|
||||||
|
rpID,
|
||||||
|
cdh[:],
|
||||||
|
[][]byte{attest.CredentialID},
|
||||||
|
h.pin,
|
||||||
|
&libfido2.AssertionOpts{
|
||||||
|
Extensions: []libfido2.Extension{libfido2.HMACSecretExtension},
|
||||||
|
HMACSalt: hmacSalt,
|
||||||
|
UP: libfido2.True,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("fido2 assertion for hmac-secret: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return attest.CredentialID, assertion.HMACSecret, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Derive computes HMAC(device_secret, salt) for an existing credential.
|
||||||
|
// Requires user touch.
|
||||||
|
func (h *HardwareFIDO2) Derive(credentialID []byte, salt []byte) ([]byte, error) {
|
||||||
|
dev, err := h.deviceForPath()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cdh := sha256.Sum256(salt)
|
||||||
|
hmacSalt := fido2Salt(salt)
|
||||||
|
|
||||||
|
assertion, err := dev.Assertion(
|
||||||
|
rpID,
|
||||||
|
cdh[:],
|
||||||
|
[][]byte{credentialID},
|
||||||
|
h.pin,
|
||||||
|
&libfido2.AssertionOpts{
|
||||||
|
Extensions: []libfido2.Extension{libfido2.HMACSecretExtension},
|
||||||
|
HMACSalt: hmacSalt,
|
||||||
|
UP: libfido2.True,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fido2 assertion: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return assertion.HMACSecret, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchesCredential reports whether the connected device might hold the
|
||||||
|
// given credential. Since probing without user presence is unreliable
|
||||||
|
// across devices, we optimistically return true and let Derive handle
|
||||||
|
// the actual verification (which requires a touch).
|
||||||
|
func (h *HardwareFIDO2) MatchesCredential(_ []byte) bool {
|
||||||
|
return h.Available()
|
||||||
|
}
|
||||||
|
|
||||||
|
// fido2Salt returns a 32-byte salt suitable for the CTAP2 hmac-secret
|
||||||
|
// extension. If the input is already 32 bytes, it is returned as-is.
|
||||||
|
// Otherwise, SHA-256 is used to derive a 32-byte value deterministically.
|
||||||
|
func fido2Salt(salt []byte) []byte {
|
||||||
|
if len(salt) == 32 {
|
||||||
|
return salt
|
||||||
|
}
|
||||||
|
h := sha256.Sum256(salt)
|
||||||
|
return h[:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceForPath returns a Device handle for the first connected FIDO2
|
||||||
|
// device. The library manages open/close internally per operation.
|
||||||
|
func (h *HardwareFIDO2) deviceForPath() (*libfido2.Device, error) {
|
||||||
|
locs, err := libfido2.DeviceLocations()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("listing fido2 devices: %w", err)
|
||||||
|
}
|
||||||
|
if len(locs) == 0 {
|
||||||
|
return nil, fmt.Errorf("no fido2 device found")
|
||||||
|
}
|
||||||
|
|
||||||
|
dev, err := libfido2.NewDevice(locs[0].Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("opening fido2 device %s: %w", locs[0].Path, err)
|
||||||
|
}
|
||||||
|
return dev, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetectHardwareFIDO2 returns a HardwareFIDO2 device if hardware is available,
|
||||||
|
// or nil if no device is connected.
|
||||||
|
func DetectHardwareFIDO2(pin string) FIDO2Device {
|
||||||
|
d := NewHardwareFIDO2(pin)
|
||||||
|
if d.Available() {
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
10
garden/fido2_nohardware.go
Normal file
10
garden/fido2_nohardware.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
//go:build !fido2
|
||||||
|
|
||||||
|
package garden
|
||||||
|
|
||||||
|
// DetectHardwareFIDO2 is a stub that returns nil when built without the
|
||||||
|
// fido2 build tag. Build with -tags fido2 and link against libfido2 to
|
||||||
|
// enable real hardware support.
|
||||||
|
func DetectHardwareFIDO2(_ string) FIDO2Device {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -48,7 +48,7 @@ func Init(root string) (*Garden, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gitignorePath := filepath.Join(absRoot, ".gitignore")
|
gitignorePath := filepath.Join(absRoot, ".gitignore")
|
||||||
if err := os.WriteFile(gitignorePath, []byte("blobs/\n"), 0o644); err != nil {
|
if err := os.WriteFile(gitignorePath, []byte("blobs/\ntags\n"), 0o644); err != nil {
|
||||||
return nil, fmt.Errorf("creating .gitignore: %w", err)
|
return nil, fmt.Errorf("creating .gitignore: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,9 +139,8 @@ func (g *Garden) DeleteBlob(hash string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// addEntry adds a single file or symlink to the manifest. If skipDup is true,
|
// addEntry adds a single file or symlink to the manifest. If skipDup is true,
|
||||||
// already-tracked paths are silently skipped. If encrypt is true, the file
|
// already-tracked paths are silently skipped.
|
||||||
// blob is encrypted before storing. If lock is true, the entry is marked locked.
|
func (g *Garden) addEntry(abs string, info os.FileInfo, now time.Time, skipDup bool, o AddOptions) error {
|
||||||
func (g *Garden) addEntry(abs string, info os.FileInfo, now time.Time, skipDup, encrypt, lock bool) error {
|
|
||||||
tilded := toTildePath(abs)
|
tilded := toTildePath(abs)
|
||||||
|
|
||||||
if g.findEntry(tilded) != nil {
|
if g.findEntry(tilded) != nil {
|
||||||
@@ -154,7 +153,9 @@ func (g *Garden) addEntry(abs string, info os.FileInfo, now time.Time, skipDup,
|
|||||||
entry := manifest.Entry{
|
entry := manifest.Entry{
|
||||||
Path: tilded,
|
Path: tilded,
|
||||||
Mode: fmt.Sprintf("%04o", info.Mode().Perm()),
|
Mode: fmt.Sprintf("%04o", info.Mode().Perm()),
|
||||||
Locked: lock,
|
Locked: o.Lock,
|
||||||
|
Only: o.Only,
|
||||||
|
Never: o.Never,
|
||||||
Updated: now,
|
Updated: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,7 +174,7 @@ func (g *Garden) addEntry(abs string, info os.FileInfo, now time.Time, skipDup,
|
|||||||
return fmt.Errorf("reading file %s: %w", abs, err)
|
return fmt.Errorf("reading file %s: %w", abs, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if encrypt {
|
if o.Encrypt {
|
||||||
if g.dek == nil {
|
if g.dek == nil {
|
||||||
return fmt.Errorf("DEK not unlocked; cannot encrypt %s", abs)
|
return fmt.Errorf("DEK not unlocked; cannot encrypt %s", abs)
|
||||||
}
|
}
|
||||||
@@ -203,6 +204,8 @@ type AddOptions struct {
|
|||||||
Encrypt bool // encrypt file blobs before storing
|
Encrypt bool // encrypt file blobs before storing
|
||||||
Lock bool // mark entries as locked (repo-authoritative)
|
Lock bool // mark entries as locked (repo-authoritative)
|
||||||
DirOnly bool // for directories: track the directory itself, don't recurse
|
DirOnly bool // for directories: track the directory itself, don't recurse
|
||||||
|
Only []string // per-machine targeting: only apply on matching machines
|
||||||
|
Never []string // per-machine targeting: never apply on matching machines
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add tracks new files, directories, or symlinks. Each path is resolved
|
// Add tracks new files, directories, or symlinks. Each path is resolved
|
||||||
@@ -236,13 +239,15 @@ func (g *Garden) Add(paths []string, opts ...AddOptions) error {
|
|||||||
// Track the directory itself as a structural entry.
|
// Track the directory itself as a structural entry.
|
||||||
tilded := toTildePath(abs)
|
tilded := toTildePath(abs)
|
||||||
if g.findEntry(tilded) != nil {
|
if g.findEntry(tilded) != nil {
|
||||||
return fmt.Errorf("already tracking %s", tilded)
|
continue
|
||||||
}
|
}
|
||||||
entry := manifest.Entry{
|
entry := manifest.Entry{
|
||||||
Path: tilded,
|
Path: tilded,
|
||||||
Type: "directory",
|
Type: "directory",
|
||||||
Mode: fmt.Sprintf("%04o", info.Mode().Perm()),
|
Mode: fmt.Sprintf("%04o", info.Mode().Perm()),
|
||||||
Locked: o.Lock,
|
Locked: o.Lock,
|
||||||
|
Only: o.Only,
|
||||||
|
Never: o.Never,
|
||||||
Updated: now,
|
Updated: now,
|
||||||
}
|
}
|
||||||
g.manifest.Files = append(g.manifest.Files, entry)
|
g.manifest.Files = append(g.manifest.Files, entry)
|
||||||
@@ -251,6 +256,13 @@ func (g *Garden) Add(paths []string, opts ...AddOptions) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
tilded := toTildePath(path)
|
||||||
|
if g.manifest.IsExcluded(tilded) {
|
||||||
|
if d.IsDir() {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if d.IsDir() {
|
if d.IsDir() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -258,14 +270,14 @@ func (g *Garden) Add(paths []string, opts ...AddOptions) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("stat %s: %w", path, err)
|
return fmt.Errorf("stat %s: %w", path, err)
|
||||||
}
|
}
|
||||||
return g.addEntry(path, fi, now, true, o.Encrypt, o.Lock)
|
return g.addEntry(path, fi, now, true, o)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("walking directory %s: %w", abs, err)
|
return fmt.Errorf("walking directory %s: %w", abs, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if err := g.addEntry(abs, info, now, false, o.Encrypt, o.Lock); err != nil {
|
if err := g.addEntry(abs, info, now, true, o); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,10 +302,19 @@ type FileStatus struct {
|
|||||||
// the manifest.
|
// the manifest.
|
||||||
func (g *Garden) Checkpoint(message string) error {
|
func (g *Garden) Checkpoint(message string) error {
|
||||||
now := g.clock.Now().UTC()
|
now := g.clock.Now().UTC()
|
||||||
|
labels := g.Identity()
|
||||||
|
|
||||||
for i := range g.manifest.Files {
|
for i := range g.manifest.Files {
|
||||||
entry := &g.manifest.Files[i]
|
entry := &g.manifest.Files[i]
|
||||||
|
|
||||||
|
applies, err := EntryApplies(entry, labels)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !applies {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
abs, err := ExpandTildePath(entry.Path)
|
abs, err := ExpandTildePath(entry.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
return fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
||||||
@@ -378,10 +399,20 @@ func (g *Garden) Checkpoint(message string) error {
|
|||||||
// and returns a status for each.
|
// and returns a status for each.
|
||||||
func (g *Garden) Status() ([]FileStatus, error) {
|
func (g *Garden) Status() ([]FileStatus, error) {
|
||||||
var results []FileStatus
|
var results []FileStatus
|
||||||
|
labels := g.Identity()
|
||||||
|
|
||||||
for i := range g.manifest.Files {
|
for i := range g.manifest.Files {
|
||||||
entry := &g.manifest.Files[i]
|
entry := &g.manifest.Files[i]
|
||||||
|
|
||||||
|
applies, err := EntryApplies(entry, labels)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !applies {
|
||||||
|
results = append(results, FileStatus{Path: entry.Path, State: "skipped"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
abs, err := ExpandTildePath(entry.Path)
|
abs, err := ExpandTildePath(entry.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
return nil, fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
||||||
@@ -450,9 +481,19 @@ func (g *Garden) Restore(paths []string, force bool, confirm func(path string) b
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
labels := g.Identity()
|
||||||
|
|
||||||
for i := range entries {
|
for i := range entries {
|
||||||
entry := &entries[i]
|
entry := &entries[i]
|
||||||
|
|
||||||
|
applies, err := EntryApplies(entry, labels)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !applies {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
abs, err := ExpandTildePath(entry.Path)
|
abs, err := ExpandTildePath(entry.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
return fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ func TestInitCreatesStructure(t *testing.T) {
|
|||||||
gitignore, err := os.ReadFile(filepath.Join(repoDir, ".gitignore"))
|
gitignore, err := os.ReadFile(filepath.Join(repoDir, ".gitignore"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf(".gitignore not found: %v", err)
|
t.Errorf(".gitignore not found: %v", err)
|
||||||
} else if string(gitignore) != "blobs/\n" {
|
} else if string(gitignore) != "blobs/\ntags\n" {
|
||||||
t.Errorf(".gitignore content = %q, want %q", gitignore, "blobs/\n")
|
t.Errorf(".gitignore content = %q, want %q", gitignore, "blobs/\ntags\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
if g.manifest.Version != 1 {
|
if g.manifest.Version != 1 {
|
||||||
@@ -200,7 +200,7 @@ func TestAddSymlink(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAddDuplicateRejected(t *testing.T) {
|
func TestAddDuplicateIsIdempotent(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
repoDir := filepath.Join(root, "repo")
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
@@ -218,8 +218,19 @@ func TestAddDuplicateRejected(t *testing.T) {
|
|||||||
t.Fatalf("first Add: %v", err)
|
t.Fatalf("first Add: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.Add([]string{testFile}); err == nil {
|
if err := g.Add([]string{testFile}); err != nil {
|
||||||
t.Fatal("second Add of same path should fail")
|
t.Fatalf("second Add of same path should be idempotent: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entries := g.List()
|
||||||
|
count := 0
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.Path == toTildePath(testFile) {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatalf("expected 1 entry, got %d", count)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
37
garden/identity.go
Normal file
37
garden/identity.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Identity returns the machine's label set: short hostname, os:<GOOS>,
|
||||||
|
// arch:<GOARCH>, and tag:<name> for each tag in <repo>/tags.
|
||||||
|
func (g *Garden) Identity() []string {
|
||||||
|
labels := []string{
|
||||||
|
shortHostname(),
|
||||||
|
"os:" + runtime.GOOS,
|
||||||
|
"arch:" + runtime.GOARCH,
|
||||||
|
}
|
||||||
|
|
||||||
|
tags := g.LoadTags()
|
||||||
|
for _, tag := range tags {
|
||||||
|
labels = append(labels, "tag:"+tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
return labels
|
||||||
|
}
|
||||||
|
|
||||||
|
// shortHostname returns the hostname before the first dot, lowercased.
|
||||||
|
func shortHostname() string {
|
||||||
|
host, err := os.Hostname()
|
||||||
|
if err != nil {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
host = strings.ToLower(host)
|
||||||
|
if idx := strings.IndexByte(host, '.'); idx >= 0 {
|
||||||
|
host = host[:idx]
|
||||||
|
}
|
||||||
|
return host
|
||||||
|
}
|
||||||
158
garden/info.go
Normal file
158
garden/info.go
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FileInfo holds detailed information about a single tracked entry.
|
||||||
|
type FileInfo struct {
|
||||||
|
Path string // tilde path from manifest
|
||||||
|
Type string // "file", "link", or "directory"
|
||||||
|
State string // "ok", "modified", "drifted", "missing", "skipped"
|
||||||
|
Mode string // octal file mode from manifest
|
||||||
|
Hash string // blob hash from manifest (files only)
|
||||||
|
PlaintextHash string // plaintext hash (encrypted files only)
|
||||||
|
CurrentHash string // SHA-256 of current file on disk (files only, empty if missing)
|
||||||
|
Encrypted bool
|
||||||
|
Locked bool
|
||||||
|
Updated string // manifest timestamp (RFC 3339)
|
||||||
|
DiskModTime string // filesystem modification time (RFC 3339, empty if missing)
|
||||||
|
Target string // symlink target (links only)
|
||||||
|
CurrentTarget string // current symlink target on disk (links only, empty if missing)
|
||||||
|
Only []string // targeting: only these labels
|
||||||
|
Never []string // targeting: never these labels
|
||||||
|
BlobStored bool // whether the blob exists in the store
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info returns detailed information about a tracked file.
|
||||||
|
func (g *Garden) Info(path string) (*FileInfo, error) {
|
||||||
|
abs, err := resolvePath(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tilded := toTildePath(abs)
|
||||||
|
|
||||||
|
entry := g.findEntry(tilded)
|
||||||
|
if entry == nil {
|
||||||
|
// Also try the path as given (it might already be a tilde path).
|
||||||
|
entry = g.findEntry(path)
|
||||||
|
if entry == nil {
|
||||||
|
return nil, fmt.Errorf("not tracked: %s", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fi := &FileInfo{
|
||||||
|
Path: entry.Path,
|
||||||
|
Type: entry.Type,
|
||||||
|
Mode: entry.Mode,
|
||||||
|
Hash: entry.Hash,
|
||||||
|
PlaintextHash: entry.PlaintextHash,
|
||||||
|
Encrypted: entry.Encrypted,
|
||||||
|
Locked: entry.Locked,
|
||||||
|
Target: entry.Target,
|
||||||
|
Only: entry.Only,
|
||||||
|
Never: entry.Never,
|
||||||
|
}
|
||||||
|
|
||||||
|
if !entry.Updated.IsZero() {
|
||||||
|
fi.Updated = entry.Updated.Format("2006-01-02 15:04:05 UTC")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check blob existence for files.
|
||||||
|
if entry.Type == "file" && entry.Hash != "" {
|
||||||
|
fi.BlobStored = g.store.Exists(entry.Hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine state and filesystem info.
|
||||||
|
labels := g.Identity()
|
||||||
|
applies, err := EntryApplies(entry, labels)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !applies {
|
||||||
|
fi.State = "skipped"
|
||||||
|
return fi, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
entryAbs, err := ExpandTildePath(entry.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("expanding path %s: %w", entry.Path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Lstat(entryAbs)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
fi.State = "missing"
|
||||||
|
return fi, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("stat %s: %w", entryAbs, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fi.DiskModTime = info.ModTime().UTC().Format("2006-01-02 15:04:05 UTC")
|
||||||
|
|
||||||
|
switch entry.Type {
|
||||||
|
case "file":
|
||||||
|
hash, err := HashFile(entryAbs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hashing %s: %w", entryAbs, err)
|
||||||
|
}
|
||||||
|
fi.CurrentHash = hash
|
||||||
|
|
||||||
|
compareHash := entry.Hash
|
||||||
|
if entry.Encrypted && entry.PlaintextHash != "" {
|
||||||
|
compareHash = entry.PlaintextHash
|
||||||
|
}
|
||||||
|
if hash != compareHash {
|
||||||
|
if entry.Locked {
|
||||||
|
fi.State = "drifted"
|
||||||
|
} else {
|
||||||
|
fi.State = "modified"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fi.State = "ok"
|
||||||
|
}
|
||||||
|
|
||||||
|
case "link":
|
||||||
|
target, err := os.Readlink(entryAbs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading symlink %s: %w", entryAbs, err)
|
||||||
|
}
|
||||||
|
fi.CurrentTarget = target
|
||||||
|
if target != entry.Target {
|
||||||
|
fi.State = "modified"
|
||||||
|
} else {
|
||||||
|
fi.State = "ok"
|
||||||
|
}
|
||||||
|
|
||||||
|
case "directory":
|
||||||
|
fi.State = "ok"
|
||||||
|
}
|
||||||
|
|
||||||
|
return fi, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolvePath resolves a user-provided path to an absolute path, handling
|
||||||
|
// tilde expansion and relative paths.
|
||||||
|
func resolvePath(path string) (string, error) {
|
||||||
|
if path == "~" || strings.HasPrefix(path, "~/") {
|
||||||
|
return ExpandTildePath(path)
|
||||||
|
}
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
// If it looks like a tilde path already, just expand it.
|
||||||
|
if strings.HasPrefix(path, home) {
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
abs, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(path, "/") {
|
||||||
|
path = abs + "/" + path
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
191
garden/info_test.go
Normal file
191
garden/info_test.go
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInfoTrackedFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a file to track.
|
||||||
|
filePath := filepath.Join(root, "hello.txt")
|
||||||
|
if err := os.WriteFile(filePath, []byte("hello\n"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{filePath}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := g.Info(filePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Info: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if fi.Type != "file" {
|
||||||
|
t.Errorf("Type = %q, want %q", fi.Type, "file")
|
||||||
|
}
|
||||||
|
if fi.State != "ok" {
|
||||||
|
t.Errorf("State = %q, want %q", fi.State, "ok")
|
||||||
|
}
|
||||||
|
if fi.Hash == "" {
|
||||||
|
t.Error("Hash is empty")
|
||||||
|
}
|
||||||
|
if fi.CurrentHash == "" {
|
||||||
|
t.Error("CurrentHash is empty")
|
||||||
|
}
|
||||||
|
if fi.Hash != fi.CurrentHash {
|
||||||
|
t.Errorf("Hash = %q != CurrentHash = %q", fi.Hash, fi.CurrentHash)
|
||||||
|
}
|
||||||
|
if fi.Updated == "" {
|
||||||
|
t.Error("Updated is empty")
|
||||||
|
}
|
||||||
|
if fi.DiskModTime == "" {
|
||||||
|
t.Error("DiskModTime is empty")
|
||||||
|
}
|
||||||
|
if !fi.BlobStored {
|
||||||
|
t.Error("BlobStored = false, want true")
|
||||||
|
}
|
||||||
|
if fi.Mode != "0644" {
|
||||||
|
t.Errorf("Mode = %q, want %q", fi.Mode, "0644")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInfoModifiedFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath := filepath.Join(root, "hello.txt")
|
||||||
|
if err := os.WriteFile(filePath, []byte("hello\n"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{filePath}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Modify the file.
|
||||||
|
if err := os.WriteFile(filePath, []byte("changed\n"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := g.Info(filePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Info: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if fi.State != "modified" {
|
||||||
|
t.Errorf("State = %q, want %q", fi.State, "modified")
|
||||||
|
}
|
||||||
|
if fi.CurrentHash == fi.Hash {
|
||||||
|
t.Error("CurrentHash should differ from Hash after modification")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInfoMissingFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath := filepath.Join(root, "hello.txt")
|
||||||
|
if err := os.WriteFile(filePath, []byte("hello\n"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{filePath}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the file.
|
||||||
|
if err := os.Remove(filePath); err != nil {
|
||||||
|
t.Fatalf("Remove: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := g.Info(filePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Info: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if fi.State != "missing" {
|
||||||
|
t.Errorf("State = %q, want %q", fi.State, "missing")
|
||||||
|
}
|
||||||
|
if fi.DiskModTime != "" {
|
||||||
|
t.Errorf("DiskModTime = %q, want empty for missing file", fi.DiskModTime)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInfoUntracked(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath := filepath.Join(root, "nope.txt")
|
||||||
|
if err := os.WriteFile(filePath, []byte("nope\n"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = g.Info(filePath)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Info should fail for untracked file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInfoSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
target := filepath.Join(root, "target.txt")
|
||||||
|
if err := os.WriteFile(target, []byte("target\n"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
linkPath := filepath.Join(root, "link.txt")
|
||||||
|
if err := os.Symlink(target, linkPath); err != nil {
|
||||||
|
t.Fatalf("Symlink: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{linkPath}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := g.Info(linkPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Info: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if fi.Type != "link" {
|
||||||
|
t.Errorf("Type = %q, want %q", fi.Type, "link")
|
||||||
|
}
|
||||||
|
if fi.State != "ok" {
|
||||||
|
t.Errorf("State = %q, want %q", fi.State, "ok")
|
||||||
|
}
|
||||||
|
if fi.Target != target {
|
||||||
|
t.Errorf("Target = %q, want %q", fi.Target, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
39
garden/lock.go
Normal file
39
garden/lock.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Lock marks existing tracked entries as locked (repo-authoritative).
|
||||||
|
func (g *Garden) Lock(paths []string) error {
|
||||||
|
return g.setLocked(paths, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlock removes the locked flag from existing tracked entries.
|
||||||
|
func (g *Garden) Unlock(paths []string) error {
|
||||||
|
return g.setLocked(paths, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Garden) setLocked(paths []string, locked bool) error {
|
||||||
|
for _, p := range paths {
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolving path %s: %w", p, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tilded := toTildePath(abs)
|
||||||
|
entry := g.findEntry(tilded)
|
||||||
|
if entry == nil {
|
||||||
|
return fmt.Errorf("not tracked: %s", tilded)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.Locked = locked
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.manifest.Save(g.manifestPath); err != nil {
|
||||||
|
return fmt.Errorf("saving manifest: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
197
garden/lock_test.go
Normal file
197
garden/lock_test.go
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLockExistingEntry(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add without lock.
|
||||||
|
if err := g.Add([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Locked {
|
||||||
|
t.Fatal("should not be locked initially")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock it.
|
||||||
|
if err := g.Lock([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Lock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !g.manifest.Files[0].Locked {
|
||||||
|
t.Error("should be locked after Lock()")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify persisted.
|
||||||
|
g2, err := Open(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Open: %v", err)
|
||||||
|
}
|
||||||
|
if !g2.manifest.Files[0].Locked {
|
||||||
|
t.Error("locked state should persist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnlockExistingEntry(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Lock: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !g.manifest.Files[0].Locked {
|
||||||
|
t.Fatal("should be locked")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Unlock([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Unlock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Locked {
|
||||||
|
t.Error("should not be locked after Unlock()")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLockUntrackedErrors(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "nottracked")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Lock([]string{testFile}); err == nil {
|
||||||
|
t.Fatal("Lock on untracked path should error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLockChangesCheckpointBehavior(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("original"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add unlocked, checkpoint picks up changes.
|
||||||
|
if err := g.Add([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
origHash := g.manifest.Files[0].Hash
|
||||||
|
|
||||||
|
if err := os.WriteFile(testFile, []byte("changed"), 0o644); err != nil {
|
||||||
|
t.Fatalf("modifying: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash == origHash {
|
||||||
|
t.Fatal("unlocked file: checkpoint should update hash")
|
||||||
|
}
|
||||||
|
|
||||||
|
newHash := g.manifest.Files[0].Hash
|
||||||
|
|
||||||
|
// Now lock it and modify again — checkpoint should NOT update.
|
||||||
|
if err := g.Lock([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Lock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.WriteFile(testFile, []byte("system overwrote"), 0o644); err != nil {
|
||||||
|
t.Fatalf("overwriting: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash != newHash {
|
||||||
|
t.Error("locked file: checkpoint should not update hash")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnlockChangesStatusBehavior(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("original"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Lock: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.WriteFile(testFile, []byte("changed"), 0o644); err != nil {
|
||||||
|
t.Fatalf("modifying: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Locked: should be "drifted".
|
||||||
|
statuses, err := g.Status()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Status: %v", err)
|
||||||
|
}
|
||||||
|
if statuses[0].State != "drifted" {
|
||||||
|
t.Errorf("locked: expected drifted, got %s", statuses[0].State)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlock: should now be "modified".
|
||||||
|
if err := g.Unlock([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Unlock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
statuses, err = g.Status()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Status: %v", err)
|
||||||
|
}
|
||||||
|
if statuses[0].State != "modified" {
|
||||||
|
t.Errorf("unlocked: expected modified, got %s", statuses[0].State)
|
||||||
|
}
|
||||||
|
}
|
||||||
192
garden/locked_combo_test.go
Normal file
192
garden/locked_combo_test.go
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEncryptedLockedFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.EncryptInit("passphrase"); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "secret")
|
||||||
|
if err := os.WriteFile(testFile, []byte("locked secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add as both encrypted and locked.
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Encrypt: true, Lock: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := g.manifest.Files[0]
|
||||||
|
if !entry.Encrypted {
|
||||||
|
t.Error("should be encrypted")
|
||||||
|
}
|
||||||
|
if !entry.Locked {
|
||||||
|
t.Error("should be locked")
|
||||||
|
}
|
||||||
|
if entry.PlaintextHash == "" {
|
||||||
|
t.Error("should have plaintext hash")
|
||||||
|
}
|
||||||
|
|
||||||
|
origHash := entry.Hash
|
||||||
|
|
||||||
|
// Modify the file — checkpoint should skip (locked).
|
||||||
|
if err := os.WriteFile(testFile, []byte("system overwrote"), 0o600); err != nil {
|
||||||
|
t.Fatalf("modifying: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash != origHash {
|
||||||
|
t.Error("checkpoint should skip locked file even if encrypted")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status should report drifted.
|
||||||
|
statuses, err := g.Status()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Status: %v", err)
|
||||||
|
}
|
||||||
|
if len(statuses) != 1 || statuses[0].State != "drifted" {
|
||||||
|
t.Errorf("expected drifted, got %v", statuses)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore should decrypt and overwrite without prompting.
|
||||||
|
if err := g.Restore(nil, false, nil); err != nil {
|
||||||
|
t.Fatalf("Restore: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := os.ReadFile(testFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading: %v", err)
|
||||||
|
}
|
||||||
|
if string(got) != "locked secret" {
|
||||||
|
t.Errorf("content = %q, want %q", got, "locked secret")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDirOnlyLocked(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testDir := filepath.Join(root, "lockdir")
|
||||||
|
if err := os.MkdirAll(testDir, 0o755); err != nil {
|
||||||
|
t.Fatalf("mkdir: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add as dir-only and locked.
|
||||||
|
if err := g.Add([]string{testDir}, AddOptions{DirOnly: true, Lock: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := g.manifest.Files[0]
|
||||||
|
if entry.Type != "directory" {
|
||||||
|
t.Errorf("type = %s, want directory", entry.Type)
|
||||||
|
}
|
||||||
|
if !entry.Locked {
|
||||||
|
t.Error("should be locked")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the directory.
|
||||||
|
if err := os.RemoveAll(testDir); err != nil {
|
||||||
|
t.Fatalf("removing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore should recreate it.
|
||||||
|
if err := g.Restore(nil, false, nil); err != nil {
|
||||||
|
t.Fatalf("Restore: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Stat(testDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("directory not restored: %v", err)
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
t.Error("should be a directory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLockUnlockEncryptedToggle(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.EncryptInit("passphrase"); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "secret")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add encrypted but not locked.
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Encrypt: true}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Locked {
|
||||||
|
t.Fatal("should not be locked initially")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock it.
|
||||||
|
if err := g.Lock([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Lock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !g.manifest.Files[0].Locked {
|
||||||
|
t.Error("should be locked")
|
||||||
|
}
|
||||||
|
if !g.manifest.Files[0].Encrypted {
|
||||||
|
t.Error("should still be encrypted")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Modify — checkpoint should skip.
|
||||||
|
origHash := g.manifest.Files[0].Hash
|
||||||
|
if err := os.WriteFile(testFile, []byte("changed"), 0o600); err != nil {
|
||||||
|
t.Fatalf("modifying: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash != origHash {
|
||||||
|
t.Error("checkpoint should skip locked encrypted file")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlock — checkpoint should now pick up changes.
|
||||||
|
if err := g.Unlock([]string{testFile}); err != nil {
|
||||||
|
t.Fatalf("Unlock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash == origHash {
|
||||||
|
t.Error("unlocked: checkpoint should update encrypted file hash")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,6 +30,13 @@ func (g *Garden) MirrorUp(paths []string) error {
|
|||||||
if walkErr != nil {
|
if walkErr != nil {
|
||||||
return walkErr
|
return walkErr
|
||||||
}
|
}
|
||||||
|
tilded := toTildePath(path)
|
||||||
|
if g.manifest.IsExcluded(tilded) {
|
||||||
|
if d.IsDir() {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if d.IsDir() {
|
if d.IsDir() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -37,7 +44,7 @@ func (g *Garden) MirrorUp(paths []string) error {
|
|||||||
if lstatErr != nil {
|
if lstatErr != nil {
|
||||||
return fmt.Errorf("stat %s: %w", path, lstatErr)
|
return fmt.Errorf("stat %s: %w", path, lstatErr)
|
||||||
}
|
}
|
||||||
return g.addEntry(path, fi, now, true, false, false)
|
return g.addEntry(path, fi, now, true, AddOptions{})
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("walking directory %s: %w", abs, err)
|
return fmt.Errorf("walking directory %s: %w", abs, err)
|
||||||
@@ -154,6 +161,9 @@ func (g *Garden) MirrorDown(paths []string, force bool, confirm func(string) boo
|
|||||||
return walkErr
|
return walkErr
|
||||||
}
|
}
|
||||||
if d.IsDir() {
|
if d.IsDir() {
|
||||||
|
if g.manifest.IsExcluded(toTildePath(path)) {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
// Collect directories for potential cleanup (post-order).
|
// Collect directories for potential cleanup (post-order).
|
||||||
if path != abs {
|
if path != abs {
|
||||||
emptyDirs = append(emptyDirs, path)
|
emptyDirs = append(emptyDirs, path)
|
||||||
@@ -163,6 +173,10 @@ func (g *Garden) MirrorDown(paths []string, force bool, confirm func(string) boo
|
|||||||
if tracked[path] {
|
if tracked[path] {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
// Excluded paths are left alone on disk.
|
||||||
|
if g.manifest.IsExcluded(toTildePath(path)) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
// Untracked file/symlink on disk.
|
// Untracked file/symlink on disk.
|
||||||
if !force {
|
if !force {
|
||||||
if confirm == nil || !confirm(path) {
|
if confirm == nil || !confirm(path) {
|
||||||
|
|||||||
65
garden/tags.go
Normal file
65
garden/tags.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LoadTags reads the tags from <repo>/tags, one per line.
|
||||||
|
func (g *Garden) LoadTags() []string {
|
||||||
|
data, err := os.ReadFile(filepath.Join(g.root, "tags"))
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var tags []string
|
||||||
|
for _, line := range strings.Split(string(data), "\n") {
|
||||||
|
tag := strings.TrimSpace(line)
|
||||||
|
if tag != "" {
|
||||||
|
tags = append(tags, tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tags
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveTag adds a tag to <repo>/tags if not already present.
|
||||||
|
func (g *Garden) SaveTag(tag string) error {
|
||||||
|
tag = strings.TrimSpace(tag)
|
||||||
|
if tag == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
tags := g.LoadTags()
|
||||||
|
for _, existing := range tags {
|
||||||
|
if existing == tag {
|
||||||
|
return nil // already present
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tags = append(tags, tag)
|
||||||
|
return g.writeTags(tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveTag removes a tag from <repo>/tags.
|
||||||
|
func (g *Garden) RemoveTag(tag string) error {
|
||||||
|
tag = strings.TrimSpace(tag)
|
||||||
|
tags := g.LoadTags()
|
||||||
|
|
||||||
|
var filtered []string
|
||||||
|
for _, t := range tags {
|
||||||
|
if t != tag {
|
||||||
|
filtered = append(filtered, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return g.writeTags(filtered)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Garden) writeTags(tags []string) error {
|
||||||
|
content := strings.Join(tags, "\n")
|
||||||
|
if content != "" {
|
||||||
|
content += "\n"
|
||||||
|
}
|
||||||
|
return os.WriteFile(filepath.Join(g.root, "tags"), []byte(content), 0o644)
|
||||||
|
}
|
||||||
34
garden/target.go
Normal file
34
garden/target.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// SetTargeting updates the Only/Never fields on an existing manifest entry.
|
||||||
|
// If clear is true, both fields are reset to nil.
|
||||||
|
func (g *Garden) SetTargeting(path string, only, never []string, clear bool) error {
|
||||||
|
abs, err := ExpandTildePath(path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("expanding path: %w", err)
|
||||||
|
}
|
||||||
|
tilded := toTildePath(abs)
|
||||||
|
|
||||||
|
entry := g.findEntry(tilded)
|
||||||
|
if entry == nil {
|
||||||
|
return fmt.Errorf("not tracking %s", tilded)
|
||||||
|
}
|
||||||
|
|
||||||
|
if clear {
|
||||||
|
entry.Only = nil
|
||||||
|
entry.Never = nil
|
||||||
|
} else {
|
||||||
|
if len(only) > 0 {
|
||||||
|
entry.Only = only
|
||||||
|
entry.Never = nil
|
||||||
|
}
|
||||||
|
if len(never) > 0 {
|
||||||
|
entry.Never = never
|
||||||
|
entry.Only = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return g.manifest.Save(g.manifestPath)
|
||||||
|
}
|
||||||
48
garden/targeting.go
Normal file
48
garden/targeting.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/manifest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EntryApplies reports whether the given entry should be active on a
|
||||||
|
// machine with the given labels. Returns an error if both Only and
|
||||||
|
// Never are set on the same entry.
|
||||||
|
func EntryApplies(entry *manifest.Entry, labels []string) (bool, error) {
|
||||||
|
if len(entry.Only) > 0 && len(entry.Never) > 0 {
|
||||||
|
return false, fmt.Errorf("entry %s has both only and never set", entry.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(entry.Only) > 0 {
|
||||||
|
for _, matcher := range entry.Only {
|
||||||
|
if matchesLabel(matcher, labels) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(entry.Never) > 0 {
|
||||||
|
for _, matcher := range entry.Never {
|
||||||
|
if matchesLabel(matcher, labels) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchesLabel checks if a matcher string matches any label in the set.
|
||||||
|
// Matching is case-insensitive.
|
||||||
|
func matchesLabel(matcher string, labels []string) bool {
|
||||||
|
matcher = strings.ToLower(matcher)
|
||||||
|
for _, label := range labels {
|
||||||
|
if strings.ToLower(label) == matcher {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
190
garden/targeting_ops_test.go
Normal file
190
garden/targeting_ops_test.go
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCheckpointSkipsNonMatching(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("original"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add with only:os:fakeos — won't match this machine.
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Only: []string{"os:fakeos"}}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
origHash := g.manifest.Files[0].Hash
|
||||||
|
|
||||||
|
// Modify file.
|
||||||
|
if err := os.WriteFile(testFile, []byte("modified"), 0o644); err != nil {
|
||||||
|
t.Fatalf("modifying: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Checkpoint should skip this entry.
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash != origHash {
|
||||||
|
t.Error("checkpoint should skip non-matching entry")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckpointProcessesMatching(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("original"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add with only matching current OS.
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Only: []string{"os:" + runtime.GOOS}}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
origHash := g.manifest.Files[0].Hash
|
||||||
|
|
||||||
|
if err := os.WriteFile(testFile, []byte("modified"), 0o644); err != nil {
|
||||||
|
t.Fatalf("modifying: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Checkpoint(""); err != nil {
|
||||||
|
t.Fatalf("Checkpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.manifest.Files[0].Hash == origHash {
|
||||||
|
t.Error("checkpoint should process matching entry")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusReportsSkipped(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Only: []string{"os:fakeos"}}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
statuses, err := g.Status()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Status: %v", err)
|
||||||
|
}
|
||||||
|
if len(statuses) != 1 || statuses[0].State != "skipped" {
|
||||||
|
t.Errorf("expected skipped, got %v", statuses)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRestoreSkipsNonMatching(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("original"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{Only: []string{"os:fakeos"}}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete file and try to restore — should skip.
|
||||||
|
_ = os.Remove(testFile)
|
||||||
|
if err := g.Restore(nil, true, nil); err != nil {
|
||||||
|
t.Fatalf("Restore: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// File should NOT have been restored.
|
||||||
|
if _, err := os.Stat(testFile); !os.IsNotExist(err) {
|
||||||
|
t.Error("restore should skip non-matching entry — file should not exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddWithTargeting(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{
|
||||||
|
Only: []string{"os:linux", "tag:work"},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := g.manifest.Files[0]
|
||||||
|
if len(entry.Only) != 2 {
|
||||||
|
t.Fatalf("expected 2 only labels, got %d", len(entry.Only))
|
||||||
|
}
|
||||||
|
if entry.Only[0] != "os:linux" || entry.Only[1] != "tag:work" {
|
||||||
|
t.Errorf("only = %v, want [os:linux tag:work]", entry.Only)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddWithNever(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testFile := filepath.Join(root, "testfile")
|
||||||
|
if err := os.WriteFile(testFile, []byte("data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("writing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := g.Add([]string{testFile}, AddOptions{
|
||||||
|
Never: []string{"arch:arm64"},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("Add: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := g.manifest.Files[0]
|
||||||
|
if len(entry.Never) != 1 || entry.Never[0] != "arch:arm64" {
|
||||||
|
t.Errorf("never = %v, want [arch:arm64]", entry.Never)
|
||||||
|
}
|
||||||
|
}
|
||||||
238
garden/targeting_test.go
Normal file
238
garden/targeting_test.go
Normal file
@@ -0,0 +1,238 @@
|
|||||||
|
package garden
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/manifest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEntryApplies_NoTargeting(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc"}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("entry with no targeting should always apply")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_OnlyMatch(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Only: []string{"os:linux"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("should match os:linux")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_OnlyNoMatch(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Only: []string{"os:darwin"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
t.Error("os:darwin should not match os:linux machine")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_OnlyHostname(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Only: []string{"vade"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("should match hostname vade")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_OnlyTag(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Only: []string{"tag:work"}}
|
||||||
|
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "tag:work"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("should match tag:work")
|
||||||
|
}
|
||||||
|
|
||||||
|
ok, err = EntryApplies(entry, []string{"vade", "os:linux"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
t.Error("should not match without tag:work")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_NeverMatch(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Never: []string{"arch:arm64"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:arm64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
t.Error("should be excluded by never:arch:arm64")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_NeverNoMatch(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Never: []string{"arch:arm64"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("arch:amd64 machine should not be excluded by never:arch:arm64")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_BothError(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{
|
||||||
|
Path: "~/.bashrc",
|
||||||
|
Only: []string{"os:linux"},
|
||||||
|
Never: []string{"arch:arm64"},
|
||||||
|
}
|
||||||
|
_, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("should error when both only and never are set")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_CaseInsensitive(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Only: []string{"OS:Linux"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("matching should be case-insensitive")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEntryApplies_OnlyMultiple(t *testing.T) {
|
||||||
|
entry := &manifest.Entry{Path: "~/.bashrc", Only: []string{"os:darwin", "os:linux"}}
|
||||||
|
ok, err := EntryApplies(entry, []string{"vade", "os:linux", "arch:amd64"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Error("should match if any label in only matches")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIdentity(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
labels := g.Identity()
|
||||||
|
|
||||||
|
// Should contain os and arch.
|
||||||
|
found := make(map[string]bool)
|
||||||
|
for _, l := range labels {
|
||||||
|
found[l] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
osLabel := "os:" + runtime.GOOS
|
||||||
|
archLabel := "arch:" + runtime.GOARCH
|
||||||
|
if !found[osLabel] {
|
||||||
|
t.Errorf("identity should contain %s", osLabel)
|
||||||
|
}
|
||||||
|
if !found[archLabel] {
|
||||||
|
t.Errorf("identity should contain %s", archLabel)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should contain a hostname (non-empty, no dots).
|
||||||
|
hostname := labels[0]
|
||||||
|
if hostname == "" || strings.Contains(hostname, ".") || strings.Contains(hostname, ":") {
|
||||||
|
t.Errorf("first label should be short hostname, got %q", hostname)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTags(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
g, err := Init(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// No tags initially.
|
||||||
|
if tags := g.LoadTags(); len(tags) != 0 {
|
||||||
|
t.Fatalf("expected no tags, got %v", tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add tags.
|
||||||
|
if err := g.SaveTag("work"); err != nil {
|
||||||
|
t.Fatalf("SaveTag: %v", err)
|
||||||
|
}
|
||||||
|
if err := g.SaveTag("desktop"); err != nil {
|
||||||
|
t.Fatalf("SaveTag: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tags := g.LoadTags()
|
||||||
|
if len(tags) != 2 {
|
||||||
|
t.Fatalf("expected 2 tags, got %v", tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duplicate add is idempotent.
|
||||||
|
if err := g.SaveTag("work"); err != nil {
|
||||||
|
t.Fatalf("SaveTag duplicate: %v", err)
|
||||||
|
}
|
||||||
|
if tags := g.LoadTags(); len(tags) != 2 {
|
||||||
|
t.Fatalf("expected 2 tags after duplicate add, got %v", tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove.
|
||||||
|
if err := g.RemoveTag("work"); err != nil {
|
||||||
|
t.Fatalf("RemoveTag: %v", err)
|
||||||
|
}
|
||||||
|
tags = g.LoadTags()
|
||||||
|
if len(tags) != 1 || tags[0] != "desktop" {
|
||||||
|
t.Fatalf("expected [desktop], got %v", tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tags appear in identity.
|
||||||
|
labels := g.Identity()
|
||||||
|
found := false
|
||||||
|
for _, l := range labels {
|
||||||
|
if l == "tag:desktop" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Errorf("identity should contain tag:desktop, got %v", labels)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInitCreatesGitignoreWithTags(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
repoDir := filepath.Join(root, "repo")
|
||||||
|
|
||||||
|
if _, err := Init(repoDir); err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(filepath.Join(repoDir, ".gitignore"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading .gitignore: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(data), "tags") {
|
||||||
|
t.Error(".gitignore should contain 'tags'")
|
||||||
|
}
|
||||||
|
}
|
||||||
20
go.mod
20
go.mod
@@ -3,17 +3,23 @@ module github.com/kisom/sgard
|
|||||||
go 1.25.7
|
go 1.25.7
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
|
github.com/jonboulle/clockwork v0.5.0
|
||||||
|
github.com/keys-pub/go-libfido2 v1.5.3
|
||||||
|
github.com/spf13/cobra v1.10.2
|
||||||
|
golang.org/x/crypto v0.49.0
|
||||||
|
golang.org/x/term v0.41.0
|
||||||
|
google.golang.org/grpc v1.79.3
|
||||||
|
google.golang.org/protobuf v1.36.11
|
||||||
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
github.com/jonboulle/clockwork v0.5.0 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/spf13/cobra v1.10.2 // indirect
|
|
||||||
github.com/spf13/pflag v1.0.9 // indirect
|
github.com/spf13/pflag v1.0.9 // indirect
|
||||||
golang.org/x/crypto v0.49.0 // indirect
|
|
||||||
golang.org/x/net v0.51.0 // indirect
|
golang.org/x/net v0.51.0 // indirect
|
||||||
golang.org/x/sys v0.42.0 // indirect
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
golang.org/x/text v0.35.0 // indirect
|
golang.org/x/text v0.35.0 // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
||||||
google.golang.org/grpc v1.79.3 // indirect
|
|
||||||
google.golang.org/protobuf v1.36.11 // indirect
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
|
||||||
)
|
)
|
||||||
|
|||||||
43
go.sum
43
go.sum
@@ -1,30 +1,73 @@
|
|||||||
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
|
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||||
|
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||||
|
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
|
github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
|
||||||
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
|
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
|
||||||
|
github.com/keys-pub/go-libfido2 v1.5.3 h1:vtgHxlSB43u6lj0TSuA3VvT6z3E7VI+L1a2hvMFdECk=
|
||||||
|
github.com/keys-pub/go-libfido2 v1.5.3/go.mod h1:P0V19qHwJNY0htZwZDe9Ilvs/nokGhdFX7faKFyZ6+U=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||||
|
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||||
|
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
|
||||||
|
go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
|
||||||
|
go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
|
||||||
|
go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
|
||||||
|
go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
|
||||||
|
go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
|
||||||
|
go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
|
||||||
|
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||||
|
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
|
||||||
|
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||||
|
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||||
|
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
265
integration/phase4_test.go
Normal file
265
integration/phase4_test.go
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
package integration
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/client"
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/kisom/sgard/server"
|
||||||
|
"github.com/kisom/sgard/sgardpb"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials"
|
||||||
|
)
|
||||||
|
|
||||||
|
func generateSelfSignedCert(t *testing.T) (tls.Certificate, *x509.CertPool) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generating key: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
template := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(1),
|
||||||
|
Subject: pkix.Name{CommonName: "sgard-e2e"},
|
||||||
|
NotBefore: time.Now().Add(-time.Minute),
|
||||||
|
NotAfter: time.Now().Add(time.Hour),
|
||||||
|
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
|
||||||
|
DNSNames: []string{"localhost"},
|
||||||
|
}
|
||||||
|
|
||||||
|
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating certificate: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||||
|
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshaling key: %v", err)
|
||||||
|
}
|
||||||
|
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
|
||||||
|
|
||||||
|
cert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("loading key pair: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pool := x509.NewCertPool()
|
||||||
|
pool.AppendCertsFromPEM(certPEM)
|
||||||
|
|
||||||
|
return cert, pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestE2E_Phase4 exercises TLS + encryption + locked files in a push/pull cycle.
|
||||||
|
func TestE2E_Phase4(t *testing.T) {
|
||||||
|
// --- Setup TLS server ---
|
||||||
|
cert, caPool := generateSelfSignedCert(t)
|
||||||
|
|
||||||
|
serverDir := t.TempDir()
|
||||||
|
serverGarden, err := garden.Init(serverDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init server garden: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverCreds := credentials.NewTLS(&tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})
|
||||||
|
srv := grpc.NewServer(grpc.Creds(serverCreds))
|
||||||
|
sgardpb.RegisterGardenSyncServer(srv, server.New(serverGarden))
|
||||||
|
t.Cleanup(func() { srv.Stop() })
|
||||||
|
|
||||||
|
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
go func() { _ = srv.Serve(lis) }()
|
||||||
|
|
||||||
|
clientCreds := credentials.NewTLS(&tls.Config{
|
||||||
|
RootCAs: caPool,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Build source garden with encryption + locked files ---
|
||||||
|
srcRoot := t.TempDir()
|
||||||
|
srcRepoDir := filepath.Join(srcRoot, "repo")
|
||||||
|
srcGarden, err := garden.Init(srcRepoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init source garden: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := srcGarden.EncryptInit("test-passphrase"); err != nil {
|
||||||
|
t.Fatalf("EncryptInit: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
plainFile := filepath.Join(srcRoot, "plain")
|
||||||
|
secretFile := filepath.Join(srcRoot, "secret")
|
||||||
|
lockedFile := filepath.Join(srcRoot, "locked")
|
||||||
|
encLockedFile := filepath.Join(srcRoot, "enc-locked")
|
||||||
|
|
||||||
|
if err := os.WriteFile(plainFile, []byte("plain data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("write: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secretFile, []byte("secret data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("write: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(lockedFile, []byte("locked data"), 0o644); err != nil {
|
||||||
|
t.Fatalf("write: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(encLockedFile, []byte("enc+locked data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("write: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := srcGarden.Add([]string{plainFile}); err != nil {
|
||||||
|
t.Fatalf("Add plain: %v", err)
|
||||||
|
}
|
||||||
|
if err := srcGarden.Add([]string{secretFile}, garden.AddOptions{Encrypt: true}); err != nil {
|
||||||
|
t.Fatalf("Add encrypted: %v", err)
|
||||||
|
}
|
||||||
|
if err := srcGarden.Add([]string{lockedFile}, garden.AddOptions{Lock: true}); err != nil {
|
||||||
|
t.Fatalf("Add locked: %v", err)
|
||||||
|
}
|
||||||
|
if err := srcGarden.Add([]string{encLockedFile}, garden.AddOptions{Encrypt: true, Lock: true}); err != nil {
|
||||||
|
t.Fatalf("Add encrypted+locked: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bump timestamp so push wins.
|
||||||
|
srcManifest := srcGarden.GetManifest()
|
||||||
|
srcManifest.Updated = time.Now().UTC().Add(time.Hour)
|
||||||
|
if err := srcGarden.ReplaceManifest(srcManifest); err != nil {
|
||||||
|
t.Fatalf("ReplaceManifest: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Push over TLS ---
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
pushConn, err := grpc.NewClient(lis.Addr().String(),
|
||||||
|
grpc.WithTransportCredentials(clientCreds),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial for push: %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = pushConn.Close() }()
|
||||||
|
|
||||||
|
pushClient := client.New(pushConn)
|
||||||
|
pushed, err := pushClient.Push(ctx, srcGarden)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Push: %v", err)
|
||||||
|
}
|
||||||
|
if pushed < 2 {
|
||||||
|
t.Errorf("expected at least 2 blobs pushed, got %d", pushed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Pull to a fresh garden over TLS ---
|
||||||
|
dstRoot := t.TempDir()
|
||||||
|
dstRepoDir := filepath.Join(dstRoot, "repo")
|
||||||
|
dstGarden, err := garden.Init(dstRepoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init dest garden: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pullConn, err := grpc.NewClient(lis.Addr().String(),
|
||||||
|
grpc.WithTransportCredentials(clientCreds),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial for pull: %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = pullConn.Close() }()
|
||||||
|
|
||||||
|
pullClient := client.New(pullConn)
|
||||||
|
pulled, err := pullClient.Pull(ctx, dstGarden)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Pull: %v", err)
|
||||||
|
}
|
||||||
|
if pulled < 2 {
|
||||||
|
t.Errorf("expected at least 2 blobs pulled, got %d", pulled)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Verify the pulled manifest ---
|
||||||
|
dstManifest := dstGarden.GetManifest()
|
||||||
|
if len(dstManifest.Files) != 4 {
|
||||||
|
t.Fatalf("expected 4 entries, got %d", len(dstManifest.Files))
|
||||||
|
}
|
||||||
|
|
||||||
|
type entryInfo struct {
|
||||||
|
encrypted bool
|
||||||
|
locked bool
|
||||||
|
}
|
||||||
|
entryMap := make(map[string]entryInfo)
|
||||||
|
for _, e := range dstManifest.Files {
|
||||||
|
entryMap[e.Path] = entryInfo{e.Encrypted, e.Locked}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify flags survived round trip.
|
||||||
|
for path, info := range entryMap {
|
||||||
|
switch {
|
||||||
|
case path == toTilde(secretFile):
|
||||||
|
if !info.encrypted {
|
||||||
|
t.Errorf("%s should be encrypted", path)
|
||||||
|
}
|
||||||
|
case path == toTilde(lockedFile):
|
||||||
|
if !info.locked {
|
||||||
|
t.Errorf("%s should be locked", path)
|
||||||
|
}
|
||||||
|
case path == toTilde(encLockedFile):
|
||||||
|
if !info.encrypted || !info.locked {
|
||||||
|
t.Errorf("%s should be encrypted+locked", path)
|
||||||
|
}
|
||||||
|
case path == toTilde(plainFile):
|
||||||
|
if info.encrypted || info.locked {
|
||||||
|
t.Errorf("%s should be plain", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify encryption config survived.
|
||||||
|
if dstManifest.Encryption == nil {
|
||||||
|
t.Fatal("encryption config should survive push/pull")
|
||||||
|
}
|
||||||
|
if dstManifest.Encryption.Algorithm != "xchacha20-poly1305" {
|
||||||
|
t.Errorf("algorithm = %s, want xchacha20-poly1305", dstManifest.Encryption.Algorithm)
|
||||||
|
}
|
||||||
|
if _, ok := dstManifest.Encryption.KekSlots["passphrase"]; !ok {
|
||||||
|
t.Error("passphrase slot should survive push/pull")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify all blobs arrived.
|
||||||
|
for _, e := range dstManifest.Files {
|
||||||
|
if e.Hash != "" && !dstGarden.BlobExists(e.Hash) {
|
||||||
|
t.Errorf("blob missing for %s (hash %s)", e.Path, e.Hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlock on dest and verify DEK works.
|
||||||
|
if err := dstGarden.UnlockDEK(func() (string, error) { return "test-passphrase", nil }); err != nil {
|
||||||
|
t.Fatalf("UnlockDEK on dest: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func toTilde(path string) string {
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
rel, err := filepath.Rel(home, path)
|
||||||
|
if err != nil || len(rel) > 0 && rel[0] == '.' {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
return "~/" + rel
|
||||||
|
}
|
||||||
148
integration/phase5_test.go
Normal file
148
integration/phase5_test.go
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
package integration
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/client"
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/kisom/sgard/server"
|
||||||
|
"github.com/kisom/sgard/sgardpb"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials/insecure"
|
||||||
|
"google.golang.org/grpc/test/bufconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
const bufSize = 1024 * 1024
|
||||||
|
|
||||||
|
// TestE2E_Phase5_Targeting verifies that targeting labels survive push/pull
|
||||||
|
// and that restore respects them.
|
||||||
|
func TestE2E_Phase5_Targeting(t *testing.T) {
|
||||||
|
// Set up bufconn server.
|
||||||
|
serverDir := t.TempDir()
|
||||||
|
serverGarden, err := garden.Init(serverDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init server: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
lis := bufconn.Listen(bufSize)
|
||||||
|
srv := grpc.NewServer()
|
||||||
|
sgardpb.RegisterGardenSyncServer(srv, server.New(serverGarden))
|
||||||
|
t.Cleanup(func() { srv.Stop() })
|
||||||
|
go func() { _ = srv.Serve(lis) }()
|
||||||
|
|
||||||
|
conn, err := grpc.NewClient("passthrough:///bufconn",
|
||||||
|
grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {
|
||||||
|
return lis.Dial()
|
||||||
|
}),
|
||||||
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = conn.Close() })
|
||||||
|
|
||||||
|
// --- Build source garden with targeted entries ---
|
||||||
|
srcRoot := t.TempDir()
|
||||||
|
srcRepoDir := filepath.Join(srcRoot, "repo")
|
||||||
|
srcGarden, err := garden.Init(srcRepoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init source: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
linuxFile := filepath.Join(srcRoot, "linux-only")
|
||||||
|
everywhereFile := filepath.Join(srcRoot, "everywhere")
|
||||||
|
neverArmFile := filepath.Join(srcRoot, "never-arm")
|
||||||
|
|
||||||
|
if err := os.WriteFile(linuxFile, []byte("linux"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(everywhereFile, []byte("everywhere"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(neverArmFile, []byte("not arm"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := srcGarden.Add([]string{linuxFile}, garden.AddOptions{Only: []string{"os:linux"}}); err != nil {
|
||||||
|
t.Fatalf("Add linux-only: %v", err)
|
||||||
|
}
|
||||||
|
if err := srcGarden.Add([]string{everywhereFile}); err != nil {
|
||||||
|
t.Fatalf("Add everywhere: %v", err)
|
||||||
|
}
|
||||||
|
if err := srcGarden.Add([]string{neverArmFile}, garden.AddOptions{Never: []string{"arch:arm64"}}); err != nil {
|
||||||
|
t.Fatalf("Add never-arm: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bump timestamp.
|
||||||
|
m := srcGarden.GetManifest()
|
||||||
|
m.Updated = time.Now().UTC().Add(time.Hour)
|
||||||
|
if err := srcGarden.ReplaceManifest(m); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Push ---
|
||||||
|
ctx := context.Background()
|
||||||
|
pushClient := client.New(conn)
|
||||||
|
if _, err := pushClient.Push(ctx, srcGarden); err != nil {
|
||||||
|
t.Fatalf("Push: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Pull to fresh garden ---
|
||||||
|
dstRoot := t.TempDir()
|
||||||
|
dstRepoDir := filepath.Join(dstRoot, "repo")
|
||||||
|
dstGarden, err := garden.Init(dstRepoDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init dest: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pullClient := client.New(conn)
|
||||||
|
if _, err := pullClient.Pull(ctx, dstGarden); err != nil {
|
||||||
|
t.Fatalf("Pull: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Verify targeting survived ---
|
||||||
|
dm := dstGarden.GetManifest()
|
||||||
|
if len(dm.Files) != 3 {
|
||||||
|
t.Fatalf("expected 3 entries, got %d", len(dm.Files))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, e := range dm.Files {
|
||||||
|
switch {
|
||||||
|
case e.Path == toTilde(linuxFile):
|
||||||
|
if len(e.Only) != 1 || e.Only[0] != "os:linux" {
|
||||||
|
t.Errorf("%s: only = %v, want [os:linux]", e.Path, e.Only)
|
||||||
|
}
|
||||||
|
case e.Path == toTilde(everywhereFile):
|
||||||
|
if len(e.Only) != 0 || len(e.Never) != 0 {
|
||||||
|
t.Errorf("%s: should have no targeting", e.Path)
|
||||||
|
}
|
||||||
|
case e.Path == toTilde(neverArmFile):
|
||||||
|
if len(e.Never) != 1 || e.Never[0] != "arch:arm64" {
|
||||||
|
t.Errorf("%s: never = %v, want [arch:arm64]", e.Path, e.Never)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify restore skips non-matching entries.
|
||||||
|
// Delete all files, then restore — only matching entries should appear.
|
||||||
|
_ = os.Remove(linuxFile)
|
||||||
|
_ = os.Remove(everywhereFile)
|
||||||
|
_ = os.Remove(neverArmFile)
|
||||||
|
|
||||||
|
if err := dstGarden.Restore(nil, true, nil); err != nil {
|
||||||
|
t.Fatalf("Restore: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// "everywhere" should always be restored.
|
||||||
|
if _, err := os.Stat(everywhereFile); os.IsNotExist(err) {
|
||||||
|
t.Error("everywhere file should be restored")
|
||||||
|
}
|
||||||
|
|
||||||
|
// "linux-only" depends on current OS — we just verify no error occurred.
|
||||||
|
// "never-arm" depends on current arch.
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
@@ -20,6 +21,8 @@ type Entry struct {
|
|||||||
Mode string `yaml:"mode,omitempty"`
|
Mode string `yaml:"mode,omitempty"`
|
||||||
Target string `yaml:"target,omitempty"`
|
Target string `yaml:"target,omitempty"`
|
||||||
Updated time.Time `yaml:"updated"`
|
Updated time.Time `yaml:"updated"`
|
||||||
|
Only []string `yaml:"only,omitempty"`
|
||||||
|
Never []string `yaml:"never,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// KekSlot describes a single KEK source that can unwrap the DEK.
|
// KekSlot describes a single KEK source that can unwrap the DEK.
|
||||||
@@ -46,9 +49,32 @@ type Manifest struct {
|
|||||||
Updated time.Time `yaml:"updated"`
|
Updated time.Time `yaml:"updated"`
|
||||||
Message string `yaml:"message,omitempty"`
|
Message string `yaml:"message,omitempty"`
|
||||||
Files []Entry `yaml:"files"`
|
Files []Entry `yaml:"files"`
|
||||||
|
Exclude []string `yaml:"exclude,omitempty"`
|
||||||
Encryption *Encryption `yaml:"encryption,omitempty"`
|
Encryption *Encryption `yaml:"encryption,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsExcluded reports whether the given tilde path should be excluded from
|
||||||
|
// tracking. A path is excluded if it matches an exclude entry exactly, or
|
||||||
|
// if it falls under an excluded directory (an exclude entry that is a prefix
|
||||||
|
// followed by a path separator).
|
||||||
|
func (m *Manifest) IsExcluded(tildePath string) bool {
|
||||||
|
for _, ex := range m.Exclude {
|
||||||
|
if tildePath == ex {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Directory exclusion: if the exclude entry is a prefix of the
|
||||||
|
// path with a separator boundary, the path is under that directory.
|
||||||
|
prefix := ex
|
||||||
|
if !strings.HasSuffix(prefix, "/") {
|
||||||
|
prefix += "/"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(tildePath, prefix) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// New creates a new empty manifest with Version 1 and timestamps set to now.
|
// New creates a new empty manifest with Version 1 and timestamps set to now.
|
||||||
func New() *Manifest {
|
func New() *Manifest {
|
||||||
return NewWithTime(time.Now().UTC())
|
return NewWithTime(time.Now().UTC())
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ message ManifestEntry {
|
|||||||
string plaintext_hash = 7; // SHA-256 of plaintext (encrypted entries only)
|
string plaintext_hash = 7; // SHA-256 of plaintext (encrypted entries only)
|
||||||
bool encrypted = 8;
|
bool encrypted = 8;
|
||||||
bool locked = 9; // repo-authoritative; restore always overwrites
|
bool locked = 9; // repo-authoritative; restore always overwrites
|
||||||
|
repeated string only = 10; // per-machine targeting: only apply on matching
|
||||||
|
repeated string never = 11; // per-machine targeting: never apply on matching
|
||||||
}
|
}
|
||||||
|
|
||||||
// KekSlot describes a single KEK source for unwrapping the DEK.
|
// KekSlot describes a single KEK source for unwrapping the DEK.
|
||||||
@@ -44,6 +46,7 @@ message Manifest {
|
|||||||
string message = 4;
|
string message = 4;
|
||||||
repeated ManifestEntry files = 5;
|
repeated ManifestEntry files = 5;
|
||||||
Encryption encryption = 6;
|
Encryption encryption = 6;
|
||||||
|
repeated string exclude = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
// BlobChunk is one piece of a streamed blob. The first chunk for a given
|
// BlobChunk is one piece of a streamed blob. The first chunk for a given
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ func ManifestToProto(m *manifest.Manifest) *sgardpb.Manifest {
|
|||||||
Updated: timestamppb.New(m.Updated),
|
Updated: timestamppb.New(m.Updated),
|
||||||
Message: m.Message,
|
Message: m.Message,
|
||||||
Files: files,
|
Files: files,
|
||||||
|
Exclude: m.Exclude,
|
||||||
}
|
}
|
||||||
if m.Encryption != nil {
|
if m.Encryption != nil {
|
||||||
pb.Encryption = EncryptionToProto(m.Encryption)
|
pb.Encryption = EncryptionToProto(m.Encryption)
|
||||||
@@ -38,6 +39,7 @@ func ProtoToManifest(p *sgardpb.Manifest) *manifest.Manifest {
|
|||||||
Updated: p.GetUpdated().AsTime(),
|
Updated: p.GetUpdated().AsTime(),
|
||||||
Message: p.GetMessage(),
|
Message: p.GetMessage(),
|
||||||
Files: files,
|
Files: files,
|
||||||
|
Exclude: p.GetExclude(),
|
||||||
}
|
}
|
||||||
if p.GetEncryption() != nil {
|
if p.GetEncryption() != nil {
|
||||||
m.Encryption = ProtoToEncryption(p.GetEncryption())
|
m.Encryption = ProtoToEncryption(p.GetEncryption())
|
||||||
@@ -57,6 +59,8 @@ func EntryToProto(e manifest.Entry) *sgardpb.ManifestEntry {
|
|||||||
PlaintextHash: e.PlaintextHash,
|
PlaintextHash: e.PlaintextHash,
|
||||||
Encrypted: e.Encrypted,
|
Encrypted: e.Encrypted,
|
||||||
Locked: e.Locked,
|
Locked: e.Locked,
|
||||||
|
Only: e.Only,
|
||||||
|
Never: e.Never,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,6 +76,8 @@ func ProtoToEntry(p *sgardpb.ManifestEntry) manifest.Entry {
|
|||||||
PlaintextHash: p.GetPlaintextHash(),
|
PlaintextHash: p.GetPlaintextHash(),
|
||||||
Encrypted: p.GetEncrypted(),
|
Encrypted: p.GetEncrypted(),
|
||||||
Locked: p.GetLocked(),
|
Locked: p.GetLocked(),
|
||||||
|
Only: p.GetOnly(),
|
||||||
|
Never: p.GetNever(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,46 @@ func TestEmptyManifestRoundTrip(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTargetingRoundTrip(t *testing.T) {
|
||||||
|
now := time.Date(2026, 3, 24, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
onlyEntry := manifest.Entry{
|
||||||
|
Path: "~/.bashrc.linux",
|
||||||
|
Type: "file",
|
||||||
|
Hash: "abcd",
|
||||||
|
Only: []string{"os:linux", "tag:work"},
|
||||||
|
Updated: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := EntryToProto(onlyEntry)
|
||||||
|
back := ProtoToEntry(proto)
|
||||||
|
|
||||||
|
if len(back.Only) != 2 || back.Only[0] != "os:linux" || back.Only[1] != "tag:work" {
|
||||||
|
t.Errorf("Only round-trip: got %v, want [os:linux tag:work]", back.Only)
|
||||||
|
}
|
||||||
|
if len(back.Never) != 0 {
|
||||||
|
t.Errorf("Never should be empty, got %v", back.Never)
|
||||||
|
}
|
||||||
|
|
||||||
|
neverEntry := manifest.Entry{
|
||||||
|
Path: "~/.config/heavy",
|
||||||
|
Type: "file",
|
||||||
|
Hash: "efgh",
|
||||||
|
Never: []string{"arch:arm64"},
|
||||||
|
Updated: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
proto2 := EntryToProto(neverEntry)
|
||||||
|
back2 := ProtoToEntry(proto2)
|
||||||
|
|
||||||
|
if len(back2.Never) != 1 || back2.Never[0] != "arch:arm64" {
|
||||||
|
t.Errorf("Never round-trip: got %v, want [arch:arm64]", back2.Never)
|
||||||
|
}
|
||||||
|
if len(back2.Only) != 0 {
|
||||||
|
t.Errorf("Only should be empty, got %v", back2.Only)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestEntryEmptyOptionalFieldsRoundTrip(t *testing.T) {
|
func TestEntryEmptyOptionalFieldsRoundTrip(t *testing.T) {
|
||||||
now := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
|
now := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
|
||||||
e := manifest.Entry{
|
e := manifest.Entry{
|
||||||
|
|||||||
237
server/tls_test.go
Normal file
237
server/tls_test.go
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/kisom/sgard/garden"
|
||||||
|
"github.com/kisom/sgard/manifest"
|
||||||
|
"github.com/kisom/sgard/sgardpb"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials"
|
||||||
|
)
|
||||||
|
|
||||||
|
// generateSelfSignedCert creates a self-signed TLS certificate for testing.
|
||||||
|
func generateSelfSignedCert(t *testing.T) (tls.Certificate, *x509.CertPool) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generating key: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
template := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(1),
|
||||||
|
Subject: pkix.Name{CommonName: "sgard-test"},
|
||||||
|
NotBefore: time.Now().Add(-time.Minute),
|
||||||
|
NotAfter: time.Now().Add(time.Hour),
|
||||||
|
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
|
||||||
|
DNSNames: []string{"localhost"},
|
||||||
|
}
|
||||||
|
|
||||||
|
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating certificate: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||||
|
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshaling key: %v", err)
|
||||||
|
}
|
||||||
|
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
|
||||||
|
|
||||||
|
cert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("loading key pair: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pool := x509.NewCertPool()
|
||||||
|
pool.AppendCertsFromPEM(certPEM)
|
||||||
|
|
||||||
|
return cert, pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// setupTLSTest creates a TLS-secured client-server pair.
|
||||||
|
func setupTLSTest(t *testing.T) (sgardpb.GardenSyncClient, *garden.Garden, *garden.Garden) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
serverDir := t.TempDir()
|
||||||
|
serverGarden, err := garden.Init(serverDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init server garden: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
clientDir := t.TempDir()
|
||||||
|
clientGarden, err := garden.Init(clientDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init client garden: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cert, caPool := generateSelfSignedCert(t)
|
||||||
|
|
||||||
|
// Server with TLS.
|
||||||
|
serverCreds := credentials.NewTLS(&tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})
|
||||||
|
srv := grpc.NewServer(grpc.Creds(serverCreds))
|
||||||
|
sgardpb.RegisterGardenSyncServer(srv, New(serverGarden))
|
||||||
|
t.Cleanup(func() { srv.Stop() })
|
||||||
|
|
||||||
|
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
_ = srv.Serve(lis)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Client with TLS, trusting the self-signed CA.
|
||||||
|
clientCreds := credentials.NewTLS(&tls.Config{
|
||||||
|
RootCAs: caPool,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})
|
||||||
|
conn, err := grpc.NewClient(lis.Addr().String(),
|
||||||
|
grpc.WithTransportCredentials(clientCreds),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial TLS: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = conn.Close() })
|
||||||
|
|
||||||
|
client := sgardpb.NewGardenSyncClient(conn)
|
||||||
|
return client, serverGarden, clientGarden
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTLS_PushPullCycle(t *testing.T) {
|
||||||
|
client, serverGarden, _ := setupTLSTest(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Write test blobs to get real hashes.
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
tmpGarden, err := garden.Init(tmpDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init tmp garden: %v", err)
|
||||||
|
}
|
||||||
|
blobData := []byte("TLS test blob content")
|
||||||
|
hash, err := tmpGarden.WriteBlob(blobData)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteBlob: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC().Add(time.Hour)
|
||||||
|
clientManifest := &manifest.Manifest{
|
||||||
|
Version: 1,
|
||||||
|
Created: now,
|
||||||
|
Updated: now,
|
||||||
|
Files: []manifest.Entry{
|
||||||
|
{Path: "~/.tlstest", Hash: hash, Type: "file", Mode: "0644", Updated: now},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push manifest over TLS.
|
||||||
|
pushResp, err := client.PushManifest(ctx, &sgardpb.PushManifestRequest{
|
||||||
|
Manifest: ManifestToProto(clientManifest),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PushManifest over TLS: %v", err)
|
||||||
|
}
|
||||||
|
if pushResp.Decision != sgardpb.PushManifestResponse_ACCEPTED {
|
||||||
|
t.Fatalf("decision: got %v, want ACCEPTED", pushResp.Decision)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push blob over TLS.
|
||||||
|
stream, err := client.PushBlobs(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PushBlobs over TLS: %v", err)
|
||||||
|
}
|
||||||
|
if err := stream.Send(&sgardpb.PushBlobsRequest{
|
||||||
|
Chunk: &sgardpb.BlobChunk{Hash: hash, Data: blobData},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("Send blob: %v", err)
|
||||||
|
}
|
||||||
|
blobResp, err := stream.CloseAndRecv()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CloseAndRecv: %v", err)
|
||||||
|
}
|
||||||
|
if blobResp.BlobsReceived != 1 {
|
||||||
|
t.Errorf("blobs_received: got %d, want 1", blobResp.BlobsReceived)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify blob arrived on server.
|
||||||
|
if !serverGarden.BlobExists(hash) {
|
||||||
|
t.Error("blob not found on server after TLS push")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pull manifest back over TLS.
|
||||||
|
pullResp, err := client.PullManifest(ctx, &sgardpb.PullManifestRequest{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PullManifest over TLS: %v", err)
|
||||||
|
}
|
||||||
|
pulledManifest := ProtoToManifest(pullResp.GetManifest())
|
||||||
|
if len(pulledManifest.Files) != 1 {
|
||||||
|
t.Fatalf("pulled manifest files: got %d, want 1", len(pulledManifest.Files))
|
||||||
|
}
|
||||||
|
if pulledManifest.Files[0].Path != "~/.tlstest" {
|
||||||
|
t.Errorf("pulled path: got %q, want %q", pulledManifest.Files[0].Path, "~/.tlstest")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTLS_RejectsPlaintextClient(t *testing.T) {
|
||||||
|
cert, _ := generateSelfSignedCert(t)
|
||||||
|
|
||||||
|
serverDir := t.TempDir()
|
||||||
|
serverGarden, err := garden.Init(serverDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("init server garden: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverCreds := credentials.NewTLS(&tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})
|
||||||
|
srv := grpc.NewServer(grpc.Creds(serverCreds))
|
||||||
|
sgardpb.RegisterGardenSyncServer(srv, New(serverGarden))
|
||||||
|
t.Cleanup(func() { srv.Stop() })
|
||||||
|
|
||||||
|
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
_ = srv.Serve(lis)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Try to connect without TLS — should fail.
|
||||||
|
conn, err := grpc.NewClient(lis.Addr().String(),
|
||||||
|
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
|
||||||
|
// No RootCAs — won't trust the self-signed cert.
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial: %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = conn.Close() }()
|
||||||
|
|
||||||
|
client := sgardpb.NewGardenSyncClient(conn)
|
||||||
|
_, err = client.PullManifest(context.Background(), &sgardpb.PullManifestRequest{})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error when connecting without trusted CA to TLS server")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||||
// versions:
|
// versions:
|
||||||
// protoc-gen-go v1.36.10
|
// protoc-gen-go v1.36.11
|
||||||
// protoc v6.32.1
|
// protoc v6.32.1
|
||||||
// source: sgard/v1/sgard.proto
|
// source: sgard/v1/sgard.proto
|
||||||
|
|
||||||
@@ -86,6 +86,8 @@ type ManifestEntry struct {
|
|||||||
PlaintextHash string `protobuf:"bytes,7,opt,name=plaintext_hash,json=plaintextHash,proto3" json:"plaintext_hash,omitempty"` // SHA-256 of plaintext (encrypted entries only)
|
PlaintextHash string `protobuf:"bytes,7,opt,name=plaintext_hash,json=plaintextHash,proto3" json:"plaintext_hash,omitempty"` // SHA-256 of plaintext (encrypted entries only)
|
||||||
Encrypted bool `protobuf:"varint,8,opt,name=encrypted,proto3" json:"encrypted,omitempty"`
|
Encrypted bool `protobuf:"varint,8,opt,name=encrypted,proto3" json:"encrypted,omitempty"`
|
||||||
Locked bool `protobuf:"varint,9,opt,name=locked,proto3" json:"locked,omitempty"` // repo-authoritative; restore always overwrites
|
Locked bool `protobuf:"varint,9,opt,name=locked,proto3" json:"locked,omitempty"` // repo-authoritative; restore always overwrites
|
||||||
|
Only []string `protobuf:"bytes,10,rep,name=only,proto3" json:"only,omitempty"` // per-machine targeting: only apply on matching
|
||||||
|
Never []string `protobuf:"bytes,11,rep,name=never,proto3" json:"never,omitempty"` // per-machine targeting: never apply on matching
|
||||||
unknownFields protoimpl.UnknownFields
|
unknownFields protoimpl.UnknownFields
|
||||||
sizeCache protoimpl.SizeCache
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
@@ -183,6 +185,20 @@ func (x *ManifestEntry) GetLocked() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *ManifestEntry) GetOnly() []string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Only
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ManifestEntry) GetNever() []string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Never
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// KekSlot describes a single KEK source for unwrapping the DEK.
|
// KekSlot describes a single KEK source for unwrapping the DEK.
|
||||||
type KekSlot struct {
|
type KekSlot struct {
|
||||||
state protoimpl.MessageState `protogen:"open.v1"`
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
@@ -338,6 +354,7 @@ type Manifest struct {
|
|||||||
Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"`
|
Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"`
|
||||||
Files []*ManifestEntry `protobuf:"bytes,5,rep,name=files,proto3" json:"files,omitempty"`
|
Files []*ManifestEntry `protobuf:"bytes,5,rep,name=files,proto3" json:"files,omitempty"`
|
||||||
Encryption *Encryption `protobuf:"bytes,6,opt,name=encryption,proto3" json:"encryption,omitempty"`
|
Encryption *Encryption `protobuf:"bytes,6,opt,name=encryption,proto3" json:"encryption,omitempty"`
|
||||||
|
Exclude []string `protobuf:"bytes,7,rep,name=exclude,proto3" json:"exclude,omitempty"`
|
||||||
unknownFields protoimpl.UnknownFields
|
unknownFields protoimpl.UnknownFields
|
||||||
sizeCache protoimpl.SizeCache
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
@@ -414,6 +431,13 @@ func (x *Manifest) GetEncryption() *Encryption {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *Manifest) GetExclude() []string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Exclude
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// BlobChunk is one piece of a streamed blob. The first chunk for a given
|
// BlobChunk is one piece of a streamed blob. The first chunk for a given
|
||||||
// hash carries the hash field; subsequent chunks omit it.
|
// hash carries the hash field; subsequent chunks omit it.
|
||||||
type BlobChunk struct {
|
type BlobChunk struct {
|
||||||
@@ -1079,7 +1103,7 @@ var File_sgard_v1_sgard_proto protoreflect.FileDescriptor
|
|||||||
|
|
||||||
const file_sgard_v1_sgard_proto_rawDesc = "" +
|
const file_sgard_v1_sgard_proto_rawDesc = "" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"\x14sgard/v1/sgard.proto\x12\bsgard.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\x8a\x02\n" +
|
"\x14sgard/v1/sgard.proto\x12\bsgard.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\xb4\x02\n" +
|
||||||
"\rManifestEntry\x12\x12\n" +
|
"\rManifestEntry\x12\x12\n" +
|
||||||
"\x04path\x18\x01 \x01(\tR\x04path\x12\x12\n" +
|
"\x04path\x18\x01 \x01(\tR\x04path\x12\x12\n" +
|
||||||
"\x04hash\x18\x02 \x01(\tR\x04hash\x12\x12\n" +
|
"\x04hash\x18\x02 \x01(\tR\x04hash\x12\x12\n" +
|
||||||
@@ -1089,7 +1113,10 @@ const file_sgard_v1_sgard_proto_rawDesc = "" +
|
|||||||
"\aupdated\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\aupdated\x12%\n" +
|
"\aupdated\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\aupdated\x12%\n" +
|
||||||
"\x0eplaintext_hash\x18\a \x01(\tR\rplaintextHash\x12\x1c\n" +
|
"\x0eplaintext_hash\x18\a \x01(\tR\rplaintextHash\x12\x1c\n" +
|
||||||
"\tencrypted\x18\b \x01(\bR\tencrypted\x12\x16\n" +
|
"\tencrypted\x18\b \x01(\bR\tencrypted\x12\x16\n" +
|
||||||
"\x06locked\x18\t \x01(\bR\x06locked\"\xe4\x01\n" +
|
"\x06locked\x18\t \x01(\bR\x06locked\x12\x12\n" +
|
||||||
|
"\x04only\x18\n" +
|
||||||
|
" \x03(\tR\x04only\x12\x14\n" +
|
||||||
|
"\x05never\x18\v \x03(\tR\x05never\"\xe4\x01\n" +
|
||||||
"\aKekSlot\x12\x12\n" +
|
"\aKekSlot\x12\x12\n" +
|
||||||
"\x04type\x18\x01 \x01(\tR\x04type\x12\x1f\n" +
|
"\x04type\x18\x01 \x01(\tR\x04type\x12\x1f\n" +
|
||||||
"\vargon2_time\x18\x02 \x01(\x05R\n" +
|
"\vargon2_time\x18\x02 \x01(\x05R\n" +
|
||||||
@@ -1106,7 +1133,7 @@ const file_sgard_v1_sgard_proto_rawDesc = "" +
|
|||||||
"\tkek_slots\x18\x02 \x03(\v2\".sgard.v1.Encryption.KekSlotsEntryR\bkekSlots\x1aN\n" +
|
"\tkek_slots\x18\x02 \x03(\v2\".sgard.v1.Encryption.KekSlotsEntryR\bkekSlots\x1aN\n" +
|
||||||
"\rKekSlotsEntry\x12\x10\n" +
|
"\rKekSlotsEntry\x12\x10\n" +
|
||||||
"\x03key\x18\x01 \x01(\tR\x03key\x12'\n" +
|
"\x03key\x18\x01 \x01(\tR\x03key\x12'\n" +
|
||||||
"\x05value\x18\x02 \x01(\v2\x11.sgard.v1.KekSlotR\x05value:\x028\x01\"\x8f\x02\n" +
|
"\x05value\x18\x02 \x01(\v2\x11.sgard.v1.KekSlotR\x05value:\x028\x01\"\xa9\x02\n" +
|
||||||
"\bManifest\x12\x18\n" +
|
"\bManifest\x12\x18\n" +
|
||||||
"\aversion\x18\x01 \x01(\x05R\aversion\x124\n" +
|
"\aversion\x18\x01 \x01(\x05R\aversion\x124\n" +
|
||||||
"\acreated\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\acreated\x124\n" +
|
"\acreated\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\acreated\x124\n" +
|
||||||
@@ -1115,7 +1142,8 @@ const file_sgard_v1_sgard_proto_rawDesc = "" +
|
|||||||
"\x05files\x18\x05 \x03(\v2\x17.sgard.v1.ManifestEntryR\x05files\x124\n" +
|
"\x05files\x18\x05 \x03(\v2\x17.sgard.v1.ManifestEntryR\x05files\x124\n" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"encryption\x18\x06 \x01(\v2\x14.sgard.v1.EncryptionR\n" +
|
"encryption\x18\x06 \x01(\v2\x14.sgard.v1.EncryptionR\n" +
|
||||||
"encryption\"3\n" +
|
"encryption\x12\x18\n" +
|
||||||
|
"\aexclude\x18\a \x03(\tR\aexclude\"3\n" +
|
||||||
"\tBlobChunk\x12\x12\n" +
|
"\tBlobChunk\x12\x12\n" +
|
||||||
"\x04hash\x18\x01 \x01(\tR\x04hash\x12\x12\n" +
|
"\x04hash\x18\x01 \x01(\tR\x04hash\x12\x12\n" +
|
||||||
"\x04data\x18\x02 \x01(\fR\x04data\"E\n" +
|
"\x04data\x18\x02 \x01(\fR\x04data\"E\n" +
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||||
// versions:
|
// versions:
|
||||||
// - protoc-gen-go-grpc v1.5.1
|
// - protoc-gen-go-grpc v1.6.1
|
||||||
// - protoc v6.32.1
|
// - protoc v6.32.1
|
||||||
// source: sgard/v1/sgard.proto
|
// source: sgard/v1/sgard.proto
|
||||||
|
|
||||||
@@ -152,22 +152,22 @@ type GardenSyncServer interface {
|
|||||||
type UnimplementedGardenSyncServer struct{}
|
type UnimplementedGardenSyncServer struct{}
|
||||||
|
|
||||||
func (UnimplementedGardenSyncServer) Authenticate(context.Context, *AuthenticateRequest) (*AuthenticateResponse, error) {
|
func (UnimplementedGardenSyncServer) Authenticate(context.Context, *AuthenticateRequest) (*AuthenticateResponse, error) {
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Authenticate not implemented")
|
return nil, status.Error(codes.Unimplemented, "method Authenticate not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedGardenSyncServer) PushManifest(context.Context, *PushManifestRequest) (*PushManifestResponse, error) {
|
func (UnimplementedGardenSyncServer) PushManifest(context.Context, *PushManifestRequest) (*PushManifestResponse, error) {
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method PushManifest not implemented")
|
return nil, status.Error(codes.Unimplemented, "method PushManifest not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedGardenSyncServer) PushBlobs(grpc.ClientStreamingServer[PushBlobsRequest, PushBlobsResponse]) error {
|
func (UnimplementedGardenSyncServer) PushBlobs(grpc.ClientStreamingServer[PushBlobsRequest, PushBlobsResponse]) error {
|
||||||
return status.Errorf(codes.Unimplemented, "method PushBlobs not implemented")
|
return status.Error(codes.Unimplemented, "method PushBlobs not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedGardenSyncServer) PullManifest(context.Context, *PullManifestRequest) (*PullManifestResponse, error) {
|
func (UnimplementedGardenSyncServer) PullManifest(context.Context, *PullManifestRequest) (*PullManifestResponse, error) {
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method PullManifest not implemented")
|
return nil, status.Error(codes.Unimplemented, "method PullManifest not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedGardenSyncServer) PullBlobs(*PullBlobsRequest, grpc.ServerStreamingServer[PullBlobsResponse]) error {
|
func (UnimplementedGardenSyncServer) PullBlobs(*PullBlobsRequest, grpc.ServerStreamingServer[PullBlobsResponse]) error {
|
||||||
return status.Errorf(codes.Unimplemented, "method PullBlobs not implemented")
|
return status.Error(codes.Unimplemented, "method PullBlobs not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedGardenSyncServer) Prune(context.Context, *PruneRequest) (*PruneResponse, error) {
|
func (UnimplementedGardenSyncServer) Prune(context.Context, *PruneRequest) (*PruneResponse, error) {
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Prune not implemented")
|
return nil, status.Error(codes.Unimplemented, "method Prune not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedGardenSyncServer) mustEmbedUnimplementedGardenSyncServer() {}
|
func (UnimplementedGardenSyncServer) mustEmbedUnimplementedGardenSyncServer() {}
|
||||||
func (UnimplementedGardenSyncServer) testEmbeddedByValue() {}
|
func (UnimplementedGardenSyncServer) testEmbeddedByValue() {}
|
||||||
@@ -180,7 +180,7 @@ type UnsafeGardenSyncServer interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func RegisterGardenSyncServer(s grpc.ServiceRegistrar, srv GardenSyncServer) {
|
func RegisterGardenSyncServer(s grpc.ServiceRegistrar, srv GardenSyncServer) {
|
||||||
// If the following call pancis, it indicates UnimplementedGardenSyncServer was
|
// If the following call panics, it indicates UnimplementedGardenSyncServer was
|
||||||
// embedded by pointer and is nil. This will cause panics if an
|
// embedded by pointer and is nil. This will cause panics if an
|
||||||
// unimplemented method is ever invoked, so we test this at initialization
|
// unimplemented method is ever invoked, so we test this at initialization
|
||||||
// time to prevent it from happening at runtime later due to I/O.
|
// time to prevent it from happening at runtime later due to I/O.
|
||||||
|
|||||||
Reference in New Issue
Block a user