feat: refactor REST API

This commit is contained in:
2025-05-04 16:26:04 +02:00
parent bdd5f7bea5
commit d15ec1f8cb
8 changed files with 336 additions and 229 deletions

View File

@@ -1,62 +1,107 @@
package http
import (
"encoding/base64"
"encoding/json"
"log"
"net/http"
"github.com/0x1d/rcond/pkg/network"
"github.com/0x1d/rcond/pkg/user"
"github.com/gorilla/mux"
)
const (
NETWORK_CONNECTION_UUID = "7d706027-727c-4d4c-a816-f0e1b99db8ab"
)
func HandleNetworkUp(w http.ResponseWriter, r *http.Request) {
type configureAPRequest struct {
Interface string `json:"interface"`
SSID string `json:"ssid"`
Password string `json:"password"`
}
type networkUpRequest struct {
UUID string `json:"uuid"`
}
type setHostnameRequest struct {
Hostname string `json:"hostname"`
}
type authorizedKeyRequest struct {
User string `json:"user"`
PubKey string `json:"pubkey"`
}
func HandleConfigureAP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Interface string `json:"interface"`
SSID string `json:"ssid"`
Password string `json:"password"`
}
var req configureAPRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Printf("Bringing up network interface %s with SSID %s", req.Interface, req.SSID)
if err := network.Up(req.Interface, req.SSID, req.Password, NETWORK_CONNECTION_UUID); err != nil {
log.Printf("Failed to bring up network interface %s: %v", req.Interface, err)
log.Printf("Configuring access point on interface %s", req.Interface)
uuid, err := network.ConfigureAP(req.Interface, req.SSID, req.Password)
if err != nil {
log.Printf("Failed to configure access point on interface %s: %v", req.Interface, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Successfully brought up network interface %s", req.Interface)
log.Printf("Successfully configured access point on interface %s with UUID %s", req.Interface, uuid)
resp := struct {
UUID string `json:"uuid"`
}{
UUID: uuid,
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Printf("Failed to encode response: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func HandleNetworkUp(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req networkUpRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
vars := mux.Vars(r)
iface := vars["interface"]
log.Printf("Bringing up network interface %s with UUID %s", iface, req.UUID)
if err := network.Up(iface, req.UUID); err != nil {
log.Printf("Failed to bring up network interface %s: %v", iface, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Successfully brought up network interface %s", iface)
w.WriteHeader(http.StatusOK)
}
func HandleNetworkDown(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Interface string `json:"interface"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := network.Down(req.Interface); err != nil {
vars := mux.Vars(r)
iface := vars["interface"]
if err := network.Down(iface); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
@@ -65,12 +110,14 @@ func HandleNetworkDown(w http.ResponseWriter, r *http.Request) {
}
func HandleNetworkRemove(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if err := network.Remove(NETWORK_CONNECTION_UUID); err != nil {
vars := mux.Vars(r)
uuid := vars["uuid"]
if err := network.Remove(uuid); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
@@ -93,10 +140,7 @@ func HandleSetHostname(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
Hostname string `json:"hostname"`
}
var req setHostnameRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
@@ -116,22 +160,21 @@ func HandleAddAuthorizedKey(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
User string `json:"user"`
PubKey string `json:"pubkey"`
}
var req authorizedKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
vars := mux.Vars(r)
username := vars["user"]
if err := user.AddAuthorizedKey(req.User, req.PubKey); err != nil {
fingerprint, err := user.AddAuthorizedKey(username, req.PubKey)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(fingerprint))
}
func HandleRemoveAuthorizedKey(w http.ResponseWriter, r *http.Request) {
@@ -140,17 +183,26 @@ func HandleRemoveAuthorizedKey(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
User string `json:"user"`
PubKey string `json:"pubkey"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
vars := mux.Vars(r)
fingerprint := vars["fingerprint"]
if fingerprint == "" {
http.Error(w, "fingerprint parameter is required", http.StatusBadRequest)
return
}
if err := user.RemoveAuthorizedKey(req.User, req.PubKey); err != nil {
username := vars["user"]
if username == "" {
http.Error(w, "user parameter is required", http.StatusBadRequest)
return
}
fingerprintBytes, err := base64.RawURLEncoding.DecodeString(fingerprint)
if err != nil {
http.Error(w, "invalid fingerprint base64", http.StatusBadRequest)
return
}
if err := user.RemoveAuthorizedKey(username, string(fingerprintBytes)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

View File

@@ -53,13 +53,14 @@ func (s *Server) verifyToken(next http.HandlerFunc) http.HandlerFunc {
func (s *Server) RegisterRoutes() {
s.router.HandleFunc("/health", s.healthHandler).Methods(http.MethodGet)
s.router.HandleFunc("/network/up", s.verifyToken(HandleNetworkUp)).Methods(http.MethodPost)
s.router.HandleFunc("/network/down", s.verifyToken(HandleNetworkDown)).Methods(http.MethodPost)
s.router.HandleFunc("/network/remove", s.verifyToken(HandleNetworkRemove)).Methods(http.MethodPost)
s.router.HandleFunc("/network/ap", s.verifyToken(HandleConfigureAP)).Methods(http.MethodPost)
s.router.HandleFunc("/network/interface/{interface}", s.verifyToken(HandleNetworkUp)).Methods(http.MethodPut)
s.router.HandleFunc("/network/interface/{interface}", s.verifyToken(HandleNetworkDown)).Methods(http.MethodDelete)
s.router.HandleFunc("/network/connection/{uuid}", s.verifyToken(HandleNetworkRemove)).Methods(http.MethodDelete)
s.router.HandleFunc("/hostname", s.verifyToken(HandleGetHostname)).Methods(http.MethodGet)
s.router.HandleFunc("/hostname", s.verifyToken(HandleSetHostname)).Methods(http.MethodPost)
s.router.HandleFunc("/authorized-key", s.verifyToken(HandleAddAuthorizedKey)).Methods(http.MethodPost)
s.router.HandleFunc("/authorized-key", s.verifyToken(HandleRemoveAuthorizedKey)).Methods(http.MethodDelete)
s.router.HandleFunc("/users/{user}/keys", s.verifyToken(HandleAddAuthorizedKey)).Methods(http.MethodPost)
s.router.HandleFunc("/users/{user}/keys/{fingerprint}", s.verifyToken(HandleRemoveAuthorizedKey)).Methods(http.MethodDelete)
}
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {

View File

@@ -7,10 +7,7 @@ import (
"time"
"github.com/godbus/dbus/v5"
)
const (
ourUUID = "7d706027-727c-4d4c-a816-f0e1b99db8ab"
"github.com/google/uuid"
)
var (
@@ -18,6 +15,40 @@ var (
defaultPassword = "raspberry"
)
// ConnectionConfig holds the configuration for a NetworkManager connection
type ConnectionConfig struct {
Type string
UUID string
ID string
AutoConnect bool
SSID string
Mode string
Band string
Channel uint32
KeyMgmt string
PSK string
IPv4Method string
IPv6Method string
}
// DefaultAPConfig returns a default access point configuration
func DefaultAPConfig(uuid uuid.UUID, ssid string, password string) *ConnectionConfig {
return &ConnectionConfig{
Type: "802-11-wireless",
UUID: uuid.String(),
ID: ssid,
AutoConnect: true,
SSID: ssid,
Mode: "ap",
Band: "bg",
Channel: 1,
KeyMgmt: "wpa-psk",
PSK: password,
IPv4Method: "shared",
IPv6Method: "ignore",
}
}
// withDbus executes the given function with a D-Bus system connection
// and handles any connection errors
func withDbus(fn func(*dbus.Conn) error) error {
@@ -185,10 +216,18 @@ func GetConnectionPath(conn *dbus.Conn, connUUID string) (dbus.ObjectPath, error
}
// AddConnection creates a new NetworkManager connection profile for a WiFi access point.
// Takes a D-Bus connection, SSID string, and password string as arguments.
// Takes a D-Bus connection, UUID string, SSID string, and password string as arguments.
// Returns the D-Bus object path of the new connection profile.
// Returns an error if the connection creation fails.
func AddConnection(conn *dbus.Conn, ssid string, password string) (dbus.ObjectPath, error) {
func AddAccessPointConnection(conn *dbus.Conn, uuid uuid.UUID, ssid string, password string) (dbus.ObjectPath, error) {
return AddConnectionWithConfig(conn, DefaultAPConfig(uuid, ssid, password))
}
// AddConnectionWithConfig creates a new NetworkManager connection profile with the given configuration.
// Takes a D-Bus connection and ConnectionConfig struct as arguments.
// Returns the D-Bus object path of the new connection profile.
// Returns an error if the connection creation fails.
func AddConnectionWithConfig(conn *dbus.Conn, cfg *ConnectionConfig) (dbus.ObjectPath, error) {
settingsObj := conn.Object(
"org.freedesktop.NetworkManager",
"/org/freedesktop/NetworkManager/Settings",
@@ -196,26 +235,26 @@ func AddConnection(conn *dbus.Conn, ssid string, password string) (dbus.ObjectPa
settingsMap := map[string]map[string]dbus.Variant{
"connection": {
"type": dbus.MakeVariant("802-11-wireless"),
"uuid": dbus.MakeVariant(ourUUID),
"id": dbus.MakeVariant(ssid),
"autoconnect": dbus.MakeVariant(true),
"type": dbus.MakeVariant(cfg.Type),
"uuid": dbus.MakeVariant(cfg.UUID),
"id": dbus.MakeVariant(cfg.ID),
"autoconnect": dbus.MakeVariant(cfg.AutoConnect),
},
"802-11-wireless": {
"ssid": dbus.MakeVariant([]byte(ssid)),
"mode": dbus.MakeVariant("ap"),
"band": dbus.MakeVariant("bg"),
"channel": dbus.MakeVariant(uint32(1)),
"ssid": dbus.MakeVariant([]byte(cfg.SSID)),
"mode": dbus.MakeVariant(cfg.Mode),
"band": dbus.MakeVariant(cfg.Band),
"channel": dbus.MakeVariant(cfg.Channel),
},
"802-11-wireless-security": {
"key-mgmt": dbus.MakeVariant("wpa-psk"),
"psk": dbus.MakeVariant(password),
"key-mgmt": dbus.MakeVariant(cfg.KeyMgmt),
"psk": dbus.MakeVariant(cfg.PSK),
},
"ipv4": {
"method": dbus.MakeVariant("shared"),
"method": dbus.MakeVariant(cfg.IPv4Method),
},
"ipv6": {
"method": dbus.MakeVariant("ignore"),
"method": dbus.MakeVariant(cfg.IPv6Method),
},
}
@@ -279,13 +318,34 @@ func SetHostname(newHost string) error {
})
}
// Up creates and activates a WiFi access point connection.
// It takes the interface name, SSID, password and UUID as arguments.
// If a connection with the given UUID exists, it will be reused.
// Otherwise, a new connection will be created.
// ConfigureAP creates a WiFi access point connection with the specified settings.
// It takes the interface name, SSID and password as arguments.
// A new connection with a generated UUID will be created.
// Returns the UUID of the created connection and any error that occurred.
func ConfigureAP(iface string, ssid string, password string) (string, error) {
uuid := uuid.New()
err := withDbus(func(conn *dbus.Conn) error {
_, err := AddAccessPointConnection(conn, uuid, ssid, password)
if err != nil {
return fmt.Errorf("failed to create access point connection: %v", err)
}
return nil
})
if err != nil {
return "", err
}
return uuid.String(), nil
}
// Up activates a connection.
// It takes the interface name and UUID as arguments.
// The connection with the given UUID must exist.
// The connection will be activated on the specified interface.
// Returns an error if any operation fails.
func Up(iface string, ssid string, password string, uuid string) error {
func Up(iface string, uuid string) error {
return withDbus(func(conn *dbus.Conn) error {
connPath, err := GetConnectionPath(conn, uuid)
if err != nil {
@@ -293,10 +353,7 @@ func Up(iface string, ssid string, password string, uuid string) error {
}
if connPath == "" {
connPath, err = AddConnection(conn, ssid, password)
if err != nil {
return err
}
return fmt.Errorf("connection with UUID %s not found", uuid)
}
log.Printf("Getting device path for interface %s", iface)

View File

@@ -9,18 +9,19 @@ import (
)
// AddAuthorizedKey verifies and adds an SSH public key to /home/<user>/.ssh/authorized_keys
// if it doesn't already exist
func AddAuthorizedKey(user string, pubKey string) error {
// Verify the public key format
_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
// if it doesn't already exist. Returns the key's fingerprint.
func AddAuthorizedKey(user string, pubKey string) (string, error) {
// Verify the public key format and get fingerprint
parsed, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
if err != nil {
return fmt.Errorf("invalid SSH public key: %v", err)
return "", fmt.Errorf("invalid SSH public key: %v", err)
}
fingerprint := ssh.FingerprintSHA256(parsed)
// Ensure .ssh directory exists
sshDir := fmt.Sprintf("/home/%s/.ssh", user)
if err := os.MkdirAll(sshDir, 0700); err != nil {
return fmt.Errorf("failed to create .ssh directory: %v", err)
return "", fmt.Errorf("failed to create .ssh directory: %v", err)
}
// Check if key already exists
@@ -28,43 +29,45 @@ func AddAuthorizedKey(user string, pubKey string) error {
if _, err := os.Stat(keyFile); err == nil {
existingKeys, err := os.ReadFile(keyFile)
if err != nil {
return fmt.Errorf("failed to read authorized_keys: %v", err)
return "", fmt.Errorf("failed to read authorized_keys: %v", err)
}
if string(existingKeys) != "" {
for _, line := range strings.Split(string(existingKeys), "\n") {
if line == pubKey {
// Key already exists, nothing to do
return nil
if line == "" {
continue
}
parsed, err := ssh.ParsePublicKey([]byte(line))
if err != nil {
continue
}
if ssh.FingerprintSHA256(parsed) == fingerprint {
// Key already exists, return fingerprint
return fingerprint, nil
}
}
}
} else if !os.IsNotExist(err) {
return fmt.Errorf("failed to check authorized_keys: %v", err)
return "", fmt.Errorf("failed to check authorized_keys: %v", err)
}
// Open authorized_keys file in append mode
f, err := os.OpenFile(keyFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open authorized_keys: %v", err)
return "", fmt.Errorf("failed to open authorized_keys: %v", err)
}
defer f.Close()
// Write the public key
if _, err := f.WriteString(pubKey + "\n"); err != nil {
return fmt.Errorf("failed to write public key: %v", err)
return "", fmt.Errorf("failed to write public key: %v", err)
}
return nil
return fingerprint, nil
}
// RemoveAuthorizedKey removes an authorized SSH key from /home/<user>/.ssh/authorized_keys
func RemoveAuthorizedKey(user string, pubKey string) error {
// Verify the public key format
_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
if err != nil {
return fmt.Errorf("invalid SSH public key: %v", err)
}
// using the key's fingerprint to identify which key to remove
func RemoveAuthorizedKey(user string, fingerprint string) error {
// Check if authorized_keys file exists
keyFile := fmt.Sprintf("/home/%s/.ssh/authorized_keys", user)
if _, err := os.Stat(keyFile); err != nil {
@@ -80,10 +83,19 @@ func RemoveAuthorizedKey(user string, pubKey string) error {
return fmt.Errorf("failed to read authorized_keys: %v", err)
}
// Filter out the key to remove
// Filter out the key with matching fingerprint
var newLines []string
for _, line := range strings.Split(string(existingKeys), "\n") {
if line != "" && line != pubKey {
if line == "" {
continue
}
parsed, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line))
if err != nil {
// Keep lines we can't parse
newLines = append(newLines, line)
continue
}
if ssh.FingerprintSHA256(parsed) != fingerprint {
newLines = append(newLines, line)
}
}