Skip to content

Commit

Permalink
add tests for handleComAtprotoAccountCreate and handleComAtprotoSessi…
Browse files Browse the repository at this point in the history
…onCreate
  • Loading branch information
erka authored and bnewbold committed Apr 3, 2023
1 parent e288519 commit 51e25d6
Show file tree
Hide file tree
Showing 10 changed files with 259 additions and 201 deletions.
41 changes: 1 addition & 40 deletions cmd/gosky/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bufio"
"bytes"
"context"
"crypto/ecdsa"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -29,13 +28,10 @@ import (
_ "github.com/joho/godotenv/autoload"

logging "github.com/ipfs/go-log"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/polydawn/refmt/cbor"
rejson "github.com/polydawn/refmt/json"
"github.com/polydawn/refmt/shared"
cli "github.com/urfave/cli/v2"
"github.com/whyrusleeping/go-did"
)

var log = logging.Logger("gosky")
Expand Down Expand Up @@ -238,7 +234,7 @@ var didCreateCmd = &cli.Command{

recoverydid := cctx.String("recoverydid")

sigkey, err := loadKey(cctx.String("signingkey"))
sigkey, err := cliutil.LoadKeyFromFile(cctx.String("signingkey"))
if err != nil {
return err
}
Expand All @@ -255,41 +251,6 @@ var didCreateCmd = &cli.Command{
},
}

func loadKey(kfile string) (*did.PrivKey, error) {
kb, err := os.ReadFile(kfile)
if err != nil {
return nil, err
}

sk, err := jwk.ParseKey(kb)
if err != nil {
return nil, err
}

var spk ecdsa.PrivateKey
if err := sk.Raw(&spk); err != nil {
return nil, err
}
curve, ok := sk.Get("crv")
if !ok {
return nil, fmt.Errorf("need a curve set")
}

var out string
kts := string(curve.(jwa.EllipticCurveAlgorithm))
switch kts {
case "P-256":
out = did.KeyTypeP256
default:
return nil, fmt.Errorf("unrecognized key type: %s", kts)
}

return &did.PrivKey{
Raw: &spk,
Type: out,
}, nil
}

var syncCmd = &cli.Command{
Name: "sync",
Subcommands: []*cli.Command{
Expand Down
80 changes: 80 additions & 0 deletions cmd/gosky/util/key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package cliutil

import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"fmt"
"os"
"path/filepath"

"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/whyrusleeping/go-did"
)

// LoadKeyFromFile reads the private key from file
func LoadKeyFromFile(kfile string) (*did.PrivKey, error) {
kb, err := os.ReadFile(kfile)
if err != nil {
return nil, err
}

sk, err := jwk.ParseKey(kb)
if err != nil {
return nil, err
}

var spk ecdsa.PrivateKey
if err := sk.Raw(&spk); err != nil {
return nil, err
}
curve, ok := sk.Get("crv")
if !ok {
return nil, fmt.Errorf("need a curve set")
}

var out string
kts := string(curve.(jwa.EllipticCurveAlgorithm))
switch kts {
case "P-256":
out = did.KeyTypeP256
default:
return nil, fmt.Errorf("unrecognized key type: %s", kts)
}

return &did.PrivKey{
Raw: &spk,
Type: out,
}, nil
}

// GenerateKeyToFile makes the private key and store it into the file
func GenerateKeyToFile(fname string) error {
raw, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("failed to generate new ECDSA private key: %s", err)
}

key, err := jwk.FromRaw(raw)
if err != nil {
return fmt.Errorf("failed to create ECDSA key: %s", err)
}

if _, ok := key.(jwk.ECDSAPrivateKey); !ok {
return fmt.Errorf("expected jwk.ECDSAPrivateKey, got %T", key)
}

key.Set(jwk.KeyIDKey, "mykey")

buf, err := json.MarshalIndent(key, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal key into JSON: %w", err)
}

// ensure data directory exists; won't error if it does
os.MkdirAll(filepath.Dir(fname), os.ModePerm)

return os.WriteFile(fname, buf, 0664)
}
30 changes: 30 additions & 0 deletions cmd/gosky/util/key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cliutil

import (
"os"
"path/filepath"
"testing"

"github.com/whyrusleeping/go-did"
)

