|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "net/url" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "github.com/hashicorp/go-multierror" |
| 11 | + |
| 12 | + clog "github.com/SenseUnit/dumbproxy/log" |
| 13 | + "github.com/SenseUnit/dumbproxy/tlsutil" |
| 14 | +) |
| 15 | + |
| 16 | +type TLSTicketAuth struct { |
| 17 | + logger *clog.CondLogger |
| 18 | + stopOnce sync.Once |
| 19 | + next Auth |
| 20 | + reject Auth |
| 21 | +} |
| 22 | + |
| 23 | +func NewTLSTicketAuth(param_url *url.URL, logger *clog.CondLogger) (*TLSTicketAuth, error) { |
| 24 | + values, err := url.ParseQuery(param_url.RawQuery) |
| 25 | + if err != nil { |
| 26 | + return nil, err |
| 27 | + } |
| 28 | + auth := &TLSTicketAuth{ |
| 29 | + logger: logger, |
| 30 | + } |
| 31 | + if nextAuth := values.Get("next"); nextAuth != "" { |
| 32 | + nap, err := NewAuth(nextAuth, logger) |
| 33 | + if err != nil { |
| 34 | + return nil, fmt.Errorf("chained auth provider construction failed: %w", err) |
| 35 | + } |
| 36 | + auth.next = nap |
| 37 | + } |
| 38 | + if nextAuth := values.Get("else"); nextAuth != "" { |
| 39 | + nap, err := NewAuth(nextAuth, logger) |
| 40 | + if err != nil { |
| 41 | + return nil, fmt.Errorf("chained auth provider construction failed: %w", err) |
| 42 | + } |
| 43 | + auth.reject = nap |
| 44 | + } |
| 45 | + return auth, nil |
| 46 | +} |
| 47 | + |
| 48 | +func (auth *TLSTicketAuth) Validate(ctx context.Context, wr http.ResponseWriter, req *http.Request) (string, bool) { |
| 49 | + if !tlsutil.NonDefaultKeyUsedFromContext(ctx) { |
| 50 | + return auth.handleReject(ctx, wr, req) |
| 51 | + } |
| 52 | + if auth.next != nil { |
| 53 | + return auth.next.Validate(ctx, wr, req) |
| 54 | + } |
| 55 | + return "", true |
| 56 | +} |
| 57 | + |
| 58 | +func (auth *TLSTicketAuth) handleReject(ctx context.Context, wr http.ResponseWriter, req *http.Request) (string, bool) { |
| 59 | + if auth.reject != nil { |
| 60 | + return auth.reject.Validate(ctx, wr, req) |
| 61 | + } |
| 62 | + http.Error(wr, BAD_REQ_MSG, http.StatusBadRequest) |
| 63 | + return "", false |
| 64 | +} |
| 65 | + |
| 66 | +func (auth *TLSTicketAuth) Close() error { |
| 67 | + var err error |
| 68 | + auth.stopOnce.Do(func() { |
| 69 | + if auth.next != nil { |
| 70 | + if closeErr := auth.next.Close(); closeErr != nil { |
| 71 | + err = multierror.Append(err, closeErr) |
| 72 | + } |
| 73 | + } |
| 74 | + if auth.reject != nil { |
| 75 | + if closeErr := auth.reject.Close(); closeErr != nil { |
| 76 | + err = multierror.Append(err, closeErr) |
| 77 | + } |
| 78 | + } |
| 79 | + }) |
| 80 | + return err |
| 81 | +} |
0 commit comments