sig-auth/main.go

110 lines
1.9 KiB
Go
Raw Normal View History

2025-02-10 23:07:41 -05:00
package main
import (
"bytes"
"crypto"
"encoding/json"
2025-02-14 19:41:22 -05:00
"flag"
2025-02-10 23:07:41 -05:00
"fmt"
2025-02-14 19:41:22 -05:00
"io"
2025-02-10 23:07:41 -05:00
"log"
2025-02-14 19:41:22 -05:00
"net/http"
2025-02-10 23:07:41 -05:00
"os"
"crispbyte.dev/sig-auth/client"
2025-02-14 19:41:22 -05:00
"crispbyte.dev/sig-auth/server"
2025-02-14 19:41:22 -05:00
"github.com/opencontainers/go-digest"
2025-02-10 23:07:41 -05:00
"golang.org/x/crypto/ssh"
)
func main() {
2025-02-14 19:41:22 -05:00
useClient := flag.Bool("c", false, "Run client")
keyPath := flag.String("key", "", "Path to the private (client mode) or public (server mode) to use")
flag.Parse()
if *useClient {
runClient(keyPath)
} else {
runServer(keyPath)
}
}
func runClient(keyFile *string) {
2025-02-10 23:07:41 -05:00
testData := map[string]string{"hello": "world"}
json_data, _ := json.Marshal(testData)
2025-02-14 19:41:22 -05:00
key, err := loadPrivateKey(*keyFile)
2025-02-10 23:07:41 -05:00
if err != nil {
log.Fatal(err)
}
client, err := client.GetSigningClient(key, "test-id")
if err != nil {
log.Fatal(err)
}
2025-02-14 19:41:22 -05:00
id := digest.FromBytes(json_data)
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")
resp, err := client.Do(req)
2025-02-10 23:07:41 -05:00
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
2025-02-14 19:41:22 -05:00
out, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.StatusCode)
fmt.Println(string(out[:]))
}
func runServer(keyFile *string) {
key, err := loadPublicKey(*keyFile)
2025-02-10 23:07:41 -05:00
2025-02-14 19:41:22 -05:00
if err != nil {
log.Fatal(err)
}
2025-02-10 23:07:41 -05:00
2025-02-14 19:41:22 -05:00
server.Start(key)
2025-02-10 23:07:41 -05:00
}
func loadPrivateKey(keyFile string) (crypto.PrivateKey, error) {
keyBytes, err := os.ReadFile(keyFile)
if err != nil {
return nil, err
}
return ssh.ParseRawPrivateKey(keyBytes)
}
2025-02-14 19:41:22 -05:00
func loadPublicKey(keyFile string) (crypto.PublicKey, error) {
keyBytes, err := os.ReadFile(keyFile)
if err != nil {
return nil, err
}
pk, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
return pk.(ssh.CryptoPublicKey).CryptoPublicKey(), err
}