Reorg client code

This commit is contained in:
cheddar 2025-02-20 21:49:05 -05:00
parent 61aa1be730
commit f313a8f1c9
No known key found for this signature in database
4 changed files with 58 additions and 37 deletions

49
main.go
View file

@ -1,20 +1,18 @@
package main
import (
"bytes"
"crypto"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"crispbyte.dev/sig-auth/client"
"crispbyte.dev/sig-auth/keydirectory"
"crispbyte.dev/sig-auth/server"
"github.com/opencontainers/go-digest"
"golang.org/x/crypto/ssh"
)
@ -29,6 +27,8 @@ func main() {
keyPath := flag.String("key", "", "Path to the private key (client mode) or public key (registration mode) to use")
baseUrlString := flag.String("base-url", "http://localhost:8080", "Base URL of the server")
simulateCaddy := flag.Bool("caddy", false, "Simulate caddy reverse proxy")
useTempDb := flag.Bool("temp-db", false, "Use a temporary in-memory database")
@ -37,20 +37,27 @@ func main() {
flag.Parse()
baseUrl, err := url.Parse(*baseUrlString)
if err != nil {
flag.PrintDefaults()
return
}
if *useClient {
if *keyPath == "" || *keyId == "" {
flag.PrintDefaults()
return
}
runClient(*keyPath, *keyId, *simulateCaddy)
runClient(baseUrl, *keyPath, *keyId, *simulateCaddy)
} else if *register {
if *keyPath == "" || *user == "" {
flag.PrintDefaults()
return
}
registerKey(*keyPath, *user)
registerKey(baseUrl, *keyPath, *user)
} else {
if !*useTempDb && *dbPath == "" {
flag.PrintDefaults()
@ -61,7 +68,7 @@ func main() {
}
}
func runClient(keyFile string, keyId string, simulateCaddy bool) {
func runClient(baseUrl *url.URL, keyFile string, keyId string, simulateCaddy bool) {
testData := map[string]string{"hello": "world"}
json_data, _ := json.Marshal(testData)
@ -71,31 +78,7 @@ func runClient(keyFile string, keyId string, simulateCaddy bool) {
log.Fatal(err)
}
client, err := client.GetSigningClient(key, keyId)
if err != nil {
log.Fatal(err)
}
id := digest.FromBytes(json_data)
var req *http.Request
req, err = http.NewRequest("POST", "http://localhost:8080/post", bytes.NewBuffer(json_data))
if err != nil {
log.Fatal(err)
}
req.Header.Add("Content-Digest", string(id.Algorithm())+"="+id.Encoded())
req.Header.Add("Content-Type", "application/json")
if simulateCaddy {
req.Header.Add("X-Forwarded-Method", req.Method)
req.Header.Add("X-Forwarded-Uri", req.RequestURI)
}
resp, err := client.Do(req)
resp, err := client.Post(baseUrl, key, keyId, json_data, simulateCaddy)
if err != nil {
log.Fatal(err)
@ -141,7 +124,7 @@ func loadPrivateKey(keyFile string) (crypto.PrivateKey, error) {
return ssh.ParseRawPrivateKey(keyBytes)
}
func registerKey(keyFile string, userId string) {
func registerKey(baseUrl *url.URL, keyFile string, userId string) {
keyBytes, err := os.ReadFile(keyFile)
if err != nil {
@ -150,7 +133,7 @@ func registerKey(keyFile string, userId string) {
keyText := string(keyBytes)
err = client.RegisterKey(keyText, userId)
err = client.RegisterKey(baseUrl, keyText, userId)
if err != nil {
log.Fatal(err)