SPB Git

Repository Public

nonce.go 5.0 KB 185 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/agent/nonce/nonce.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Package nonce is the agent's durable anti-replay journal: a command nonce43// is remembered on disk (fsynced) before the command is accepted, and kept44// until the command can no longer be valid. A replayed envelope is therefore45// refused even across agent restarts and crashes.46package nonce4748import (49	"bufio"50	"fmt"51	"os"52	"strconv"53	"strings"54	"sync"55	"time"56)5758// Store implements protocol.NonceStore.59type Store struct {60	path string61	now  func() time.Time6263	mu      sync.Mutex64	f       *os.File65	seen    map[string]time.Time66	appends int67}6869// Open loads the journal, dropping expired entries and compacting the file.70func Open(path string) (*Store, error) {71	s := &Store{path: path, now: time.Now, seen: map[string]time.Time{}}72	if f, err := os.Open(path); err == nil {73		sc := bufio.NewScanner(f)74		now := s.now()75		for sc.Scan() {76			// A torn last line (crash during append) fails to parse and is ignored:77			// its command was never accepted, since acceptance follows the fsync.78			parts := strings.Fields(sc.Text())79			if len(parts) != 2 {80				continue81			}82			until, err := strconv.ParseInt(parts[1], 10, 64)83			if err != nil {84				continue85			}86			if t := time.Unix(until, 0); t.After(now) {87				s.seen[parts[0]] = t88			}89		}90		f.Close()91	} else if !os.IsNotExist(err) {92		return nil, err93	}94	if err := s.compactLocked(); err != nil {95		return nil, err96	}97	return s, nil98}99100// compactLocked rewrites the journal with the live entries only.101func (s *Store) compactLocked() error {102	tmp := s.path + ".tmp"103	f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)104	if err != nil {105		return err106	}107	w := bufio.NewWriter(f)108	for n, until := range s.seen {109		fmt.Fprintf(w, "%s %d\n", n, until.Unix())110	}111	if err := w.Flush(); err != nil {112		f.Close()113		return err114	}115	if err := f.Sync(); err != nil {116		f.Close()117		return err118	}119	f.Close()120	if err := os.Rename(tmp, s.path); err != nil {121		return err122	}123	if s.f != nil {124		s.f.Close()125	}126	s.f, err = os.OpenFile(s.path, os.O_WRONLY|os.O_APPEND, 0o600)127	s.appends = 0128	return err129}130131// Remember records the nonce durably. It returns false when the nonce was132// already present, and an error (the caller must then refuse the command)133// when durability could not be guaranteed.134func (s *Store) Remember(nonce string, until time.Time) (bool, error) {135	if nonce == "" || len(nonce) > 128 || strings.ContainsAny(nonce, " \t\r\n") {136		return false, fmt.Errorf("nonce: invalid value")137	}138	s.mu.Lock()139	defer s.mu.Unlock()140	now := s.now()141	if exp, ok := s.seen[nonce]; ok && exp.After(now) {142		return false, nil143	}144	if s.appends >= 256 {145		for n, exp := range s.seen {146			if !exp.After(now) {147				delete(s.seen, n)148			}149		}150		if err := s.compactLocked(); err != nil {151			return false, err152		}153	}154	// Seconds resolution on disk: round the expiry up so it never shortens.155	until = time.Unix(until.Unix()+1, 0)156	if _, err := fmt.Fprintf(s.f, "%s %d\n", nonce, until.Unix()); err != nil {157		return false, err158	}159	if err := s.f.Sync(); err != nil {160		return false, err161	}162	s.seen[nonce] = until163	s.appends++164	return true, nil165}166167// Len returns the number of remembered nonces.168func (s *Store) Len() int {169	s.mu.Lock()170	defer s.mu.Unlock()171	return len(s.seen)172}173174// Close releases the journal file.175func (s *Store) Close() error {176	s.mu.Lock()177	defer s.mu.Unlock()178	if s.f == nil {179		return nil180	}181	err := s.f.Close()182	s.f = nil183	return err184}185
Files main
Menu

Theme