Compare commits

..

No commits in common. "1029cc8f0f70d9173d76d6039b98083b3b94f0d5" and "2fbc7186c0778fe39c12ebdbccefbede9e9760ed" have entirely different histories.

9 changed files with 160 additions and 188 deletions

View File

@ -39,7 +39,6 @@ import (
"github.com/lestrrat-go/jwx/v2/jwk" "github.com/lestrrat-go/jwx/v2/jwk"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/wlynxg/anet"
_ "embed" _ "embed"
@ -252,7 +251,7 @@ func runApp(ctx context.Context, path, address, documentStoreDSN, blobStoreDSN,
fetchModule.Mount(), fetchModule.Mount(),
), ),
appHTTP.WithHTTPMiddlewares( appHTTP.WithHTTPMiddlewares(
authModuleMiddleware.DefaultUser(key, jwa.HS256, authModuleMiddleware.WithAnonymousUser()), authModuleMiddleware.AnonymousUser(key, jwa.HS256),
), ),
) )
if err := handler.Load(ctx, bundle); err != nil { if err := handler.Load(ctx, bundle); err != nil {
@ -361,13 +360,13 @@ func findMatchingDeviceAddress(ctx context.Context, from string, defaultAddr str
return defaultAddr, nil return defaultAddr, nil
} }
ifaces, err := anet.Interfaces() ifaces, err := net.Interfaces()
if err != nil { if err != nil {
return "", errors.WithStack(err) return "", errors.WithStack(err)
} }
for _, ifa := range ifaces { for _, ifa := range ifaces {
addrs, err := anet.InterfaceAddrsByInterface(&ifa) addrs, err := ifa.Addrs()
if err != nil { if err != nil {
logger.Error( logger.Error(
ctx, "could not retrieve iface adresses", ctx, "could not retrieve iface adresses",

2
go.mod
View File

@ -16,7 +16,6 @@ require (
github.com/lestrrat-go/jwx/v2 v2.0.8 github.com/lestrrat-go/jwx/v2 v2.0.8
github.com/mitchellh/hashstructure/v2 v2.0.2 github.com/mitchellh/hashstructure/v2 v2.0.2
github.com/ulikunitz/xz v0.5.11 github.com/ulikunitz/xz v0.5.11
github.com/wlynxg/anet v0.0.1
go.uber.org/goleak v1.3.0 go.uber.org/goleak v1.3.0
modernc.org/sqlite v1.20.4 modernc.org/sqlite v1.20.4
) )
@ -44,6 +43,7 @@ require (
github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect github.com/muesli/termenv v0.15.2 // indirect
github.com/rivo/uniseg v0.4.4 // indirect github.com/rivo/uniseg v0.4.4 // indirect
github.com/wlynxg/anet v0.0.1 // indirect
go.opentelemetry.io/otel v1.21.0 // indirect go.opentelemetry.io/otel v1.21.0 // indirect
go.opentelemetry.io/otel/trace v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect
golang.org/x/sync v0.5.0 // indirect golang.org/x/sync v0.5.0 // indirect

View File

@ -16,7 +16,7 @@ func TestBundle(t *testing.T) {
bundles := []Bundle{ bundles := []Bundle{
NewDirectoryBundle("testdata/bundle"), NewDirectoryBundle("testdata/bundle"),
NewTarBundle("testdata/bundle.tar.gz"), NewTarBundle("testdata/bundle.tar.gz"),
Must(NewZipBundleFromPath("testdata/bundle.zip")), NewZipBundle("testdata/bundle.zip"),
} }
for _, b := range bundles { for _, b := range bundles {

View File

@ -54,7 +54,7 @@ func matchArchivePattern(archivePath string) (Bundle, error) {
} }
if matches { if matches {
return NewZipBundleFromPath(archivePath) return NewZipBundle(archivePath), nil
} }
matches, err = filepath.Match(fmt.Sprintf("*.%s", ExtZim), base) matches, err = filepath.Match(fmt.Sprintf("*.%s", ExtZim), base)

View File

@ -13,10 +13,15 @@ import (
) )
type ZipBundle struct { type ZipBundle struct {
reader *zip.Reader archivePath string
} }
func (b *ZipBundle) File(filename string) (io.ReadCloser, os.FileInfo, error) { func (b *ZipBundle) File(filename string) (io.ReadCloser, os.FileInfo, error) {
reader, err := b.openArchive()
if err != nil {
return nil, nil, err
}
ctx := logger.With( ctx := logger.With(
context.Background(), context.Background(),
logger.F("filename", filename), logger.F("filename", filename),
@ -24,7 +29,7 @@ func (b *ZipBundle) File(filename string) (io.ReadCloser, os.FileInfo, error) {
logger.Debug(ctx, "opening file") logger.Debug(ctx, "opening file")
f, err := b.reader.Open(filename) f, err := reader.Open(filename)
if err != nil { if err != nil {
return nil, nil, errors.WithStack(err) return nil, nil, errors.WithStack(err)
} }
@ -38,10 +43,21 @@ func (b *ZipBundle) File(filename string) (io.ReadCloser, os.FileInfo, error) {
} }
func (b *ZipBundle) Dir(dirname string) ([]os.FileInfo, error) { func (b *ZipBundle) Dir(dirname string) ([]os.FileInfo, error) {
reader, err := b.openArchive()
if err != nil {
return nil, err
}
defer func() {
if err := reader.Close(); err != nil {
panic(errors.WithStack(err))
}
}()
files := make([]os.FileInfo, 0) files := make([]os.FileInfo, 0)
ctx := context.Background() ctx := context.Background()
for _, f := range b.reader.File { for _, f := range reader.File {
if !strings.HasPrefix(f.Name, dirname) { if !strings.HasPrefix(f.Name, dirname) {
continue continue
} }
@ -66,35 +82,17 @@ func (b *ZipBundle) Dir(dirname string) ([]os.FileInfo, error) {
return files, nil return files, nil
} }
func NewZipBundleFromReader(reader io.ReaderAt, size int64) (*ZipBundle, error) { func (b *ZipBundle) openArchive() (*zip.ReadCloser, error) {
zipReader, err := zip.NewReader(reader, size) zr, err := zip.OpenReader(b.archivePath)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.Wrapf(err, "could not decompress '%v'", b.archivePath)
} }
return zr, nil
}
func NewZipBundle(archivePath string) *ZipBundle {
return &ZipBundle{ return &ZipBundle{
reader: zipReader, archivePath: archivePath,
}, nil
}
func NewZipBundleFromPath(filename string) (*ZipBundle, error) {
file, err := os.Open(filename)
if err != nil {
return nil, errors.WithStack(err)
} }
stat, err := file.Stat()
if err != nil {
return nil, errors.WithStack(err)
}
return NewZipBundleFromReader(file, stat.Size())
}
func Must(bundle Bundle, err error) Bundle {
if err != nil {
panic(errors.WithStack(err))
}
return bundle
} }

View File

@ -5,43 +5,99 @@ import (
"fmt" "fmt"
"math/big" "math/big"
"net/http" "net/http"
"time"
"forge.cadoles.com/arcad/edge/pkg/jwtutil"
"forge.cadoles.com/arcad/edge/pkg/module/auth"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/pkg/errors" "github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
) )
const AnonIssuer = "anon" const AnonIssuer = "anon"
func WithAnonymousUser(funcs ...DefaultUserOptionFunc) DefaultUserOptionFunc { func AnonymousUser(key jwk.Key, signingAlgorithm jwa.SignatureAlgorithm, funcs ...AnonymousUserOptionFunc) func(next http.Handler) http.Handler {
return func(opts *DefaultUserOptions) { opts := defaultAnonymousUserOptions()
opts.GetSubject = getAnonymousSubject
opts.GetPreferredUsername = getAnonymousPreferredUsername
opts.Issuer = AnonIssuer
for _, fn := range funcs { for _, fn := range funcs {
fn(opts) fn(opts)
} }
}
}
func getAnonymousSubject(r *http.Request) (string, error) { return func(next http.Handler) http.Handler {
handler := func(w http.ResponseWriter, r *http.Request) {
rawToken, err := jwtutil.FindRawToken(r, jwtutil.WithFinders(
jwtutil.FindTokenFromAuthorizationHeader,
jwtutil.FindTokenFromQueryString(auth.CookieName),
jwtutil.FindTokenFromCookie(auth.CookieName),
))
// If request already has a raw token, we do nothing
if rawToken != "" && err == nil {
next.ServeHTTP(w, r)
return
}
ctx := r.Context()
uuid, err := uuid.NewUUID() uuid, err := uuid.NewUUID()
if err != nil { if err != nil {
return "", errors.Wrap(err, "could not generate uuid for anonymous user") logger.Error(ctx, "could not generate uuid for anonymous user", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
} }
subject := fmt.Sprintf("%s-%s", AnonIssuer, uuid.String()) subject := fmt.Sprintf("%s-%s", AnonIssuer, uuid.String())
return subject, nil
}
func getAnonymousPreferredUsername(r *http.Request) (string, error) {
preferredUsername, err := generateRandomPreferredUsername(8) preferredUsername, err := generateRandomPreferredUsername(8)
if err != nil { if err != nil {
return "", errors.Wrap(err, "could not generate preferred username for anonymous user") logger.Error(ctx, "could not generate preferred username for anonymous user", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
} }
return preferredUsername, nil claims := map[string]any{
auth.ClaimSubject: subject,
auth.ClaimIssuer: AnonIssuer,
auth.ClaimPreferredUsername: preferredUsername,
auth.ClaimEdgeRole: opts.Role,
auth.ClaimEdgeEntrypoint: opts.Entrypoint,
auth.ClaimEdgeTenant: opts.Tenant,
}
token, err := jwtutil.SignedToken(key, signingAlgorithm, claims)
if err != nil {
logger.Error(ctx, "could not generate signed token", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
cookieDomain, err := opts.GetCookieDomain(r)
if err != nil {
logger.Error(ctx, "could not retrieve cookie domain", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
cookie := http.Cookie{
Name: auth.CookieName,
Value: string(token),
Domain: cookieDomain,
HttpOnly: false,
Expires: time.Now().Add(opts.CookieDuration),
Path: "/",
}
http.SetCookie(w, &cookie)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(handler)
}
} }
func generateRandomPreferredUsername(size int) (string, error) { func generateRandomPreferredUsername(size int) (string, error) {

View File

@ -1,94 +0,0 @@
package middleware
import (
"net/http"
"time"
"forge.cadoles.com/arcad/edge/pkg/jwtutil"
"forge.cadoles.com/arcad/edge/pkg/module/auth"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
func DefaultUser(key jwk.Key, signingAlgorithm jwa.SignatureAlgorithm, funcs ...DefaultUserOptionFunc) func(next http.Handler) http.Handler {
opts := defaultUserOptions()
for _, fn := range funcs {
fn(opts)
}
return func(next http.Handler) http.Handler {
handler := func(w http.ResponseWriter, r *http.Request) {
rawToken, err := jwtutil.FindRawToken(r, jwtutil.WithFinders(
jwtutil.FindTokenFromAuthorizationHeader,
jwtutil.FindTokenFromQueryString(auth.CookieName),
jwtutil.FindTokenFromCookie(auth.CookieName),
))
// If request already has a raw token, we do nothing
if rawToken != "" && err == nil {
next.ServeHTTP(w, r)
return
}
ctx := r.Context()
subject, err := opts.GetSubject(r)
if err != nil {
logger.Error(ctx, "could not retrieve user subject", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
preferredUsername, err := opts.GetPreferredUsername(r)
if err != nil {
logger.Error(ctx, "could not retrieve user preferred username", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
claims := map[string]any{
auth.ClaimSubject: subject,
auth.ClaimIssuer: opts.Issuer,
auth.ClaimPreferredUsername: preferredUsername,
auth.ClaimEdgeRole: opts.Role,
auth.ClaimEdgeEntrypoint: opts.Entrypoint,
auth.ClaimEdgeTenant: opts.Tenant,
}
token, err := jwtutil.SignedToken(key, signingAlgorithm, claims)
if err != nil {
logger.Error(ctx, "could not generate signed token", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
cookieDomain, err := opts.GetCookieDomain(r)
if err != nil {
logger.Error(ctx, "could not retrieve cookie domain", logger.CapturedE(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
cookie := http.Cookie{
Name: auth.CookieName,
Value: string(token),
Domain: cookieDomain,
HttpOnly: false,
Expires: time.Now().Add(opts.CookieDuration),
Path: "/",
}
http.SetCookie(w, &cookie)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(handler)
}
}

View File

@ -11,52 +11,47 @@ func defaultGetCookieDomain(r *http.Request) (string, error) {
return "", nil return "", nil
} }
type DefaultUserOptions struct { type AnonymousUserOptions struct {
GetCookieDomain GetCookieDomainFunc GetCookieDomain GetCookieDomainFunc
CookieDuration time.Duration CookieDuration time.Duration
Tenant string Tenant string
Entrypoint string Entrypoint string
Role string Role string
Issuer string
GetPreferredUsername func(r *http.Request) (string, error)
GetSubject func(r *http.Request) (string, error)
} }
type DefaultUserOptionFunc func(opts *DefaultUserOptions) type AnonymousUserOptionFunc func(*AnonymousUserOptions)
func defaultUserOptions() *DefaultUserOptions { func defaultAnonymousUserOptions() *AnonymousUserOptions {
return &DefaultUserOptions{ return &AnonymousUserOptions{
GetCookieDomain: defaultGetCookieDomain, GetCookieDomain: defaultGetCookieDomain,
CookieDuration: 24 * time.Hour, CookieDuration: 24 * time.Hour,
Tenant: "", Tenant: "",
Entrypoint: "", Entrypoint: "",
Role: "", Role: "",
GetSubject: getAnonymousSubject,
GetPreferredUsername: getAnonymousPreferredUsername,
} }
} }
func WithCookieOptions(getCookieDomain GetCookieDomainFunc, duration time.Duration) DefaultUserOptionFunc { func WithCookieOptions(getCookieDomain GetCookieDomainFunc, duration time.Duration) AnonymousUserOptionFunc {
return func(opts *DefaultUserOptions) { return func(opts *AnonymousUserOptions) {
opts.GetCookieDomain = getCookieDomain opts.GetCookieDomain = getCookieDomain
opts.CookieDuration = duration opts.CookieDuration = duration
} }
} }
func WithTenant(tenant string) DefaultUserOptionFunc { func WithTenant(tenant string) AnonymousUserOptionFunc {
return func(opts *DefaultUserOptions) { return func(opts *AnonymousUserOptions) {
opts.Tenant = tenant opts.Tenant = tenant
} }
} }
func WithEntrypoint(entrypoint string) DefaultUserOptionFunc { func WithEntrypoint(entrypoint string) AnonymousUserOptionFunc {
return func(opts *DefaultUserOptions) { return func(opts *AnonymousUserOptions) {
opts.Entrypoint = entrypoint opts.Entrypoint = entrypoint
} }
} }
func WithRole(role string) DefaultUserOptionFunc { func WithRole(role string) AnonymousUserOptionFunc {
return func(opts *DefaultUserOptions) { return func(opts *AnonymousUserOptions) {
opts.Role = role opts.Role = role
} }
} }

View File

@ -3,6 +3,8 @@ package chromecast
import ( import (
"context" "context"
"net" "net"
"regexp"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -13,7 +15,6 @@ import (
"github.com/barnybug/go-cast/log" "github.com/barnybug/go-cast/log"
"github.com/hashicorp/mdns" "github.com/hashicorp/mdns"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/wlynxg/anet"
) )
const ( const (
@ -150,11 +151,28 @@ func (d *Discovery) listener(ctx context.Context) {
case d.found <- client: case d.found <- client:
case <-time.After(time.Second): case <-time.After(time.Second):
case <-ctx.Done(): case <-ctx.Done():
return break
} }
} }
} }
func decodeDnsEntry(text string) string {
text = strings.Replace(text, `\.`, ".", -1)
text = strings.Replace(text, `\ `, " ", -1)
re := regexp.MustCompile(`([\\][0-9][0-9][0-9])`)
text = re.ReplaceAllStringFunc(text, func(source string) string {
i, err := strconv.Atoi(source[1:])
if err != nil {
return ""
}
return string([]byte{byte(i)})
})
return text
}
func decodeTxtRecord(txt string) map[string]string { func decodeTxtRecord(txt string) map[string]string {
m := make(map[string]string) m := make(map[string]string)
@ -178,7 +196,7 @@ func isIPv6(ip net.IP) bool {
} }
func findMulticastInterfaces(ctx context.Context) ([]net.Interface, error) { func findMulticastInterfaces(ctx context.Context) ([]net.Interface, error) {
ifaces, err := anet.Interfaces() ifaces, err := net.Interfaces()
if err != nil { if err != nil {
return nil, nil return nil, nil
} }
@ -205,7 +223,7 @@ func findMulticastInterfaces(ctx context.Context) ([]net.Interface, error) {
} }
func retrieveSupportedProtocols(iface net.Interface) (bool, bool, error) { func retrieveSupportedProtocols(iface net.Interface) (bool, bool, error) {
adresses, err := anet.InterfaceAddrsByInterface(&iface) adresses, err := iface.Addrs()
if err != nil { if err != nil {
return false, false, errors.WithStack(err) return false, false, errors.WithStack(err)
} }