You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.0 KiB
Go
63 lines
2.0 KiB
Go
package console
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.luoli.live/root/virt/gateway/internal/protocol"
|
|
)
|
|
|
|
type memoryNonceStore struct {
|
|
mu sync.Mutex
|
|
values map[string]time.Time
|
|
}
|
|
|
|
func (s *memoryNonceStore) UseNonce(nonce string, now, expiresAt time.Time) (bool, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if expiry, exists := s.values[nonce]; exists && expiry.After(now) {
|
|
return false, nil
|
|
}
|
|
s.values[nonce] = expiresAt
|
|
return true, nil
|
|
}
|
|
|
|
func TestHTTPIntrospectorSignsExactBodyAndTarget(t *testing.T) {
|
|
secret := []byte(strings.Repeat("i", 32))
|
|
authenticator, _ := protocol.NewAuthenticator(secret, time.Minute, 2*time.Minute,
|
|
&memoryNonceStore{values: map[string]time.Time{}})
|
|
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
|
body, _ := io.ReadAll(request.Body)
|
|
actor, err := authenticator.Authenticate(request, body)
|
|
if err != nil || actor.Service != "agent-gateway" {
|
|
http.Error(response, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
var input IntrospectionRequest
|
|
if json.Unmarshal(body, &input) != nil || !input.Consume || input.Ticket != strings.Repeat("b", 32) {
|
|
http.Error(response, "bad request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
response.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(response).Encode(IntrospectionResult{Active: true,
|
|
ConnectionID: strings.Repeat("c", 32), AgentID: "12",
|
|
AgentTicket: strings.Repeat("a", 32),
|
|
AgentExpiresAt: time.Now().Add(time.Minute).UTC().Format(time.RFC3339)})
|
|
}))
|
|
defer server.Close()
|
|
client, err := NewHTTPIntrospector(server.URL+RequiredIntrospectionPath, secret, time.Second)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
result, err := client.Inspect(t.Context(), IntrospectionRequest{Ticket: strings.Repeat("b", 32), Consume: true})
|
|
if err != nil || !result.Active || result.ConnectionID != strings.Repeat("c", 32) {
|
|
t.Fatalf("result=%#v err=%v", result, err)
|
|
}
|
|
}
|