diff --git a/LICENCE b/LICENCE new file mode 100644 index 0000000..4153cd3 --- /dev/null +++ b/LICENCE @@ -0,0 +1,287 @@ + EUROPEAN UNION PUBLIC LICENCE v. 1.2 + EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined +below) which is provided under the terms of this Licence. Any use of the Work, +other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as +defined below) has placed the following notice immediately following the +copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + +- ‘The Licence’: this Licence. + +- ‘The Original Work’: the work or software distributed or communicated by the + Licensor under this Licence, available as Source Code and also as Executable + Code as the case may be. + +- ‘Derivative Works’: the works or software that could be created by the + Licensee, based upon the Original Work or modifications thereof. This Licence + does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is + determined by copyright law applicable in the country mentioned in Article 15. + +- ‘The Work’: the Original Work or its Derivative Works. + +- ‘The Source Code’: the human-readable form of the Work which is the most + convenient for people to study and modify. + +- ‘The Executable Code’: any code which has generally been compiled and which is + meant to be interpreted by a computer as a program. + +- ‘The Licensor’: the natural or legal person that distributes or communicates + the Work under the Licence. + +- ‘Contributor(s)’: any natural or legal person who modifies the Work under the + Licence, or otherwise contributes to the creation of a Derivative Work. + +- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of + the Work under the terms of the Licence. + +- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, + renting, distributing, communicating, transmitting, or otherwise making + available, online or offline, copies of the Work or providing access to its + essential functionalities at the disposal of any other natural or legal + person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +sublicensable licence to do the following, for the duration of copyright vested +in the Original Work: + +- use the Work in any circumstance and for all usage, +- reproduce the Work, +- modify the Work, and make Derivative Works based upon the Work, +- communicate to the public, including the right to make available or display + the Work or copies thereof to the public and perform publicly, as the case may + be, the Work, +- distribute the Work or copies thereof, +- lend and rent the Work or copies thereof, +- sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now +known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to +exercise his moral right to the extent allowed by law in order to make effective +the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to +any patents held by the Licensor, to the extent necessary to make use of the +rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as +Executable Code. If the Work is provided as Executable Code, the Licensor +provides in addition a machine-readable copy of the Source Code of the Work +along with each copy of the Work that the Licensor distributes or indicates, in +a notice following the copyright notice attached to the Work, a repository where +the Source Code is easily and freely accessible for as long as the Licensor +continues to distribute or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from +any exception or limitation to the exclusive rights of the rights owners in the +Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and +obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or +trademarks notices and all notices that refer to the Licence and to the +disclaimer of warranties. The Licensee must include a copy of such notices and a +copy of the Licence with every copy of the Work he/she distributes or +communicates. The Licensee must cause any Derivative Work to carry prominent +notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the +Original Works or Derivative Works, this Distribution or Communication will be +done under the terms of this Licence or of a later version of this Licence +unless the Original Work is expressly distributed only under this version of the +Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee +(becoming Licensor) cannot offer or impose any additional terms or conditions on +the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative +Works or copies thereof based upon both the Work and another work licensed under +a Compatible Licence, this Distribution or Communication can be done under the +terms of this Compatible Licence. For the sake of this clause, ‘Compatible +Licence’ refers to the licences listed in the appendix attached to this Licence. +Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible +Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, +the Licensee will provide a machine-readable copy of the Source Code or indicate +a repository where this Source will be easily and freely available for as long +as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, +trademarks, service marks, or names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted +hereunder is owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings +to the Work are owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent +Contributors grant You a licence to their contributions to the Work, under the +terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous +Contributors. It is not a finished work and may therefore contain defects or +‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis +and without warranties of any kind concerning the Work, including without +limitation merchantability, fitness for a particular purpose, absence of defects +or errors, accuracy, non-infringement of intellectual property rights other than +copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition +for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural +persons, the Licensor will in no event be liable for any direct or indirect, +material or moral, damages of any kind, arising out of the Licence or of the use +of the Work, including without limitation, damages for loss of goodwill, work +stoppage, computer failure or malfunction, loss of data or any commercial +damage, even if the Licensor has been advised of the possibility of such damage. +However, the Licensor will be liable under statutory product liability laws as +far such laws apply to the Work. + +9. Additional agreements + +While distributing the Work, You may choose to conclude an additional agreement, +defining obligations or services consistent with this Licence. However, if +accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor harmless +for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ +placed under the bottom of a window displaying the text of this Licence or by +affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable +acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and +conditions by exercising any rights granted to You by Article 2 of this Licence, +such as the use of the Work, the creation by You of a Derivative Work or the +Distribution or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution or Communication of the Work by means of electronic +communication by You (for example, by offering to download the Work from a +remote location) the distribution channel or media (for example, a website) must +at least provide to the public the information requested by the applicable law +regarding the Licensor, the Licence and the way it may be accessible, concluded, +stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon +any breach by the Licensee of the terms of the Licence. + +Such a termination will not terminate the licences of any person who has +received the Work from the Licensee under the Licence, provided such persons +remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete +agreement between the Parties as to the Work. + +If any provision of the Licence is invalid or unenforceable under applicable +law, this will not affect the validity or enforceability of the Licence as a +whole. Such provision will be construed or reformed so as necessary to make it +valid and enforceable. + +The European Commission may publish other linguistic versions or new versions of +this Licence or updated versions of the Appendix, so far this is required and +reasonable, without reducing the scope of the rights granted by the Licence. New +versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, +have identical value. Parties can take advantage of the linguistic version of +their choice. + +14. Jurisdiction + +Without prejudice to specific agreement between parties, + +- any litigation resulting from the interpretation of this License, arising + between the European Union institutions, bodies, offices or agencies, as a + Licensor, and any Licensee, will be subject to the jurisdiction of the Court + of Justice of the European Union, as laid down in article 272 of the Treaty on + the Functioning of the European Union, + +- any litigation arising between other parties and resulting from the + interpretation of this License, will be subject to the exclusive jurisdiction + of the competent court where the Licensor resides or conducts its primary + business. + +15. Applicable Law + +Without prejudice to specific agreement between parties, + +- this Licence shall be governed by the law of the European Union Member State + where the Licensor has his seat, resides or has his registered office, + +- this licence shall be governed by Belgian law if the Licensor has no seat, + residence or registered office inside a European Union Member State. + +Appendix + +‘Compatible Licences’ according to Article 5 EUPL are: + +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 +- Open Software License (OSL) v. 2.1, v. 3.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for + works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong + Reciprocity (LiLiQ-R+). + +The European Commission may update this Appendix to later versions of the above +licences without producing a new version of the EUPL, as long as they provide +the rights granted in Article 2 of this Licence and protect the covered Source +Code from exclusive appropriation. + +All other changes or additions to this Appendix require the production of a new +EUPL version. diff --git a/external/go b/external/go index d661b70..7c95f96 160000 --- a/external/go +++ b/external/go @@ -1 +1 @@ -Subproject commit d661b703e16183b3cbab101de189f688888a1174 +Subproject commit 7c95f964f84bd52c728c67c9cce49f1b9bf5e066 diff --git a/external/go-io b/external/go-io index 8d72624..40f5452 160000 --- a/external/go-io +++ b/external/go-io @@ -1 +1 @@ -Subproject commit 8d726243d1018ca85b7a55767f08c6d6f7dd9607 +Subproject commit 40f545248bb8c095b55673afb86cb0baf680a724 diff --git a/go.work b/go.work index a457927..104a5cd 100644 --- a/go.work +++ b/go.work @@ -11,5 +11,5 @@ go 1.26.2 use ( ./go ./external/go - ./external/go-io + ./external/go-io/go ) diff --git a/go/go.mod b/go/go.mod index 2dd6973..864795b 100644 --- a/go/go.mod +++ b/go/go.mod @@ -3,6 +3,6 @@ module dappco.re/go/cache go 1.26.0 require ( - dappco.re/go v0.9.0 + dappco.re/go v0.10.4 dappco.re/go/io v0.9.0 ) diff --git a/go/go.sum b/go/go.sum index 5018d65..2bd0944 100644 --- a/go/go.sum +++ b/go/go.sum @@ -1,5 +1,5 @@ -dappco.re/go v0.9.0 h1:4ruZRNqKDDva8o6g65tYggjGVe42E6/lMZfVKXtr3p0= -dappco.re/go v0.9.0/go.mod h1:xapr7fLK4/9Pu2iSCr4qZuIuatmtx1j56zS/oPDbGyQ= +dappco.re/go v0.10.4 h1:vir5AK8AkHbTxhPUT0et6Tc0P8i/i+gLInM0LRLt1EU= +dappco.re/go v0.10.4/go.mod h1:xapr7fLK4/9Pu2iSCr4qZuIuatmtx1j56zS/oPDbGyQ= dappco.re/go/io v0.9.0 h1:TyHUuUJdZ73CXQlBpqx47SNyFFzgwA5OPSKu4Twb2f0= dappco.re/go/io v0.9.0/go.mod h1:K5jWSLMdk0X9HqJ6b1I+8tKqcNpNWgpcUZi/fGm28Q8= forge.lthn.ai/Snider/Borg v0.3.1 h1:gfC1ZTpLoZai07oOWJiVeQ8+qJYK8A795tgVGJHbVL8= diff --git a/go/service.go b/go/service.go new file mode 100644 index 0000000..1c7c9cf --- /dev/null +++ b/go/service.go @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: EUPL-1.2 + +// Service registration for the cache package. Exposes the Cache surface +// as a Core service with action handlers so consumers can wire cache +// operations through the same plumbing as every other core service. +// +// Usage example: `c, _ := core.New(core.WithName("cache", cache.NewService(cache.CacheConfig{BaseDir: "/var/lib/core/cache", TTL: time.Hour})))` + +package cache + +import ( + "context" + "time" + + core "dappco.re/go" + coreio "dappco.re/go/io" +) + +// CacheConfig is the typed-options struct for the cache service. Empty +// values fall back to package defaults (`coreio.Local` medium, CWD-rooted +// `.core/cache` baseDir, `DefaultTTL` cacheTTL). +// +// Usage example: `cfg := cache.CacheConfig{BaseDir: "/var/lib/core/cache", TTL: time.Hour}` +type CacheConfig struct { + // Medium is the storage backend. Nil → coreio.Local. + Medium coreio.Medium + // BaseDir is the root directory. Empty → CWD/.core/cache. + BaseDir string + // TTL is the default cache TTL. Zero → DefaultTTL (1 hour). + TTL time.Duration +} + +// Service is the registerable handle for the cache package — embeds +// *core.ServiceRuntime[CacheConfig] for typed options access and holds +// a live *Cache ready for direct method calls or action use. +// +// Usage example: `svc := core.MustServiceFor[*cache.Service](c, "cache"); _ = svc.Cache.Delete("key")` +type Service struct { + *core.ServiceRuntime[CacheConfig] + // Cache is the live *Cache the service was constructed with. + // Usage example: `svc.Cache.Delete("key")` + Cache *Cache + registrations core.Once +} + +// NewService returns a factory that constructs the cache and produces a +// *Service ready for c.Service() registration. Use through core.WithName +// so the framework wires lifecycle (OnStartup registers actions). +// +// Usage example: `c, _ := core.New(core.WithName("cache", cache.NewService(cache.CacheConfig{BaseDir: "/var/lib/core/cache"})))` +func NewService(config CacheConfig) func(*core.Core) core.Result { + return func(c *core.Core) core.Result { + r := New(config.Medium, config.BaseDir, config.TTL) + if !r.OK { + return r + } + return core.Ok(&Service{ + ServiceRuntime: core.NewServiceRuntime(c, config), + Cache: r.Value.(*Cache), + }) + } +} + +// OnStartup registers the cache action handlers on the attached Core. +// Implements core.Startable. Idempotent via core.Once — multiple startups +// (e.g. test re-entry) won't double-register. +// +// Note: Get / Set / SetBinary / GetBinary stay direct method calls because +// they need a typed `dest any` argument that doesn't round-trip through +// Options cleanly. Other operations are exposed as actions. +// +// Usage example: `r := svc.OnStartup(ctx)` +func (s *Service) OnStartup(context.Context) core.Result { + if s == nil { + return core.Ok(nil) + } + s.registrations.Do(func() { + c := s.Core() + if c == nil { + return + } + c.Action("cache.delete", s.handleDelete) + c.Action("cache.delete_many", s.handleDeleteMany) + c.Action("cache.path", s.handlePath) + c.Action("cache.invalidate", s.handleInvalidate) + c.Action("cache.clear_scope", s.handleClearScope) + }) + return core.Ok(nil) +} + +// OnShutdown is a no-op for the cache service — the Cache holds no +// long-lived handles requiring teardown. Implements core.Stoppable for +// shape parity with other services. +// +// Usage example: `r := svc.OnShutdown(ctx)` +func (s *Service) OnShutdown(context.Context) core.Result { + return core.Ok(nil) +} + +// handleDelete — `cache.delete` action handler. Reads opts.key. +// +// r := c.Action("cache.delete").Run(ctx, core.NewOptions( +// core.Option{Key: "key", Value: "user.profile.42"}, +// )) +func (s *Service) handleDelete(_ core.Context, opts core.Options) core.Result { + if s == nil || s.Cache == nil { + return core.Fail(core.E("cache.delete", "service not initialised", nil)) + } + return s.Cache.Delete(opts.String("key")) +} + +// handleDeleteMany — `cache.delete_many` action handler. Reads +// opts.keys (string slice). Removes every supplied key in one pass and +// returns a count of successful deletions in r.Value. +// +// r := c.Action("cache.delete_many").Run(ctx, core.NewOptions( +// core.Option{Key: "keys", Value: []string{"a", "b", "c"}}, +// )) +func (s *Service) handleDeleteMany(_ core.Context, opts core.Options) core.Result { + if s == nil || s.Cache == nil { + return core.Fail(core.E("cache.delete_many", "service not initialised", nil)) + } + r := opts.Get("keys") + if !r.OK { + return core.Fail(core.E("cache.delete_many", "keys is required", nil)) + } + keys, ok := r.Value.([]string) + if !ok { + return core.Fail(core.E("cache.delete_many", "keys must be []string", nil)) + } + return s.Cache.DeleteMany(keys...) +} + +// handlePath — `cache.path` action handler. Reads opts.key and returns +// the on-disk JSON path in r.Value. +// +// r := c.Action("cache.path").Run(ctx, core.NewOptions( +// core.Option{Key: "key", Value: "user.profile.42"}, +// )) +// path, _ := r.Value.(string) +func (s *Service) handlePath(_ core.Context, opts core.Options) core.Result { + if s == nil || s.Cache == nil { + return core.Fail(core.E("cache.path", "service not initialised", nil)) + } + return s.Cache.Path(opts.String("key")) +} + +// handleInvalidate — `cache.invalidate` action handler. Reads +// opts.trigger and runs every InvalidateFunc registered for that trigger. +// +// r := c.Action("cache.invalidate").Run(ctx, core.NewOptions( +// core.Option{Key: "trigger", Value: "user.updated"}, +// )) +func (s *Service) handleInvalidate(_ core.Context, opts core.Options) core.Result { + if s == nil || s.Cache == nil { + return core.Fail(core.E("cache.invalidate", "service not initialised", nil)) + } + return s.Cache.Invalidate(opts.String("trigger")) +} + +// handleClearScope — `cache.clear_scope` action handler. Reads +// opts.origin and removes every entry under that scope. +// +// r := c.Action("cache.clear_scope").Run(ctx, core.NewOptions( +// core.Option{Key: "origin", Value: "users"}, +// )) +func (s *Service) handleClearScope(_ core.Context, opts core.Options) core.Result { + if s == nil || s.Cache == nil { + return core.Fail(core.E("cache.clear_scope", "service not initialised", nil)) + } + return s.Cache.ClearScope(opts.String("origin")) +} diff --git a/go/service_example_test.go b/go/service_example_test.go new file mode 100644 index 0000000..5ae7702 --- /dev/null +++ b/go/service_example_test.go @@ -0,0 +1,57 @@ +package cache_test + +import ( + "context" + + core "dappco.re/go" + "dappco.re/go/cache" +) + +// ExampleNewService constructs the cache service factory through +// `NewService` for go-cache Core service registration. The factory +// produces a *cache.Service ready for c.Service() — OnStartup wires +// the cache.* action handlers, OnShutdown is a no-op. +// +// Usage example: `c.Service("cache", cache.NewService(cache.CacheConfig{BaseDir: "/var/lib/core/cache"}))` +func ExampleNewService() { + factory := cache.NewService(cache.CacheConfig{}) + core.Println(factory != nil) + // Output: true +} + +// ExampleService_OnStartup registers the cache.* action handlers on the +// attached Core through `Service.OnStartup` for go-cache Core service +// registration. Idempotent — multiple startups won't double-register. +// +// Usage example: `r := svc.OnStartup(ctx)` +func ExampleService_OnStartup() { + c := core.New() + r := cache.NewService(cache.CacheConfig{})(c) + if !r.OK { + core.Println("startup-init-failed") + return + } + svc := r.Value.(*cache.Service) + startup := svc.OnStartup(context.Background()) + core.Println(startup.OK) + // Output: true +} + +// ExampleService_OnShutdown drains the service through +// `Service.OnShutdown` for go-cache Core service registration. The cache +// holds no long-lived handles requiring teardown — Shutdown is a no-op +// returning Ok for shape parity with other services. +// +// Usage example: `r := svc.OnShutdown(ctx)` +func ExampleService_OnShutdown() { + c := core.New() + r := cache.NewService(cache.CacheConfig{})(c) + if !r.OK { + core.Println("startup-init-failed") + return + } + svc := r.Value.(*cache.Service) + shutdown := svc.OnShutdown(context.Background()) + core.Println(shutdown.OK) + // Output: true +} diff --git a/go/service_test.go b/go/service_test.go new file mode 100644 index 0000000..2eb9430 --- /dev/null +++ b/go/service_test.go @@ -0,0 +1,83 @@ +package cache + +import ( + "context" + + core "dappco.re/go" +) + +// --- AX-7 compliance triplets --- + +func TestService_NewService_Good(t *core.T) { + cfg := CacheConfig{BaseDir: t.TempDir()} + factory := NewService(cfg) + core.AssertNotNil(t, factory) +} + +func TestService_NewService_Bad(t *core.T) { + // NewService alone is a factory; resolution happens in c.Service(). + // Empty config falls back to package defaults. + cfg := CacheConfig{} + factory := NewService(cfg) + core.AssertNotNil(t, factory) +} + +func TestService_NewService_Ugly(t *core.T) { + a := NewService(CacheConfig{BaseDir: t.TempDir()}) + b := NewService(CacheConfig{BaseDir: t.TempDir()}) + core.AssertNotNil(t, a) + core.AssertNotNil(t, b) +} + +// serviceForTest builds a *Service directly, mirroring the canonical +// pattern used in config/go/service_test.go: construct via factory then +// resolve through *Core. +func serviceForTest(t *core.T) *Service { + t.Helper() + c := core.New() + r := NewService(CacheConfig{BaseDir: t.TempDir()})(c) + core.RequireTrue(t, r.OK) + return r.Value.(*Service) +} + +func TestService_Service_OnStartup_Good(t *core.T) { + svc := serviceForTest(t) + startup := svc.OnStartup(context.Background()) + core.AssertTrue(t, startup.OK) +} + +func TestService_Service_OnStartup_Bad(t *core.T) { + var s *Service + r := s.OnStartup(context.Background()) + core.AssertTrue(t, r.OK) +} + +func TestService_Service_OnStartup_Ugly(t *core.T) { + svc := serviceForTest(t) + // Idempotent — second OnStartup is a no-op via core.Once. + svc.OnStartup(context.Background()) + again := svc.OnStartup(context.Background()) + core.AssertTrue(t, again.OK) +} + +func TestService_Service_OnShutdown_Good(t *core.T) { + svc := serviceForTest(t) + shutdown := svc.OnShutdown(context.Background()) + core.AssertTrue(t, shutdown.OK) +} + +func TestService_Service_OnShutdown_Bad(t *core.T) { + var s *Service + r := s.OnShutdown(context.Background()) + core.AssertTrue(t, r.OK) +} + +func TestService_Service_OnShutdown_Ugly(t *core.T) { + svc := serviceForTest(t) + // Multiple shutdowns return Ok cleanly. + svc.OnShutdown(context.Background()) + again := svc.OnShutdown(context.Background()) + core.AssertTrue(t, again.OK) +} + +// --- end AX-7 compliance triplets --- diff --git a/threats.md b/threats.md deleted file mode 100644 index fe00225..0000000 --- a/threats.md +++ /dev/null @@ -1,111 +0,0 @@ -# go-cache threat-model audit - -Audit-by: Cerberus (via codex) -Repo: dappco.re/go/cache -Date: 2026-04-25 - -## 1. Untrusted-key DoS - -Status: Complete - -Question: Are key lengths bounded on the externally reachable write paths? - -Finding: Yes. `Cache.Path` validates every key with `ensureSafeKey` before constructing storage paths (`cache.go:131`, `cache.go:136`). That helper rejects empty keys, keys longer than 4096 bytes, backslashes, control bytes, empty path segments, `.`, and `..` (`cache.go:743`, `cache.go:747`, `cache.go:750`, `cache.go:753`, `cache.go:757`). `Set`, `SetWithTTL`, `SetBinary`, and `SetBinaryWithTTL` all route through `entryPaths` and therefore through `Path` before writing (`cache.go:207`, `cache.go:218`, `cache.go:225`, `cache.go:230`, `cache.go:324`, `cache.go:335`, `cache.go:342`, `cache.go:346`). Regression coverage: `TestCache_ThreatUntrustedKeyDoS_RejectsOversizedKeysOnWritePaths` (`cache_test.go:2487`). - -Severity: None for overlong single-key path or memory amplification via key string on those write paths. - -Question: Can a flood of unique valid keys cause unbounded growth? - -Finding: Yes, for storage growth inside the configured cache root. Cache entries are persisted via the configured `coreio.Medium`, and there is no entry-count or byte quota before `medium.Write` in JSON or binary writes (`cache.go:268`, `cache.go:384`, `cache.go:390`). The ordinary cache does not keep cached values in a Go map; the in-memory maps are invalidation callbacks and opened HTTP cache handles (`cache.go:48`, `cache.go:978`). A downstream consumer that forwards attacker-controlled unique valid keys can therefore grow files/inodes within `baseDir` until the backing medium or host quota stops it. - -Severity: Medium. This is bounded to the configured cache root and by the underlying storage backend, but the package does not provide a built-in quota/eviction policy. No code fix was applied because adding a default global entry cap would change cache semantics and there is no existing public configuration surface for quotas in this ticket scope. - -Question: Does `Invalidate` accept callback-returned glob patterns without a length backstop before `keysByPattern` lists and matches all cache keys? - -Finding: Yes (prior-pass finding, retained). Validate invalidation patterns with a fixed byte limit before listing cache entries. - -Severity: Medium. - -Repro test: `TestCache_Invalidate_UntrustedPatternLength_Bad`. - -## 2. Path traversal - -Status: Complete - -Question: Do disk paths derive from raw keys without sanitisation? - -Finding: No for the core cache. `Path` validates the key, joins `baseDir` with `key + ".json"`, normalizes to an absolute path, and rejects paths outside the cache root prefix (`cache.go:136`, `cache.go:140`, `cache.go:141`, `cache.go:144`). Binary sidecar paths use the same validated key through `entryPaths` before writes (`cache.go:154`, `cache.go:155`, `cache.go:161`). - -Severity: None for direct `../`, absolute path, control-byte, or backslash traversal through `Set`, `SetWithTTL`, `SetBinary`, `Get`, `Delete`, and related key-based operations. - -Question: Do CacheStorage or HTTPCache paths derive from untrusted names or request URLs? - -Finding: No direct traversal found. `CacheStorage.Open` and `CacheStorage.Delete` validate cache names before joining them under the storage base directory (`cache.go:1015`, `cache.go:1019`, `cache.go:1029`, `cache.go:1047`, `cache.go:1051`, `cache.go:1057`). The validator rejects empty names, names over 255 bytes, `/`, `\`, control bytes, `.`, and `..` (`cache.go:1066`, `cache.go:1070`, `cache.go:1073`, `cache.go:1076`, `cache.go:1079`). `HTTPCache` stores request metadata under SHA-256 hex request keys rather than raw URLs (`cache.go:1215`, `cache.go:1452`, `cache.go:1457`), and cached response body reads validate that `BodyPath` is a relative `responses/.bin` path with safe segments (`cache.go:1407`, `cache.go:1410`, `cache.go:775`, `cache.go:789`, `cache.go:800`). - -Severity: None for reviewed raw-name and raw-URL path traversal. - -Question: Does ScopedCache origin namespacing allow path injection? - -Finding: No. Scope prefixes are `scope_` plus a SHA-256 hex digest of the origin string, so raw origins are not embedded in file paths (`cache.go:711`, `cache.go:714`, `cache.go:814`, `cache.go:815`, `cache.go:817`). Scoped keys are prefixed and then passed back through the parent cache validation and path containment checks (`cache.go:820`, `cache.go:835`, `cache.go:839`). Regression coverage: `TestCache_ThreatPathTraversal_ScopedOriginIsHashedAndKeysStillValidated` (`cache_test.go:2534`). - -Severity: None for origin-derived path traversal. - -Question: Do HTTPCache request URLs become path components? - -Finding: No. HTTP request storage keys are SHA-256 hex digests of `method + NUL + URL` (`cache.go:1215`, `cache.go:1452`, `cache.go:1457`), and `Put` writes metadata/body under `responses/.json` and `responses/.bin` (`cache.go:1343`, `cache.go:1347`, `cache.go:1362`, `cache.go:1363`, `cache.go:1383`, `cache.go:1388`). Regression coverage: `TestCache_ThreatPathTraversal_HTTPCacheUsesHashedRequestStorageKeys` (`cache_test.go:2557`). - -Severity: None for raw-URL path traversal on the reviewed HTTPCache write path. - -Question (prior pass): Symlink-following inside the cache root? - -Finding: A symlinked directory or file already under `baseDir` could redirect an otherwise safe key outside the cache root. Reject existing symlink components from the cache root through the resolved cache path before returning paths for filesystem use. - -Severity: high. - -Repro test: `TestCache_Path_PathTraversalSymlink_Bad`. - -## 3. Eviction TOCTOU - -Status: Complete - -### 3.1 Invalidate map walk / OnInvalidate registration - -Status: Complete - -Question: What lock is held while `Invalidate` walks callbacks, and can `OnInvalidate` append to the same trigger while that walk is in progress? - -Finding: No map-walk race found. `Cache.mu` is the lock protecting the invalidation callback map (`cache.go:56`). `OnInvalidate` takes the write lock before appending to `cache.invalidation[trigger]` (`cache.go:818`, `cache.go:820`). `Invalidate` takes the read lock only long enough to copy the trigger's callback slice, then releases the lock before executing callbacks and deleting entries (`cache.go:831`, `cache.go:832`, `cache.go:833`, `cache.go:835`). A callback that registers more invalidations therefore cannot mutate the map while it is being read, and it does not deadlock by trying to acquire the write lock from inside the callback. The newly registered callback is not included in the already-snapshotted invalidation pass, which is acceptable snapshot semantics. No `delete(cache.invalidation, trigger)` call exists in the reviewed cache implementation. - -Severity: None. - -Repro test: `TestCache_ThreatTOCTOU_InvalidateOnInvalidateRegistrationIsSnapshotRaceClean` and `TestCache_ThreatTOCTOU_InvalidateConcurrentRegistrationRaceClean` (`cache_test.go:2688`, `cache_test.go:2734`). - -Fix: No code change required. The existing callback snapshot under `Cache.mu` is the intended mitigation; the added tests pin the race-clean and snapshot semantics. - -### 3.2 TTL expiry race on Get - -Status: Complete - -Question: Can two concurrent readers of a freshly expired entry return expired data, or does one reader delete/alter state out from under the other? - -Finding: No unsafe TTL expiry race found. `Get` reads the entry under the entry read lock, unmarshals the cache envelope, checks `time.Now().After(entry.ExpiresAt)`, and returns `found=false` before unmarshalling cached data into the caller's destination (`cache.go:300`, `cache.go:317`, `cache.go:322`, `cache.go:323`, `cache.go:326`). `GetBinary` follows the same metadata-first expiry check and returns `found=false` before reading the payload body (`cache.go:545`, `cache.go:562`, `cache.go:567`, `cache.go:568`, `cache.go:571`). Expired reads do not delete files, so two readers can both lose and safely return not-found; neither path returns expired data after observing the expiry check. - -Severity: None. - -Repro test: `TestCache_ThreatTOCTOU_ExpiredGetConcurrentReadersReturnNotFound` (`cache_test.go:2782`). - -Fix: No code change required. The current metadata-first expiry check and non-mutating expired-read behavior are safe for concurrent readers. - -### 3.3 Get-then-Set caller-site TOCTOU - -Status: Complete - -Question: If two consumers both observe `Get` as missing or expired and then both call `Set`, does `Cache.mu` serialize the writes, or is this just last-writer-wins cache behavior? - -Finding: Yes, fixed. `Cache.mu` protects invalidation callback registration and snapshotting, while `entryMu` serializes cache entry I/O separately (`cache.go:56`, `cache.go:57`). `Get` and `GetBinary` take `entryMu.RLock` while reading entries (`cache.go:300`, `cache.go:545`). `Set` and `SetBinary` take `entryMu.Lock` across path resolution, rollback snapshot, and writes (`cache.go:360`, `cache.go:368`, `cache.go:401`, `cache.go:482`, `cache.go:490`, `cache.go:494`, `cache.go:523`, `cache.go:529`). Delete paths are also serialized: single-key removal locks before deleting metadata and binary sidecars, `DeleteMany` locks across its batch, and invalidation pattern listing takes the entry read lock while walking keys (`cache.go:428`, `cache.go:431`, `cache.go:591`, `cache.go:667`, `cache.go:672`, `cache.go:675`). Pure cache freshness remains last-writer-wins, but callers no longer need the backing `coreio.Medium` to tolerate overlapping entry operations. - -Severity: Medium before fix; mitigated by entry-level serialization. - -Repro test: `TestCache_ThreatTOCTOU_GetThenSetSerializesEntryWrites` (`cache_test.go:2825`). - -Fix: Use `entryMu` for cache entry I/O so concurrent caller-side `Get`-then-`Set` misses cannot overlap backing-medium writes. This preserves last-writer-wins cache semantics while removing the lower-level I/O race.