package bearer import ( "context" "errors" "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestStatusForKeepsTheUnreachableDaemonOutOfThe401(t *testing.T) { // The arm the whole table exists for: a token service that cannot be // reached must not read as a bad credential. assert.Equal(t, http.StatusServiceUnavailable, StatusFor(ErrUnavailable)) assert.Equal(t, http.StatusServiceUnavailable, StatusFor(fmt.Errorf("ask tokens.sr.ht: %w", ErrUnavailable)), "a wrapped one too — services wrap before returning") assert.Equal(t, http.StatusForbidden, StatusFor(ErrForbidden)) assert.Equal(t, http.StatusForbidden, StatusFor(fmt.Errorf("check the grant: %w", ErrForbidden))) // The three the caller is responsible for answer alike, on purpose. for _, err := range []error{ErrInvalid, ErrRevoked, ErrNotOurs} { assert.Equal(t, http.StatusUnauthorized, StatusFor(err), "%v", err) } assert.Equal(t, http.StatusOK, StatusFor(nil)) assert.Equal(t, http.StatusUnauthorized, StatusFor(errors.New("something new")), "an unrecognised failure refuses the request rather than declaring the service unwell") } // TestIsRefusalSeparatesOurVocabularyFromTheServices is the guard a resolver // needs: its own failures must not be answered as a bad credential. func TestIsRefusalSeparatesOurVocabularyFromTheServices(t *testing.T) { for _, err := range []error{ErrInvalid, ErrNotOurs, ErrForbidden, ErrRevoked, ErrUnavailable} { assert.True(t, IsRefusal(err), "%v", err) assert.True(t, IsRefusal(fmt.Errorf("validate the token: %w", err)), "wrapped %v", err) } assert.False(t, IsRefusal(nil)) assert.False(t, IsRefusal(errors.New("dial tcp 127.0.0.1:5432: connection refused")), "a database that did not answer is not a refused credential") assert.False(t, IsRefusal(context.DeadlineExceeded)) } func TestChallengeNamesTheServiceAndQuotesIt(t *testing.T) { assert.Equal(t, `Bearer realm="bench.sr.ht"`, Challenge("bench.sr.ht")) assert.Equal(t, `Bearer realm="dolt.sr.ht"`, Challenge("dolt.sr.ht")) // A quote in the realm would end the parameter early if it were pasted in. assert.Equal(t, `Bearer realm="a\"b"`, Challenge(`a"b`)) }