Prepare verified laboratory 7 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 20afc2c790
commit eb1b5c7b84
677 changed files with 208256 additions and 64 deletions
@@ -0,0 +1,47 @@
package freshness
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
)
func TestFileReaderIsBoundedAndDoesNotRevealMissingPath(t *testing.T) {
path := filepath.Join(t.TempDir(), "freshness")
if err := os.WriteFile(path, []byte("oversized-sensitive-content"), 0600); err != nil {
t.Fatal(err)
}
raw, err := FileReader(path)(context.Background(), 4)
if err != nil {
t.Fatal(err)
}
if string(raw) != "over" {
t.Fatalf("length=%d", len(raw))
}
_, err = FileReader(path+"missing")(context.Background(), MaxBytes+1)
if !errors.Is(err, ErrUnreadable) {
t.Fatalf("got %v", err)
}
}
func TestFileReaderRejectsSymlink(t *testing.T) {
target := filepath.Join(t.TempDir(), "target")
if err := os.WriteFile(target, []byte("value"), 0600); err != nil {
t.Fatal(err)
}
link := target + "-link"
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
if _, err := FileReader(link)(context.Background(), MaxBytes+1); !errors.Is(err, ErrUnreadable) {
t.Fatalf("got %v", err)
}
}
func TestFileReaderRejectsDirectory(t *testing.T) {
if _, err := FileReader(t.TempDir())(context.Background(), MaxBytes+1); !errors.Is(err, ErrUnreadable) {
t.Fatalf("got %v", err)
}
}
@@ -0,0 +1,135 @@
// Package freshness bounds how long a process may use OpenBao-rendered credentials.
package freshness
import (
"context"
"errors"
"io"
"os"
"strings"
"syscall"
"time"
)
const MaxBytes int64 = 128
var (
ErrInvalid = errors.New("secret freshness timestamp invalid")
ErrFuture = errors.New("secret freshness timestamp is in the future")
ErrStale = errors.New("secret freshness expired")
ErrUnreadable = errors.New("secret freshness unavailable")
ErrConfiguration = errors.New("secret freshness configuration invalid")
)
type Reader func(context.Context, int64) ([]byte, error)
type Ticker struct {
C <-chan time.Time
Stop func()
}
type Ports struct {
Read Reader
Now func() time.Time
NewTicker func(time.Duration) Ticker
}
type Watcher struct {
ports Ports
maxAge, interval time.Duration
}
// New requires explicit ports so tests cannot accidentally read live credentials or control processes.
func New(ports Ports, maxAge, interval time.Duration) (*Watcher, error) {
if ports.Read == nil || ports.Now == nil || ports.NewTicker == nil || maxAge <= 0 || interval <= 0 || interval > 5*time.Second || interval > maxAge {
return nil, ErrConfiguration
}
return &Watcher{ports: ports, maxAge: maxAge, interval: interval}, nil
}
func (w *Watcher) Check(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
raw, err := w.ports.Read(ctx, MaxBytes+1)
if contextErr := ctx.Err(); contextErr != nil {
return contextErr
}
if err != nil {
return ErrUnreadable
}
if len(raw) == 0 || int64(len(raw)) > MaxBytes {
return ErrInvalid
}
issued, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(string(raw)))
if err != nil {
return ErrInvalid
}
now := w.ports.Now()
if issued.After(now) {
return ErrFuture
}
if now.Sub(issued) > w.maxAge {
return ErrStale
}
return nil
}
// Run validates startup before allocating its ticker and returns the first failure.
// The composition root owns graceful shutdown; this package never exits or signals a process.
func (w *Watcher) Run(ctx context.Context) error {
if err := w.Check(ctx); err != nil {
return err
}
ticker := w.ports.NewTicker(w.interval)
if ticker.Stop == nil {
return ErrConfiguration
}
defer ticker.Stop()
if ticker.C == nil {
return ErrConfiguration
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case _, ok := <-ticker.C:
if !ok {
return ErrConfiguration
}
if err := w.Check(ctx); err != nil {
return err
}
}
}
}
// FileReader opens only the named file, never reads more than the requested bound,
// and deliberately hides path/system error detail from the runtime failure signal.
func FileReader(path string) Reader {
return func(ctx context.Context, limit int64) ([]byte, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if limit < 1 || limit > MaxBytes+1 {
return nil, ErrConfiguration
}
file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, ErrUnreadable
}
defer func() { _ = file.Close() }()
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() {
return nil, ErrUnreadable
}
raw, err := io.ReadAll(io.LimitReader(file, limit))
if err != nil {
return nil, ErrUnreadable
}
if err = ctx.Err(); err != nil {
return nil, err
}
return raw, nil
}
}
func SystemTicker(interval time.Duration) Ticker {
ticker := time.NewTicker(interval)
return Ticker{C: ticker.C, Stop: ticker.Stop}
}
@@ -0,0 +1,147 @@
package freshness
import (
"context"
"errors"
"strings"
"testing"
"time"
)
func factory(t *testing.T, text string, clock *time.Time, readError error) (*Watcher, chan time.Time, *int) {
t.Helper()
ticks := make(chan time.Time, 1)
stopped := new(int)
watcher, err := New(Ports{Read: func(ctx context.Context, limit int64) ([]byte, error) {
if limit != MaxBytes+1 {
t.Errorf("requested read limit %d", limit)
}
return []byte(text), readError
}, Now: func() time.Time { return *clock }, NewTicker: func(time.Duration) Ticker { return Ticker{C: ticks, Stop: func() { *stopped++ }} }}, 120*time.Second, 5*time.Second)
if err != nil {
t.Fatal(err)
}
return watcher, ticks, stopped
}
func TestCheckUsesFiniteNonfutureBoundedTimestamp(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
cases := []struct {
name, text string
want error
}{{"now", now.Format(time.RFC3339Nano), nil}, {"boundary", now.Add(-120 * time.Second).Format(time.RFC3339Nano), nil}, {"stale", now.Add(-120*time.Second - time.Nanosecond).Format(time.RFC3339Nano), ErrStale}, {"future", now.Add(time.Nanosecond).Format(time.RFC3339Nano), ErrFuture}, {"empty", "", ErrInvalid}, {"malformed", "not-a-date", ErrInvalid}, {"oversized", strings.Repeat("x", 129), ErrInvalid}, {"extra_data", now.Format(time.RFC3339Nano) + " second", ErrInvalid}, {"trimmed", now.Format(time.RFC3339Nano) + "\n", nil}}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
watcher, _, _ := factory(t, c.text, &now, nil)
if got := watcher.Check(context.Background()); !errors.Is(got, c.want) {
t.Fatalf("got %v, want %v", got, c.want)
}
})
}
}
func TestReadFailureDoesNotRevealReaderError(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
watcher, _, _ := factory(t, "", &now, errors.New("sensitive path"))
err := watcher.Check(context.Background())
if !errors.Is(err, ErrUnreadable) {
t.Fatalf("got %v", err)
}
if strings.Contains(err.Error(), "sensitive") {
t.Fatal("reader detail leaked")
}
}
func TestRunReturnsOnLaterExpiryAndStopsTicker(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
clock := now
ticks := make(chan time.Time, 1)
stops := 0
reads := 0
watcher, err := New(Ports{Read: func(context.Context, int64) ([]byte, error) {
reads++
if reads == 2 {
clock = now.Add(121 * time.Second)
}
return []byte(now.Format(time.RFC3339Nano)), nil
}, Now: func() time.Time { return clock }, NewTicker: func(time.Duration) Ticker { ticks <- now; return Ticker{C: ticks, Stop: func() { stops++ }} }}, 120*time.Second, 5*time.Second)
if err != nil {
t.Fatal(err)
}
if err = watcher.Run(context.Background()); !errors.Is(err, ErrStale) {
t.Fatalf("got %v", err)
}
if stops != 1 {
t.Fatalf("stops=%d", stops)
}
}
func TestRunReturnsOnLaterReadFailure(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
ticks := make(chan time.Time, 1)
reads := 0
watcher, err := New(Ports{Read: func(context.Context, int64) ([]byte, error) {
reads++
if reads == 2 {
return nil, errors.New("reader failed")
}
return []byte(now.Format(time.RFC3339Nano)), nil
}, Now: func() time.Time { return now }, NewTicker: func(time.Duration) Ticker { ticks <- now; return Ticker{C: ticks, Stop: func() {}} }}, 120*time.Second, 5*time.Second)
if err != nil {
t.Fatal(err)
}
if err = watcher.Run(context.Background()); !errors.Is(err, ErrUnreadable) {
t.Fatalf("got %v", err)
}
}
func TestCancellationDoesNotReadAndStopsTicker(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
watcher, _, stops := factory(t, now.Format(time.RFC3339Nano), &now, nil)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := watcher.Check(ctx); !errors.Is(err, context.Canceled) {
t.Fatalf("got %v", err)
}
// Explicit fake ticker cancels only after startup Check; no goroutine or wall-clock wait.
ctx, cancel = context.WithCancel(context.Background())
watcher.ports.NewTicker = func(time.Duration) Ticker {
cancel()
return Ticker{C: make(chan time.Time), Stop: func() { *stops++ }}
}
if err := watcher.Run(ctx); !errors.Is(err, context.Canceled) {
t.Fatalf("got %v", err)
}
if *stops != 1 {
t.Fatal("ticker not stopped")
}
}
func TestFactoryRejectsMissingPortsAndUnsafeTiming(t *testing.T) {
valid := Ports{Read: func(context.Context, int64) ([]byte, error) { return nil, nil }, Now: time.Now, NewTicker: func(time.Duration) Ticker { return Ticker{C: make(chan time.Time), Stop: func() {}} }}
cases := []struct {
p Ports
age, interval time.Duration
}{{Ports{}, 120 * time.Second, time.Second}, {valid, 0, time.Second}, {valid, 120 * time.Second, 0}, {valid, 120 * time.Second, 6 * time.Second}, {valid, time.Second, 2 * time.Second}}
for _, c := range cases {
if _, err := New(c.p, c.age, c.interval); !errors.Is(err, ErrConfiguration) {
t.Fatal("unsafe factory accepted")
}
}
}
func TestRunRejectsClosedTicker(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
watcher, _, _ := factory(t, now.Format(time.RFC3339Nano), &now, nil)
closed := make(chan time.Time)
close(closed)
watcher.ports.NewTicker = func(time.Duration) Ticker { return Ticker{C: closed, Stop: func() {}} }
if err := watcher.Run(context.Background()); !errors.Is(err, ErrConfiguration) {
t.Fatalf("got %v", err)
}
}
func TestRunStopsAllocatedTickerWhenChannelIsInvalid(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
watcher, _, stops := factory(t, now.Format(time.RFC3339Nano), &now, nil)
watcher.ports.NewTicker = func(time.Duration) Ticker { return Ticker{C: nil, Stop: func() { *stops++ }} }
if err := watcher.Run(context.Background()); !errors.Is(err, ErrConfiguration) {
t.Fatalf("got %v", err)
}
if *stops != 1 {
t.Fatalf("stops=%d, want1", *stops)
}
}