Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions diddoc/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Package diddoc serves a DID document over HTTP, for services that publish
// their did:web identity at /.well-known/did.json.
package diddoc

import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"

"github.com/fil-forge/ucantone/did"
)

// DefaultTTL is how long clients may cache the document when [WithTTL] is not
// given.
const DefaultTTL = 5 * time.Minute

type config struct {
ttl time.Duration
lastModified time.Time
}

type Option func(*config) error

// WithTTL sets how long clients may cache the document before asking for it
// again, sent as the Cache-Control max-age. The default is [DefaultTTL]. It
// is how long a key removed from the document can go on being trusted by
// those who already fetched it, so keep it short enough for a key rotation.
// Whole seconds are sent; a fraction is dropped. Zero tells clients to
// revalidate on every use (Cache-Control: no-cache).
func WithTTL(ttl time.Duration) Option {
return func(c *config) error {
if ttl < 0 {
return fmt.Errorf("TTL cannot be negative")
}
c.ttl = ttl
return nil
}
}

// WithLastModified sets the time the document last changed, sent as the
// Last-Modified header. The default is the time the handler was created.
func WithLastModified(t time.Time) Option {
return func(c *config) error {
if t.IsZero() {
return fmt.Errorf("last modified time cannot be zero")
}
c.lastModified = t
return nil
}
}

// NewHandler creates an [http.Handler] that serves doc as JSON in answer to
// GET and HEAD requests, whatever the request path. Mount it at
// /.well-known/did.json (ucantone's web.WellKnownDIDPath) for a did:web DID
// with no path.
//
// Responses carry a Cache-Control max-age (see [WithTTL]), an ETag derived
// from the document's content and a Last-Modified time, and the handler
// answers If-None-Match and If-Modified-Since requests with 304 Not Modified
// when the client's copy is current. The ETag is the same in every process
// serving the same document, so revalidation works across restarts and
// replicas.
//
// The document is encoded once, here. To serve a changed document, create a
// new handler.
func NewHandler(doc did.Document, options ...Option) (http.Handler, error) {
cfg := config{ttl: DefaultTTL, lastModified: time.Now()}
for _, opt := range options {
if err := opt(&cfg); err != nil {
return nil, err
}
}

body, err := json.Marshal(doc)
if err != nil {
return nil, fmt.Errorf("encoding DID document: %w", err)
}
sum := sha256.Sum256(body)
etag := `"` + hex.EncodeToString(sum[:16]) + `"`

cacheControl := "no-cache"
if seconds := int64(cfg.ttl / time.Second); seconds > 0 {
cacheControl = "max-age=" + strconv.FormatInt(seconds, 10)
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
h := w.Header()
h.Set("Content-Type", "application/json")
h.Set("Cache-Control", cacheControl)
h.Set("ETag", etag)
// ServeContent sets Last-Modified and answers conditional requests.
http.ServeContent(w, r, "", cfg.lastModified, bytes.NewReader(body))
}), nil
}
159 changes: 159 additions & 0 deletions diddoc/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package diddoc_test

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/fil-forge/libforge/diddoc"
"github.com/fil-forge/libforge/identity"
"github.com/fil-forge/ucantone/did"
"github.com/fil-forge/ucantone/did/web"
"github.com/stretchr/testify/require"
)

func newDocument(t *testing.T, serviceDID string) did.Document {
t.Helper()
id, err := identity.New("", serviceDID)
require.NoError(t, err)
doc, err := id.DIDDocument()
require.NoError(t, err)
return doc
}

func serve(t *testing.T, h http.Handler, method string, header http.Header) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, web.WellKnownDIDPath, nil)
for k, v := range header {
req.Header[k] = v
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}

func TestHandler(t *testing.T) {
doc := newDocument(t, "did:web:example.com")
modified := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
const modifiedHeader = "Thu, 01 Jan 2026 12:00:00 GMT"

newHandler := func(t *testing.T, options ...diddoc.Option) http.Handler {
t.Helper()
h, err := diddoc.NewHandler(doc, append([]diddoc.Option{diddoc.WithLastModified(modified)}, options...)...)
require.NoError(t, err)
return h
}

t.Run("serves the document", func(t *testing.T) {
rec := serve(t, newHandler(t), http.MethodGet, nil)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "application/json", rec.Header().Get("Content-Type"))
require.Equal(t, "max-age=300", rec.Header().Get("Cache-Control"))
require.Equal(t, modifiedHeader, rec.Header().Get("Last-Modified"))
require.Regexp(t, `^"[0-9a-f]{32}"$`, rec.Header().Get("ETag"))

want, err := json.Marshal(doc)
require.NoError(t, err)
require.JSONEq(t, string(want), rec.Body.String())
})

