Files
archie/internal/infrastructure/signedoci/freshness.go
T
sam 9d8f364af1
Quality / check (push) Successful in 5m53s
deploy / gate (push) Canceled after 0s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
feat(releaseupdate): signed OCI distribution sources for releases and the catalogue (#1715)
2026-10-31 18:18:43 +11:00

87 lines
2.2 KiB
Go

package signedoci
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/fsutil"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
// FileFreshness is the durable freshness mark of accepted issue times, kept as one small JSON file
// written atomically so a crash never leaves a half-written mark. A missing
// file is no mark yet; a file that exists but does not parse is an error, so
// a corrupt mark fails closed instead of opening a replay window.
type FileFreshness struct {
Path string
mu sync.Mutex
}
func (f *FileFreshness) Newest(context.Context) (time.Time, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.read()
}
func (f *FileFreshness) Accept(_ context.Context, issuedAt time.Time) error {
f.mu.Lock()
defer f.mu.Unlock()
current, err := f.read()
if err != nil {
return err
}
if !issuedAt.After(current) {
return nil
}
encoded, err := json.Marshal(struct {
IssuedAt time.Time `json:"issued_at"`
}{IssuedAt: issuedAt.UTC()})
if err != nil {
return err
}
return fsutil.WriteFileAtomic(f.Path, encoded, 0o600)
}
// read returns the mark, or the zero time when nothing has been
// accepted yet.
func (f *FileFreshness) read() (time.Time, error) {
raw, err := os.ReadFile(f.Path)
if errors.Is(err, fs.ErrNotExist) {
return time.Time{}, nil
}
if err != nil {
return time.Time{}, err
}
var mark struct {
IssuedAt time.Time `json:"issued_at"`
}
if err := json.Unmarshal(raw, &mark); err != nil {
return time.Time{}, fmt.Errorf("freshness mark %s: %w", f.Path, err)
}
return mark.IssuedAt, nil
}
// MarkPath is where the freshness mark for one kind of artifact from one
// source lives: $XDG_STATE_HOME/<instance>/<kind>/<key>.json, the state home
// the update journal uses too. The key names the reference, so two sources
// never share a mark.
func MarkPath(kind, reference string) string {
dir := os.Getenv("XDG_STATE_HOME")
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".local", "state")
}
sum := sha256.Sum256([]byte(reference))
return filepath.Join(dir, configuration.InstanceName(), kind, hex.EncodeToString(sum[:8])+".json")
}