From ff29f14170346ff79f0553c0a333b3a545a2fb10 Mon Sep 17 00:00:00 2001 From: Anirudh Oppiliappan Date: Sat, 1 Feb 2025 19:09:56 +0200 Subject: [PATCH] appview: do /settings/keys + misc cleanups --- .air.toml => .air/appview.toml | 4 +- .air/knotserver.toml | 7 +++ .gitignore | 1 + appview/auth/auth.go | 62 ++++++++++++++-------- appview/db/db.go | 14 +++-- appview/db/pubkeys.go | 70 +++++++++++++++++++++++++ appview/state/middleware.go | 4 +- appview/state/state.go | 94 ++++++++++++++++++++++++++++------ git/git.go | 6 +-- 9 files changed, 211 insertions(+), 51 deletions(-) rename .air.toml => .air/appview.toml (63%) create mode 100644 .air/knotserver.toml create mode 100644 appview/db/pubkeys.go diff --git a/.air.toml b/.air/appview.toml similarity index 63% rename from .air.toml rename to .air/appview.toml index 6391fa5d..a669704d 100644 --- a/.air.toml +++ b/.air/appview.toml @@ -1,6 +1,6 @@ [build] -cmd = "go build -o knot ./cmd/knotserver/main.go" -bin = "knot" +cmd = "go build -o .bin/app ./cmd/appview/main.go" +bin = ".bin/app" root = "." exclude_regex = [".*_templ.go"] diff --git a/.air/knotserver.toml b/.air/knotserver.toml new file mode 100644 index 00000000..d0d874c0 --- /dev/null +++ b/.air/knotserver.toml @@ -0,0 +1,7 @@ +[build] +cmd = "go build -o .bin/knot ./cmd/knotserver/main.go" +bin = ".bin/knot" +root = "." + +exclude_regex = [""] +include_ext = ["go", "templ"] diff --git a/.gitignore b/.gitignore index e8951b49..b36c224f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .direnv/ tmp *.db +.bin/ diff --git a/appview/auth/auth.go b/appview/auth/auth.go index b689c5bb..9bb59708 100644 --- a/appview/auth/auth.go +++ b/appview/auth/auth.go @@ -2,7 +2,6 @@ package auth import ( "context" - "encoding/json" "fmt" "net/http" "time" @@ -44,11 +43,7 @@ func ResolveIdent(ctx context.Context, arg string) (*identity.Identity, error) { return dir.Lookup(ctx, *id) } -func (a *Auth) CreateInitialSession(ctx context.Context, username, appPassword string) (*comatproto.ServerCreateSession_Output, error) { - resolved, err := ResolveIdent(ctx, username) - if err != nil { - return nil, fmt.Errorf("invalid handle: %s", err) - } +func (a *Auth) CreateInitialSession(ctx context.Context, resolved *identity.Identity, appPassword string) (*comatproto.ServerCreateSession_Output, error) { pdsUrl := resolved.PDSEndpoint() client := xrpc.Client{ @@ -143,22 +138,7 @@ func (s *CreateSessionWrapper) GetStatus() *string { return s.Status } -func (a *Auth) StoreSession(r *http.Request, w http.ResponseWriter, atSessionish Sessionish) error { - var didDoc identity.DIDDocument - - bytes, _ := json.Marshal(atSessionish.GetDidDoc()) - err := json.Unmarshal(bytes, &didDoc) - if err != nil { - return fmt.Errorf("invalid did document for session") - } - - identity := identity.ParseIdentity(&didDoc) - pdsEndpoint := identity.PDSEndpoint() - - if pdsEndpoint == "" { - return fmt.Errorf("no pds endpoint found") - } - +func (a *Auth) StoreSession(r *http.Request, w http.ResponseWriter, atSessionish Sessionish, pdsEndpoint string) error { clientSession, _ := a.Store.Get(r, appview.SESSION_NAME) clientSession.Values[appview.SESSION_HANDLE] = atSessionish.GetHandle() clientSession.Values[appview.SESSION_DID] = atSessionish.GetDid() @@ -170,3 +150,41 @@ func (a *Auth) StoreSession(r *http.Request, w http.ResponseWriter, atSessionish return clientSession.Save(r, w) } + +func (a *Auth) AuthorizedClient(r *http.Request) (*xrpc.Client, error) { + clientSession, err := a.Store.Get(r, "appview-session") + + if err != nil || clientSession.IsNew { + return nil, err + } + + did := clientSession.Values["did"].(string) + pdsUrl := clientSession.Values["pds"].(string) + accessJwt := clientSession.Values["accessJwt"].(string) + refreshJwt := clientSession.Values["refreshJwt"].(string) + + client := &xrpc.Client{ + Host: pdsUrl, + Auth: &xrpc.AuthInfo{ + AccessJwt: accessJwt, + RefreshJwt: refreshJwt, + Did: did, + }, + } + + return client, nil +} + +func (a *Auth) GetSession(r *http.Request) (*sessions.Session, error) { + return a.Store.Get(r, appview.SESSION_NAME) +} + +func (a *Auth) GetDID(r *http.Request) string { + clientSession, _ := a.Store.Get(r, appview.SESSION_NAME) + return clientSession.Values[appview.SESSION_DID].(string) +} + +func (a *Auth) GetHandle(r *http.Request) string { + clientSession, _ := a.Store.Get(r, appview.SESSION_NAME) + return clientSession.Values[appview.SESSION_HANDLE].(string) +} diff --git a/appview/db/db.go b/appview/db/db.go index acaee3d1..dffd447f 100644 --- a/appview/db/db.go +++ b/appview/db/db.go @@ -6,6 +6,7 @@ import ( "log" "github.com/google/uuid" + _ "github.com/mattn/go-sqlite3" ) @@ -25,7 +26,14 @@ func Make(dbPath string) (*DB, error) { did text not null, secret text not null, created integer default (strftime('%s', 'now')), - registered integer + registered integer); + 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) ); `) if err != nil { @@ -86,10 +94,6 @@ func (d *DB) GenerateRegistrationKey(domain, did string) (string, error) { secret := uuid.New().String() - if err != nil { - return "", err - } - _, err = d.db.Exec(` insert into registrations (domain, did, secret) values (?, ?, ?) diff --git a/appview/db/pubkeys.go b/appview/db/pubkeys.go new file mode 100644 index 00000000..9817fc01 --- /dev/null +++ b/appview/db/pubkeys.go @@ -0,0 +1,70 @@ +package db + +import "time" + +func (d *DB) AddPublicKey(did, name, key string) error { + query := `insert into public_keys (did, name, key) values (?, ?, ?)` + _, err := d.db.Exec(query, did, name, key) + return err +} + +func (d *DB) RemovePublicKey(did string) error { + query := `delete from public_keys where did = ?` + _, err := d.db.Exec(query, did) + return err +} + +type PublicKey struct { + Key string + Name string + DID string + Created time.Time +} + +func (d *DB) GetAllPublicKeys() ([]PublicKey, error) { + var keys []PublicKey + + rows, err := d.db.Query(`select key, name, did, created from public_keys`) + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + var publicKey PublicKey + if err := rows.Scan(&publicKey.Key, &publicKey.Name, &publicKey.DID, &publicKey.Created); err != nil { + return nil, err + } + keys = append(keys, publicKey) + } + + if err := rows.Err(); err != nil { + return nil, err + } + + return keys, nil +} + +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) + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + var publicKey PublicKey + if err := rows.Scan(&publicKey.DID, &publicKey.Key, &publicKey.Name, &publicKey.Created); err != nil { + return nil, err + } + keys = append(keys, publicKey) + } + + if err := rows.Err(); err != nil { + return nil, err + } + + return keys, nil +} diff --git a/appview/state/middleware.go b/appview/state/middleware.go index 959afada..0447a9eb 100644 --- a/appview/state/middleware.go +++ b/appview/state/middleware.go @@ -16,7 +16,7 @@ type Middleware func(http.Handler) http.Handler func AuthMiddleware(s *State) Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - session, _ := s.Auth.Store.Get(r, appview.SESSION_NAME) + session, _ := s.auth.Store.Get(r, appview.SESSION_NAME) authorized, ok := session.Values[appview.SESSION_AUTHENTICATED].(bool) if !ok || !authorized { @@ -56,7 +56,7 @@ func AuthMiddleware(s *State) Middleware { sessionish := auth.RefreshSessionWrapper{atSession} - err = s.Auth.StoreSession(r, w, &sessionish) + err = s.auth.StoreSession(r, w, &sessionish, pdsUrl) if err != nil { log.Printf("failed to store session for did: %s\n: %s", atSession.Did, err) return diff --git a/appview/state/state.go b/appview/state/state.go index 0f960dd2..e88022e6 100644 --- a/appview/state/state.go +++ b/appview/state/state.go @@ -9,15 +9,20 @@ import ( "net/http" "time" + comatproto "github.com/bluesky-social/indigo/api/atproto" + lexutil "github.com/bluesky-social/indigo/lex/util" + "github.com/gliderlabs/ssh" "github.com/go-chi/chi/v5" + "github.com/google/uuid" + shbild "github.com/icyphox/bild/api/bild" "github.com/icyphox/bild/appview" "github.com/icyphox/bild/appview/auth" "github.com/icyphox/bild/appview/db" ) type State struct { - Db *db.DB - Auth *auth.Auth + db *db.DB + auth *auth.Auth } func Make() (*State, error) { @@ -42,17 +47,26 @@ func (s *State) Login(w http.ResponseWriter, r *http.Request) { log.Println("unimplemented") return case http.MethodPost: - username := r.FormValue("username") - appPassword := r.FormValue("password") + handle := r.FormValue("handle") + appPassword := r.FormValue("app_password") - atSession, err := s.Auth.CreateInitialSession(ctx, username, appPassword) + fmt.Println("handle", handle) + fmt.Println("app_password", appPassword) + + resolved, err := auth.ResolveIdent(ctx, handle) + if err != nil { + log.Printf("resolving identity: %s", err) + return + } + + atSession, err := s.auth.CreateInitialSession(ctx, resolved, appPassword) if err != nil { log.Printf("creating initial session: %s", err) return } - sessionish := auth.CreateSessionWrapper{atSession} + sessionish := auth.CreateSessionWrapper{ServerCreateSession_Output: atSession} - err = s.Auth.StoreSession(r, w, &sessionish) + err = s.auth.StoreSession(r, w, &sessionish, resolved.PDSEndpoint()) if err != nil { log.Printf("storing session: %s", err) return @@ -65,14 +79,14 @@ func (s *State) Login(w http.ResponseWriter, r *http.Request) { } // requires auth -func (s *State) Key(w http.ResponseWriter, r *http.Request) { +func (s *State) RegistrationKey(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: // list open registrations under this did return case http.MethodPost: - session, err := s.Auth.Store.Get(r, appview.SESSION_NAME) + session, err := s.auth.Store.Get(r, appview.SESSION_NAME) if err != nil || session.IsNew { log.Println("unauthorized attempt to generate registration key") http.Error(w, "Forbidden", http.StatusUnauthorized) @@ -83,13 +97,12 @@ func (s *State) Key(w http.ResponseWriter, r *http.Request) { // check if domain is valid url, and strip extra bits down to just host domain := r.FormValue("domain") - if domain == "" || err != nil { - log.Println(err) + if domain == "" { http.Error(w, "Invalid form", http.StatusBadRequest) return } - key, err := s.Db.GenerateRegistrationKey(domain, did) + key, err := s.db.GenerateRegistrationKey(domain, did) if err != nil { log.Println(err) @@ -98,6 +111,52 @@ func (s *State) Key(w http.ResponseWriter, r *http.Request) { } w.Write([]byte(key)) + } +} + +func (s *State) Keys(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + w.Write([]byte("unimplemented")) + log.Println("unimplemented") + return + case http.MethodPut: + did := s.auth.GetDID(r) + key := r.FormValue("key") + name := r.FormValue("name") + client, _ := s.auth.AuthorizedClient(r) + + _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key)) + if err != nil { + log.Printf("parsing public key: %s", err) + return + } + + if err := s.db.AddPublicKey(did, name, key); err != nil { + log.Printf("adding public key: %s", err) + return + } + + // store in pds too + resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{ + Collection: "sh.bild.publicKey", + Repo: did, + Rkey: uuid.New().String(), + Record: &lexutil.LexiconTypeDecoder{Val: &shbild.PublicKey{ + Created: time.Now().String(), + Key: key, + Name: name, + }}, + }) + + // invalid record + if err != nil { + log.Printf("failed to create record: %s", err) + return + } + + log.Println("created atproto record: ", resp.Uri) + return } } @@ -114,7 +173,7 @@ func (s *State) Check(w http.ResponseWriter, r *http.Request) { log.Println("checking ", domain) - secret, err := s.Db.GetRegistrationKey(domain) + secret, err := s.db.GetRegistrationKey(domain) if err != nil { log.Printf("no key found for domain %s: %s\n", domain, err) return @@ -164,7 +223,7 @@ func (s *State) Check(w http.ResponseWriter, r *http.Request) { w.Write([]byte("check success")) // mark as registered - err = s.Db.Register(domain) + err = s.db.Register(domain) if err != nil { log.Println("failed to register domain", err) http.Error(w, err.Error(), http.StatusInternalServerError) @@ -201,9 +260,14 @@ func (s *State) Router() http.Handler { r.Group(func(r chi.Router) { r.Use(AuthMiddleware(s)) - r.Post("/key", s.Key) + r.Post("/key", s.RegistrationKey) }) }) + r.Route("/settings", func(r chi.Router) { + r.Use(AuthMiddleware(s)) + r.Put("/keys", s.Keys) + }) + return r } diff --git a/git/git.go b/git/git.go index ecd9ddaa..8510e9b4 100644 --- a/git/git.go +++ b/git/git.go @@ -202,11 +202,7 @@ func (g *GitRepo) Branches() ([]*plumbing.Reference, error) { } func (g *GitRepo) FindMainBranch(branches []string) (string, error) { - branches = append(branches, []string{ - "main", - "master", - "trunk", - }...) + for _, b := range branches { _, err := g.r.ResolveRevision(plumbing.Revision(b)) if err == nil { -- knotmirror 0.0.1