Skip to content
This repository has been archived by the owner on Aug 17, 2023. It is now read-only.

Commit

Permalink
refactor for OT-Auth service client.
Browse files Browse the repository at this point in the history
  • Loading branch information
zensh committed Oct 20, 2020
1 parent 59fbb9d commit cbdc9ed
Show file tree
Hide file tree
Showing 18 changed files with 930 additions and 551 deletions.
4 changes: 2 additions & 2 deletions cmd/otgo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func (c *verifyCmd) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface
func (c *verifyCmd) verify(ctx context.Context, token string) error {
s := c.jwk
var err error
var ks *otgo.Keys
var ks *otgo.JWKSet
if strings.HasPrefix(s, "http") {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
Expand All @@ -285,7 +285,7 @@ func (c *verifyCmd) verify(ctx context.Context, token string) error {
s = string(b)
}

ks, err = otgo.ParseKeys(s)
ks, err = otgo.ParseSet(s)
}

if err == nil {
Expand Down
49 changes: 49 additions & 0 deletions example/otclient/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package main

import (
"context"
"encoding/json"
"fmt"

otgo "github.com/open-trust/ot-go-lib"
)

func mustMarshal(v interface{}) string {
s, e := json.Marshal(v)
if e != nil {
panic(e)
}
return string(s)
}

func main() {
td := otgo.TrustDomain("ot.example.com")
agent := td.NewOTID("agent", "admin")
key, err := otgo.ParseKey(`{"kty":"EC","alg":"ES256","crv":"P-256","d":"oPMtH9jXcUv14YMeKZobee4f3oqS9CSGBwHzvzlJGW8","kid":"RJEq_LyfqYxf0M6NNPz-RnLirou3fvVbF-rMsbly3oQ","x":"cleqDz1kCXSI9QVU2HdPu97qLt5QTlvLKIttwzswe2E","y":"IQ0IqixMzPHWSEAT9_3Ojot1V6ql5uGfTy7hCpYl_jg"}`)
if err != nil {
panic(err)
}

cli, err := otgo.NewOTClient(context.Background(), agent)
if err != nil {
panic(err)
}
cli.SetHTTPClient(otgo.NewTestClient("http://localhost:8081").WithUA("ot-go-lib"))
cli.SetPrivateKeys(*otgo.MustKeys(key))
err = cli.LoadConfig()
if err != nil {
panic(err)
}

token, err := cli.Sign(context.Background(), otgo.SignInput{
Subject: agent,
Audience: td.NewOTID("svc", "testing"),
})
fmt.Printf("cli.Sign: %#v\n\n", token)

vid, err := cli.ParseOTVID(context.Background(), token, td.NewOTID("svc", "testing"))
fmt.Printf("cli.ParseOTVID: %#v\n\n", vid)

vid, err = cli.Verify(context.Background(), token, td.NewOTID("svc", "testing"))
fmt.Printf("cli.Verify: %#v\n\n", vid)
}
46 changes: 36 additions & 10 deletions helper.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
package otgo

import (
"context"
"errors"
"net/http"
"strings"
"sync/atomic"
"time"
)

// Version ...
const Version = "v0.7.1"
const Version = "v0.8.0"

const headerAuthorization = "Authorization"
const authPrefix = "Bearer "

// Debugger ...
type Debugger interface {
Debug(v interface{})
Debugf(format string, args ...interface{})
}

// Debugging ...
var Debugging Debugger

// DefaultHTTPClient ...
var DefaultHTTPClient = NewHTTPClient(nil)

Expand All @@ -38,3 +33,34 @@ func AddTokenToHeader(h http.Header, token string) {
h.Set(headerAuthorization, authPrefix+token)
}
}

// SelectEndpoints ...
func SelectEndpoints(ctx context.Context, cli *HTTPClient, serviceEndpoints []string) (string, error) {
if len(serviceEndpoints) == 0 {
return "", errors.New("no service endpoints")
}
if cli == nil {
cli = DefaultHTTPClient
}

ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
ch := make(chan string)
i := int32(len(serviceEndpoints))
for _, serviceEndpoint := range serviceEndpoints {
go func(url string) {
if err := cli.Get(ctx, url, nil); err == nil {
ch <- url
}
if atomic.AddInt32(&i, -1) == 0 {
cancel()
}
}(serviceEndpoint)
}
select {
case url := <-ch:
return url, nil
case <-ctx.Done():
return "", errors.New("no valid service endpoints")
}
}
45 changes: 43 additions & 2 deletions helper_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package otgo_test

import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"

otgo "github.com/open-trust/ot-go-lib"
"github.com/stretchr/testify/assert"
Expand All @@ -26,8 +29,46 @@ func TestHelper(t *testing.T) {
assert.Equal("456", otgo.ExtractTokenFromHeader(h))
})

t.Run("Debugging", func(t *testing.T) {
t.Run("SelectEndpoints func", func(t *testing.T) {
assert := assert.New(t)
assert.True(otgo.Debugging == nil)

ts0 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(100 * time.Millisecond)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
w.Write([]byte(`{"result": "ok"}`))
}))
defer ts0.Close()

ts1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(50 * time.Millisecond)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
w.Write([]byte(`{"result": "ok"}`))
}))
defer ts1.Close()

ts2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(500)
w.Write([]byte(`{"result": "error"}`))
}))
defer ts2.Close()

ts3 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(50 * time.Millisecond)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(500)
w.Write([]byte(`{"result": "error"}`))
}))
defer ts3.Close()

url, err := otgo.SelectEndpoints(context.Background(), nil, []string{ts0.URL, ts1.URL, ts2.URL})
assert.Nil(err)
assert.Equal(ts1.URL, url)

url, err = otgo.SelectEndpoints(context.Background(), nil, []string{ts2.URL, ts3.URL})
assert.NotNil(err)
assert.Equal("", url)
})
}
124 changes: 0 additions & 124 deletions holder.go

This file was deleted.

Loading

0 comments on commit cbdc9ed

Please sign in to comment.