t.Run("answers HEAD without a body", func(t *testing.T) {
rec := serve(t, newHandler(t), http.MethodHead, nil)
require.Equal(t, http.StatusOK, rec.Code)
require.Empty(t, rec.Body.Bytes())
require.NotEmpty(t, rec.Header().Get("ETag"))
require.NotEmpty(t, rec.Header().Get("Content-Length"))
})

t.Run("refuses other methods", func(t *testing.T) {
rec := serve(t, newHandler(t), http.MethodPost, nil)
require.Equal(t, http.StatusMethodNotAllowed, rec.Code)
require.Equal(t, "GET, HEAD", rec.Header().Get("Allow"))
})

t.Run("TTL", func(t *testing.T) {
tests := []struct {
name string
ttl time.Duration
want string
}{
{"minutes", 10 * time.Minute, "max-age=600"},
{"fraction of a second dropped", 1500 * time.Millisecond, "max-age=1"},
{"zero", 0, "no-cache"},
{"under a second", 500 * time.Millisecond, "no-cache"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := serve(t, newHandler(t, diddoc.WithTTL(tt.ttl)), http.MethodGet, nil)
require.Equal(t, tt.want, rec.Header().Get("Cache-Control"))
})
}
})

t.Run("conditional requests", func(t *testing.T) {
h := newHandler(t)
etag := serve(t, h, http.MethodGet, nil).Header().Get("ETag")

tests := []struct {
name string
header http.Header
want int
}{
{"matching If-None-Match", http.Header{"If-None-Match": {etag}}, http.StatusNotModified},
{"weak matching If-None-Match", http.Header{"If-None-Match": {"W/" + etag}}, http.StatusNotModified},
{"If-None-Match list", http.Header{"If-None-Match": {`"other", ` + etag}}, http.StatusNotModified},
{"If-None-Match any", http.Header{"If-None-Match": {"*"}}, http.StatusNotModified},
{"other If-None-Match", http.Header{"If-None-Match": {`"other"`}}, http.StatusOK},
{"If-Modified-Since at the modification time", http.Header{"If-Modified-Since": {modifiedHeader}}, http.StatusNotModified},
{"If-Modified-Since after it", http.Header{"If-Modified-Since": {"Fri, 02 Jan 2026 12:00:00 GMT"}}, http.StatusNotModified},
{"If-Modified-Since before it", http.Header{"If-Modified-Since": {"Wed, 31 Dec 2025 12:00:00 GMT"}}, http.StatusOK},
{
"If-None-Match takes precedence over If-Modified-Since",
http.Header{"If-None-Match": {`"other"`}, "If-Modified-Since": {modifiedHeader}},
http.StatusOK,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := serve(t, h, http.MethodGet, tt.header)
require.Equal(t, tt.want, rec.Code)
require.Equal(t, etag, rec.Header().Get("ETag"))
require.Equal(t, "max-age=300", rec.Header().Get("Cache-Control"))
if tt.want == http.StatusNotModified {
require.Empty(t, rec.Body.Bytes())
} else {
require.NotEmpty(t, rec.Body.Bytes())
}
})
}
})

t.Run("ETag follows the document", func(t *testing.T) {
etag := func(doc did.Document) string {
h, err := diddoc.NewHandler(doc)
require.NoError(t, err)
return serve(t, h, http.MethodGet, nil).Header().Get("ETag")
}
require.Equal(t, etag(doc), etag(doc))
require.NotEqual(t, etag(doc), etag(newDocument(t, "did:web:example.com")))
})

t.Run("Last-Modified defaults to the time the handler was created", func(t *testing.T) {
before := time.Now().Truncate(time.Second)
h, err := diddoc.NewHandler(doc)
require.NoError(t, err)
got, err := http.ParseTime(serve(t, h, http.MethodGet, nil).Header().Get("Last-Modified"))
require.NoError(t, err)
require.False(t, got.Before(before))
require.False(t, got.After(time.Now()))
})

