mirror of
https://github.com/safing/portbase
synced 2025-09-01 18:19:57 +00:00
Add api bridge for database
This commit is contained in:
parent
8c1c522475
commit
8814d279bd
4 changed files with 192 additions and 6 deletions
178
api/api_bridge.go
Normal file
178
api/api_bridge.go
Normal file
|
@ -0,0 +1,178 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/safing/portbase/database"
|
||||
"github.com/safing/portbase/database/record"
|
||||
"github.com/safing/portbase/database/storage"
|
||||
"github.com/safing/portbase/log"
|
||||
)
|
||||
|
||||
const (
|
||||
endpointBridgeRemoteAddress = "websocket-bridge"
|
||||
apiDatabaseName = "api"
|
||||
)
|
||||
|
||||
func registerEndpointBridgeDB() error {
|
||||
if _, err := database.Register(&database.Database{
|
||||
Name: apiDatabaseName,
|
||||
Description: "API Bridge",
|
||||
StorageType: "injected",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := database.InjectDatabase("api", &endpointBridgeStorage{})
|
||||
return err
|
||||
}
|
||||
|
||||
type endpointBridgeStorage struct {
|
||||
storage.InjectBase
|
||||
}
|
||||
|
||||
type EndpointBridgeRequest struct {
|
||||
record.Base
|
||||
sync.Mutex
|
||||
|
||||
Method string
|
||||
Path string
|
||||
Query map[string]string
|
||||
Data []byte
|
||||
MimeType string
|
||||
}
|
||||
|
||||
type EndpointBridgeResponse struct {
|
||||
record.Base
|
||||
sync.Mutex
|
||||
|
||||
MimeType string
|
||||
Body string
|
||||
}
|
||||
|
||||
// Get returns a database record.
|
||||
func (ebs *endpointBridgeStorage) Get(key string) (record.Record, error) {
|
||||
log.Errorf("api bridge: getting %s", key)
|
||||
|
||||
if key == "" {
|
||||
return nil, database.ErrNotFound
|
||||
}
|
||||
|
||||
return callAPI(&EndpointBridgeRequest{
|
||||
Method: http.MethodGet,
|
||||
Path: key,
|
||||
})
|
||||
}
|
||||
|
||||
// Get returns the metadata of a database record.
|
||||
func (ebs *endpointBridgeStorage) GetMeta(key string) (*record.Meta, error) {
|
||||
// This interface is an API, always return a fresh copy.
|
||||
m := &record.Meta{}
|
||||
m.Update()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Put stores a record in the database.
|
||||
func (ebs *endpointBridgeStorage) Put(r record.Record) (record.Record, error) {
|
||||
log.Errorf("api bridge: putting %s", r.Key())
|
||||
|
||||
if r.DatabaseKey() == "" {
|
||||
return nil, database.ErrNotFound
|
||||
}
|
||||
|
||||
// Prepare data.
|
||||
var ebr *EndpointBridgeRequest
|
||||
if r.IsWrapped() {
|
||||
// Only allocate a new struct, if we need it.
|
||||
ebr = &EndpointBridgeRequest{}
|
||||
err := record.Unwrap(r, ebr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
var ok bool
|
||||
ebr, ok = r.(*EndpointBridgeRequest)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("record not of type *EndpointBridgeRequest, but %T", r)
|
||||
}
|
||||
}
|
||||
log.Errorf("api bridge: putting %+v", ebr)
|
||||
|
||||
// Override path with key to mitigate sneaky stuff.
|
||||
ebr.Path = r.DatabaseKey()
|
||||
return callAPI(ebr)
|
||||
}
|
||||
|
||||
// ReadOnly returns whether the database is read only.
|
||||
func (ebs *endpointBridgeStorage) ReadOnly() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func callAPI(ebr *EndpointBridgeRequest) (record.Record, error) {
|
||||
// Add API prefix to path.
|
||||
requestURL := path.Join(apiV1Path, ebr.Path)
|
||||
// Check if path is correct. (Defense in depth)
|
||||
if !strings.HasPrefix(requestURL, apiV1Path) {
|
||||
return nil, fmt.Errorf("bridged request for %q violates scope", ebr.Path)
|
||||
}
|
||||
|
||||
// Apply default Method.
|
||||
if ebr.Method == "" {
|
||||
if len(ebr.Data) > 0 {
|
||||
ebr.Method = http.MethodPost
|
||||
} else {
|
||||
ebr.Method = http.MethodGet
|
||||
}
|
||||
}
|
||||
|
||||
// Build URL.
|
||||
u, err := url.ParseRequestURI(requestURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to build bridged request url: %w", err)
|
||||
}
|
||||
// Build query values.
|
||||
if ebr.Query != nil && len(ebr.Query) > 0 {
|
||||
query := url.Values{}
|
||||
for k, v := range ebr.Query {
|
||||
query.Set(k, v)
|
||||
}
|
||||
u.RawQuery = query.Encode()
|
||||
}
|
||||
log.Errorf("api bridge: calling %s", u.String())
|
||||
|
||||
// Create request and response objects.
|
||||
r := httptest.NewRequest(ebr.Method, u.String(), bytes.NewBuffer(ebr.Data))
|
||||
r.RemoteAddr = endpointBridgeRemoteAddress
|
||||
if ebr.MimeType != "" {
|
||||
r.Header.Set("Content-Type", ebr.MimeType)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
// Let the API handle the request.
|
||||
server.Handler.ServeHTTP(w, r)
|
||||
switch w.Code {
|
||||
case 200:
|
||||
// Everything okay, continue.
|
||||
case 500:
|
||||
// A Go error was returned internally.
|
||||
// We can safely return this as an error.
|
||||
return nil, fmt.Errorf("bridged api call failed: %s", w.Body.String())
|
||||
default:
|
||||
return nil, fmt.Errorf("bridged api call returned unexpected error code %d", w.Code)
|
||||
}
|
||||
|
||||
response := &EndpointBridgeResponse{
|
||||
MimeType: w.Result().Header.Get("Content-Type"),
|
||||
Body: w.Body.String(),
|
||||
}
|
||||
response.SetKey(apiDatabaseName + ":" + ebr.Path)
|
||||
response.UpdateMeta()
|
||||
|
||||
return response, nil
|
||||
}
|
|
@ -250,6 +250,14 @@ func checkAuth(w http.ResponseWriter, r *http.Request, authRequired bool) (token
|
|||
}, false
|
||||
}
|
||||
|
||||
// Database Bridge Access.
|
||||
if r.RemoteAddr == endpointBridgeRemoteAddress {
|
||||
return &AuthToken{
|
||||
Read: dbCompatibilityPermission,
|
||||
Write: dbCompatibilityPermission,
|
||||
}, false
|
||||
}
|
||||
|
||||
// Check for valid API key.
|
||||
token = checkAPIKey(r)
|
||||
if token != nil {
|
||||
|
|
|
@ -260,7 +260,7 @@ func (eh *endpointHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
default:
|
||||
http.Error(w, "Unsupported method for the actions API.", http.StatusMethodNotAllowed)
|
||||
http.Error(w, "unsupported method for the actions API", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -298,13 +298,13 @@ func (eh *endpointHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
|
||||
default:
|
||||
http.Error(w, "Internal server error: Missing handler.", http.StatusInternalServerError)
|
||||
http.Error(w, "missing handler", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Check for handler error.
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error: "+err.Error(), http.StatusInternalServerError)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -321,14 +321,14 @@ func (eh *endpointHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
func readBody(w http.ResponseWriter, r *http.Request) (inputData []byte, ok bool) {
|
||||
// Check for too long content in order to prevent death.
|
||||
if r.ContentLength > 20000000 { // 20MB
|
||||
http.Error(w, "Too much input data.", http.StatusRequestEntityTooLarge)
|
||||
http.Error(w, "too much input data", http.StatusRequestEntityTooLarge)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Read and close body.
|
||||
inputData, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read body: "+err.Error(), http.StatusInternalServerError)
|
||||
http.Error(w, "failed to read body"+err.Error(), http.StatusInternalServerError)
|
||||
return nil, false
|
||||
}
|
||||
return inputData, true
|
||||
|
|
|
@ -67,7 +67,7 @@ func start() error {
|
|||
module.NewTask("clean api sessions", cleanSessions).Repeat(5 * time.Minute)
|
||||
}
|
||||
|
||||
return nil
|
||||
return registerEndpointBridgeDB()
|
||||
}
|
||||
|
||||
func stop() error {
|
||||
|
|
Loading…
Add table
Reference in a new issue