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/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/wlynxg/anet"
_ "embed"
@ -252,7 +251,7 @@ func runApp(ctx context.Context, path, address, documentStoreDSN, blobStoreDSN,
fetchModule.Mount(),
),
appHTTP.WithHTTPMiddlewares(
authModuleMiddleware.DefaultUser(key, jwa.HS256, authModuleMiddleware.WithAnonymousUser()),
authModuleMiddleware.AnonymousUser(key, jwa.HS256),
),
)
if err := handler.Load(ctx, bundle); err != nil {
@ -361,13 +360,13 @@ func findMatchingDeviceAddress(ctx context.Context, from string, defaultAddr str
return defaultAddr, nil
}
ifaces, err := anet.Interfaces()
ifaces, err := net.Interfaces()
if err != nil {
return "", errors.WithStack(err)
}
for _, ifa := range ifaces {
addrs, err := anet.InterfaceAddrsByInterface(&ifa)
addrs, err := ifa.Addrs()
if err != nil {
logger.Error(
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/mitchellh/hashstructure/v2 v2.0.2
github.com/ulikunitz/xz v0.5.11
github.com/wlynxg/anet v0.0.1
go.uber.org/goleak v1.3.0
modernc.org/sqlite v1.20.4
)
@ -44,6 +43,7 @@ require (
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // 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/trace v1.21.0 // indirect
golang.org/x/sync v0.5.0 // indirect

View File

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

View File

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

View File

@ -13,10 +13,15 @@ import (
)
type ZipBundle struct {
reader *zip.Reader
archivePath string
}
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(
context.Background(),
logger.F("filename", filename),
@ -24,7 +29,7 @@ func (b *ZipBundle) File(filename string) (io.ReadCloser, os.FileInfo, error) {
logger.Debug(ctx, "opening file")
f, err := b.reader.Open(filename)
f, err := reader.Open(filename)
if err != nil {
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) {
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)
ctx := context.Background()
for _, f := range b.reader.File {
for _, f := range reader.File {
if !strings.HasPrefix(f.Name, dirname) {
continue
}
@ -66,35 +82,17 @@ func (b *ZipBundle) Dir(dirname string) ([]os.FileInfo, error) {
return files, nil
}
func NewZipBundleFromReader(reader io.ReaderAt, size int64) (*ZipBundle, error) {
zipReader, err := zip.NewReader(reader, size)
func (b *ZipBundle) openArchive() (*zip.ReadCloser, error) {
zr, err := zip.OpenReader(b.archivePath)
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{
reader: zipReader,
}, nil
}
func NewZipBundleFromPath(filename string) (*ZipBundle, error) {
file, err := os.Open(filename)
if err != nil {
return nil, errors.WithStack(err)
archivePath: archivePath,
}
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,45 +5,101 @@ import (
"fmt"
"math/big"
"net/http"
"time"
"forge.cadoles.com/arcad/edge/pkg/jwtutil"
"forge.cadoles.com/arcad/edge/pkg/module/auth"
"github.com/google/uuid"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
const AnonIssuer = "anon"
func WithAnonymousUser(funcs ...DefaultUserOptionFunc) DefaultUserOptionFunc {
return func(opts *DefaultUserOptions) {
opts.GetSubject = getAnonymousSubject
opts.GetPreferredUsername = getAnonymousPreferredUsername
opts.Issuer = AnonIssuer
func AnonymousUser(key jwk.Key, signingAlgorithm jwa.SignatureAlgorithm, funcs ...AnonymousUserOptionFunc) func(next http.Handler) http.Handler {
opts := defaultAnonymousUserOptions()
for _, fn := range funcs {
fn(opts)
}
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()
uuid, err := uuid.NewUUID()
if err != nil {
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())
preferredUsername, err := generateRandomPreferredUsername(8)
if err != nil {
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
}
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 getAnonymousSubject(r *http.Request) (string, error) {
uuid, err := uuid.NewUUID()
if err != nil {
return "", errors.Wrap(err, "could not generate uuid for anonymous user")
}
subject := fmt.Sprintf("%s-%s", AnonIssuer, uuid.String())
return subject, nil
}
func getAnonymousPreferredUsername(r *http.Request) (string, error) {
preferredUsername, err := generateRandomPreferredUsername(8)
if err != nil {
return "", errors.Wrap(err, "could not generate preferred username for anonymous user")
}
return preferredUsername, nil
}
func generateRandomPreferredUsername(size int) (string, error) {
var letters = []rune("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
max := big.NewInt(int64(len(letters)))

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

View File

@ -3,6 +3,8 @@ package chromecast
import (
"context"
"net"
"regexp"
"strconv"
"strings"
"sync"
"time"
@ -13,7 +15,6 @@ import (
"github.com/barnybug/go-cast/log"
"github.com/hashicorp/mdns"
"github.com/pkg/errors"
"github.com/wlynxg/anet"
)
const (
@ -150,11 +151,28 @@ func (d *Discovery) listener(ctx context.Context) {
case d.found <- client:
case <-time.After(time.Second):
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 {
m := make(map[string]string)
@ -178,7 +196,7 @@ func isIPv6(ip net.IP) bool {
}
func findMulticastInterfaces(ctx context.Context) ([]net.Interface, error) {
ifaces, err := anet.Interfaces()
ifaces, err := net.Interfaces()
if err != nil {
return nil, nil
}
@ -205,7 +223,7 @@ func findMulticastInterfaces(ctx context.Context) ([]net.Interface, error) {
}
func retrieveSupportedProtocols(iface net.Interface) (bool, bool, error) {
adresses, err := anet.InterfaceAddrsByInterface(&iface)
adresses, err := iface.Addrs()
if err != nil {
return false, false, errors.WithStack(err)
}