t.Run("refuses invalid options", func(t *testing.T) {
_, err := diddoc.NewHandler(doc, diddoc.WithTTL(-time.Second))
require.ErrorContains(t, err, "TTL cannot be negative")
_, err = diddoc.NewHandler(doc, diddoc.WithLastModified(time.Time{}))
require.ErrorContains(t, err, "last modified time cannot be zero")
})
}
48 changes: 48 additions & 0 deletions diddoc/resolver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package diddoc_test

import (
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/fil-forge/libforge/diddoc"
"github.com/fil-forge/ucantone/did"
"github.com/fil-forge/ucantone/did/web"
"github.com/stretchr/testify/require"
)

// A ucantone did:web resolver pointed at the handler caches the document and
// revalidates it with a conditional request.
func TestHandlerWithResolver(t *testing.T) {
var statuses []int
var handler http.Handler
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, r)
statuses = append(statuses, rec.Code)
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, _ = w.Write(rec.Body.Bytes())
}))
defer srv.Close()

serviceDID := did.MustParse("did:web:" + strings.ReplaceAll(srv.Listener.Addr().String(), ":", "%3A"))
doc := newDocument(t, serviceDID.String())
var err error
handler, err = diddoc.NewHandler(doc, diddoc.WithTTL(0))
require.NoError(t, err)

resolver, err := web.NewResolver(web.WithInsecure(true))
require.NoError(t, err)

for range 3 {
got, err := resolver.Resolve(t.Context(), serviceDID)
require.NoError(t, err)
require.Equal(t, doc.ID, got.ID)
require.Equal(t, doc.VerificationMethods, got.VerificationMethods)
}
require.Equal(t, []int{http.StatusOK, http.StatusNotModified, http.StatusNotModified}, statuses)
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.27.0
require (
github.com/alanshaw/dag-json-gen v0.0.11
github.com/fil-forge/automobile v0.0.1
github.com/fil-forge/ucantone v0.0.0-20261120104359-4253712d41e4
github.com/fil-forge/ucantone v0.0.0-20261120160831-cf6c452a3cd7
github.com/filecoin-project/go-data-segment v0.0.1
github.com/filecoin-project/go-fil-commcid v0.3.1
github.com/filecoin-project/go-fil-commp-hashhash v0.4.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ github.com/alanshaw/dag-json-gen v0.0.11 h1:QJRnj9LeHlHtMnrJ1rY2czINHIfun7jmzA/M
github.com/alanshaw/dag-json-gen v0.0.11/go.mod h1:v1YBZcS4B355MqxtyQr+fGNbEhm0CzHd+gOqOO/MZ+I=
github.com/fil-forge/automobile v0.0.1 h1:9xB3yc4l5b9EdRJSJcNwudgBFNHoMPEAdcb7GfobLhA=
github.com/fil-forge/automobile v0.0.1/go.mod h1:TsO7jlO8ykJZY5tF8j4GsUcu3F02lEzxO7ULoB61hRA=
github.com/fil-forge/ucantone v0.0.0-20261120104359-4253712d41e4 h1:2hQIpdhNOu0QKY1rpdsYnJRtNG/0MklyETPraR/ms+Y=
github.com/fil-forge/ucantone v0.0.0-20261120104359-4253712d41e4/go.mod h1:PJe9Lcv+QWawlM29ItA9y5JzFIs37gZ3jODxYKXbQkM=
github.com/fil-forge/ucantone v0.0.0-20261120160831-cf6c452a3cd7 h1:3Bhat1RvTC2z3NMpy6l22C97VKQYp2dEBxY1SdJsW4I=
github.com/fil-forge/ucantone v0.0.0-20261120160831-cf6c452a3cd7/go.mod h1:PJe9Lcv+QWawlM29ItA9y5JzFIs37gZ3jODxYKXbQkM=
github.com/filecoin-project/go-data-segment v0.0.1 h1:1wmDxOG4ubWQm3ZC1XI5nCon5qgSq7Ra3Rb6Dbu10Gs=
github.com/filecoin-project/go-data-segment v0.0.1/go.mod h1:H0/NKbsRxmRFBcLibmABv+yFNHdmtl5AyplYLnb0Zv4=
github.com/filecoin-project/go-fil-commcid v0.3.1 h1:4EfxpHSlvtkOqa9weG2Yt5kxFmPib2xU7Uc9Lbqk7fs=
Expand Down
Loading