From f07a3151917db755c173a0daa5308bfdd81f8ab8 Mon Sep 17 00:00:00 2001 From: Anirudh Oppiliappan Date: Sun, 2 Feb 2025 19:08:38 +0200 Subject: [PATCH] knotserver: setup known_dids and dev mode --- cmd/knotserver/main.go | 5 ++++ knotserver/config/config.go | 2 ++ knotserver/db/init.go | 14 +++++----- knotserver/db/known_dids.go | 44 ++++++++++++++++++++++++++++++ knotserver/db/pubkeys.go | 14 +++++----- knotserver/db/users.go | 11 -------- knotserver/handler.go | 26 +++++++++++------- knotserver/middleware.go | 3 +++ knotserver/routes.go | 54 +++++++++++++------------------------ 9 files changed, 101 insertions(+), 72 deletions(-) create mode 100644 knotserver/db/known_dids.go delete mode 100644 knotserver/db/users.go diff --git a/cmd/knotserver/main.go b/cmd/knotserver/main.go index 341b487..75aa0e9 100644 --- a/cmd/knotserver/main.go +++ b/cmd/knotserver/main.go @@ -24,6 +24,11 @@ func main() { if err != nil { log.Fatal(err) } + + if c.Server.Dev { + log.Println("running in dev mode, signature verification is disabled") + } + db, err := db.Setup(c.Server.DBPath) if err != nil { log.Fatalf("failed to setup db: %s", err) diff --git a/knotserver/config/config.go b/knotserver/config/config.go index 6a52cbe..116bb6e 100644 --- a/knotserver/config/config.go +++ b/knotserver/config/config.go @@ -17,6 +17,8 @@ type Server struct { Port int `env:"PORT, default=5555"` Secret string `env:"SECRET, required"` DBPath string `env:"DB_PATH, default=knotserver.db"` + // This disables signature verification so use with caution. + Dev bool `env:"DEV, default=false"` } type Config struct { diff --git a/knotserver/db/init.go b/knotserver/db/init.go index f99a1e3..2e1488b 100644 --- a/knotserver/db/init.go +++ b/knotserver/db/init.go @@ -17,20 +17,18 @@ func Setup(dbPath string) (*DB, error) { } _, err = db.Exec(` + create table if not exists known_dids ( + did text primary key + ); create table if not exists public_keys ( id integer primary key autoincrement, did text not null, - name text not null, key text not null, created timestamp default current_timestamp, - unique(did, name, key) - ); - create table if not exists users ( - id integer primary key autoincrement, - did text not null, - unique(did), - foreign key (did) references public_keys(did) on delete cascade + unique(did, key), + foreign key (did) references known_dids(did) on delete cascade ); + create table if not exists repos ( id integer primary key autoincrement, did text not null, diff --git a/knotserver/db/known_dids.go b/knotserver/db/known_dids.go new file mode 100644 index 0000000..46fddfc --- /dev/null +++ b/knotserver/db/known_dids.go @@ -0,0 +1,44 @@ +package db + +func (d *DB) AddDID(did string) error { + _, err := d.db.Exec(`insert into known_dids (did) values (?)`, did) + return err +} + +func (d *DB) RemoveDID(did string) error { + _, err := d.db.Exec(`delete from known_dids where did = ?`, did) + return err +} + +func (d *DB) GetAllDIDs() ([]string, error) { + var dids []string + + rows, err := d.db.Query(`select did from known_dids`) + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + var did string + if err := rows.Scan(&did); err != nil { + return nil, err + } + dids = append(dids, did) + } + + if err := rows.Err(); err != nil { + return nil, err + } + + return dids, nil +} + +func (d *DB) HasKnownDIDs() bool { + var count int + err := d.db.QueryRow(`select count(*) from known_dids`).Scan(&count) + if err != nil { + return false + } + return count > 0 +} diff --git a/knotserver/db/pubkeys.go b/knotserver/db/pubkeys.go index 455c5c0..bd647ee 100644 --- a/knotserver/db/pubkeys.go +++ b/knotserver/db/pubkeys.go @@ -22,7 +22,6 @@ func (d *DB) AddPublicKeyFromRecord(did string, recordIface map[string]interface pk := PublicKey{ Did: did, } - pk.Name = record["name"] pk.Key = record["key"] pk.Created = record["created"] @@ -34,8 +33,8 @@ func (d *DB) AddPublicKey(pk PublicKey) error { pk.Created = time.Now().Format("2006-01-02 15:04:05.99999999 -0700 MST m=-0000.000000000") } - query := `insert into public_keys (did, name, key, created) values (?, ?, ?, ?)` - _, err := d.db.Exec(query, pk.Did, pk.Name, pk.Key, pk.Created) + query := `insert into public_keys (did, key, created) values (?, ?, ?)` + _, err := d.db.Exec(query, pk.Did, pk.Key, pk.Created) return err } @@ -49,7 +48,6 @@ func (pk *PublicKey) JSON() map[string]interface{} { return map[string]interface{}{ pk.Did: map[string]interface{}{ "key": pk.Key, - "name": pk.Name, "created": pk.Created, }, } @@ -58,7 +56,7 @@ func (pk *PublicKey) JSON() map[string]interface{} { func (d *DB) GetAllPublicKeys() ([]PublicKey, error) { var keys []PublicKey - rows, err := d.db.Query(`select key, name, did, created from public_keys`) + rows, err := d.db.Query(`select key, did, created from public_keys`) if err != nil { return nil, err } @@ -66,7 +64,7 @@ func (d *DB) GetAllPublicKeys() ([]PublicKey, error) { for rows.Next() { var publicKey PublicKey - if err := rows.Scan(&publicKey.Key, &publicKey.Name, &publicKey.Did, &publicKey.Created); err != nil { + if err := rows.Scan(&publicKey.Key, &publicKey.Did, &publicKey.Created); err != nil { return nil, err } keys = append(keys, publicKey) @@ -82,7 +80,7 @@ func (d *DB) GetAllPublicKeys() ([]PublicKey, error) { func (d *DB) GetPublicKeys(did string) ([]PublicKey, error) { var keys []PublicKey - rows, err := d.db.Query(`select did, key, name, created from public_keys where did = ?`, did) + rows, err := d.db.Query(`select did, key, created from public_keys where did = ?`, did) if err != nil { return nil, err } @@ -90,7 +88,7 @@ func (d *DB) GetPublicKeys(did string) ([]PublicKey, error) { for rows.Next() { var publicKey PublicKey - if err := rows.Scan(&publicKey.Did, &publicKey.Key, &publicKey.Name, &publicKey.Created); err != nil { + if err := rows.Scan(&publicKey.Did, &publicKey.Key, &publicKey.Created); err != nil { return nil, err } keys = append(keys, publicKey) diff --git a/knotserver/db/users.go b/knotserver/db/users.go deleted file mode 100644 index a2f484e..0000000 --- a/knotserver/db/users.go +++ /dev/null @@ -1,11 +0,0 @@ -package db - -func (d *DB) AddUser(did string) error { - _, err := d.db.Exec(`insert into users (did) values (?)`, did) - return err -} - -func (d *DB) RemoveUser(did string) error { - _, err := d.db.Exec(`delete from users where did = ?`, did) - return err -} diff --git a/knotserver/handler.go b/knotserver/handler.go index ef00993..05e7de6 100644 --- a/knotserver/handler.go +++ b/knotserver/handler.go @@ -39,10 +39,18 @@ func Setup(ctx context.Context, c *config.Config, db *db.DB) (http.Handler, erro return nil, fmt.Errorf("failed to start jetstream: %w", err) } - // TODO: close this channel and set h.knotInitialized *only after* - // checking if we have an owner. - close(h.init) - h.knotInitialized = true + // Check if the knot knows about any DIDs; + // if it does, it is already initialized and we can repopulate the + // Jetstream subscriptions. + dids, err := db.GetAllDIDs() + if err != nil { + return nil, fmt.Errorf("failed to get all DIDs: %w", err) + } + if len(dids) > 0 { + h.knotInitialized = true + close(h.init) + h.js.UpdateDids(dids) + } r.Get("/", h.Index) r.Route("/{did}", func(r chi.Router) { @@ -67,20 +75,19 @@ func Setup(ctx context.Context, c *config.Config, db *db.DB) (http.Handler, erro }) }) - // Create a new repository + // Create a new repository. r.Route("/repo", func(r chi.Router) { r.Use(h.VerifySignature) r.Put("/new", h.NewRepo) }) - // Add a new user to the knot - r.With(h.VerifySignature).Put("/user", h.AddUser) + // Initialize the knot with an owner and public key. r.With(h.VerifySignature).Post("/init", h.Init) // Health check. Used for two-way verification with appview. r.With(h.VerifySignature).Get("/health", h.Health) - // All public keys on the knot + // All public keys on the knot. r.Get("/keys", h.Keys) return r, nil @@ -117,8 +124,9 @@ func (h *Handle) StartJetstream(ctx context.Context) error { record := commit["record"].(map[string]interface{}) if err := h.db.AddPublicKeyFromRecord(did, record); err != nil { log.Printf("failed to add public key: %v", err) + } else { + log.Printf("added public key from firehose: %s", data["did"]) } - log.Printf("added public key from firehose: %s", data["did"]) default: } } diff --git a/knotserver/middleware.go b/knotserver/middleware.go index 06e9d72..d96b232 100644 --- a/knotserver/middleware.go +++ b/knotserver/middleware.go @@ -10,6 +10,9 @@ import ( ) func (h *Handle) VerifySignature(next http.Handler) http.Handler { + if h.c.Server.Dev { + return next + } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { signature := r.Header.Get("X-Signature") log.Println(signature) diff --git a/knotserver/routes.go b/knotserver/routes.go index 77ab23a..1a5e3ca 100644 --- a/knotserver/routes.go +++ b/knotserver/routes.go @@ -391,10 +391,17 @@ func (h *Handle) NewRepo(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } -func (h *Handle) AddUser(w http.ResponseWriter, r *http.Request) { +// TODO: make this set the initial user as the owner +func (h *Handle) Init(w http.ResponseWriter, r *http.Request) { + if h.knotInitialized { + writeError(w, "knot already initialized", http.StatusConflict) + return + } + data := struct { DID string `json:"did"` - PublicKey string `json:"pubkey"` + PublicKey string `json:"key"` + Created string `json:"created"` }{} if err := json.NewDecoder(r.Body).Decode(&data); err != nil { @@ -404,54 +411,29 @@ func (h *Handle) AddUser(w http.ResponseWriter, r *http.Request) { did := data.DID key := data.PublicKey + created := data.Created - if err := h.db.AddUser(did); err == nil { - pk := db.PublicKey{ - Did: did, - } - pk.Key = key - pk.Name = "default" - err := h.db.AddPublicKey(pk) - if err != nil { - writeError(w, err.Error(), http.StatusInternalServerError) - return - } - } else { - writeError(w, err.Error(), http.StatusInternalServerError) + if did == "" { + writeError(w, "did is empty", http.StatusBadRequest) return } - h.js.UpdateDids([]string{did}) - - w.WriteHeader(http.StatusNoContent) -} - -// TODO: make this set the initial user as the owner -func (h *Handle) Init(w http.ResponseWriter, r *http.Request) { - if h.knotInitialized { - writeError(w, "knot already initialized", http.StatusConflict) + if key == "" { + writeError(w, "key is empty", http.StatusBadRequest) return } - data := struct { - DID string `json:"did"` - PublicKey string `json:"pubkey"` - }{} - - if err := json.NewDecoder(r.Body).Decode(&data); err != nil { - writeError(w, "invalid request body", http.StatusBadRequest) + if created == "" { + writeError(w, "created timestamp is empty", http.StatusBadRequest) return } - did := data.DID - key := data.PublicKey - - if err := h.db.AddUser(did); err == nil { + if err := h.db.AddDID(did); err == nil { pk := db.PublicKey{ Did: did, } pk.Key = key - pk.Name = "default" + pk.Created = created err := h.db.AddPublicKey(pk) if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) -- knotmirror 0.0.1