func TestKeyGenerationAndLoading(t *testing.T) {
tempdir, err := os.MkdirTemp("", "msttest-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempdir)
fkey := filepath.Join(tempdir, "test.key")
err = GenerateKeyToFile(fkey)
if err != nil {
t.Fatal(err)
}
key, err := LoadKeyFromFile(fkey)
if err != nil {
t.Fatal(err)
}

if key.Type != did.KeyTypeP256 {
t.Fatalf("unexpected type of the key %s", key.KeyType())
}
}
2 changes: 1 addition & 1 deletion cmd/labelmaker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func run(args []string) {
hiveAIToken := cctx.String("hiveai-api-token")
sqrlURL := cctx.String("sqrl-url")

serkey, err := labeling.LoadKeyFromFile(repoKeyPath)
serkey, err := cliutil.LoadKeyFromFile(repoKeyPath)
if err != nil {
return err
}
Expand Down
40 changes: 8 additions & 32 deletions cmd/laputa/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
package main

import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"fmt"
"os"
"path/filepath"

Expand All @@ -19,7 +14,6 @@ import (
_ "github.com/joho/godotenv/autoload"

logging "github.com/ipfs/go-log"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/urfave/cli/v2"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
Expand Down Expand Up @@ -166,7 +160,13 @@ func run(args []string) {
}

pdshost := cctx.String("name")
srv, err := pds.NewServer(db, cstore, keypath, pdsdomain, pdshost, didr, jwtsecret)

key, err := cliutil.LoadKeyFromFile(keypath)
if err != nil {
return err
}

srv, err := pds.NewServer(db, cstore, key, pdsdomain, pdshost, didr, jwtsecret)
if err != nil {
return err
}
Expand All @@ -187,31 +187,7 @@ var generateKeyCmd = &cli.Command{
},
},
Action: func(cctx *cli.Context) error {
raw, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("failed to generate new ECDSA private key: %s", err)
}

key, err := jwk.FromRaw(raw)
if err != nil {
return fmt.Errorf("failed to create ECDSA key: %s", err)
}

if _, ok := key.(jwk.ECDSAPrivateKey); !ok {
return fmt.Errorf("expected jwk.ECDSAPrivateKey, got %T", key)
}

key.Set(jwk.KeyIDKey, "mykey")

buf, err := json.MarshalIndent(key, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal key into JSON: %w", err)
}

fname := cctx.String("output")
// ensure data directory exists; won't error if it does
os.MkdirAll(filepath.Dir(fname), os.ModePerm)

return os.WriteFile(fname, buf, 0664)
return cliutil.GenerateKeyToFile(fname)
},
}
46 changes: 0 additions & 46 deletions labeling/util.go
Original file line number Diff line number Diff line change
@@ -1,51 +1,5 @@
package labeling

import (
"crypto/ecdsa"
"fmt"
"os"

"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/whyrusleeping/go-did"
)

// TODO:(bnewbold): duplicates elsewhere; should refactor into cliutil
func LoadKeyFromFile(kfile string) (*did.PrivKey, error) {
kb, err := os.ReadFile(kfile)
if err != nil {
return nil, err
}

sk, err := jwk.ParseKey(kb)
if err != nil {
return nil, err
}

var spk ecdsa.PrivateKey
if err := sk.Raw(&spk); err != nil {
return nil, err
}
curve, ok := sk.Get("crv")
if !ok {
return nil, fmt.Errorf("need a curve set")
}

var out string
kts := string(curve.(jwa.EllipticCurveAlgorithm))
switch kts {
case "P-256":
out = did.KeyTypeP256
default:
return nil, fmt.Errorf("unrecognized key type: %s", kts)
}

return &did.PrivKey{
Raw: &spk,
Type: out,
}, nil
}

func dedupeStrings(in []string) []string {
var out []string
seen := make(map[string]bool)
Expand Down
4 changes: 3 additions & 1 deletion pds/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -470,14 +470,16 @@ func (s *Server) handleComAtprotoServerDescribeServer(ctx context.Context) (*com
}, nil
}

var ErrInvalidUsernameOrPassword = fmt.Errorf("invalid username or password")

func (s *Server) handleComAtprotoServerCreateSession(ctx context.Context, body *comatprototypes.ServerCreateSession_Input) (*comatprototypes.ServerCreateSession_Output, error) {
u, err := s.lookupUserByHandle(ctx, *body.Identifier)
if err != nil {
return nil, err
}

if body.Password != u.Password {
return nil, fmt.Errorf("invalid username or password")
return nil, ErrInvalidUsernameOrPassword
}

tok, err := s.createAuthTokenForUser(ctx, *body.Identifier, u.Did)
Expand Down
Loading

0 comments on commit 51e25d6

Please sign in to comment.